@takeal/cusfront-sdk 0.6.11 → 0.8.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 (59) hide show
  1. package/CHANGELOG.md +97 -0
  2. package/README.md +54 -2
  3. package/dist/analytics.cjs +44 -6
  4. package/dist/analytics.cjs.map +1 -1
  5. package/dist/analytics.js +44 -6
  6. package/dist/analytics.js.map +1 -1
  7. package/dist/{cards-nXmDP0ei.d.cts → cards-BPu8Ill7.d.cts} +159 -12
  8. package/dist/{cards-CuUdrQ0H.d.ts → cards-DP1fJc_c.d.ts} +159 -12
  9. package/dist/index.cjs +261 -89
  10. package/dist/index.cjs.map +1 -1
  11. package/dist/index.d.cts +5 -5
  12. package/dist/index.d.ts +5 -5
  13. package/dist/index.js +257 -90
  14. package/dist/index.js.map +1 -1
  15. package/dist/react/index.d.cts +1 -1
  16. package/dist/react/index.d.ts +1 -1
  17. package/dist/resources/attribution.cjs +99 -4
  18. package/dist/resources/attribution.cjs.map +1 -1
  19. package/dist/resources/attribution.d.cts +58 -1
  20. package/dist/resources/attribution.d.ts +58 -1
  21. package/dist/resources/attribution.js +96 -5
  22. package/dist/resources/attribution.js.map +1 -1
  23. package/dist/resources/auth.cjs +66 -3
  24. package/dist/resources/auth.cjs.map +1 -1
  25. package/dist/resources/auth.d.cts +7 -2
  26. package/dist/resources/auth.d.ts +7 -2
  27. package/dist/resources/auth.js +66 -3
  28. package/dist/resources/auth.js.map +1 -1
  29. package/dist/resources/cards.cjs +111 -3
  30. package/dist/resources/cards.cjs.map +1 -1
  31. package/dist/resources/cards.d.cts +3 -1
  32. package/dist/resources/cards.d.ts +3 -1
  33. package/dist/resources/cards.js +110 -4
  34. package/dist/resources/cards.js.map +1 -1
  35. package/dist/resources/codes.cjs.map +1 -1
  36. package/dist/resources/codes.d.cts +21 -1
  37. package/dist/resources/codes.d.ts +21 -1
  38. package/dist/resources/codes.js.map +1 -1
  39. package/dist/resources/consents.cjs +15 -0
  40. package/dist/resources/consents.cjs.map +1 -1
  41. package/dist/resources/consents.js +15 -0
  42. package/dist/resources/consents.js.map +1 -1
  43. package/dist/resources/deposits.cjs +50 -0
  44. package/dist/resources/deposits.cjs.map +1 -1
  45. package/dist/resources/deposits.d.cts +3 -1
  46. package/dist/resources/deposits.d.ts +3 -1
  47. package/dist/resources/deposits.js +50 -0
  48. package/dist/resources/deposits.js.map +1 -1
  49. package/dist/resources/funding-options.d.cts +3 -1
  50. package/dist/resources/funding-options.d.ts +3 -1
  51. package/dist/resources/me.d.cts +1 -1
  52. package/dist/resources/me.d.ts +1 -1
  53. package/dist/telegram.cjs +253 -69
  54. package/dist/telegram.cjs.map +1 -1
  55. package/dist/telegram.d.cts +35 -4
  56. package/dist/telegram.d.ts +35 -4
  57. package/dist/telegram.js +253 -70
  58. package/dist/telegram.js.map +1 -1
  59. package/package.json +1 -1
package/dist/telegram.cjs CHANGED
@@ -144,6 +144,150 @@ async function parseResponse(resp) {
144
144
  return body;
145
145
  }
146
146
 
147
+ // src/resources/attribution.ts
148
+ var AttributionResource = class {
149
+ constructor(http) {
150
+ this.http = http;
151
+ }
152
+ /** Record a visit. No session needed; safe to call on every page load. */
153
+ async touch(input) {
154
+ return this.http.post("/attribution/touches", { body: input, skipAuth: true });
155
+ }
156
+ /** A one-day token that carries the visitor's analytics ids into the
157
+ * Telegram Mini App, whose sign-in reads it back. Most callers want
158
+ * {@link AttributionResource.telegramStartParam}. Errors: 400 when none of
159
+ * the ids is valid. */
160
+ async handoff(ids) {
161
+ return this.http.post("/attribution/handoff", { body: ids, skipAuth: true });
162
+ }
163
+ /**
164
+ * The `startapp` value for a link from the site to the Mini App: the code
165
+ * as it is, followed by `__<token>` when the visitor has analytics ids, so
166
+ * a payment made in Telegram is still credited to the visit it came from.
167
+ * Without ids, or when the token can't be had, just the code.
168
+ *
169
+ * ```ts
170
+ * const start = await client.attribution.telegramStartParam("SPRING");
171
+ * location.href = `https://t.me/our_bot/app?startapp=${start}`;
172
+ * ```
173
+ */
174
+ async telegramStartParam(code = "") {
175
+ const ids = analyticsIds();
176
+ if (!ids) return code;
177
+ try {
178
+ const { token } = await this.handoff(ids);
179
+ return `${code}__${token}`;
180
+ } catch {
181
+ return code;
182
+ }
183
+ }
184
+ /** Send the visitor's analytics ids for the signed-in account, e.g. right
185
+ * after they agreed to analytics cookies in the cabinet. Without an
186
+ * argument the ids this browser holds are sent; nothing is sent when it
187
+ * holds none. */
188
+ async sendAnalyticsIds(ids = analyticsIds()) {
189
+ if (!ids) return;
190
+ await this.http.post("/me/analytics/ids", { body: ids });
191
+ }
192
+ /** Whether to ask the signed-in user how they heard about us. */
193
+ async status() {
194
+ return this.http.get("/me/attribution");
195
+ }
196
+ /** Answer the question once. Send `"skipped"` when the user closes it.
197
+ * `otherText` is kept only with `"other"`, up to 500 characters.
198
+ * Errors: 400 `validation`, 409 `survey_answered`. */
199
+ async answerSurvey(answer, otherText) {
200
+ const body = { answer };
201
+ if (otherText !== void 0) body.other_text = otherText;
202
+ return this.http.put("/me/attribution/survey", { body });
203
+ }
204
+ };
205
+ function tgWebApp() {
206
+ return globalThis.Telegram?.WebApp?.initDataUnsafe;
207
+ }
208
+ function readCookie(name) {
209
+ const doc = globalThis.document;
210
+ if (!doc?.cookie) return void 0;
211
+ for (const part of doc.cookie.split(";")) {
212
+ const [k, ...v] = part.trim().split("=");
213
+ if (k === name) return decodeURIComponent(v.join("="));
214
+ }
215
+ return void 0;
216
+ }
217
+ var KEY_SHAPE = /^[A-Za-z0-9_-]{8,64}$/;
218
+ function anonymousKey(opts = {}) {
219
+ const tgId = tgWebApp()?.user?.id;
220
+ if (tgId) return `tg:${tgId}`;
221
+ const g = globalThis;
222
+ if (!g.document) return void 0;
223
+ const name = opts.name ?? "takeal_anon";
224
+ let stored2;
225
+ try {
226
+ stored2 = g.localStorage?.getItem(name) ?? void 0;
227
+ } catch {
228
+ stored2 = void 0;
229
+ }
230
+ const fromCookie = readCookie(name);
231
+ let key = [fromCookie, stored2].find((k) => !!k && KEY_SHAPE.test(k));
232
+ if (!key) {
233
+ key = g.crypto?.randomUUID?.() ?? `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 14)}`;
234
+ }
235
+ try {
236
+ g.localStorage?.setItem(name, key);
237
+ } catch {
238
+ }
239
+ const domain = opts.cookieDomain ? `; domain=${opts.cookieDomain}` : "";
240
+ g.document.cookie = `${name}=${encodeURIComponent(key)}; max-age=31536000; path=/; SameSite=Lax${domain}`;
241
+ return key;
242
+ }
243
+ var IDS_KEY = "takeal_analytics_ids";
244
+ function storage() {
245
+ try {
246
+ return globalThis.localStorage;
247
+ } catch {
248
+ return void 0;
249
+ }
250
+ }
251
+ function stored() {
252
+ try {
253
+ const raw = storage()?.getItem(IDS_KEY);
254
+ const v = raw ? JSON.parse(raw) : {};
255
+ return typeof v === "object" && v !== null ? v : {};
256
+ } catch {
257
+ return {};
258
+ }
259
+ }
260
+ function clean(ids) {
261
+ const out = {};
262
+ const ym = ids.metrika_client_id?.trim();
263
+ if (ym && /^\d{1,32}$/.test(ym)) out.metrika_client_id = ym;
264
+ const ga = ids.ga_client_id?.trim();
265
+ if (ga && /^\d+\.\d+$/.test(ga) && ga.length <= 64) out.ga_client_id = ga;
266
+ return out.metrika_client_id || out.ga_client_id ? out : void 0;
267
+ }
268
+ function forgetAnalyticsIds() {
269
+ try {
270
+ storage()?.removeItem(IDS_KEY);
271
+ } catch {
272
+ }
273
+ }
274
+ function analyticsIds() {
275
+ const kept = stored();
276
+ return clean({
277
+ metrika_client_id: kept.metrika_client_id ?? readCookie("_ym_uid"),
278
+ ga_client_id: kept.ga_client_id ?? readCookie("_ga")?.split(".").slice(-2).join(".")
279
+ });
280
+ }
281
+ function withAnalyticsIds(attribution) {
282
+ const ids = analyticsIds();
283
+ if (!ids) return attribution;
284
+ return {
285
+ ...attribution,
286
+ metrika_client_id: attribution?.metrika_client_id ?? ids.metrika_client_id,
287
+ ga_client_id: attribution?.ga_client_id ?? ids.ga_client_id
288
+ };
289
+ }
290
+
147
291
  // src/resources/cards.ts
148
292
  function cardRequestBody(input) {
149
293
  const {
@@ -167,6 +311,19 @@ function cardRequestBody(input) {
167
311
  if (consentChannel !== void 0) body["consent_channel"] = consentChannel;
168
312
  return body;
169
313
  }
314
+ function cardOrderQuoteBody(input) {
315
+ const body = {
316
+ product_id: input.productId,
317
+ method: input.method
318
+ };
319
+ if (input.designId !== void 0) body["design_id"] = input.designId;
320
+ if (input.funderSlug !== void 0) body["funder_slug"] = input.funderSlug;
321
+ if (input.currency !== void 0) body["currency"] = input.currency;
322
+ if (input.extraLoad !== void 0) body["extra_load"] = input.extraLoad;
323
+ if (input.promoCode !== void 0) body["promo_code"] = input.promoCode;
324
+ if (input.useBonus !== void 0) body["use_bonus"] = input.useBonus;
325
+ return body;
326
+ }
170
327
  function cardOrderBody(input) {
171
328
  const body = {
172
329
  product_id: input.productId,
@@ -182,6 +339,10 @@ function cardOrderBody(input) {
182
339
  if (input.consents !== void 0) body["consents"] = input.consents;
183
340
  if (input.consentChannel !== void 0) body["consent_channel"] = input.consentChannel;
184
341
  if (input.metadata !== void 0) body["metadata"] = input.metadata;
342
+ const ids = input.analyticsIds ?? analyticsIds();
343
+ if (ids !== void 0) body["analytics_ids"] = ids;
344
+ if (input.expectedAmount !== void 0) body["expected_amount"] = input.expectedAmount;
345
+ if (input.expectedCurrency !== void 0) body["expected_currency"] = input.expectedCurrency;
185
346
  return body;
186
347
  }
187
348
  function revealState(r) {
@@ -216,8 +377,13 @@ var CardsResource = class {
216
377
  * `idempotencyKey` returns the same order.
217
378
  * Errors: 400 `unknown_product` / `method_not_available` / a limit of the
218
379
  * way of paying, 409 `holder_data_consent_required` (the product has
219
- * `holder_data_required` and the user has not agreed to it), 503 no
220
- * funding connector or no exchange rate.
380
+ * `holder_data_required` and the user has not agreed to it), 409
381
+ * `payments_on_hold` (a payment on this account was not accepted and new
382
+ * ones wait until support sorts it out: show the message and point the
383
+ * user to support), 409 `price_changed` (the order came to another amount
384
+ * than `expectedAmount`; no payment was opened, and
385
+ * {@link priceChangedQuote} gives the new quote), 503 no funding connector
386
+ * or no exchange rate.
221
387
  */
222
388
  async order(input) {
223
389
  const { idempotencyKey, ...order } = input;
@@ -226,12 +392,41 @@ var CardsResource = class {
226
392
  idempotencyKey
227
393
  });
228
394
  }
395
+ /**
396
+ * What an order of this card would cost the signed-in user now, with the
397
+ * promo code: the same calculation {@link order} makes, with every
398
+ * condition of the code checked. Nothing is reserved or used up. Pass
399
+ * `amount` and `currency` to the order as `expectedAmount` and
400
+ * `expectedCurrency`.
401
+ */
402
+ async quote(input) {
403
+ return this.http.post("/me/card-orders/quote", {
404
+ body: cardOrderQuoteBody(input)
405
+ });
406
+ }
407
+ /**
408
+ * The same quote before sign-in, for a landing page or the purchase form
409
+ * before the e-mail code. Prices are list prices, and a code whose
410
+ * conditions depend on the person (first card only, say) comes back
411
+ * `conditional`, with `preliminary` set. Send `expectedAmount` with the
412
+ * order placed at sign-in: if the price turns out different, no payment
413
+ * is opened and `card_order_error` carries the new quote. The API limits
414
+ * how often one address can ask (429 `too_many_requests`).
415
+ */
416
+ async quotePublic(input) {
417
+ return this.http.post("/card-orders/quote", {
418
+ body: cardOrderQuoteBody(input),
419
+ skipAuth: true
420
+ });
421
+ }
229
422
  /**
230
423
  * The cards the caller can order, in the order the storefront shows them
231
424
  * (`is_default` marks the one issued when none is chosen). Each item
232
425
  * carries its product card (name, tagline, benefits, tile picture),
233
426
  * artwork, and the issuance price after the caller's subscription
234
- * discount, in the caller's wallet currency. Pass an item's `id` as
427
+ * discount, in the currency the operator set it in (`price.from_wallet`
428
+ * is the same price from the wallet, when that holds another currency).
429
+ * Pass an item's `id` as
235
430
  * `productId` to {@link create}.
236
431
  */
237
432
  async listProducts() {
@@ -476,8 +671,11 @@ var AuthResource = class {
476
671
  /** Password-auth entry. May resolve to a JWT, or to a step-up
477
672
  * challenge that needs `verifyTotp` / `verifyOtp` next. */
478
673
  async login(input) {
674
+ const body = withRemember(input);
675
+ const attribution = withAnalyticsIds(void 0);
676
+ if (attribution !== void 0) body["attribution"] = attribution;
479
677
  const resp = await this.http.post("/auth/login", {
480
- body: withRemember(input),
678
+ body,
481
679
  skipAuth: true
482
680
  });
483
681
  if (resp.stage === "jwt") {
@@ -514,6 +712,8 @@ var AuthResource = class {
514
712
  async register(input) {
515
713
  const { cardOrder, ...rest } = input;
516
714
  const body = withRemember(rest);
715
+ const attribution = withAnalyticsIds(rest.attribution);
716
+ if (attribution !== void 0) body["attribution"] = attribution;
517
717
  if (cardOrder !== void 0) body["card_order"] = cardOrderBody(cardOrder);
518
718
  const resp = await this.http.post("/auth/register", {
519
719
  body,
@@ -549,7 +749,8 @@ var AuthResource = class {
549
749
  };
550
750
  if (input.remember) body["remember_me"] = true;
551
751
  if (input.walletCurrency !== void 0) body["wallet_currency"] = input.walletCurrency;
552
- if (input.attribution !== void 0) body["attribution"] = input.attribution;
752
+ const attribution = withAnalyticsIds(input.attribution);
753
+ if (attribution !== void 0) body["attribution"] = attribution;
553
754
  if (input.promoCode !== void 0) body["promo_code"] = input.promoCode;
554
755
  if (input.consents !== void 0) body["consents"] = input.consents;
555
756
  if (input.consentChannel !== void 0) body["consent_channel"] = input.consentChannel;
@@ -595,7 +796,8 @@ var AuthResource = class {
595
796
  init_data: input.initData
596
797
  };
597
798
  if (input.provision !== void 0) body.provision = input.provision;
598
- if (input.attribution !== void 0) body.attribution = input.attribution;
799
+ const attribution = withAnalyticsIds(input.attribution);
800
+ if (attribution !== void 0) body.attribution = attribution;
599
801
  if (input.code !== void 0) body.code = input.code;
600
802
  if (input.consents !== void 0) body.consents = input.consents;
601
803
  if (input.consentChannel !== void 0) body.consent_channel = input.consentChannel;
@@ -701,10 +903,17 @@ var DepositsResource = class {
701
903
  if (connectorSlug !== void 0) body["connector_slug"] = connectorSlug;
702
904
  return this.http.post("/me/deposits/quotes", { body });
703
905
  }
906
+ /**
907
+ * Start a top-up. 409 `payments_on_hold`: a payment on this account was
908
+ * not accepted and new ones wait until support sorts it out. Show the
909
+ * message as it comes and point the user to support.
910
+ */
704
911
  async initiate(input) {
705
912
  const { idempotencyKey, issue_card, ...rest } = input;
706
913
  const body = { ...rest };
707
914
  if (issue_card !== void 0) body["issue_card"] = cardRequestBody(issue_card);
915
+ const ids = input.analytics_ids ?? analyticsIds();
916
+ if (ids !== void 0) body["analytics_ids"] = ids;
708
917
  return this.http.post("/me/deposits", {
709
918
  body,
710
919
  idempotencyKey
@@ -1306,67 +1515,6 @@ var DevicesResource = class {
1306
1515
  }
1307
1516
  };
1308
1517
 
1309
- // src/resources/attribution.ts
1310
- var AttributionResource = class {
1311
- constructor(http) {
1312
- this.http = http;
1313
- }
1314
- /** Record a visit. No session needed; safe to call on every page load. */
1315
- async touch(input) {
1316
- return this.http.post("/attribution/touches", { body: input, skipAuth: true });
1317
- }
1318
- /** Whether to ask the signed-in user how they heard about us. */
1319
- async status() {
1320
- return this.http.get("/me/attribution");
1321
- }
1322
- /** Answer the question once. Send `"skipped"` when the user closes it.
1323
- * `otherText` is kept only with `"other"`, up to 500 characters.
1324
- * Errors: 400 `validation`, 409 `survey_answered`. */
1325
- async answerSurvey(answer, otherText) {
1326
- const body = { answer };
1327
- if (otherText !== void 0) body.other_text = otherText;
1328
- return this.http.put("/me/attribution/survey", { body });
1329
- }
1330
- };
1331
- function tgWebApp() {
1332
- return globalThis.Telegram?.WebApp?.initDataUnsafe;
1333
- }
1334
- function readCookie(name) {
1335
- const doc = globalThis.document;
1336
- if (!doc?.cookie) return void 0;
1337
- for (const part of doc.cookie.split(";")) {
1338
- const [k, ...v] = part.trim().split("=");
1339
- if (k === name) return decodeURIComponent(v.join("="));
1340
- }
1341
- return void 0;
1342
- }
1343
- var KEY_SHAPE = /^[A-Za-z0-9_-]{8,64}$/;
1344
- function anonymousKey(opts = {}) {
1345
- const tgId = tgWebApp()?.user?.id;
1346
- if (tgId) return `tg:${tgId}`;
1347
- const g = globalThis;
1348
- if (!g.document) return void 0;
1349
- const name = opts.name ?? "takeal_anon";
1350
- let stored;
1351
- try {
1352
- stored = g.localStorage?.getItem(name) ?? void 0;
1353
- } catch {
1354
- stored = void 0;
1355
- }
1356
- const fromCookie = readCookie(name);
1357
- let key = [fromCookie, stored].find((k) => !!k && KEY_SHAPE.test(k));
1358
- if (!key) {
1359
- key = g.crypto?.randomUUID?.() ?? `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 14)}`;
1360
- }
1361
- try {
1362
- g.localStorage?.setItem(name, key);
1363
- } catch {
1364
- }
1365
- const domain = opts.cookieDomain ? `; domain=${opts.cookieDomain}` : "";
1366
- g.document.cookie = `${name}=${encodeURIComponent(key)}; max-age=31536000; path=/; SameSite=Lax${domain}`;
1367
- return key;
1368
- }
1369
-
1370
1518
  // src/resources/history.ts
1371
1519
  var HistoryResource = class {
1372
1520
  constructor(http) {
@@ -1470,6 +1618,7 @@ var ConsentsResource = class {
1470
1618
  const key = input.anonymousKey ?? anonymousKey();
1471
1619
  if (key !== void 0) body.anonymous_key = key;
1472
1620
  if (input.channel !== void 0) body.channel = input.channel;
1621
+ if (!input.analytics) forgetAnalyticsIds();
1473
1622
  return this.http.post("/consents/cookies", { body });
1474
1623
  }
1475
1624
  };
@@ -1567,7 +1716,7 @@ var FundingOptionsResource = class {
1567
1716
  };
1568
1717
 
1569
1718
  // src/version.ts
1570
- var SDK_VERSION = "0.6.11";
1719
+ var SDK_VERSION = "0.8.0";
1571
1720
 
1572
1721
  // src/client-platform.ts
1573
1722
  var CLIENT_HEADER = "X-Takeal-Client";
@@ -1642,7 +1791,7 @@ function isAbsolute(url) {
1642
1791
  }
1643
1792
 
1644
1793
  // src/compat.ts
1645
- var SUPPORTED_MEISTER = ">=0.7.6, <1.0.0";
1794
+ var SUPPORTED_MEISTER = ">=0.8.0, <1.0.0";
1646
1795
  var SEMVER = /^v?(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;
1647
1796
  function parse(v) {
1648
1797
  const m = SEMVER.exec(v.trim());
@@ -1825,6 +1974,40 @@ function assertWellFormed(initData, opts = {}) {
1825
1974
  }
1826
1975
  return parsed;
1827
1976
  }
1977
+ function describeInitData(initData, opts = {}) {
1978
+ if (typeof initData !== "string") {
1979
+ return {
1980
+ type: typeof initData,
1981
+ length: 0,
1982
+ fields: [],
1983
+ hasHash: false,
1984
+ hasSignature: false,
1985
+ hasAuthDate: false,
1986
+ hasUserId: false,
1987
+ reason: "not_a_string"
1988
+ };
1989
+ }
1990
+ const parsed = parseInitData(initData);
1991
+ const now = opts.nowUnix ?? Math.floor(Date.now() / 1e3);
1992
+ let reason = null;
1993
+ try {
1994
+ assertWellFormed(initData, opts);
1995
+ } catch (e) {
1996
+ if (e instanceof InitDataError) reason = e.reason;
1997
+ else throw e;
1998
+ }
1999
+ return {
2000
+ type: "string",
2001
+ length: initData.length,
2002
+ fields: Object.keys(parsed.params).sort(),
2003
+ hasHash: parsed.hash !== void 0,
2004
+ hasSignature: typeof parsed.params.signature === "string" && parsed.params.signature !== "",
2005
+ hasAuthDate: parsed.auth_date !== void 0,
2006
+ ...parsed.auth_date !== void 0 ? { authDateAgeSeconds: now - parsed.auth_date } : {},
2007
+ hasUserId: typeof parsed.user?.id === "number",
2008
+ reason
2009
+ };
2010
+ }
1828
2011
  var TelegramUnknownError = class extends Error {
1829
2012
  constructor(initData) {
1830
2013
  super("this Telegram account is not linked to any user (provision: false)");
@@ -1886,6 +2069,7 @@ async function fromTelegramWebApp(config, opts = {}) {
1886
2069
  exports.InitDataError = InitDataError;
1887
2070
  exports.TelegramUnknownError = TelegramUnknownError;
1888
2071
  exports.assertWellFormed = assertWellFormed;
2072
+ exports.describeInitData = describeInitData;
1889
2073
  exports.exchangeInitData = exchangeInitData;
1890
2074
  exports.fromInitData = fromInitData;
1891
2075
  exports.fromTelegramWebApp = fromTelegramWebApp;