@takeal/cusfront-sdk 0.3.18 → 0.5.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 (121) hide show
  1. package/CHANGELOG.md +139 -0
  2. package/README.md +430 -9
  3. package/dist/analytics.cjs +417 -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 +403 -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 +964 -77
  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 +949 -78
  22. package/dist/index.js.map +1 -1
  23. package/dist/react/index.d.cts +12 -5
  24. package/dist/react/index.d.ts +12 -5
  25. package/dist/resources/attribution.cjs +82 -0
  26. package/dist/resources/attribution.cjs.map +1 -0
  27. package/dist/resources/attribution.d.cts +100 -0
  28. package/dist/resources/attribution.d.ts +100 -0
  29. package/dist/resources/attribution.js +78 -0
  30. package/dist/resources/attribution.js.map +1 -0
  31. package/dist/resources/auth.cjs +81 -15
  32. package/dist/resources/auth.cjs.map +1 -1
  33. package/dist/resources/auth.d.cts +53 -6
  34. package/dist/resources/auth.d.ts +53 -6
  35. package/dist/resources/auth.js +81 -15
  36. package/dist/resources/auth.js.map +1 -1
  37. package/dist/resources/balance.d.cts +1 -1
  38. package/dist/resources/balance.d.ts +1 -1
  39. package/dist/resources/blog.cjs.map +1 -1
  40. package/dist/resources/blog.d.cts +8 -1
  41. package/dist/resources/blog.d.ts +8 -1
  42. package/dist/resources/blog.js.map +1 -1
  43. package/dist/resources/bonus.cjs +28 -0
  44. package/dist/resources/bonus.cjs.map +1 -0
  45. package/dist/resources/bonus.d.cts +121 -0
  46. package/dist/resources/bonus.d.ts +121 -0
  47. package/dist/resources/bonus.js +26 -0
  48. package/dist/resources/bonus.js.map +1 -0
  49. package/dist/resources/branding.d.cts +1 -1
  50. package/dist/resources/branding.d.ts +1 -1
  51. package/dist/resources/cards.cjs +73 -10
  52. package/dist/resources/cards.cjs.map +1 -1
  53. package/dist/resources/cards.d.cts +2 -281
  54. package/dist/resources/cards.d.ts +2 -281
  55. package/dist/resources/cards.js +73 -11
  56. package/dist/resources/cards.js.map +1 -1
  57. package/dist/resources/codes.cjs +20 -0
  58. package/dist/resources/codes.cjs.map +1 -0
  59. package/dist/resources/codes.d.cts +100 -0
  60. package/dist/resources/codes.d.ts +100 -0
  61. package/dist/resources/codes.js +18 -0
  62. package/dist/resources/codes.js.map +1 -0
  63. package/dist/resources/deposits.cjs +28 -3
  64. package/dist/resources/deposits.cjs.map +1 -1
  65. package/dist/resources/deposits.d.cts +3 -176
  66. package/dist/resources/deposits.d.ts +3 -176
  67. package/dist/resources/deposits.js +28 -3
  68. package/dist/resources/deposits.js.map +1 -1
  69. package/dist/resources/devices.d.cts +2 -2
  70. package/dist/resources/devices.d.ts +2 -2
  71. package/dist/resources/documents.cjs +64 -0
  72. package/dist/resources/documents.cjs.map +1 -0
  73. package/dist/resources/documents.d.cts +212 -0
  74. package/dist/resources/documents.d.ts +212 -0
  75. package/dist/resources/documents.js +62 -0
  76. package/dist/resources/documents.js.map +1 -0
  77. package/dist/resources/funding-options.cjs +16 -0
  78. package/dist/resources/funding-options.cjs.map +1 -0
  79. package/dist/resources/funding-options.d.cts +3 -0
  80. package/dist/resources/funding-options.d.ts +3 -0
  81. package/dist/resources/funding-options.js +14 -0
  82. package/dist/resources/funding-options.js.map +1 -0
  83. package/dist/resources/history.cjs +31 -0
  84. package/dist/resources/history.cjs.map +1 -0
  85. package/dist/resources/history.d.cts +95 -0
  86. package/dist/resources/history.d.ts +95 -0
  87. package/dist/resources/history.js +29 -0
  88. package/dist/resources/history.js.map +1 -0
  89. package/dist/resources/me.d.cts +3 -1
  90. package/dist/resources/me.d.ts +3 -1
  91. package/dist/resources/notifications.d.cts +1 -1
  92. package/dist/resources/notifications.d.ts +1 -1
  93. package/dist/resources/push.d.cts +1 -1
  94. package/dist/resources/push.d.ts +1 -1
  95. package/dist/resources/referral.cjs +16 -0
  96. package/dist/resources/referral.cjs.map +1 -0
  97. package/dist/resources/referral.d.cts +58 -0
  98. package/dist/resources/referral.d.ts +58 -0
  99. package/dist/resources/referral.js +14 -0
  100. package/dist/resources/referral.js.map +1 -0
  101. package/dist/resources/sessions.d.cts +1 -1
  102. package/dist/resources/sessions.d.ts +1 -1
  103. package/dist/resources/subscription.cjs +24 -0
  104. package/dist/resources/subscription.cjs.map +1 -0
  105. package/dist/resources/subscription.d.cts +48 -0
  106. package/dist/resources/subscription.d.ts +48 -0
  107. package/dist/resources/subscription.js +22 -0
  108. package/dist/resources/subscription.js.map +1 -0
  109. package/dist/resources/subscriptions.d.cts +1 -1
  110. package/dist/resources/subscriptions.d.ts +1 -1
  111. package/dist/resources/wallet.d.cts +1 -1
  112. package/dist/resources/wallet.d.ts +1 -1
  113. package/dist/telegram.cjs +499 -77
  114. package/dist/telegram.cjs.map +1 -1
  115. package/dist/telegram.d.cts +12 -5
  116. package/dist/telegram.d.ts +12 -5
  117. package/dist/telegram.js +499 -77
  118. package/dist/telegram.js.map +1 -1
  119. package/package.json +46 -1
  120. package/dist/customer-CoxPwe5o.d.cts +0 -32
  121. package/dist/customer-CoxPwe5o.d.ts +0 -32
@@ -2,20 +2,27 @@ import * as react from 'react';
2
2
  import { ReactNode } from 'react';
3
3
  import { CusfrontClient } from '../index.cjs';
4
4
  import { User } from '../resources/auth.cjs';
5
- import { Deposit } from '../resources/deposits.cjs';
6
- import { CardProduct, Card } from '../resources/cards.cjs';
5
+ import { D as Deposit } from '../deposits-BEc8U80M.cjs';
6
+ import { C as CardProduct, a as Card } from '../cards-B_aNY35J.cjs';
7
7
  import { Balance } from '../resources/balance.cjs';
8
8
  import { NotificationPage, InboxItem, NotificationCategory } from '../resources/notifications.cjs';
9
- import '../http-B-OQwMYn.cjs';
9
+ import '../http-DeANAoTs.cjs';
10
+ import '../resources/bonus.cjs';
11
+ import '../resources/codes.cjs';
12
+ import '../resources/referral.cjs';
13
+ import '../resources/subscription.cjs';
10
14
  import '../resources/branding.cjs';
11
15
  import '../resources/wallet.cjs';
12
16
  import '../resources/blog.cjs';
17
+ import '../resources/documents.cjs';
13
18
  import '../resources/subscriptions.cjs';
14
19
  import '../resources/sessions.cjs';
15
20
  import '../resources/push.cjs';
16
21
  import '../resources/me.cjs';
17
- import '../devices-C3JHi2Hi.cjs';
18
- import '../customer-CoxPwe5o.cjs';
22
+ import '../devices-a5Z45Mx_.cjs';
23
+ import '../resources/attribution.cjs';
24
+ import '../resources/history.cjs';
25
+ import '../analytics.cjs';
19
26
 
20
27
  interface ClientProviderProps {
21
28
  /** The client built by `createClient(...)`. Create it once (e.g. in
@@ -2,20 +2,27 @@ import * as react from 'react';
2
2
  import { ReactNode } from 'react';
3
3
  import { CusfrontClient } from '../index.js';
4
4
  import { User } from '../resources/auth.js';
5
- import { Deposit } from '../resources/deposits.js';
6
- import { CardProduct, Card } from '../resources/cards.js';
5
+ import { D as Deposit } from '../deposits-DScyT_D9.js';
6
+ import { C as CardProduct, a as Card } from '../cards-Ba1wZttb.js';
7
7
  import { Balance } from '../resources/balance.js';
8
8
  import { NotificationPage, InboxItem, NotificationCategory } from '../resources/notifications.js';
9
- import '../http-B-OQwMYn.js';
9
+ import '../http-DeANAoTs.js';
10
+ import '../resources/bonus.js';
11
+ import '../resources/codes.js';
12
+ import '../resources/referral.js';
13
+ import '../resources/subscription.js';
10
14
  import '../resources/branding.js';
11
15
  import '../resources/wallet.js';
12
16
  import '../resources/blog.js';
17
+ import '../resources/documents.js';
13
18
  import '../resources/subscriptions.js';
14
19
  import '../resources/sessions.js';
15
20
  import '../resources/push.js';
16
21
  import '../resources/me.js';
17
- import '../devices-DP_hxwmW.js';
18
- import '../customer-CoxPwe5o.js';
22
+ import '../devices-B_YveTl9.js';
23
+ import '../resources/attribution.js';
24
+ import '../resources/history.js';
25
+ import '../analytics.js';
19
26
 
20
27
  interface ClientProviderProps {
21
28
  /** The client built by `createClient(...)`. Create it once (e.g. in
@@ -0,0 +1,82 @@
1
+ 'use strict';
2
+
3
+ // src/resources/attribution.ts
4
+ var AttributionResource = class {
5
+ constructor(http) {
6
+ this.http = http;
7
+ }
8
+ /** Record a visit. No session needed; safe to call on every page load. */
9
+ async touch(input) {
10
+ return this.http.post("/attribution/touches", { body: input, skipAuth: true });
11
+ }
12
+ /** Whether to ask the signed-in user how they heard about us. */
13
+ async status() {
14
+ return this.http.get("/me/attribution");
15
+ }
16
+ /** Answer the question once. Send `"skipped"` when the user closes it.
17
+ * `otherText` is kept only with `"other"`, up to 500 characters.
18
+ * Errors: 400 `validation`, 409 `survey_answered`. */
19
+ async answerSurvey(answer, otherText) {
20
+ const body = { answer };
21
+ if (otherText !== void 0) body.other_text = otherText;
22
+ return this.http.put("/me/attribution/survey", { body });
23
+ }
24
+ };
25
+ function tgWebApp() {
26
+ return globalThis.Telegram?.WebApp?.initDataUnsafe;
27
+ }
28
+ function readCookie(name) {
29
+ const doc = globalThis.document;
30
+ if (!doc?.cookie) return void 0;
31
+ for (const part of doc.cookie.split(";")) {
32
+ const [k, ...v] = part.trim().split("=");
33
+ if (k === name) return decodeURIComponent(v.join("="));
34
+ }
35
+ return void 0;
36
+ }
37
+ var KEY_SHAPE = /^[A-Za-z0-9_-]{8,64}$/;
38
+ function anonymousKey(opts = {}) {
39
+ const tgId = tgWebApp()?.user?.id;
40
+ if (tgId) return `tg:${tgId}`;
41
+ const g = globalThis;
42
+ if (!g.document) return void 0;
43
+ const name = opts.name ?? "takeal_anon";
44
+ let stored;
45
+ try {
46
+ stored = g.localStorage?.getItem(name) ?? void 0;
47
+ } catch {
48
+ stored = void 0;
49
+ }
50
+ const fromCookie = readCookie(name);
51
+ let key = [fromCookie, stored].find((k) => !!k && KEY_SHAPE.test(k));
52
+ if (!key) {
53
+ key = g.crypto?.randomUUID?.() ?? `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 14)}`;
54
+ }
55
+ try {
56
+ g.localStorage?.setItem(name, key);
57
+ } catch {
58
+ }
59
+ const domain = opts.cookieDomain ? `; domain=${opts.cookieDomain}` : "";
60
+ g.document.cookie = `${name}=${encodeURIComponent(key)}; max-age=31536000; path=/; SameSite=Lax${domain}`;
61
+ return key;
62
+ }
63
+ function currentTouch() {
64
+ const g = globalThis;
65
+ const tg = tgWebApp();
66
+ const out = {};
67
+ if (g.location?.href) out.url = g.location.href;
68
+ if (g.document?.referrer) out.referrer = g.document.referrer;
69
+ if (tg?.start_param) out.campaign_code = tg.start_param;
70
+ if (tg?.user?.id) out.platform = "miniapp";
71
+ const ym = readCookie("_ym_uid");
72
+ if (ym) out.metrika_client_id = ym;
73
+ const ga = readCookie("_ga")?.split(".").slice(-2).join(".");
74
+ if (ga) out.ga_client_id = ga;
75
+ return out;
76
+ }
77
+
78
+ exports.AttributionResource = AttributionResource;
79
+ exports.anonymousKey = anonymousKey;
80
+ exports.currentTouch = currentTouch;
81
+ //# sourceMappingURL=attribution.cjs.map
82
+ //# sourceMappingURL=attribution.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/resources/attribution.ts"],"names":[],"mappings":";;;AAmFO,IAAM,sBAAN,MAA0B;AAAA,EAC/B,YAA6B,IAAA,EAAkB;AAAlB,IAAA,IAAA,CAAA,IAAA,GAAA,IAAA;AAAA,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,EAAA,CAAA,CAAE,QAAA,CAAS,SAAS,CAAA,EAAG,IAAI,IAAI,kBAAA,CAAmB,GAAG,CAAC,CAAA,wCAAA,EAA2C,MAAM,CAAA,CAAA;AACvG,EAAA,OAAO,GAAA;AACT;AAIO,SAAS,YAAA,GAA4B;AAC1C,EAAA,MAAM,CAAA,GAAI,UAAA;AACV,EAAA,MAAM,KAAK,QAAA,EAAS;AACpB,EAAA,MAAM,MAAmB,EAAC;AAC1B,EAAA,IAAI,EAAE,QAAA,EAAU,IAAA,EAAM,GAAA,CAAI,GAAA,GAAM,EAAE,QAAA,CAAS,IAAA;AAC3C,EAAA,IAAI,EAAE,QAAA,EAAU,QAAA,EAAU,GAAA,CAAI,QAAA,GAAW,EAAE,QAAA,CAAS,QAAA;AACpD,EAAA,IAAI,EAAA,EAAI,WAAA,EAAa,GAAA,CAAI,aAAA,GAAgB,EAAA,CAAG,WAAA;AAC5C,EAAA,IAAI,EAAA,EAAI,IAAA,EAAM,EAAA,EAAI,GAAA,CAAI,QAAA,GAAW,SAAA;AACjC,EAAA,MAAM,EAAA,GAAK,WAAW,SAAS,CAAA;AAC/B,EAAA,IAAI,EAAA,MAAQ,iBAAA,GAAoB,EAAA;AAEhC,EAAA,MAAM,EAAA,GAAK,UAAA,CAAW,KAAK,CAAA,EAAG,KAAA,CAAM,GAAG,CAAA,CAAE,KAAA,CAAM,EAAE,CAAA,CAAE,IAAA,CAAK,GAAG,CAAA;AAC3D,EAAA,IAAI,EAAA,MAAQ,YAAA,GAAe,EAAA;AAC3B,EAAA,OAAO,GAAA;AACT","file":"attribution.cjs","sourcesContent":["import type { HttpClient } from \"../http.js\";\n\n/**\n * Attribution resource — `client.attribution.*`: where users come from.\n *\n * Send a touch on page load ({@link AttributionResource.touch}); the\n * platform keeps the visits that bring something new (campaign tags, a\n * click id, a referrer from another site, a Telegram code, the first visit\n * from this browser) under the visitor's anonymous key. Pass the same key\n * to `auth.register({ attribution })` and the new account is credited with\n * those visits. After sign-up, ask \"how did you hear about us\" once\n * ({@link AttributionResource.status}, {@link AttributionResource.answerSurvey}).\n *\n * ```ts\n * const key = anonymousKey();\n * await client.attribution.touch({ anonymous_key: key, ...currentTouch() });\n * // …later, in the sign-up form:\n * await client.auth.register({ email, password, attribution: { anonymous_key: key } });\n * ```\n */\n\n/** A visit as the browser saw it. {@link currentTouch} fills it from the page. */\nexport interface TouchFields {\n /** Full address of the landing page, query included. Tags and click ids\n * are read from it; anything that looks like an e-mail address, a phone\n * number or a secret is dropped on the server. */\n url?: string;\n /** `document.referrer`; leave out or empty for none. */\n referrer?: string;\n /** The code of a Telegram link to the bot or the Mini App. */\n campaign_code?: string;\n /** `web`, `miniapp` or `app`. Taken from the client's platform when left out. */\n platform?: \"web\" | \"miniapp\" | \"app\";\n /** When the visit happened, ISO 8601, for a touch sent later. Defaults to now. */\n occurred_at?: string;\n /** Yandex Metrica client id (`_ym_uid` cookie). */\n metrika_client_id?: string;\n /** Google Analytics client id (from the `_ga` cookie). */\n ga_client_id?: string;\n}\n\nexport interface TouchInput extends TouchFields {\n /** The visitor's anonymous id, see {@link anonymousKey}. */\n anonymous_key: string;\n}\n\nexport interface TouchResult {\n /** `false` when the visit brought nothing new or the visitor already has fifty touches. */\n recorded: boolean;\n}\n\n/** Sent with `auth.register` and `auth.exchangeTelegram`. */\nexport interface SignupAttribution {\n /** The key the touches were sent with. Ignored in the Mini App, where the\n * Telegram id is the key. */\n anonymous_key?: string;\n /** The first touch this browser kept. Used only when none of its touches\n * reached the server (a blocker, a flaky network). */\n first_touch?: TouchFields;\n /** The last touch before sign-up, on the same terms. */\n last_touch?: TouchFields;\n metrika_client_id?: string;\n ga_client_id?: string;\n /** PostHog distinct id, so a report can open the session recording. */\n posthog_distinct_id?: string;\n}\n\nexport type SurveyAnswer =\n | \"friend\"\n | \"telegram_channel\"\n | \"search\"\n | \"ads\"\n | \"review\"\n | \"other\"\n | \"skipped\";\n\nexport interface AttributionStatus {\n /** `true` while the app should ask \"how did you hear about us\". */\n survey_pending: boolean;\n /** The answer given, `skipped`, or `null`. */\n survey_answer: SurveyAnswer | null;\n}\n\nexport class AttributionResource {\n constructor(private readonly http: HttpClient) {}\n\n /** Record a visit. No session needed; safe to call on every page load. */\n async touch(input: TouchInput): Promise<TouchResult> {\n return this.http.post<TouchResult>(\"/attribution/touches\", { body: input, skipAuth: true });\n }\n\n /** Whether to ask the signed-in user how they heard about us. */\n async status(): Promise<AttributionStatus> {\n return this.http.get<AttributionStatus>(\"/me/attribution\");\n }\n\n /** Answer the question once. Send `\"skipped\"` when the user closes it.\n * `otherText` is kept only with `\"other\"`, up to 500 characters.\n * Errors: 400 `validation`, 409 `survey_answered`. */\n async answerSurvey(answer: SurveyAnswer, otherText?: string): Promise<AttributionStatus> {\n const body: { answer: SurveyAnswer; other_text?: string } = { answer };\n if (otherText !== undefined) body.other_text = otherText;\n return this.http.put<AttributionStatus>(\"/me/attribution/survey\", { body });\n }\n}\n\n// ---------------------------------------------------------------------------\n// Browser helpers\n// ---------------------------------------------------------------------------\n\ninterface TelegramGlobal {\n Telegram?: { WebApp?: { initDataUnsafe?: { user?: { id?: number }; start_param?: string } } };\n}\n\nfunction tgWebApp() {\n return (globalThis as unknown as TelegramGlobal).Telegram?.WebApp?.initDataUnsafe;\n}\n\nfunction readCookie(name: string): string | undefined {\n const doc = (globalThis as { document?: Document }).document;\n if (!doc?.cookie) return undefined;\n for (const part of doc.cookie.split(\";\")) {\n const [k, ...v] = part.trim().split(\"=\");\n if (k === name) return decodeURIComponent(v.join(\"=\"));\n }\n return undefined;\n}\n\nexport interface AnonymousKeyOptions {\n /** Cookie and storage name. Default `takeal_anon`. */\n name?: string;\n /** Cookie domain, e.g. `.example.com` to share the key between the site and the app. */\n cookieDomain?: string;\n}\n\nconst KEY_SHAPE = /^[A-Za-z0-9_-]{8,64}$/;\n\n/**\n * The visitor's anonymous key. In the Telegram Mini App it is\n * `tg:<telegram id>`. In a browser it is a random id kept both in a cookie\n * and in `localStorage` for a year: if one of the two is lost it comes back\n * from the other, and the cookie's year is renewed on every call while its\n * value never changes. Returns `undefined` outside a browser.\n */\nexport function anonymousKey(opts: AnonymousKeyOptions = {}): string | undefined {\n const tgId = tgWebApp()?.user?.id;\n if (tgId) return `tg:${tgId}`;\n const g = globalThis as { document?: Document; localStorage?: Storage; crypto?: Crypto };\n if (!g.document) return undefined;\n const name = opts.name ?? \"takeal_anon\";\n let stored: string | undefined;\n try {\n stored = g.localStorage?.getItem(name) ?? undefined;\n } catch {\n stored = undefined;\n }\n const fromCookie = readCookie(name);\n let key = [fromCookie, stored].find((k): k is string => !!k && KEY_SHAPE.test(k));\n if (!key) {\n key = g.crypto?.randomUUID?.() ?? `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 14)}`;\n }\n try {\n g.localStorage?.setItem(name, key);\n } catch {\n // Storage full or blocked: the cookie still holds it.\n }\n const domain = opts.cookieDomain ? `; domain=${opts.cookieDomain}` : \"\";\n g.document.cookie = `${name}=${encodeURIComponent(key)}; max-age=31536000; path=/; SameSite=Lax${domain}`;\n return key;\n}\n\n/** The current page as a touch: address, referrer, the Mini App's start\n * code and the analytics cookies. Empty outside a browser. */\nexport function currentTouch(): TouchFields {\n const g = globalThis as { location?: Location; document?: Document };\n const tg = tgWebApp();\n const out: TouchFields = {};\n if (g.location?.href) out.url = g.location.href;\n if (g.document?.referrer) out.referrer = g.document.referrer;\n if (tg?.start_param) out.campaign_code = tg.start_param;\n if (tg?.user?.id) out.platform = \"miniapp\";\n const ym = readCookie(\"_ym_uid\");\n if (ym) out.metrika_client_id = ym;\n // `_ga` is `GA1.1.<id>.<timestamp>`; the client id is the last two parts.\n const ga = readCookie(\"_ga\")?.split(\".\").slice(-2).join(\".\");\n if (ga) out.ga_client_id = ga;\n return out;\n}\n"]}
@@ -0,0 +1,100 @@
1
+ import { H as HttpClient } from '../http-DeANAoTs.cjs';
2
+
3
+ /**
4
+ * Attribution resource — `client.attribution.*`: where users come from.
5
+ *
6
+ * Send a touch on page load ({@link AttributionResource.touch}); the
7
+ * platform keeps the visits that bring something new (campaign tags, a
8
+ * click id, a referrer from another site, a Telegram code, the first visit
9
+ * from this browser) under the visitor's anonymous key. Pass the same key
10
+ * to `auth.register({ attribution })` and the new account is credited with
11
+ * those visits. After sign-up, ask "how did you hear about us" once
12
+ * ({@link AttributionResource.status}, {@link AttributionResource.answerSurvey}).
13
+ *
14
+ * ```ts
15
+ * const key = anonymousKey();
16
+ * await client.attribution.touch({ anonymous_key: key, ...currentTouch() });
17
+ * // …later, in the sign-up form:
18
+ * await client.auth.register({ email, password, attribution: { anonymous_key: key } });
19
+ * ```
20
+ */
21
+ /** A visit as the browser saw it. {@link currentTouch} fills it from the page. */
22
+ interface TouchFields {
23
+ /** Full address of the landing page, query included. Tags and click ids
24
+ * are read from it; anything that looks like an e-mail address, a phone
25
+ * number or a secret is dropped on the server. */
26
+ url?: string;
27
+ /** `document.referrer`; leave out or empty for none. */
28
+ referrer?: string;
29
+ /** The code of a Telegram link to the bot or the Mini App. */
30
+ campaign_code?: string;
31
+ /** `web`, `miniapp` or `app`. Taken from the client's platform when left out. */
32
+ platform?: "web" | "miniapp" | "app";
33
+ /** When the visit happened, ISO 8601, for a touch sent later. Defaults to now. */
34
+ occurred_at?: string;
35
+ /** Yandex Metrica client id (`_ym_uid` cookie). */
36
+ metrika_client_id?: string;
37
+ /** Google Analytics client id (from the `_ga` cookie). */
38
+ ga_client_id?: string;
39
+ }
40
+ interface TouchInput extends TouchFields {
41
+ /** The visitor's anonymous id, see {@link anonymousKey}. */
42
+ anonymous_key: string;
43
+ }
44
+ interface TouchResult {
45
+ /** `false` when the visit brought nothing new or the visitor already has fifty touches. */
46
+ recorded: boolean;
47
+ }
48
+ /** Sent with `auth.register` and `auth.exchangeTelegram`. */
49
+ interface SignupAttribution {
50
+ /** The key the touches were sent with. Ignored in the Mini App, where the
51
+ * Telegram id is the key. */
52
+ anonymous_key?: string;
53
+ /** The first touch this browser kept. Used only when none of its touches
54
+ * reached the server (a blocker, a flaky network). */
55
+ first_touch?: TouchFields;
56
+ /** The last touch before sign-up, on the same terms. */
57
+ last_touch?: TouchFields;
58
+ metrika_client_id?: string;
59
+ ga_client_id?: string;
60
+ /** PostHog distinct id, so a report can open the session recording. */
61
+ posthog_distinct_id?: string;
62
+ }
63
+ type SurveyAnswer = "friend" | "telegram_channel" | "search" | "ads" | "review" | "other" | "skipped";
64
+ interface AttributionStatus {
65
+ /** `true` while the app should ask "how did you hear about us". */
66
+ survey_pending: boolean;
67
+ /** The answer given, `skipped`, or `null`. */
68
+ survey_answer: SurveyAnswer | null;
69
+ }
70
+ declare class AttributionResource {
71
+ private readonly http;
72
+ constructor(http: HttpClient);
73
+ /** Record a visit. No session needed; safe to call on every page load. */
74
+ touch(input: TouchInput): Promise<TouchResult>;
75
+ /** Whether to ask the signed-in user how they heard about us. */
76
+ status(): Promise<AttributionStatus>;
77
+ /** Answer the question once. Send `"skipped"` when the user closes it.
78
+ * `otherText` is kept only with `"other"`, up to 500 characters.
79
+ * Errors: 400 `validation`, 409 `survey_answered`. */
80
+ answerSurvey(answer: SurveyAnswer, otherText?: string): Promise<AttributionStatus>;
81
+ }
82
+ interface AnonymousKeyOptions {
83
+ /** Cookie and storage name. Default `takeal_anon`. */
84
+ name?: string;
85
+ /** Cookie domain, e.g. `.example.com` to share the key between the site and the app. */
86
+ cookieDomain?: string;
87
+ }
88
+ /**
89
+ * The visitor's anonymous key. In the Telegram Mini App it is
90
+ * `tg:<telegram id>`. In a browser it is a random id kept both in a cookie
91
+ * and in `localStorage` for a year: if one of the two is lost it comes back
92
+ * from the other, and the cookie's year is renewed on every call while its
93
+ * value never changes. Returns `undefined` outside a browser.
94
+ */
95
+ declare function anonymousKey(opts?: AnonymousKeyOptions): string | undefined;
96
+ /** The current page as a touch: address, referrer, the Mini App's start
97
+ * code and the analytics cookies. Empty outside a browser. */
98
+ declare function currentTouch(): TouchFields;
99
+
100
+ export { type AnonymousKeyOptions, AttributionResource, type AttributionStatus, type SignupAttribution, type SurveyAnswer, type TouchFields, type TouchInput, type TouchResult, anonymousKey, currentTouch };
@@ -0,0 +1,100 @@
1
+ import { H as HttpClient } from '../http-DeANAoTs.js';
2
+
3
+ /**
4
+ * Attribution resource — `client.attribution.*`: where users come from.
5
+ *
6
+ * Send a touch on page load ({@link AttributionResource.touch}); the
7
+ * platform keeps the visits that bring something new (campaign tags, a
8
+ * click id, a referrer from another site, a Telegram code, the first visit
9
+ * from this browser) under the visitor's anonymous key. Pass the same key
10
+ * to `auth.register({ attribution })` and the new account is credited with
11
+ * those visits. After sign-up, ask "how did you hear about us" once
12
+ * ({@link AttributionResource.status}, {@link AttributionResource.answerSurvey}).
13
+ *
14
+ * ```ts
15
+ * const key = anonymousKey();
16
+ * await client.attribution.touch({ anonymous_key: key, ...currentTouch() });
17
+ * // …later, in the sign-up form:
18
+ * await client.auth.register({ email, password, attribution: { anonymous_key: key } });
19
+ * ```
20
+ */
21
+ /** A visit as the browser saw it. {@link currentTouch} fills it from the page. */
22
+ interface TouchFields {
23
+ /** Full address of the landing page, query included. Tags and click ids
24
+ * are read from it; anything that looks like an e-mail address, a phone
25
+ * number or a secret is dropped on the server. */
26
+ url?: string;
27
+ /** `document.referrer`; leave out or empty for none. */
28
+ referrer?: string;
29
+ /** The code of a Telegram link to the bot or the Mini App. */
30
+ campaign_code?: string;
31
+ /** `web`, `miniapp` or `app`. Taken from the client's platform when left out. */
32
+ platform?: "web" | "miniapp" | "app";
33
+ /** When the visit happened, ISO 8601, for a touch sent later. Defaults to now. */
34
+ occurred_at?: string;
35
+ /** Yandex Metrica client id (`_ym_uid` cookie). */
36
+ metrika_client_id?: string;
37
+ /** Google Analytics client id (from the `_ga` cookie). */
38
+ ga_client_id?: string;
39
+ }
40
+ interface TouchInput extends TouchFields {
41
+ /** The visitor's anonymous id, see {@link anonymousKey}. */
42
+ anonymous_key: string;
43
+ }
44
+ interface TouchResult {
45
+ /** `false` when the visit brought nothing new or the visitor already has fifty touches. */
46
+ recorded: boolean;
47
+ }
48
+ /** Sent with `auth.register` and `auth.exchangeTelegram`. */
49
+ interface SignupAttribution {
50
+ /** The key the touches were sent with. Ignored in the Mini App, where the
51
+ * Telegram id is the key. */
52
+ anonymous_key?: string;
53
+ /** The first touch this browser kept. Used only when none of its touches
54
+ * reached the server (a blocker, a flaky network). */
55
+ first_touch?: TouchFields;
56
+ /** The last touch before sign-up, on the same terms. */
57
+ last_touch?: TouchFields;
58
+ metrika_client_id?: string;
59
+ ga_client_id?: string;
60
+ /** PostHog distinct id, so a report can open the session recording. */
61
+ posthog_distinct_id?: string;
62
+ }
63
+ type SurveyAnswer = "friend" | "telegram_channel" | "search" | "ads" | "review" | "other" | "skipped";
64
+ interface AttributionStatus {
65
+ /** `true` while the app should ask "how did you hear about us". */
66
+ survey_pending: boolean;
67
+ /** The answer given, `skipped`, or `null`. */
68
+ survey_answer: SurveyAnswer | null;
69
+ }
70
+ declare class AttributionResource {
71
+ private readonly http;
72
+ constructor(http: HttpClient);
73
+ /** Record a visit. No session needed; safe to call on every page load. */
74
+ touch(input: TouchInput): Promise<TouchResult>;
75
+ /** Whether to ask the signed-in user how they heard about us. */
76
+ status(): Promise<AttributionStatus>;
77
+ /** Answer the question once. Send `"skipped"` when the user closes it.
78
+ * `otherText` is kept only with `"other"`, up to 500 characters.
79
+ * Errors: 400 `validation`, 409 `survey_answered`. */
80
+ answerSurvey(answer: SurveyAnswer, otherText?: string): Promise<AttributionStatus>;
81
+ }
82
+ interface AnonymousKeyOptions {
83
+ /** Cookie and storage name. Default `takeal_anon`. */
84
+ name?: string;
85
+ /** Cookie domain, e.g. `.example.com` to share the key between the site and the app. */
86
+ cookieDomain?: string;
87
+ }
88
+ /**
89
+ * The visitor's anonymous key. In the Telegram Mini App it is
90
+ * `tg:<telegram id>`. In a browser it is a random id kept both in a cookie
91
+ * and in `localStorage` for a year: if one of the two is lost it comes back
92
+ * from the other, and the cookie's year is renewed on every call while its
93
+ * value never changes. Returns `undefined` outside a browser.
94
+ */
95
+ declare function anonymousKey(opts?: AnonymousKeyOptions): string | undefined;
96
+ /** The current page as a touch: address, referrer, the Mini App's start
97
+ * code and the analytics cookies. Empty outside a browser. */
98
+ declare function currentTouch(): TouchFields;
99
+
100
+ export { type AnonymousKeyOptions, AttributionResource, type AttributionStatus, type SignupAttribution, type SurveyAnswer, type TouchFields, type TouchInput, type TouchResult, anonymousKey, currentTouch };
@@ -0,0 +1,78 @@
1
+ // src/resources/attribution.ts
2
+ var AttributionResource = class {
3
+ constructor(http) {
4
+ this.http = http;
5
+ }
6
+ /** Record a visit. No session needed; safe to call on every page load. */
7
+ async touch(input) {
8
+ return this.http.post("/attribution/touches", { body: input, skipAuth: true });
9
+ }
10
+ /** Whether to ask the signed-in user how they heard about us. */
11
+ async status() {
12
+ return this.http.get("/me/attribution");
13
+ }
14
+ /** Answer the question once. Send `"skipped"` when the user closes it.
15
+ * `otherText` is kept only with `"other"`, up to 500 characters.
16
+ * Errors: 400 `validation`, 409 `survey_answered`. */
17
+ async answerSurvey(answer, otherText) {
18
+ const body = { answer };
19
+ if (otherText !== void 0) body.other_text = otherText;
20
+ return this.http.put("/me/attribution/survey", { body });
21
+ }
22
+ };
23
+ function tgWebApp() {
24
+ return globalThis.Telegram?.WebApp?.initDataUnsafe;
25
+ }
26
+ function readCookie(name) {
27
+ const doc = globalThis.document;
28
+ if (!doc?.cookie) return void 0;
29
+ for (const part of doc.cookie.split(";")) {
30
+ const [k, ...v] = part.trim().split("=");
31
+ if (k === name) return decodeURIComponent(v.join("="));
32
+ }
33
+ return void 0;
34
+ }
35
+ var KEY_SHAPE = /^[A-Za-z0-9_-]{8,64}$/;
36
+ function anonymousKey(opts = {}) {
37
+ const tgId = tgWebApp()?.user?.id;
38
+ if (tgId) return `tg:${tgId}`;
39
+ const g = globalThis;
40
+ if (!g.document) return void 0;
41
+ const name = opts.name ?? "takeal_anon";
42
+ let stored;
43
+ try {
44
+ stored = g.localStorage?.getItem(name) ?? void 0;
45
+ } catch {
46
+ stored = void 0;
47
+ }
48
+ const fromCookie = readCookie(name);
49
+ let key = [fromCookie, stored].find((k) => !!k && KEY_SHAPE.test(k));
50
+ if (!key) {
51
+ key = g.crypto?.randomUUID?.() ?? `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 14)}`;
52
+ }
53
+ try {
54
+ g.localStorage?.setItem(name, key);
55
+ } catch {
56
+ }
57
+ const domain = opts.cookieDomain ? `; domain=${opts.cookieDomain}` : "";
58
+ g.document.cookie = `${name}=${encodeURIComponent(key)}; max-age=31536000; path=/; SameSite=Lax${domain}`;
59
+ return key;
60
+ }
61
+ function currentTouch() {
62
+ const g = globalThis;
63
+ const tg = tgWebApp();
64
+ const out = {};
65
+ if (g.location?.href) out.url = g.location.href;
66
+ if (g.document?.referrer) out.referrer = g.document.referrer;
67
+ if (tg?.start_param) out.campaign_code = tg.start_param;
68
+ if (tg?.user?.id) out.platform = "miniapp";
69
+ const ym = readCookie("_ym_uid");
70
+ if (ym) out.metrika_client_id = ym;
71
+ const ga = readCookie("_ga")?.split(".").slice(-2).join(".");
72
+ if (ga) out.ga_client_id = ga;
73
+ return out;
74
+ }
75
+
76
+ export { AttributionResource, anonymousKey, currentTouch };
77
+ //# sourceMappingURL=attribution.js.map
78
+ //# sourceMappingURL=attribution.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/resources/attribution.ts"],"names":[],"mappings":";AAmFO,IAAM,sBAAN,MAA0B;AAAA,EAC/B,YAA6B,IAAA,EAAkB;AAAlB,IAAA,IAAA,CAAA,IAAA,GAAA,IAAA;AAAA,EAAmB;AAAA;AAAA,EAGhD,MAAM,MAAM,KAAA,EAAyC;AACnD,IAAA,OAAO,IAAA,CAAK,KAAK,IAAA,CAAkB,sBAAA,EAAwB,EAAE,IAAA,EAAM,KAAA,EAAO,QAAA,EAAU,IAAA,EAAM,CAAA;AAAA,EAC5F;AAAA;AAAA,EAGA,MAAM,MAAA,GAAqC;AACzC,IAAA,OAAO,IAAA,CAAK,IAAA,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A,MAAM,MAAmB,EAAC;AAC1B,EAAA,IAAI,EAAE,QAAA,EAAU,IAAA,EAAM,GAAA,CAAI,GAAA,GAAM,EAAE,QAAA,CAAS,IAAA;AAC3C,EAAA,IAAI,EAAE,QAAA,EAAU,QAAA,EAAU,GAAA,CAAI,QAAA,GAAW,EAAE,QAAA,CAAS,QAAA;AACpD,EAAA,IAAI,EAAA,EAAI,WAAA,EAAa,GAAA,CAAI,aAAA,GAAgB,EAAA,CAAG,WAAA;AAC5C,EAAA,IAAI,EAAA,EAAI,IAAA,EAAM,EAAA,EAAI,GAAA,CAAI,QAAA,GAAW,SAAA;AACjC,EAAA,MAAM,EAAA,GAAK,WAAW,SAAS,CAAA;AAC/B,EAAA,IAAI,EAAA,MAAQ,iBAAA,GAAoB,EAAA;AAEhC,EAAA,MAAM,EAAA,GAAK,UAAA,CAAW,KAAK,CAAA,EAAG,KAAA,CAAM,GAAG,CAAA,CAAE,KAAA,CAAM,EAAE,CAAA,CAAE,IAAA,CAAK,GAAG,CAAA;AAC3D,EAAA,IAAI,EAAA,MAAQ,YAAA,GAAe,EAAA;AAC3B,EAAA,OAAO,GAAA;AACT","file":"attribution.js","sourcesContent":["import type { HttpClient } from \"../http.js\";\n\n/**\n * Attribution resource — `client.attribution.*`: where users come from.\n *\n * Send a touch on page load ({@link AttributionResource.touch}); the\n * platform keeps the visits that bring something new (campaign tags, a\n * click id, a referrer from another site, a Telegram code, the first visit\n * from this browser) under the visitor's anonymous key. Pass the same key\n * to `auth.register({ attribution })` and the new account is credited with\n * those visits. After sign-up, ask \"how did you hear about us\" once\n * ({@link AttributionResource.status}, {@link AttributionResource.answerSurvey}).\n *\n * ```ts\n * const key = anonymousKey();\n * await client.attribution.touch({ anonymous_key: key, ...currentTouch() });\n * // …later, in the sign-up form:\n * await client.auth.register({ email, password, attribution: { anonymous_key: key } });\n * ```\n */\n\n/** A visit as the browser saw it. {@link currentTouch} fills it from the page. */\nexport interface TouchFields {\n /** Full address of the landing page, query included. Tags and click ids\n * are read from it; anything that looks like an e-mail address, a phone\n * number or a secret is dropped on the server. */\n url?: string;\n /** `document.referrer`; leave out or empty for none. */\n referrer?: string;\n /** The code of a Telegram link to the bot or the Mini App. */\n campaign_code?: string;\n /** `web`, `miniapp` or `app`. Taken from the client's platform when left out. */\n platform?: \"web\" | \"miniapp\" | \"app\";\n /** When the visit happened, ISO 8601, for a touch sent later. Defaults to now. */\n occurred_at?: string;\n /** Yandex Metrica client id (`_ym_uid` cookie). */\n metrika_client_id?: string;\n /** Google Analytics client id (from the `_ga` cookie). */\n ga_client_id?: string;\n}\n\nexport interface TouchInput extends TouchFields {\n /** The visitor's anonymous id, see {@link anonymousKey}. */\n anonymous_key: string;\n}\n\nexport interface TouchResult {\n /** `false` when the visit brought nothing new or the visitor already has fifty touches. */\n recorded: boolean;\n}\n\n/** Sent with `auth.register` and `auth.exchangeTelegram`. */\nexport interface SignupAttribution {\n /** The key the touches were sent with. Ignored in the Mini App, where the\n * Telegram id is the key. */\n anonymous_key?: string;\n /** The first touch this browser kept. Used only when none of its touches\n * reached the server (a blocker, a flaky network). */\n first_touch?: TouchFields;\n /** The last touch before sign-up, on the same terms. */\n last_touch?: TouchFields;\n metrika_client_id?: string;\n ga_client_id?: string;\n /** PostHog distinct id, so a report can open the session recording. */\n posthog_distinct_id?: string;\n}\n\nexport type SurveyAnswer =\n | \"friend\"\n | \"telegram_channel\"\n | \"search\"\n | \"ads\"\n | \"review\"\n | \"other\"\n | \"skipped\";\n\nexport interface AttributionStatus {\n /** `true` while the app should ask \"how did you hear about us\". */\n survey_pending: boolean;\n /** The answer given, `skipped`, or `null`. */\n survey_answer: SurveyAnswer | null;\n}\n\nexport class AttributionResource {\n constructor(private readonly http: HttpClient) {}\n\n /** Record a visit. No session needed; safe to call on every page load. */\n async touch(input: TouchInput): Promise<TouchResult> {\n return this.http.post<TouchResult>(\"/attribution/touches\", { body: input, skipAuth: true });\n }\n\n /** Whether to ask the signed-in user how they heard about us. */\n async status(): Promise<AttributionStatus> {\n return this.http.get<AttributionStatus>(\"/me/attribution\");\n }\n\n /** Answer the question once. Send `\"skipped\"` when the user closes it.\n * `otherText` is kept only with `\"other\"`, up to 500 characters.\n * Errors: 400 `validation`, 409 `survey_answered`. */\n async answerSurvey(answer: SurveyAnswer, otherText?: string): Promise<AttributionStatus> {\n const body: { answer: SurveyAnswer; other_text?: string } = { answer };\n if (otherText !== undefined) body.other_text = otherText;\n return this.http.put<AttributionStatus>(\"/me/attribution/survey\", { body });\n }\n}\n\n// ---------------------------------------------------------------------------\n// Browser helpers\n// ---------------------------------------------------------------------------\n\ninterface TelegramGlobal {\n Telegram?: { WebApp?: { initDataUnsafe?: { user?: { id?: number }; start_param?: string } } };\n}\n\nfunction tgWebApp() {\n return (globalThis as unknown as TelegramGlobal).Telegram?.WebApp?.initDataUnsafe;\n}\n\nfunction readCookie(name: string): string | undefined {\n const doc = (globalThis as { document?: Document }).document;\n if (!doc?.cookie) return undefined;\n for (const part of doc.cookie.split(\";\")) {\n const [k, ...v] = part.trim().split(\"=\");\n if (k === name) return decodeURIComponent(v.join(\"=\"));\n }\n return undefined;\n}\n\nexport interface AnonymousKeyOptions {\n /** Cookie and storage name. Default `takeal_anon`. */\n name?: string;\n /** Cookie domain, e.g. `.example.com` to share the key between the site and the app. */\n cookieDomain?: string;\n}\n\nconst KEY_SHAPE = /^[A-Za-z0-9_-]{8,64}$/;\n\n/**\n * The visitor's anonymous key. In the Telegram Mini App it is\n * `tg:<telegram id>`. In a browser it is a random id kept both in a cookie\n * and in `localStorage` for a year: if one of the two is lost it comes back\n * from the other, and the cookie's year is renewed on every call while its\n * value never changes. Returns `undefined` outside a browser.\n */\nexport function anonymousKey(opts: AnonymousKeyOptions = {}): string | undefined {\n const tgId = tgWebApp()?.user?.id;\n if (tgId) return `tg:${tgId}`;\n const g = globalThis as { document?: Document; localStorage?: Storage; crypto?: Crypto };\n if (!g.document) return undefined;\n const name = opts.name ?? \"takeal_anon\";\n let stored: string | undefined;\n try {\n stored = g.localStorage?.getItem(name) ?? undefined;\n } catch {\n stored = undefined;\n }\n const fromCookie = readCookie(name);\n let key = [fromCookie, stored].find((k): k is string => !!k && KEY_SHAPE.test(k));\n if (!key) {\n key = g.crypto?.randomUUID?.() ?? `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 14)}`;\n }\n try {\n g.localStorage?.setItem(name, key);\n } catch {\n // Storage full or blocked: the cookie still holds it.\n }\n const domain = opts.cookieDomain ? `; domain=${opts.cookieDomain}` : \"\";\n g.document.cookie = `${name}=${encodeURIComponent(key)}; max-age=31536000; path=/; SameSite=Lax${domain}`;\n return key;\n}\n\n/** The current page as a touch: address, referrer, the Mini App's start\n * code and the analytics cookies. Empty outside a browser. */\nexport function currentTouch(): TouchFields {\n const g = globalThis as { location?: Location; document?: Document };\n const tg = tgWebApp();\n const out: TouchFields = {};\n if (g.location?.href) out.url = g.location.href;\n if (g.document?.referrer) out.referrer = g.document.referrer;\n if (tg?.start_param) out.campaign_code = tg.start_param;\n if (tg?.user?.id) out.platform = \"miniapp\";\n const ym = readCookie(\"_ym_uid\");\n if (ym) out.metrika_client_id = ym;\n // `_ga` is `GA1.1.<id>.<timestamp>`; the client id is the last two parts.\n const ga = readCookie(\"_ga\")?.split(\".\").slice(-2).join(\".\");\n if (ga) out.ga_client_id = ga;\n return out;\n}\n"]}
@@ -6,20 +6,73 @@ function isApiError(e) {
6
6
  }
7
7
 
8
8
  // src/resources/auth.ts
9
+ function withRemember(input) {
10
+ const { remember, ...rest } = input;
11
+ return remember ? { ...rest, remember_me: true } : rest;
12
+ }
9
13
  var AuthResource = class {
10
- constructor(http, tokens) {
14
+ constructor(http, tokens, remembered) {
11
15
  this.http = http;
12
16
  this.tokens = tokens;
17
+ this.remembered = remembered;
18
+ if (remembered) http.setRefresher(() => this.renew().then((r) => r.kind !== "gone"));
19
+ }
20
+ /** Store what a finished sign-in returned. */
21
+ async keep(resp) {
22
+ await Promise.resolve(this.tokens.set(resp.access_token));
23
+ if (resp.remember_token && this.remembered) {
24
+ await Promise.resolve(this.remembered.set(resp.remember_token));
25
+ }
26
+ }
27
+ /** Renew a remembered sign-in: a new session and a new remember token,
28
+ * both stored. Resolves `null` (and forgets the remember token) when there
29
+ * is none or it no longer works; the app then shows the sign-in form.
30
+ * The SDK does this by itself on a 401; call it on app start to resume a
31
+ * session without a request failing first. */
32
+ async refresh() {
33
+ const r = await this.renew();
34
+ if (r.kind === "renewed") return r.resp;
35
+ if (r.kind === "taken_over") {
36
+ const access = await Promise.resolve(this.tokens.get());
37
+ const user = await this.me();
38
+ return { stage: "jwt", access_token: access ?? "", expires_at: "", user };
39
+ }
40
+ return null;
41
+ }
42
+ /** The renewal itself, for the 401 path: it must not call the API again
43
+ * through the client, or a second 401 would wait on this very renewal. */
44
+ async renew() {
45
+ const token = this.remembered ? await Promise.resolve(this.remembered.get()) : null;
46
+ if (!token) return { kind: "gone" };
47
+ try {
48
+ const resp = await this.http.post("/auth/refresh", {
49
+ body: { remember_token: token },
50
+ skipAuth: true
51
+ });
52
+ await this.keep(resp);
53
+ return { kind: "renewed", resp };
54
+ } catch (e) {
55
+ if (isApiError(e) && e.status === 401) {
56
+ const now = await Promise.resolve(this.remembered.get());
57
+ if (now && now !== token && await Promise.resolve(this.tokens.get())) {
58
+ return { kind: "taken_over" };
59
+ }
60
+ await Promise.resolve(this.remembered.clear());
61
+ await Promise.resolve(this.tokens.clear());
62
+ return { kind: "gone" };
63
+ }
64
+ throw e;
65
+ }
13
66
  }
14
67
  /** Password-auth entry. May resolve to a JWT, or to a step-up
15
68
  * challenge that needs `verifyTotp` / `verifyOtp` next. */
16
69
  async login(input) {
17
70
  const resp = await this.http.post("/auth/login", {
18
- body: input,
71
+ body: withRemember(input),
19
72
  skipAuth: true
20
73
  });
21
74
  if (resp.stage === "jwt") {
22
- await Promise.resolve(this.tokens.set(resp.access_token));
75
+ await this.keep(resp);
23
76
  }
24
77
  return resp;
25
78
  }
@@ -27,20 +80,20 @@ var AuthResource = class {
27
80
  * `totp_required` challenge. On success the JWT is stored. */
28
81
  async verifyTotp(input) {
29
82
  const resp = await this.http.post("/auth/login/totp", {
30
- body: input,
83
+ body: withRemember(input),
31
84
  skipAuth: true
32
85
  });
33
- await Promise.resolve(this.tokens.set(resp.access_token));
86
+ await this.keep(resp);
34
87
  return resp;
35
88
  }
36
89
  /** Verify a 6-digit OTP code (Telegram / email) against an
37
90
  * `otp_sent` challenge. */
38
91
  async verifyOtp(input) {
39
92
  const resp = await this.http.post("/auth/login/otp/verify", {
40
- body: input,
93
+ body: withRemember(input),
41
94
  skipAuth: true
42
95
  });
43
- await Promise.resolve(this.tokens.set(resp.access_token));
96
+ await this.keep(resp);
44
97
  return resp;
45
98
  }
46
99
  /** Create an end-user account and sign it in. The JWT is stored.
@@ -50,10 +103,10 @@ var AuthResource = class {
50
103
  * Errors: 400 `validation` / `currency_not_allowed`, 409 email taken. */
51
104
  async register(input) {
52
105
  const resp = await this.http.post("/auth/register", {
53
- body: input,
106
+ body: withRemember(input),
54
107
  skipAuth: true
55
108
  });
56
- await Promise.resolve(this.tokens.set(resp.access_token));
109
+ await this.keep(resp);
57
110
  return resp;
58
111
  }
59
112
  /** Finish a `totp_setup_required` login: send the first code from the
@@ -62,10 +115,10 @@ var AuthResource = class {
62
115
  * the user right away and don't keep them on the device. */
63
116
  async completeTotpSetup(input) {
64
117
  const resp = await this.http.post("/auth/login/totp-setup", {
65
- body: input,
118
+ body: withRemember(input),
66
119
  skipAuth: true
67
120
  });
68
- await Promise.resolve(this.tokens.set(resp.access_token));
121
+ await this.keep(resp);
69
122
  return resp;
70
123
  }
71
124
  /** Change the signed-in user's password. Every other session of the
@@ -86,8 +139,12 @@ var AuthResource = class {
86
139
  });
87
140
  }
88
141
  async exchangeTelegram(input) {
89
- const body = { init_data: input.initData };
142
+ const body = {
143
+ init_data: input.initData
144
+ };
90
145
  if (input.provision !== void 0) body.provision = input.provision;
146
+ if (input.attribution !== void 0) body.attribution = input.attribution;
147
+ if (input.code !== void 0) body.code = input.code;
91
148
  let resp;
92
149
  try {
93
150
  resp = await this.http.post("/auth/telegram/exchange", {
@@ -133,11 +190,20 @@ var AuthResource = class {
133
190
  async me() {
134
191
  return this.http.get("/auth/me");
135
192
  }
136
- /** Local sign-out: forgets the stored JWT. To end the session on the
137
- * server as well, revoke it first with `client.sessions.revoke(jti)`
138
- * (the current one is marked `current: true` in `client.sessions.list()`). */
193
+ /** Sign out: ends this session and the remembered sign-in on the
194
+ * server (best effort: a network failure still signs out locally), then
195
+ * forgets both tokens. */
139
196
  async signOut() {
197
+ const remember = this.remembered ? await Promise.resolve(this.remembered.get()) : null;
198
+ try {
199
+ await this.http.post("/auth/logout", {
200
+ body: remember ? { remember_token: remember } : {},
201
+ retried: true
202
+ });
203
+ } catch {
204
+ }
140
205
  await Promise.resolve(this.tokens.clear());
206
+ if (this.remembered) await Promise.resolve(this.remembered.clear());
141
207
  }
142
208
  };
143
209