@takeal/cusfront-sdk 0.3.20 → 0.6.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 (133) hide show
  1. package/CHANGELOG.md +137 -2
  2. package/README.md +407 -8
  3. package/dist/analytics.cjs +438 -0
  4. package/dist/analytics.cjs.map +1 -0
  5. package/dist/analytics.d.cts +129 -0
  6. package/dist/analytics.d.ts +129 -0
  7. package/dist/analytics.js +424 -0
  8. package/dist/analytics.js.map +1 -0
  9. package/dist/cards-B_aNY35J.d.cts +514 -0
  10. package/dist/cards-Ba1wZttb.d.ts +514 -0
  11. package/dist/deposits-BEc8U80M.d.cts +310 -0
  12. package/dist/deposits-DScyT_D9.d.ts +310 -0
  13. package/dist/{devices-DP_hxwmW.d.ts → devices-B_YveTl9.d.ts} +1 -1
  14. package/dist/{devices-C3JHi2Hi.d.cts → devices-a5Z45Mx_.d.cts} +1 -1
  15. package/dist/{http-B-OQwMYn.d.cts → http-DeANAoTs.d.cts} +11 -3
  16. package/dist/{http-B-OQwMYn.d.ts → http-DeANAoTs.d.ts} +11 -3
  17. package/dist/index.cjs +978 -101
  18. package/dist/index.cjs.map +1 -1
  19. package/dist/index.d.cts +101 -13
  20. package/dist/index.d.ts +101 -13
  21. package/dist/index.js +963 -102
  22. package/dist/index.js.map +1 -1
  23. package/dist/react/index.cjs +2 -8
  24. package/dist/react/index.cjs.map +1 -1
  25. package/dist/react/index.d.cts +12 -5
  26. package/dist/react/index.d.ts +12 -5
  27. package/dist/react/index.js +2 -8
  28. package/dist/react/index.js.map +1 -1
  29. package/dist/resources/attribution.cjs +82 -0
  30. package/dist/resources/attribution.cjs.map +1 -0
  31. package/dist/resources/attribution.d.cts +100 -0
  32. package/dist/resources/attribution.d.ts +100 -0
  33. package/dist/resources/attribution.js +78 -0
  34. package/dist/resources/attribution.js.map +1 -0
  35. package/dist/resources/auth.cjs +81 -15
  36. package/dist/resources/auth.cjs.map +1 -1
  37. package/dist/resources/auth.d.cts +53 -6
  38. package/dist/resources/auth.d.ts +53 -6
  39. package/dist/resources/auth.js +81 -15
  40. package/dist/resources/auth.js.map +1 -1
  41. package/dist/resources/balance.d.cts +1 -1
  42. package/dist/resources/balance.d.ts +1 -1
  43. package/dist/resources/blog.cjs.map +1 -1
  44. package/dist/resources/blog.d.cts +8 -1
  45. package/dist/resources/blog.d.ts +8 -1
  46. package/dist/resources/blog.js.map +1 -1
  47. package/dist/resources/bonus.cjs +28 -0
  48. package/dist/resources/bonus.cjs.map +1 -0
  49. package/dist/resources/bonus.d.cts +121 -0
  50. package/dist/resources/bonus.d.ts +121 -0
  51. package/dist/resources/bonus.js +26 -0
  52. package/dist/resources/bonus.js.map +1 -0
  53. package/dist/resources/branding.d.cts +1 -1
  54. package/dist/resources/branding.d.ts +1 -1
  55. package/dist/resources/cards.cjs +55 -28
  56. package/dist/resources/cards.cjs.map +1 -1
  57. package/dist/resources/cards.d.cts +2 -347
  58. package/dist/resources/cards.d.ts +2 -347
  59. package/dist/resources/cards.js +55 -29
  60. package/dist/resources/cards.js.map +1 -1
  61. package/dist/resources/codes.cjs +20 -0
  62. package/dist/resources/codes.cjs.map +1 -0
  63. package/dist/resources/codes.d.cts +100 -0
  64. package/dist/resources/codes.d.ts +100 -0
  65. package/dist/resources/codes.js +18 -0
  66. package/dist/resources/codes.js.map +1 -0
  67. package/dist/resources/deposits.cjs +32 -7
  68. package/dist/resources/deposits.cjs.map +1 -1
  69. package/dist/resources/deposits.d.cts +3 -176
  70. package/dist/resources/deposits.d.ts +3 -176
  71. package/dist/resources/deposits.js +32 -7
  72. package/dist/resources/deposits.js.map +1 -1
  73. package/dist/resources/devices.cjs +3 -1
  74. package/dist/resources/devices.cjs.map +1 -1
  75. package/dist/resources/devices.d.cts +2 -2
  76. package/dist/resources/devices.d.ts +2 -2
  77. package/dist/resources/devices.js +3 -1
  78. package/dist/resources/devices.js.map +1 -1
  79. package/dist/resources/documents.cjs +66 -0
  80. package/dist/resources/documents.cjs.map +1 -0
  81. package/dist/resources/documents.d.cts +212 -0
  82. package/dist/resources/documents.d.ts +212 -0
  83. package/dist/resources/documents.js +64 -0
  84. package/dist/resources/documents.js.map +1 -0
  85. package/dist/resources/funding-options.cjs +16 -0
  86. package/dist/resources/funding-options.cjs.map +1 -0
  87. package/dist/resources/funding-options.d.cts +3 -0
  88. package/dist/resources/funding-options.d.ts +3 -0
  89. package/dist/resources/funding-options.js +14 -0
  90. package/dist/resources/funding-options.js.map +1 -0
  91. package/dist/resources/history.cjs +33 -0
  92. package/dist/resources/history.cjs.map +1 -0
  93. package/dist/resources/history.d.cts +95 -0
  94. package/dist/resources/history.d.ts +95 -0
  95. package/dist/resources/history.js +31 -0
  96. package/dist/resources/history.js.map +1 -0
  97. package/dist/resources/me.d.cts +3 -1
  98. package/dist/resources/me.d.ts +3 -1
  99. package/dist/resources/notifications.d.cts +1 -1
  100. package/dist/resources/notifications.d.ts +1 -1
  101. package/dist/resources/push.cjs +3 -1
  102. package/dist/resources/push.cjs.map +1 -1
  103. package/dist/resources/push.d.cts +1 -1
  104. package/dist/resources/push.d.ts +1 -1
  105. package/dist/resources/push.js +3 -1
  106. package/dist/resources/push.js.map +1 -1
  107. package/dist/resources/referral.cjs +16 -0
  108. package/dist/resources/referral.cjs.map +1 -0
  109. package/dist/resources/referral.d.cts +58 -0
  110. package/dist/resources/referral.d.ts +58 -0
  111. package/dist/resources/referral.js +14 -0
  112. package/dist/resources/referral.js.map +1 -0
  113. package/dist/resources/sessions.d.cts +1 -1
  114. package/dist/resources/sessions.d.ts +1 -1
  115. package/dist/resources/subscription.cjs +24 -0
  116. package/dist/resources/subscription.cjs.map +1 -0
  117. package/dist/resources/subscription.d.cts +48 -0
  118. package/dist/resources/subscription.d.ts +48 -0
  119. package/dist/resources/subscription.js +22 -0
  120. package/dist/resources/subscription.js.map +1 -0
  121. package/dist/resources/subscriptions.d.cts +1 -1
  122. package/dist/resources/subscriptions.d.ts +1 -1
  123. package/dist/resources/wallet.d.cts +1 -1
  124. package/dist/resources/wallet.d.ts +1 -1
  125. package/dist/telegram.cjs +495 -111
  126. package/dist/telegram.cjs.map +1 -1
  127. package/dist/telegram.d.cts +12 -5
  128. package/dist/telegram.d.ts +12 -5
  129. package/dist/telegram.js +495 -111
  130. package/dist/telegram.js.map +1 -1
  131. package/package.json +57 -5
  132. package/dist/customer-CoxPwe5o.d.cts +0 -32
  133. package/dist/customer-CoxPwe5o.d.ts +0 -32
package/dist/index.cjs CHANGED
@@ -44,6 +44,20 @@ var HttpClient = class {
44
44
  this.defaultHeaders = defaultHeaders;
45
45
  if (!baseUrl) throw new Error("HttpClient: baseUrl is required");
46
46
  }
47
+ /** Called once on a 401; resolves `true` when a new session was stored. */
48
+ setRefresher(fn) {
49
+ this.refresher = fn;
50
+ }
51
+ /** One refresh at a time, whoever asks. */
52
+ refreshOnce() {
53
+ if (!this.refresher) return Promise.resolve(false);
54
+ if (!this.refreshing) {
55
+ this.refreshing = this.refresher().catch(() => false).finally(() => {
56
+ this.refreshing = void 0;
57
+ });
58
+ }
59
+ return this.refreshing;
60
+ }
47
61
  async get(path, opts = {}) {
48
62
  return this.request("GET", path, opts);
49
63
  }
@@ -84,10 +98,12 @@ var HttpClient = class {
84
98
  try {
85
99
  resp = await this.fetchImpl(url, init);
86
100
  } catch (e) {
87
- throw new NetworkError(
88
- e instanceof Error ? e.message : "network error",
89
- e
90
- );
101
+ throw new NetworkError(e instanceof Error ? e.message : "network error", e);
102
+ }
103
+ if (resp.status === 401 && !opts.skipAuth && !opts.retried && this.refresher) {
104
+ if (await this.refreshOnce()) {
105
+ return this.request(method, path, { ...opts, retried: true });
106
+ }
91
107
  }
92
108
  return parseResponse(resp);
93
109
  }
@@ -122,20 +138,73 @@ async function parseResponse(resp) {
122
138
  }
123
139
 
124
140
  // src/resources/auth.ts
141
+ function withRemember(input) {
142
+ const { remember, ...rest } = input;
143
+ return remember ? { ...rest, remember_me: true } : rest;
144
+ }
125
145
  var AuthResource = class {
126
- constructor(http, tokens) {
146
+ constructor(http, tokens, remembered) {
127
147
  this.http = http;
128
148
  this.tokens = tokens;
149
+ this.remembered = remembered;
150
+ if (remembered) http.setRefresher(() => this.renew().then((r) => r.kind !== "gone"));
151
+ }
152
+ /** Store what a finished sign-in returned. */
153
+ async keep(resp) {
154
+ await Promise.resolve(this.tokens.set(resp.access_token));
155
+ if (resp.remember_token && this.remembered) {
156
+ await Promise.resolve(this.remembered.set(resp.remember_token));
157
+ }
158
+ }
159
+ /** Renew a remembered sign-in: a new session and a new remember token,
160
+ * both stored. Resolves `null` (and forgets the remember token) when there
161
+ * is none or it no longer works; the app then shows the sign-in form.
162
+ * The SDK does this by itself on a 401; call it on app start to resume a
163
+ * session without a request failing first. */
164
+ async refresh() {
165
+ const r = await this.renew();
166
+ if (r.kind === "renewed") return r.resp;
167
+ if (r.kind === "taken_over") {
168
+ const access = await Promise.resolve(this.tokens.get());
169
+ const user = await this.me();
170
+ return { stage: "jwt", access_token: access ?? "", expires_at: "", user };
171
+ }
172
+ return null;
173
+ }
174
+ /** The renewal itself, for the 401 path: it must not call the API again
175
+ * through the client, or a second 401 would wait on this very renewal. */
176
+ async renew() {
177
+ const token = this.remembered ? await Promise.resolve(this.remembered.get()) : null;
178
+ if (!token) return { kind: "gone" };
179
+ try {
180
+ const resp = await this.http.post("/auth/refresh", {
181
+ body: { remember_token: token },
182
+ skipAuth: true
183
+ });
184
+ await this.keep(resp);
185
+ return { kind: "renewed", resp };
186
+ } catch (e) {
187
+ if (isApiError(e) && e.status === 401) {
188
+ const now = await Promise.resolve(this.remembered.get());
189
+ if (now && now !== token && await Promise.resolve(this.tokens.get())) {
190
+ return { kind: "taken_over" };
191
+ }
192
+ await Promise.resolve(this.remembered.clear());
193
+ await Promise.resolve(this.tokens.clear());
194
+ return { kind: "gone" };
195
+ }
196
+ throw e;
197
+ }
129
198
  }
130
199
  /** Password-auth entry. May resolve to a JWT, or to a step-up
131
200
  * challenge that needs `verifyTotp` / `verifyOtp` next. */
132
201
  async login(input) {
133
202
  const resp = await this.http.post("/auth/login", {
134
- body: input,
203
+ body: withRemember(input),
135
204
  skipAuth: true
136
205
  });
137
206
  if (resp.stage === "jwt") {
138
- await Promise.resolve(this.tokens.set(resp.access_token));
207
+ await this.keep(resp);
139
208
  }
140
209
  return resp;
141
210
  }
@@ -143,20 +212,20 @@ var AuthResource = class {
143
212
  * `totp_required` challenge. On success the JWT is stored. */
144
213
  async verifyTotp(input) {
145
214
  const resp = await this.http.post("/auth/login/totp", {
146
- body: input,
215
+ body: withRemember(input),
147
216
  skipAuth: true
148
217
  });
149
- await Promise.resolve(this.tokens.set(resp.access_token));
218
+ await this.keep(resp);
150
219
  return resp;
151
220
  }
152
221
  /** Verify a 6-digit OTP code (Telegram / email) against an
153
222
  * `otp_sent` challenge. */
154
223
  async verifyOtp(input) {
155
224
  const resp = await this.http.post("/auth/login/otp/verify", {
156
- body: input,
225
+ body: withRemember(input),
157
226
  skipAuth: true
158
227
  });
159
- await Promise.resolve(this.tokens.set(resp.access_token));
228
+ await this.keep(resp);
160
229
  return resp;
161
230
  }
162
231
  /** Create an end-user account and sign it in. The JWT is stored.
@@ -166,10 +235,10 @@ var AuthResource = class {
166
235
  * Errors: 400 `validation` / `currency_not_allowed`, 409 email taken. */
167
236
  async register(input) {
168
237
  const resp = await this.http.post("/auth/register", {
169
- body: input,
238
+ body: withRemember(input),
170
239
  skipAuth: true
171
240
  });
172
- await Promise.resolve(this.tokens.set(resp.access_token));
241
+ await this.keep(resp);
173
242
  return resp;
174
243
  }
175
244
  /** Finish a `totp_setup_required` login: send the first code from the
@@ -178,10 +247,10 @@ var AuthResource = class {
178
247
  * the user right away and don't keep them on the device. */
179
248
  async completeTotpSetup(input) {
180
249
  const resp = await this.http.post("/auth/login/totp-setup", {
181
- body: input,
250
+ body: withRemember(input),
182
251
  skipAuth: true
183
252
  });
184
- await Promise.resolve(this.tokens.set(resp.access_token));
253
+ await this.keep(resp);
185
254
  return resp;
186
255
  }
187
256
  /** Change the signed-in user's password. Every other session of the
@@ -202,8 +271,12 @@ var AuthResource = class {
202
271
  });
203
272
  }
204
273
  async exchangeTelegram(input) {
205
- const body = { init_data: input.initData };
274
+ const body = {
275
+ init_data: input.initData
276
+ };
206
277
  if (input.provision !== void 0) body.provision = input.provision;
278
+ if (input.attribution !== void 0) body.attribution = input.attribution;
279
+ if (input.code !== void 0) body.code = input.code;
207
280
  let resp;
208
281
  try {
209
282
  resp = await this.http.post("/auth/telegram/exchange", {
@@ -249,62 +322,44 @@ var AuthResource = class {
249
322
  async me() {
250
323
  return this.http.get("/auth/me");
251
324
  }
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()`). */
325
+ /** Sign out: ends this session and the remembered sign-in on the
326
+ * server (best effort: a network failure still signs out locally), then
327
+ * forgets both tokens. */
255
328
  async signOut() {
329
+ const remember = this.remembered ? await Promise.resolve(this.remembered.get()) : null;
330
+ try {
331
+ await this.http.post("/auth/logout", {
332
+ body: remember ? { remember_token: remember } : {},
333
+ retried: true
334
+ });
335
+ } catch {
336
+ }
256
337
  await Promise.resolve(this.tokens.clear());
257
- }
258
- };
259
-
260
- // src/resources/deposits.ts
261
- var DepositsResource = class {
262
- constructor(http) {
263
- this.http = http;
264
- }
265
- /**
266
- * Initiate a top-up. Resolves to the freshly-created `Deposit`, whose
267
- * `status` may already be `confirmed` (synchronous rails / mock) or
268
- * `redirect_required` (3DS / APM — forward the user to `redirect_url`).
269
- */
270
- /**
271
- * Price a cross-currency deposit BEFORE paying. The rate is locked
272
- * server-side until `expires_at`; deposits in the local currency need no
273
- * quote (the API answers 400 `no_quote_needed`).
274
- */
275
- async quote(input) {
276
- return this.http.post("/me/deposits/quotes", { body: input });
277
- }
278
- async initiate(input) {
279
- const { idempotencyKey, ...body } = input;
280
- return this.http.post("/me/deposits", {
281
- body,
282
- idempotencyKey
283
- });
284
- }
285
- /** Fetch one deposit by id — the poll target while a redirect resolves. */
286
- async get(id) {
287
- return this.http.get(`/me/deposits/${encodeURIComponent(id)}`);
288
- }
289
- /** List the caller's deposits, most recent first. */
290
- async list() {
291
- return this.http.get("/me/deposits");
292
- }
293
- /**
294
- * Refund a previously-confirmed deposit. Synchronous when the
295
- * connector settles inline; otherwise the row stays `pending` and flips
296
- * later via the inbound `deposit.refunded` event.
297
- */
298
- async refund(depositId, input) {
299
- const { idempotencyKey, ...body } = input;
300
- return this.http.post(
301
- `/me/deposits/${encodeURIComponent(depositId)}/refunds`,
302
- { body, idempotencyKey }
303
- );
338
+ if (this.remembered) await Promise.resolve(this.remembered.clear());
304
339
  }
305
340
  };
306
341
 
307
342
  // src/resources/cards.ts
343
+ function cardRequestBody(input) {
344
+ const {
345
+ productId,
346
+ name,
347
+ designId,
348
+ useBonus,
349
+ bonusAmount,
350
+ promoCode,
351
+ initial_amount: _ignored,
352
+ ...rest
353
+ } = input;
354
+ const body = { ...rest };
355
+ if (productId !== void 0) body["product_id"] = productId;
356
+ if (name !== void 0) body["name"] = name;
357
+ if (designId !== void 0) body["design_id"] = designId;
358
+ if (useBonus !== void 0) body["use_bonus"] = useBonus;
359
+ if (bonusAmount !== void 0) body["bonus_amount"] = bonusAmount;
360
+ if (promoCode !== void 0) body["promo_code"] = promoCode;
361
+ return body;
362
+ }
308
363
  var CardsResource = class {
309
364
  constructor(http) {
310
365
  this.http = http;
@@ -316,30 +371,26 @@ var CardsResource = class {
316
371
  * `failure_reason` on the result.
317
372
  */
318
373
  async create(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;
374
+ const { idempotencyKey, ...card } = input;
324
375
  return this.http.post("/me/cards", {
325
- body,
376
+ body: cardRequestBody(card),
326
377
  idempotencyKey
327
378
  });
328
379
  }
329
380
  /**
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}.
381
+ * The cards the caller can order, in the order the storefront shows them
382
+ * (`is_default` marks the one issued when none is chosen). Each item
383
+ * carries its product card (name, tagline, benefits, tile picture),
384
+ * artwork, and the issuance price after the caller's subscription
385
+ * discount, in the caller's wallet currency. Pass an item's `id` as
386
+ * `productId` to {@link create}.
334
387
  */
335
388
  async listProducts() {
336
389
  return this.http.get("/me/card-products");
337
390
  }
338
391
  /** One product from the catalog. 404 when unknown, disabled or hidden. */
339
392
  async getProduct(id) {
340
- return this.http.get(
341
- `/me/card-products/${encodeURIComponent(id)}`
342
- );
393
+ return this.http.get(`/me/card-products/${encodeURIComponent(id)}`);
343
394
  }
344
395
  /**
345
396
  * The public catalog: the same products, order and default as
@@ -378,9 +429,7 @@ var CardsResource = class {
378
429
  */
379
430
  async balance(id, currency) {
380
431
  const q = new URLSearchParams({ currency }).toString();
381
- return this.http.get(
382
- `/me/cards/${encodeURIComponent(id)}/balance?${q}`
383
- );
432
+ return this.http.get(`/me/cards/${encodeURIComponent(id)}/balance?${q}`);
384
433
  }
385
434
  /**
386
435
  * What a top-up of this card can be right now: whether it is possible, the
@@ -407,16 +456,32 @@ var CardsResource = class {
407
456
  idempotencyKey
408
457
  });
409
458
  }
459
+ /**
460
+ * Move money from one of the caller's cards to another. Both must be
461
+ * theirs, active, in the same currency and of the same kind. The money
462
+ * travels through the wallet one leg at a time: when the second leg does
463
+ * not go through, the call still resolves, `transfer.status` is
464
+ * `on_wallet` and the money is on the wallet — never between two cards.
465
+ * Errors carry a sentence the user can read: 400 the same card twice,
466
+ * different currencies or different kinds · 402 the card holds less than
467
+ * that · 404 one of the cards isn't theirs · 409 a card is frozen, closed
468
+ * or still being issued, or the key was reused with a different body ·
469
+ * 501/502/503 the provider cannot or will not move it.
470
+ */
471
+ async transfer(fromCardId, input) {
472
+ const { toCardId, amount, idempotencyKey } = input;
473
+ return this.http.post(`/me/cards/${encodeURIComponent(fromCardId)}/transfer`, {
474
+ body: { to_card_id: toCardId, amount },
475
+ idempotencyKey
476
+ });
477
+ }
410
478
  /**
411
479
  * Freeze the caller's own card. Reversible via {@link unfreeze}. The optional
412
480
  * `reason` is recorded on the audit trail. Resolves to the updated card.
413
481
  * 404 if the card isn't the caller's; 501 if the issuer can't freeze.
414
482
  */
415
483
  async freeze(id, reason) {
416
- return this.http.post(
417
- `/me/cards/${encodeURIComponent(id)}/freeze`,
418
- { body: { reason } }
419
- );
484
+ return this.http.post(`/me/cards/${encodeURIComponent(id)}/freeze`, { body: { reason } });
420
485
  }
421
486
  /**
422
487
  * Reveal the FULL PAN + CVV for the caller's own card. The signed-in
@@ -436,10 +501,7 @@ var CardsResource = class {
436
501
  }
437
502
  /** Unfreeze a previously-frozen card. Idempotent on an already-active card. */
438
503
  async unfreeze(id) {
439
- return this.http.post(
440
- `/me/cards/${encodeURIComponent(id)}/unfreeze`,
441
- { body: {} }
442
- );
504
+ return this.http.post(`/me/cards/${encodeURIComponent(id)}/unfreeze`, { body: {} });
443
505
  }
444
506
  /**
445
507
  * Terminate the caller's own card. **One-way** — a terminated card cannot be
@@ -447,10 +509,59 @@ var CardsResource = class {
447
509
  * already-terminated card.
448
510
  */
449
511
  async terminate(id, reason) {
450
- return this.http.post(
451
- `/me/cards/${encodeURIComponent(id)}/terminate`,
452
- { body: { reason } }
453
- );
512
+ return this.http.post(`/me/cards/${encodeURIComponent(id)}/terminate`, {
513
+ body: { reason }
514
+ });
515
+ }
516
+ };
517
+
518
+ // src/resources/deposits.ts
519
+ var DepositsResource = class {
520
+ constructor(http) {
521
+ this.http = http;
522
+ }
523
+ /**
524
+ * Initiate a top-up. Resolves to the freshly-created `Deposit`, whose
525
+ * `status` may already be `confirmed` (synchronous rails / mock) or
526
+ * `redirect_required` (3DS / APM — forward the user to `redirect_url`).
527
+ */
528
+ /**
529
+ * Price a cross-currency deposit BEFORE paying. The rate is locked
530
+ * server-side until `expires_at`; deposits already in the currency they
531
+ * credit (the wallet's, or the card's with `card_id`) need no quote (the
532
+ * API answers 400 `no_quote_needed`).
533
+ */
534
+ async quote(input) {
535
+ return this.http.post("/me/deposits/quotes", { body: input });
536
+ }
537
+ async initiate(input) {
538
+ const { idempotencyKey, issue_card, ...rest } = input;
539
+ const body = { ...rest };
540
+ if (issue_card !== void 0) body["issue_card"] = cardRequestBody(issue_card);
541
+ return this.http.post("/me/deposits", {
542
+ body,
543
+ idempotencyKey
544
+ });
545
+ }
546
+ /** Fetch one deposit by id — the poll target while a redirect resolves. */
547
+ async get(id) {
548
+ return this.http.get(`/me/deposits/${encodeURIComponent(id)}`);
549
+ }
550
+ /** List the caller's deposits, most recent first. */
551
+ async list() {
552
+ return this.http.get("/me/deposits");
553
+ }
554
+ /**
555
+ * Refund a previously-confirmed deposit. Synchronous when the
556
+ * connector settles inline; otherwise the row stays `pending` and flips
557
+ * later via the inbound `deposit.refunded` event.
558
+ */
559
+ async refund(depositId, input) {
560
+ const { idempotencyKey, ...body } = input;
561
+ return this.http.post(`/me/deposits/${encodeURIComponent(depositId)}/refunds`, {
562
+ body,
563
+ idempotencyKey
564
+ });
454
565
  }
455
566
  };
456
567
 
@@ -471,6 +582,74 @@ var BalanceResource = class {
471
582
  }
472
583
  };
473
584
 
585
+ // src/resources/bonus.ts
586
+ var BonusResource = class {
587
+ constructor(http) {
588
+ this.http = http;
589
+ }
590
+ /** The user's bonuses: balance, where they can go, credits and history. */
591
+ async get(opts = {}) {
592
+ return this.http.get("/me/bonus", { signal: opts.signal });
593
+ }
594
+ /**
595
+ * Work out how bonuses would change a price, at the rate the payment
596
+ * would use. Nothing is held; the numbers may move by the time the user
597
+ * pays if prices, rates or bonuses change.
598
+ */
599
+ async preview(input) {
600
+ const { productId, bonusAmount, ...rest } = input;
601
+ const body = { ...rest };
602
+ if (productId !== void 0) body["product_id"] = productId;
603
+ if (bonusAmount !== void 0) body["bonus_amount"] = bonusAmount;
604
+ return this.http.post("/me/bonus/preview", { body });
605
+ }
606
+ };
607
+
608
+ // src/resources/codes.ts
609
+ var CodesResource = class {
610
+ constructor(http) {
611
+ this.http = http;
612
+ }
613
+ /**
614
+ * Whether a code can be used on an operation now and what it would do.
615
+ * Nothing is used up. For sign-up there is nothing to check here: send
616
+ * the code with `auth.register` and read `code_result`.
617
+ */
618
+ async validate(input) {
619
+ return this.http.post("/me/codes/validate", { body: input });
620
+ }
621
+ };
622
+
623
+ // src/resources/referral.ts
624
+ var ReferralResource = class {
625
+ constructor(http) {
626
+ this.http = http;
627
+ }
628
+ /** The user's referral code, link, invited friends and rewards. */
629
+ async get(opts = {}) {
630
+ return this.http.get("/me/referral", { signal: opts.signal });
631
+ }
632
+ };
633
+
634
+ // src/resources/subscription.ts
635
+ var SubscriptionResource = class {
636
+ constructor(http) {
637
+ this.http = http;
638
+ }
639
+ /** The user's subscription, or `null` when there is none. */
640
+ async get(opts = {}) {
641
+ return this.http.get("/me/subscription", { signal: opts.signal });
642
+ }
643
+ /**
644
+ * Charge the monthly fee with a promo code, as long as the code allows.
645
+ * `null` removes it. A code that can't be used on the fee fails with 400
646
+ * `promo_code_*`; no paid subscription running → 404.
647
+ */
648
+ async setPromoCode(code) {
649
+ return this.http.put("/me/subscription/promo-code", { body: { code } });
650
+ }
651
+ };
652
+
474
653
  // src/resources/branding.ts
475
654
  var BrandingResource = class {
476
655
  constructor(http) {
@@ -535,6 +714,67 @@ var BlogResource = class {
535
714
  }
536
715
  };
537
716
 
717
+ // src/resources/documents.ts
718
+ var DocumentsResource = class {
719
+ constructor(http) {
720
+ this.http = http;
721
+ }
722
+ /**
723
+ * Published documents you may read, paged. The blog comes newest first,
724
+ * other categories in the order set by the editors.
725
+ */
726
+ async list(input = {}) {
727
+ const q = new URLSearchParams();
728
+ if (input.category) q.set("category", input.category);
729
+ if (input.folderId) q.set("folder_id", input.folderId);
730
+ if (input.tag) q.set("tag", input.tag);
731
+ if (input.locale) q.set("locale", input.locale);
732
+ if (input.q) q.set("q", input.q);
733
+ if (input.page) q.set("page", String(input.page));
734
+ if (input.perPage) q.set("per_page", String(input.perPage));
735
+ const qs = q.toString();
736
+ return this.http.get(`/documents${qs ? `?${qs}` : ""}`);
737
+ }
738
+ /** Folders and documents for a sidebar or a table of contents. */
739
+ async tree(input = {}) {
740
+ const qs = input.category ? `?category=${encodeURIComponent(input.category)}` : "";
741
+ return this.http.get(`/documents/tree${qs}`);
742
+ }
743
+ /** Every tag on a document you may read, most used first. */
744
+ async tags() {
745
+ return this.http.get("/documents/tags");
746
+ }
747
+ /**
748
+ * One document by its address. Without `at`, the text in force now; with
749
+ * `at` (an ISO 8601 moment), the text that was in force then. Unknown
750
+ * addresses and documents above your level are a 404.
751
+ */
752
+ async get(slug, opts = {}) {
753
+ const at = opts.at instanceof Date ? opts.at.toISOString() : opts.at;
754
+ const qs = at ? `?at=${encodeURIComponent(at)}` : "";
755
+ return this.http.get(`/documents/${encodeURIComponent(slug)}${qs}`);
756
+ }
757
+ /** Every saved text of a document, newest first, with the date each took effect. */
758
+ async versions(slug) {
759
+ return this.http.get(
760
+ `/documents/${encodeURIComponent(slug)}/versions`
761
+ );
762
+ }
763
+ /** The document as it read in one version. */
764
+ async version(slug, version) {
765
+ return this.http.get(`/documents/${encodeURIComponent(slug)}/versions/${version}`);
766
+ }
767
+ /**
768
+ * Absolute URL for an image path returned inside a document (`cover_url`,
769
+ * or an image block's `url`). Handy when the app renders on a different
770
+ * origin than the API.
771
+ */
772
+ imageUrl(baseUrl, path) {
773
+ if (/^https?:\/\//i.test(path)) return path;
774
+ return `${baseUrl.replace(/\/$/, "")}${path.startsWith("/") ? "" : "/"}${path}`;
775
+ }
776
+ };
777
+
538
778
  // src/resources/subscriptions.ts
539
779
  var SubscriptionsResource = class {
540
780
  constructor(http) {
@@ -602,7 +842,9 @@ var PushResource = class {
602
842
  async enable(registration) {
603
843
  const { vapid_public_key } = await this.status();
604
844
  if (!vapid_public_key) {
605
- throw new Error("@takeal/cusfront-sdk: push notifications are not enabled on this deployment");
845
+ throw new Error(
846
+ "@takeal/cusfront-sdk: push notifications are not enabled on this deployment"
847
+ );
606
848
  }
607
849
  const sub = await registration.pushManager.subscribe({
608
850
  userVisibleOnly: true,
@@ -747,7 +989,9 @@ var DevicesResource = class {
747
989
  async registerWebPush(registration, opts = {}) {
748
990
  const key = opts.vapidPublicKey ?? await this.vapidPublicKey();
749
991
  if (!key) {
750
- throw new Error("@takeal/cusfront-sdk: push notifications are not enabled on this deployment");
992
+ throw new Error(
993
+ "@takeal/cusfront-sdk: push notifications are not enabled on this deployment"
994
+ );
751
995
  }
752
996
  const sub = await registration.pushManager.subscribe({
753
997
  userVisibleOnly: true,
@@ -788,8 +1032,122 @@ var DevicesResource = class {
788
1032
  }
789
1033
  };
790
1034
 
1035
+ // src/resources/attribution.ts
1036
+ var AttributionResource = class {
1037
+ constructor(http) {
1038
+ this.http = http;
1039
+ }
1040
+ /** Record a visit. No session needed; safe to call on every page load. */
1041
+ async touch(input) {
1042
+ return this.http.post("/attribution/touches", { body: input, skipAuth: true });
1043
+ }
1044
+ /** Whether to ask the signed-in user how they heard about us. */
1045
+ async status() {
1046
+ return this.http.get("/me/attribution");
1047
+ }
1048
+ /** Answer the question once. Send `"skipped"` when the user closes it.
1049
+ * `otherText` is kept only with `"other"`, up to 500 characters.
1050
+ * Errors: 400 `validation`, 409 `survey_answered`. */
1051
+ async answerSurvey(answer, otherText) {
1052
+ const body = { answer };
1053
+ if (otherText !== void 0) body.other_text = otherText;
1054
+ return this.http.put("/me/attribution/survey", { body });
1055
+ }
1056
+ };
1057
+ function tgWebApp() {
1058
+ return globalThis.Telegram?.WebApp?.initDataUnsafe;
1059
+ }
1060
+ function readCookie(name) {
1061
+ const doc = globalThis.document;
1062
+ if (!doc?.cookie) return void 0;
1063
+ for (const part of doc.cookie.split(";")) {
1064
+ const [k, ...v] = part.trim().split("=");
1065
+ if (k === name) return decodeURIComponent(v.join("="));
1066
+ }
1067
+ return void 0;
1068
+ }
1069
+ var KEY_SHAPE = /^[A-Za-z0-9_-]{8,64}$/;
1070
+ function anonymousKey(opts = {}) {
1071
+ const tgId = tgWebApp()?.user?.id;
1072
+ if (tgId) return `tg:${tgId}`;
1073
+ const g = globalThis;
1074
+ if (!g.document) return void 0;
1075
+ const name = opts.name ?? "takeal_anon";
1076
+ let stored;
1077
+ try {
1078
+ stored = g.localStorage?.getItem(name) ?? void 0;
1079
+ } catch {
1080
+ stored = void 0;
1081
+ }
1082
+ const fromCookie = readCookie(name);
1083
+ let key = [fromCookie, stored].find((k) => !!k && KEY_SHAPE.test(k));
1084
+ if (!key) {
1085
+ key = g.crypto?.randomUUID?.() ?? `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 14)}`;
1086
+ }
1087
+ try {
1088
+ g.localStorage?.setItem(name, key);
1089
+ } catch {
1090
+ }
1091
+ const domain = opts.cookieDomain ? `; domain=${opts.cookieDomain}` : "";
1092
+ g.document.cookie = `${name}=${encodeURIComponent(key)}; max-age=31536000; path=/; SameSite=Lax${domain}`;
1093
+ return key;
1094
+ }
1095
+ function currentTouch() {
1096
+ const g = globalThis;
1097
+ const tg = tgWebApp();
1098
+ const out = {};
1099
+ if (g.location?.href) out.url = g.location.href;
1100
+ if (g.document?.referrer) out.referrer = g.document.referrer;
1101
+ if (tg?.start_param) out.campaign_code = tg.start_param;
1102
+ if (tg?.user?.id) out.platform = "miniapp";
1103
+ const ym = readCookie("_ym_uid");
1104
+ if (ym) out.metrika_client_id = ym;
1105
+ const ga = readCookie("_ga")?.split(".").slice(-2).join(".");
1106
+ if (ga) out.ga_client_id = ga;
1107
+ return out;
1108
+ }
1109
+
1110
+ // src/resources/history.ts
1111
+ var HistoryResource = class {
1112
+ constructor(http) {
1113
+ this.http = http;
1114
+ }
1115
+ /** One page of the history. Errors: 400 bad cursor or limit, 404 `cardId` is not the user's card. */
1116
+ async list(params = {}) {
1117
+ const q = new URLSearchParams();
1118
+ if (params.cardId) q.set("card_id", params.cardId);
1119
+ if (params.cursor) q.set("cursor", params.cursor);
1120
+ if (params.limit !== void 0) q.set("limit", String(params.limit));
1121
+ if (params.lang) q.set("lang", params.lang);
1122
+ const qs = q.toString();
1123
+ return this.http.get(`/me/history${qs ? `?${qs}` : ""}`, {
1124
+ signal: params.signal
1125
+ });
1126
+ }
1127
+ /** Every entry, page after page, newest first. */
1128
+ async *all(params = {}) {
1129
+ let cursor;
1130
+ do {
1131
+ const page2 = await this.list({ ...params, cursor });
1132
+ yield* page2.items;
1133
+ cursor = page2.next_cursor ?? void 0;
1134
+ } while (cursor);
1135
+ }
1136
+ };
1137
+
1138
+ // src/resources/funding-options.ts
1139
+ var FundingOptionsResource = class {
1140
+ constructor(http) {
1141
+ this.http = http;
1142
+ }
1143
+ /** The ways to top up, preferred first. Empty when none is configured. */
1144
+ async list() {
1145
+ return this.http.get("/me/funding-options");
1146
+ }
1147
+ };
1148
+
791
1149
  // src/version.ts
792
- var SDK_VERSION = "0.3.20";
1150
+ var SDK_VERSION = "0.6.0";
793
1151
 
794
1152
  // src/client-platform.ts
795
1153
  var CLIENT_HEADER = "X-Takeal-Client";
@@ -863,9 +1221,503 @@ function isAbsolute(url) {
863
1221
  return /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i.test(url);
864
1222
  }
865
1223
 
1224
+ // src/compat.ts
1225
+ var SUPPORTED_MEISTER = ">=0.5.0, <0.7.0";
1226
+ var SEMVER = /^v?(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;
1227
+ function parse(v) {
1228
+ const m = SEMVER.exec(v.trim());
1229
+ if (!m) return null;
1230
+ return { core: [Number(m[1]), Number(m[2]), Number(m[3])], pre: m[4] ?? null };
1231
+ }
1232
+ function cmpCore(a, b) {
1233
+ for (let i = 0; i < 3; i++) {
1234
+ if (a.core[i] !== b.core[i]) return a.core[i] < b.core[i] ? -1 : 1;
1235
+ }
1236
+ return 0;
1237
+ }
1238
+ function satisfies(version, range) {
1239
+ const v = parse(version);
1240
+ if (!v) return false;
1241
+ const parts = range.split(",").map((p) => p.trim()).filter(Boolean);
1242
+ if (parts.length === 0) return false;
1243
+ let exactPre = false;
1244
+ for (const part of parts) {
1245
+ const m = /^(>=|<=|>|<|=)?\s*(.+)$/.exec(part);
1246
+ if (!m) return false;
1247
+ const op = m[1] ?? "=";
1248
+ const target = parse(m[2]);
1249
+ if (!target) return false;
1250
+ const c = cmpCore(v, target);
1251
+ if (op === "=") {
1252
+ if (c !== 0 || v.pre !== target.pre) return false;
1253
+ if (v.pre !== null) exactPre = true;
1254
+ continue;
1255
+ }
1256
+ const ok = op === ">=" ? c >= 0 : op === ">" ? c > 0 : op === "<=" ? c <= 0 : c < 0;
1257
+ if (!ok) return false;
1258
+ }
1259
+ return v.pre === null || exactPre;
1260
+ }
1261
+ function readyInfo(raw, healthy) {
1262
+ const reported = raw?.ops?.platform_version;
1263
+ const platformVersion = typeof reported === "string" && reported ? reported : null;
1264
+ const base = {
1265
+ platformVersion,
1266
+ supportedMeister: SUPPORTED_MEISTER,
1267
+ healthy,
1268
+ status: typeof raw?.status === "string" ? raw.status : healthy ? "ready" : "degraded",
1269
+ raw
1270
+ };
1271
+ if (platformVersion === null) {
1272
+ return {
1273
+ ...base,
1274
+ compatible: false,
1275
+ warning: `The platform didn't report its version; this SDK supports ${SUPPORTED_MEISTER}.`
1276
+ };
1277
+ }
1278
+ if (!satisfies(platformVersion, SUPPORTED_MEISTER)) {
1279
+ return {
1280
+ ...base,
1281
+ compatible: false,
1282
+ warning: `This SDK supports platform ${SUPPORTED_MEISTER}, the platform runs ${platformVersion}. Some calls may fail until the SDK is updated.`
1283
+ };
1284
+ }
1285
+ return { ...base, compatible: true };
1286
+ }
1287
+ async function fetchReady(http, opts = {}) {
1288
+ try {
1289
+ const body = await http.get("/ready", { skipAuth: true, signal: opts.signal });
1290
+ return readyInfo(body ?? {}, true);
1291
+ } catch (e) {
1292
+ if (isApiError(e) && e.status === 503 && typeof e.body === "object" && e.body !== null) {
1293
+ return readyInfo(e.body, false);
1294
+ }
1295
+ throw e;
1296
+ }
1297
+ }
1298
+
1299
+ // src/analytics.ts
1300
+ var ANALYTICS_EVENTS = [
1301
+ "signup_started",
1302
+ "signup_completed",
1303
+ "signup",
1304
+ "login",
1305
+ "deposit_started",
1306
+ "deposit_confirmed",
1307
+ "deposit_failed",
1308
+ "card_issued",
1309
+ "card_issue_failed",
1310
+ "card_activated",
1311
+ "card_topped_up",
1312
+ "card_transferred",
1313
+ "card_frozen",
1314
+ "card_unfrozen",
1315
+ "card_terminated",
1316
+ "txn_cleared",
1317
+ "txn_declined",
1318
+ "subscription_started",
1319
+ "subscription_renewed",
1320
+ "subscription_cancelled",
1321
+ "fee_charged",
1322
+ "refund_issued"
1323
+ ];
1324
+ var METRIKA_GOALS = ["signup_started", "signup_completed"];
1325
+ var NO_CAPTURE_CLASS = "ph-no-capture";
1326
+ var UUID = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi;
1327
+ var EMAIL = /[^\s@"'<>(),;:]+@[^\s@"'<>(),;:]+\.[a-z]{2,}/gi;
1328
+ var DIGIT_RUN = /\+?\d[\d\s().-]{7,}\d/g;
1329
+ var UUID_ONLY = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
1330
+ function isId(v) {
1331
+ return /^\d+$/.test(v) || UUID_ONLY.test(v) || /^[0-9a-f]{16,}$/i.test(v) || /^[A-Za-z0-9_]{20,}$/.test(v) && /\d.*\d/.test(v) && /[A-Za-z].*[A-Za-z]/.test(v);
1332
+ }
1333
+ var PLACEHOLDER = ":id";
1334
+ var PERSONAL_WORDS = /* @__PURE__ */ new Set([
1335
+ "email",
1336
+ "mail",
1337
+ "phone",
1338
+ "tel",
1339
+ "telephone",
1340
+ "mobile",
1341
+ "msisdn",
1342
+ "surname",
1343
+ "patronymic",
1344
+ "firstname",
1345
+ "lastname",
1346
+ "fullname",
1347
+ "username",
1348
+ "nickname"
1349
+ ]);
1350
+ var PERSON_NAME_QUALIFIERS = /* @__PURE__ */ new Set([
1351
+ "first",
1352
+ "last",
1353
+ "full",
1354
+ "user",
1355
+ "display",
1356
+ "given",
1357
+ "family",
1358
+ "middle",
1359
+ "nick",
1360
+ "real",
1361
+ "holder",
1362
+ "cardholder",
1363
+ "customer",
1364
+ "contact",
1365
+ "person",
1366
+ "owner",
1367
+ "account",
1368
+ "legal"
1369
+ ]);
1370
+ var SECRET_QUERY_WORDS = /* @__PURE__ */ new Set([
1371
+ "token",
1372
+ "code",
1373
+ "key",
1374
+ "secret",
1375
+ "password",
1376
+ "pass",
1377
+ "pwd",
1378
+ "otp",
1379
+ "sig",
1380
+ "signature",
1381
+ "session",
1382
+ "sid",
1383
+ "auth",
1384
+ "jwt",
1385
+ "pan",
1386
+ "cvv",
1387
+ "cvc",
1388
+ "iban"
1389
+ ]);
1390
+ var MONEY_KEYS = /* @__PURE__ */ new Set([
1391
+ "amount",
1392
+ "amount_minor",
1393
+ "currency",
1394
+ "value",
1395
+ "price",
1396
+ "revenue",
1397
+ "sum"
1398
+ ]);
1399
+ function words(key) {
1400
+ return key.replace(/^\$+/, "").replace(/([a-z])([A-Z])/g, "$1_$2").toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);
1401
+ }
1402
+ function personalKey(key) {
1403
+ const w = words(key);
1404
+ const joined = w.join("");
1405
+ if (joined.includes("email") || joined.includes("phone")) return true;
1406
+ if (w.some((x) => PERSONAL_WORDS.has(x)) || PERSONAL_WORDS.has(joined)) return true;
1407
+ if (key.startsWith("$")) return false;
1408
+ return w.some(
1409
+ (x, i) => x === "name" && (w.length === 1 || PERSON_NAME_QUALIFIERS.has(w[i - 1] ?? ""))
1410
+ );
1411
+ }
1412
+ function urlKey(key) {
1413
+ const k = key.replace(/^\$+/, "").toLowerCase();
1414
+ return /(^|_)(url|href|pathname|path|referrer|referer)$/.test(k) || k === "page" || k.startsWith("attr__href");
1415
+ }
1416
+ function digitCount(s) {
1417
+ return s.replace(/\D/g, "").length;
1418
+ }
1419
+ function redactText(v) {
1420
+ return v.replace(EMAIL, "[email]").replace(DIGIT_RUN, (m) => digitCount(m) >= 9 && digitCount(m) <= 19 ? "[number]" : m);
1421
+ }
1422
+ function idSegment(seg) {
1423
+ let s = seg;
1424
+ try {
1425
+ s = decodeURIComponent(seg);
1426
+ } catch {
1427
+ }
1428
+ if (isId(s)) return PLACEHOLDER;
1429
+ const replaced = s.replace(UUID, PLACEHOLDER);
1430
+ if (replaced !== s) return replaced;
1431
+ return redactText(s) === s ? seg : PLACEHOLDER;
1432
+ }
1433
+ function sanitizeUrl(raw) {
1434
+ const absolute = /^[a-z][a-z0-9+.-]*:\/\//i.test(raw);
1435
+ let u;
1436
+ try {
1437
+ u = new URL(raw, "http://relative.invalid");
1438
+ } catch {
1439
+ return redactText(raw.split(/[?#]/)[0] ?? "").replace(UUID, PLACEHOLDER);
1440
+ }
1441
+ const path = u.pathname.split("/").map((seg) => seg ? idSegment(seg) : seg).join("/");
1442
+ const query = [];
1443
+ u.searchParams.forEach((value, key) => {
1444
+ const k = words(key);
1445
+ if (k.some((w) => SECRET_QUERY_WORDS.has(w)) || personalKey(key)) return;
1446
+ if (redactText(value) !== value) return;
1447
+ query.push(
1448
+ `${encodeURIComponent(key)}=${isId(value) ? PLACEHOLDER : encodeURIComponent(value)}`
1449
+ );
1450
+ });
1451
+ const search = query.length ? `?${query.join("&")}` : "";
1452
+ return (absolute ? `${u.protocol}//${u.host}` : "") + path + search;
1453
+ }
1454
+ function cleanValue(key, v, depth) {
1455
+ if (v === null || v === void 0 || typeof v === "number" || typeof v === "boolean") return v;
1456
+ if (typeof v === "string") {
1457
+ if (MONEY_KEYS.has(key.toLowerCase()) || UUID_ONLY.test(v)) return v;
1458
+ if (urlKey(key) || /^https?:\/\//i.test(v)) return sanitizeUrl(v);
1459
+ if (key === "$elements_chain") {
1460
+ return redactText(v).replace(
1461
+ /attr__href="([^"]*)"/g,
1462
+ (_, h) => `attr__href="${sanitizeUrl(h)}"`
1463
+ );
1464
+ }
1465
+ const r = redactText(v);
1466
+ return r.replace(/\[(email|number)\]/g, "").trim() === "" && r !== v ? void 0 : r;
1467
+ }
1468
+ if (depth > 5) return void 0;
1469
+ if (Array.isArray(v))
1470
+ return v.map((x) => cleanValue(key, x, depth + 1)).filter((x) => x !== void 0);
1471
+ if (typeof v === "object") return sanitizeProperties(v, depth + 1);
1472
+ return void 0;
1473
+ }
1474
+ function sanitizeProperties(props, depth = 0) {
1475
+ const out = {};
1476
+ for (const [k, v] of Object.entries(props)) {
1477
+ if (personalKey(k)) continue;
1478
+ const c = cleanValue(k, v, depth);
1479
+ if (c !== void 0) out[k] = c;
1480
+ }
1481
+ return out;
1482
+ }
1483
+ function beforeSend(event) {
1484
+ if (!event) return event;
1485
+ const out = { ...event };
1486
+ if (event.properties) out.properties = sanitizeProperties(event.properties);
1487
+ if (event.$set) out.$set = sanitizeProperties(event.$set);
1488
+ if (event.$set_once) out.$set_once = sanitizeProperties(event.$set_once);
1489
+ return out;
1490
+ }
1491
+ var win = () => globalThis;
1492
+ function injectScript(src, onLoad, onError) {
1493
+ const doc = win().document;
1494
+ if (!doc) return;
1495
+ const s = doc.createElement("script");
1496
+ s.async = true;
1497
+ s.src = src;
1498
+ s.crossOrigin = "anonymous";
1499
+ if (onLoad) s.addEventListener("load", onLoad);
1500
+ if (onError) s.addEventListener("error", onError);
1501
+ (doc.head ?? doc.documentElement).appendChild(s);
1502
+ }
1503
+ function posthogConfig(zone, o) {
1504
+ const host = (o.host ?? "https://eu.i.posthog.com").replace(/\/+$/, "");
1505
+ const base = {
1506
+ api_host: host,
1507
+ ui_host: o.uiHost ?? "https://eu.posthog.com",
1508
+ // Profiles for signed-in users only.
1509
+ person_profiles: "identified_only",
1510
+ // Page views go through `page()`, with a cleaned address.
1511
+ capture_pageview: false,
1512
+ capture_pageleave: true,
1513
+ before_send: beforeSend
1514
+ };
1515
+ return { ...base, ...zoneConfig(zone, o) };
1516
+ }
1517
+ function zoneConfig(zone, o) {
1518
+ if (zone === "public") {
1519
+ return {
1520
+ autocapture: true,
1521
+ mask_all_text: false,
1522
+ mask_all_element_attributes: false,
1523
+ enable_heatmaps: true,
1524
+ disable_session_recording: true
1525
+ };
1526
+ }
1527
+ return {
1528
+ // A click is "the third button in the cards block", never its label.
1529
+ autocapture: { capture_copied_text: false },
1530
+ mask_all_text: true,
1531
+ mask_all_element_attributes: true,
1532
+ enable_heatmaps: false,
1533
+ disable_session_recording: !o.sessionRecording,
1534
+ session_recording: {
1535
+ maskAllInputs: true,
1536
+ maskTextSelector: "*",
1537
+ blockClass: NO_CAPTURE_CLASS
1538
+ }
1539
+ };
1540
+ }
1541
+ function assetsHost(o) {
1542
+ if (o.assetsHost) return o.assetsHost.replace(/\/+$/, "");
1543
+ const host = (o.host ?? "https://eu.i.posthog.com").replace(/\/+$/, "");
1544
+ return host.replace(".i.posthog.com", "-assets.i.posthog.com");
1545
+ }
1546
+ function loadPostHogScript(o, config) {
1547
+ return new Promise((resolve) => {
1548
+ const w = win();
1549
+ if (!w.document) return resolve(void 0);
1550
+ const placeholder = Object.assign([], {
1551
+ __SV: 1,
1552
+ _i: [[o.key, config, "posthog"]]
1553
+ });
1554
+ w.posthog = placeholder;
1555
+ injectScript(
1556
+ `${assetsHost(o)}/static/array.js`,
1557
+ () => {
1558
+ const ph = w.posthog;
1559
+ const live = ph !== placeholder && typeof ph?.capture === "function";
1560
+ resolve(live ? ph : void 0);
1561
+ },
1562
+ () => resolve(void 0)
1563
+ );
1564
+ });
1565
+ }
1566
+ var PostHogSink = class {
1567
+ constructor(o, zone) {
1568
+ this.o = o;
1569
+ const config = posthogConfig(zone, o);
1570
+ this.ready = (o.load ? o.load().then((ph) => {
1571
+ ph.init(o.key, config);
1572
+ return ph;
1573
+ }) : loadPostHogScript(o, config)).then((ph) => {
1574
+ ph?.register({ zone });
1575
+ return ph;
1576
+ }).catch(() => void 0);
1577
+ }
1578
+ with(fn) {
1579
+ void this.ready.then((ph) => ph && fn(ph));
1580
+ }
1581
+ capture(event, props) {
1582
+ this.with((ph) => ph.capture(event, props));
1583
+ }
1584
+ page(url, referrer) {
1585
+ const props = { $current_url: url };
1586
+ if (referrer) props.$referrer = referrer;
1587
+ this.with((ph) => ph.capture("$pageview", props));
1588
+ }
1589
+ identify(userId) {
1590
+ this.with((ph) => ph.identify(userId));
1591
+ }
1592
+ reset() {
1593
+ this.with((ph) => ph.reset());
1594
+ }
1595
+ setZone(zone) {
1596
+ this.with((ph) => {
1597
+ ph.set_config(zoneConfig(zone, this.o));
1598
+ ph.register({ zone });
1599
+ if (zone === "public" || !this.o.sessionRecording) ph.stopSessionRecording?.();
1600
+ else ph.startSessionRecording?.();
1601
+ });
1602
+ }
1603
+ };
1604
+ var MetrikaSink = class {
1605
+ constructor(o) {
1606
+ this.live = true;
1607
+ this.id = Number(o.counterId);
1608
+ const w = win();
1609
+ if (!w.ym) {
1610
+ const ym = ((...args) => {
1611
+ (ym.a = ym.a ?? []).push(args);
1612
+ });
1613
+ ym.l = Date.now();
1614
+ w.ym = ym;
1615
+ injectScript(o.scriptUrl ?? "https://mc.yandex.ru/metrika/tag.js");
1616
+ }
1617
+ this.ym("init", {
1618
+ defer: true,
1619
+ webvisor: false,
1620
+ clickmap: false,
1621
+ trackLinks: false,
1622
+ accurateTrackBounce: true
1623
+ });
1624
+ }
1625
+ ym(...args) {
1626
+ if (this.live) win().ym?.(this.id, ...args);
1627
+ }
1628
+ capture(event, props) {
1629
+ if (METRIKA_GOALS.includes(event)) this.ym("reachGoal", event, props);
1630
+ }
1631
+ page(url, referrer) {
1632
+ this.ym("hit", url, referrer ? { referer: referrer } : {});
1633
+ }
1634
+ identify(userId) {
1635
+ this.ym("setUserID", userId);
1636
+ }
1637
+ reset() {
1638
+ }
1639
+ setZone(zone) {
1640
+ this.live = zone === "public";
1641
+ }
1642
+ };
1643
+ var KEY = /* @__PURE__ */ Symbol.for("takeal.cusfront-sdk.analytics");
1644
+ var holder = globalThis;
1645
+ var state = () => holder[KEY];
1646
+ function sinks(s) {
1647
+ if (s.zone === "public" && s.options.metrika && !s.metrika) {
1648
+ s.metrika = new MetrikaSink(s.options.metrika);
1649
+ if (s.userId) s.metrika.identify(s.userId);
1650
+ }
1651
+ return [s.posthog, s.metrika].filter((x) => !!x);
1652
+ }
1653
+ function initAnalytics(options) {
1654
+ if (state() || !win().document) return;
1655
+ if (options.zone !== "public" && win().ym) {
1656
+ console.warn(
1657
+ "[analytics] Yandex Metrica is on a page outside the public zone; it must not be."
1658
+ );
1659
+ }
1660
+ const s = { options, zone: options.zone };
1661
+ holder[KEY] = s;
1662
+ if (options.posthog?.key) s.posthog = new PostHogSink(options.posthog, options.zone);
1663
+ sinks(s);
1664
+ if (options.initialPageview !== false) page();
1665
+ }
1666
+ function setAnalyticsZone(zone) {
1667
+ const s = state();
1668
+ if (!s || s.zone === zone) return;
1669
+ s.zone = zone;
1670
+ for (const sink of sinks(s)) sink.setZone(zone);
1671
+ }
1672
+ function track(event, props = {}) {
1673
+ const s = state();
1674
+ if (!s || !ANALYTICS_EVENTS.includes(event)) return;
1675
+ const clean = sanitizeProperties(props);
1676
+ for (const sink of sinks(s)) sink.capture(event, clean);
1677
+ }
1678
+ function page(url) {
1679
+ const s = state();
1680
+ const w = win();
1681
+ const raw = url ?? w.location?.href;
1682
+ if (!s || !raw) return;
1683
+ const clean = sanitizeUrl(raw);
1684
+ if (clean === s.lastPage) return;
1685
+ const referrer = s.lastPage ?? (w.document?.referrer ? sanitizeUrl(w.document.referrer) : void 0);
1686
+ s.lastPage = clean;
1687
+ for (const sink of sinks(s)) sink.page(clean, referrer);
1688
+ }
1689
+ function identify(userId) {
1690
+ const s = state();
1691
+ if (!s || !userId) return;
1692
+ s.userId = userId;
1693
+ for (const sink of sinks(s)) sink.identify(userId);
1694
+ }
1695
+ function resetAnalytics() {
1696
+ const s = state();
1697
+ if (!s) return;
1698
+ s.userId = void 0;
1699
+ for (const sink of sinks(s)) sink.reset();
1700
+ }
1701
+ async function posthogDistinctId(timeoutMs = 3e3) {
1702
+ const ready = state()?.posthog?.ready;
1703
+ if (!ready) return void 0;
1704
+ let timer;
1705
+ const timeout = new Promise((r) => {
1706
+ timer = setTimeout(r, timeoutMs);
1707
+ });
1708
+ const ph = await Promise.race([ready, timeout]);
1709
+ clearTimeout(timer);
1710
+ try {
1711
+ return ph?.get_distinct_id() || void 0;
1712
+ } catch {
1713
+ return void 0;
1714
+ }
1715
+ }
1716
+
866
1717
  // src/index.ts
867
1718
  function createClient(opts) {
868
1719
  const tokens = opts.tokenStore ?? pickDefaultStore();
1720
+ const remembered = opts.rememberStore ?? pickDefaultStore("takeal_remember");
869
1721
  const fetchImpl = opts.fetch ?? defaultFetch();
870
1722
  const client = resolveClientDescriptor(opts.client);
871
1723
  const http = new HttpClient(opts.baseUrl, tokens, fetchImpl, {
@@ -876,24 +1728,33 @@ function createClient(opts) {
876
1728
  client,
877
1729
  tokens,
878
1730
  assetUrl: (url) => resolveAssetUrl(opts.baseUrl, url),
879
- auth: new AuthResource(http, tokens),
1731
+ ready: (o) => fetchReady(http, o),
1732
+ auth: new AuthResource(http, tokens, remembered),
880
1733
  deposits: new DepositsResource(http),
1734
+ fundingOptions: new FundingOptionsResource(http),
881
1735
  cards: new CardsResource(http),
882
1736
  balance: new BalanceResource(http),
1737
+ bonus: new BonusResource(http),
1738
+ codes: new CodesResource(http),
1739
+ referral: new ReferralResource(http),
1740
+ subscription: new SubscriptionResource(http),
883
1741
  wallet: new WalletResource(http),
884
1742
  branding: new BrandingResource(http),
1743
+ documents: new DocumentsResource(http),
885
1744
  blog: new BlogResource(http),
886
1745
  subscriptions: new SubscriptionsResource(http),
887
1746
  sessions: new SessionsResource(http),
888
1747
  push: new PushResource(http),
889
1748
  me: new MeResource(http),
890
1749
  notifications: new NotificationsResource(http),
891
- devices: new DevicesResource(http, client)
1750
+ devices: new DevicesResource(http, client),
1751
+ attribution: new AttributionResource(http),
1752
+ history: new HistoryResource(http)
892
1753
  };
893
1754
  }
894
- function pickDefaultStore() {
1755
+ function pickDefaultStore(key) {
895
1756
  if (typeof globalThis !== "undefined" && "localStorage" in globalThis) {
896
- return defaultBrowserStore();
1757
+ return defaultBrowserStore(key);
897
1758
  }
898
1759
  return inMemoryStore();
899
1760
  }
@@ -906,17 +1767,33 @@ function defaultFetch() {
906
1767
  );
907
1768
  }
908
1769
 
1770
+ exports.ANALYTICS_EVENTS = ANALYTICS_EVENTS;
909
1771
  exports.ApiError = ApiError;
910
1772
  exports.CLIENT_HEADER = CLIENT_HEADER;
1773
+ exports.METRIKA_GOALS = METRIKA_GOALS;
1774
+ exports.NO_CAPTURE_CLASS = NO_CAPTURE_CLASS;
911
1775
  exports.NetworkError = NetworkError;
912
1776
  exports.SDK_VERSION = SDK_VERSION;
1777
+ exports.SUPPORTED_MEISTER = SUPPORTED_MEISTER;
1778
+ exports.anonymousKey = anonymousKey;
913
1779
  exports.createClient = createClient;
1780
+ exports.currentTouch = currentTouch;
914
1781
  exports.defaultBrowserStore = defaultBrowserStore;
915
1782
  exports.detectClientPlatform = detectClientPlatform;
1783
+ exports.identify = identify;
916
1784
  exports.inMemoryStore = inMemoryStore;
1785
+ exports.initAnalytics = initAnalytics;
917
1786
  exports.isApiError = isApiError;
918
1787
  exports.isCardOtp = isCardOtp;
919
1788
  exports.isNetworkError = isNetworkError;
1789
+ exports.page = page;
1790
+ exports.posthogDistinctId = posthogDistinctId;
1791
+ exports.resetAnalytics = resetAnalytics;
920
1792
  exports.resolveAssetUrl = resolveAssetUrl;
1793
+ exports.sanitizeProperties = sanitizeProperties;
1794
+ exports.sanitizeUrl = sanitizeUrl;
1795
+ exports.satisfies = satisfies;
1796
+ exports.setAnalyticsZone = setAnalyticsZone;
1797
+ exports.track = track;
921
1798
  //# sourceMappingURL=index.cjs.map
922
1799
  //# sourceMappingURL=index.cjs.map