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