@takeal/cusfront-sdk 0.5.0 → 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 (49) hide show
  1. package/CHANGELOG.md +10 -2
  2. package/README.md +2 -2
  3. package/dist/analytics.cjs +28 -7
  4. package/dist/analytics.cjs.map +1 -1
  5. package/dist/analytics.js +28 -7
  6. package/dist/analytics.js.map +1 -1
  7. package/dist/index.cjs +58 -43
  8. package/dist/index.cjs.map +1 -1
  9. package/dist/index.d.cts +2 -2
  10. package/dist/index.d.ts +2 -2
  11. package/dist/index.js +58 -43
  12. package/dist/index.js.map +1 -1
  13. package/dist/react/index.cjs +2 -8
  14. package/dist/react/index.cjs.map +1 -1
  15. package/dist/react/index.js +2 -8
  16. package/dist/react/index.js.map +1 -1
  17. package/dist/resources/attribution.cjs.map +1 -1
  18. package/dist/resources/attribution.js.map +1 -1
  19. package/dist/resources/auth.cjs.map +1 -1
  20. package/dist/resources/auth.js.map +1 -1
  21. package/dist/resources/cards.cjs +11 -22
  22. package/dist/resources/cards.cjs.map +1 -1
  23. package/dist/resources/cards.js +11 -22
  24. package/dist/resources/cards.js.map +1 -1
  25. package/dist/resources/deposits.cjs +4 -4
  26. package/dist/resources/deposits.cjs.map +1 -1
  27. package/dist/resources/deposits.js +4 -4
  28. package/dist/resources/deposits.js.map +1 -1
  29. package/dist/resources/devices.cjs +3 -1
  30. package/dist/resources/devices.cjs.map +1 -1
  31. package/dist/resources/devices.js +3 -1
  32. package/dist/resources/devices.js.map +1 -1
  33. package/dist/resources/documents.cjs +3 -1
  34. package/dist/resources/documents.cjs.map +1 -1
  35. package/dist/resources/documents.js +3 -1
  36. package/dist/resources/documents.js.map +1 -1
  37. package/dist/resources/history.cjs +3 -1
  38. package/dist/resources/history.cjs.map +1 -1
  39. package/dist/resources/history.js +3 -1
  40. package/dist/resources/history.js.map +1 -1
  41. package/dist/resources/push.cjs +3 -1
  42. package/dist/resources/push.cjs.map +1 -1
  43. package/dist/resources/push.js +3 -1
  44. package/dist/resources/push.js.map +1 -1
  45. package/dist/telegram.cjs +33 -46
  46. package/dist/telegram.cjs.map +1 -1
  47. package/dist/telegram.js +33 -46
  48. package/dist/telegram.js.map +1 -1
  49. package/package.json +12 -5
@@ -6,11 +6,7 @@ var react = require('react');
6
6
  var ClientContext = react.createContext(null);
7
7
  ClientContext.displayName = "CusfrontClientContext";
8
8
  function ClientProvider(props) {
9
- return react.createElement(
10
- ClientContext.Provider,
11
- { value: props.client },
12
- props.children
13
- );
9
+ return react.createElement(ClientContext.Provider, { value: props.client }, props.children);
14
10
  }
15
11
  function useClient() {
16
12
  const client = react.useContext(ClientContext);
@@ -70,9 +66,7 @@ function useCards() {
70
66
  }
71
67
  function useCardProducts() {
72
68
  const client = useClient();
73
- return publicState(
74
- useAsyncResource(() => client.cards.listProducts(), [client])
75
- );
69
+ return publicState(useAsyncResource(() => client.cards.listProducts(), [client]));
76
70
  }
77
71
  function useBalance(currency) {
78
72
  const client = useClient();
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/react/context.ts","../../src/react/hooks.ts"],"names":["createContext","createElement","useContext","useState","useCallback","useEffect","useRef"],"mappings":";;;;;AAiBA,IAAM,aAAA,GAAgBA,oBAAqC,IAAI,CAAA;AAC/D,aAAA,CAAc,WAAA,GAAc,uBAAA;AAyBrB,SAAS,eAAe,KAAA,EAA4B;AACzD,EAAA,OAAOC,mBAAA;AAAA,IACL,aAAA,CAAc,QAAA;AAAA,IACd,EAAE,KAAA,EAAO,KAAA,CAAM,MAAA,EAAO;AAAA,IACtB,KAAA,CAAM;AAAA,GACR;AACF;AAOO,SAAS,SAAA,GAA4B;AAC1C,EAAA,MAAM,MAAA,GAASC,iBAAW,aAAa,CAAA;AACvC,EAAA,IAAI,WAAW,IAAA,EAAM;AACnB,IAAA,MAAM,IAAI,KAAA;AAAA,MACR;AAAA,KAGF;AAAA,EACF;AACA,EAAA,OAAO,MAAA;AACT;ACCA,SAAS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,EAAQ,OAAO,CAAC,CAAA;AAE5B,EAAA,OAAO,YAAY,KAAK,CAAA;AAC1B;AASA,SAAS,sBAAA,GAA+C;AACtD,EAAA,MAAM,MAAO,UAAA,CAA2D,SAAA;AACxE,EAAA,MAAM,KAAK,GAAA,EAAK,aAAA;AAChB,EAAA,IAAI,CAAC,EAAA,IAAM,OAAO,EAAA,CAAG,gBAAA,KAAqB,YAAY,OAAO,IAAA;AAC7D,EAAA,OAAO,EAAA;AACT","file":"index.cjs","sourcesContent":["import { createContext, createElement, useContext, type ReactNode } from \"react\";\nimport type { CusfrontClient } from \"../index.js\";\n\n/**\n * React context carrying a single {@link CusfrontClient} instance.\n *\n * The client is created once by the consumer (via `createClient`) and\n * handed to {@link ClientProvider}; every hook in this entry point\n * reads it back through {@link useClient}. Keeping the client in\n * context (rather than module state) means multiple deployments /\n * brands can coexist in one tree, and the SDK ships no global\n * singleton.\n *\n * SSR-safe: nothing here touches `window` / `document`, and the\n * context default is `null` so a missing provider fails loudly\n * instead of silently using a stale client.\n */\nconst ClientContext = createContext<CusfrontClient | null>(null);\nClientContext.displayName = \"CusfrontClientContext\";\n\nexport interface ClientProviderProps {\n /** The client built by `createClient(...)`. Create it once (e.g. in\n * a module-level `const` or a `useMemo`) and pass it here — do not\n * rebuild it on every render. */\n client: CusfrontClient;\n children?: ReactNode;\n}\n\n/**\n * Provides a {@link CusfrontClient} to the subtree. Place it near the\n * root of your app:\n *\n * ```tsx\n * const client = createClient({ baseUrl: \"https://api.example.com\" });\n *\n * <ClientProvider client={client}>\n * <App />\n * </ClientProvider>\n * ```\n *\n * Authored with `createElement` rather than JSX so the SDK's build\n * needs no JSX transform configured.\n */\nexport function ClientProvider(props: ClientProviderProps) {\n return createElement(\n ClientContext.Provider,\n { value: props.client },\n props.children,\n );\n}\n\n/**\n * Read the {@link CusfrontClient} from context. Throws a clear error\n * when used outside a {@link ClientProvider} — surfacing the missing\n * wiring at the call site instead of a confusing null-deref later.\n */\nexport function useClient(): CusfrontClient {\n const client = useContext(ClientContext);\n if (client === null) {\n throw new Error(\n \"@takeal/cusfront-sdk/react: useClient() (or a data hook) was called \" +\n \"outside of a <ClientProvider>. Wrap your app in \" +\n \"<ClientProvider client={createClient(...)}>.\",\n );\n }\n return client;\n}\n","import { useCallback, useEffect, useRef, useState } from \"react\";\nimport { useClient } from \"./context.js\";\nimport type { User } from \"../resources/auth.js\";\nimport type { Deposit } from \"../resources/deposits.js\";\nimport type { Card, CardProduct } from \"../resources/cards.js\";\nimport type { Balance } from \"../resources/balance.js\";\nimport type {\n InboxItem,\n NotificationCategory,\n NotificationPage,\n} from \"../resources/notifications.js\";\n\n/**\n * Data-fetching hooks for the React entry point.\n *\n * Each hook wraps one resource call and exposes the same small,\n * predictable shape:\n *\n * ```ts\n * const { data, error, loading, refetch } = useDeposits();\n * ```\n *\n * Design notes:\n * - Pure React (`useState` + `useEffect` + `useCallback`); no external\n * data-fetching library, so the React entry stays tiny and the\n * consumer keeps full control of caching.\n * - The effect is cancellation-guarded: if the component unmounts (or\n * the inputs change) before the request settles, the stale result is\n * dropped instead of writing to an unmounted component.\n * - SSR-safe: the fetch only runs inside `useEffect`, which never\n * executes during server render.\n * - `error` holds whatever the resource threw — typically the SDK's\n * `ApiError` / `NetworkError` (branch with `isApiError` /\n * `isNetworkError`).\n */\n\n/** Common return shape for every data hook. */\nexport interface AsyncState<T> {\n /** The resolved value, or `null` before the first success / on error. */\n data: T | null;\n /** The thrown error, or `null` while loading / on success. */\n error: unknown;\n /** True from mount (and from each `refetch`) until the call settles. */\n loading: boolean;\n /** Re-run the underlying resource call. Returns a promise that\n * resolves once the refetch settles (useful for pull-to-refresh). */\n refetch: () => Promise<void>;\n}\n\n/**\n * Internal engine shared by every public hook.\n *\n * `fetcher` is invoked on mount and whenever the caller's `deps`\n * change. It is handed an `AbortSignal` so resource calls that accept\n * one can cancel in-flight work; results are additionally gated behind\n * a `cancelled` flag so a late resolve never lands after teardown.\n *\n * The caller passes a stable `fetcher` (memoise it with `useCallback`)\n * — `useAsyncResource` does not re-subscribe on identity changes alone,\n * only on the explicit `deps` array, mirroring `useEffect` semantics.\n */\ninterface AsyncStateWithSetter<T> extends AsyncState<T> {\n /** Replace `data` without a round-trip (optimistic updates, silent\n * refreshes). Internal: never exposed on a public hook. */\n setData: (update: T | null | ((prev: T | null) => T | null)) => void;\n}\n\nfunction useAsyncResource<T>(\n fetcher: (signal: AbortSignal) => Promise<T>,\n deps: ReadonlyArray<unknown>,\n): AsyncStateWithSetter<T> {\n const [data, setData] = useState<T | null>(null);\n const [error, setError] = useState<unknown>(null);\n const [loading, setLoading] = useState<boolean>(true);\n // Bumping this re-runs the effect on demand, reusing the exact same\n // cancellation machinery a dependency change would.\n const [nonce, setNonce] = useState(0);\n\n const refetch = useCallback(async () => {\n setNonce((n) => n + 1);\n }, []);\n\n useEffect(() => {\n let cancelled = false;\n const controller = new AbortController();\n\n setLoading(true);\n setError(null);\n\n fetcher(controller.signal)\n .then((result) => {\n if (cancelled) return;\n setData(result);\n })\n .catch((e: unknown) => {\n if (cancelled) return;\n // Ignore the abort we triggered ourselves on teardown.\n if (controller.signal.aborted) return;\n setError(e);\n })\n .finally(() => {\n if (cancelled) return;\n setLoading(false);\n });\n\n return () => {\n cancelled = true;\n controller.abort();\n };\n // `fetcher` is intentionally omitted from the dep list: callers\n // memoise it, and re-runs are driven by `deps` + `nonce` so that an\n // unstable inline fetcher can't cause an effect loop.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [...deps, nonce]);\n\n return { data, error, loading, refetch, setData };\n}\n\n/** Strip the internal setter so public hooks return exactly {@link AsyncState}. */\nfunction publicState<T>(state: AsyncStateWithSetter<T>): AsyncState<T> {\n const { data, error, loading, refetch } = state;\n return { data, error, loading, refetch };\n}\n\n/** Current authenticated user (`client.auth.me()`). 401 surfaces as\n * the thrown `ApiError` in `error` — treat it as \"no session\". */\nexport function useMe(): AsyncState<User> {\n const client = useClient();\n return publicState(useAsyncResource<User>(() => client.auth.me(), [client]));\n}\n\n/** The caller's deposits, most recent first (`client.deposits.list()`). */\nexport function useDeposits(): AsyncState<Deposit[]> {\n const client = useClient();\n return publicState(useAsyncResource<Deposit[]>(() => client.deposits.list(), [client]));\n}\n\n/** The caller's cards, most recent first (`client.cards.list()`). */\nexport function useCards(): AsyncState<Card[]> {\n const client = useClient();\n return publicState(useAsyncResource<Card[]>(() => client.cards.list(), [client]));\n}\n\n/**\n * The cards the user can order, default product first\n * (`client.cards.listProducts()`). Render each item's artwork through\n * `client.assetUrl(product.design.image_url)`.\n */\nexport function useCardProducts(): AsyncState<CardProduct[]> {\n const client = useClient();\n return publicState(\n useAsyncResource<CardProduct[]>(() => client.cards.listProducts(), [client]),\n );\n}\n\n/**\n * The user's wallet balance for one currency\n * (`client.balance.get(currency)`). Re-fetches when `currency`\n * changes.\n */\nexport function useBalance(currency: string): AsyncState<Balance> {\n const client = useClient();\n return publicState(\n useAsyncResource<Balance>(() => client.balance.get(currency), [client, currency]),\n );\n}\n\nexport interface UseNotificationsOptions {\n /** Only unread items. */\n unreadOnly?: boolean;\n category?: NotificationCategory;\n /** Page size. */\n limit?: number;\n}\n\nexport interface NotificationsState extends AsyncState<NotificationPage> {\n /** Mark one item read on the server and in `data` right away. */\n markRead: (id: string) => Promise<InboxItem>;\n /** Mark everything read on the server and in `data` right away. */\n markAllRead: () => Promise<{ marked: number }>;\n /** Fetch the next page (`data.next_cursor`) and append its items.\n * Resolves at once when there is no next page or a load is running. */\n loadMore: () => Promise<void>;\n /** True while `loadMore` is in flight. */\n loadingMore: boolean;\n}\n\n/**\n * The user's inbox (`client.notifications.list(opts)`), newest first, with\n * paging and read-state helpers. `data.items` grows as `loadMore` is\n * called; `refetch` starts over from the first page.\n *\n * ```tsx\n * const inbox = useNotifications({ limit: 20 });\n * inbox.data?.items.map((n) => (\n * <Row key={n.id} onClick={() => inbox.markRead(n.id)} unread={!n.read_at}>\n * {n.title}\n * </Row>\n * ));\n * ```\n */\nexport function useNotifications(opts: UseNotificationsOptions = {}): NotificationsState {\n const client = useClient();\n const { unreadOnly, category, limit } = opts;\n const state = useAsyncResource<NotificationPage>(\n () =>\n client.notifications.list({\n ...(unreadOnly !== undefined ? { unreadOnly } : {}),\n ...(category !== undefined ? { category } : {}),\n ...(limit !== undefined ? { limit } : {}),\n }),\n [client, unreadOnly, category, limit],\n );\n const { setData } = state;\n const [loadingMore, setLoadingMore] = useState(false);\n // The cursor lives in a ref too, so `loadMore` doesn't change identity\n // (and re-trigger consumer effects) on every page.\n const cursorRef = useRef<string | null>(null);\n cursorRef.current = state.data?.next_cursor ?? null;\n const mounted = useRef(true);\n useEffect(() => {\n mounted.current = true;\n return () => {\n mounted.current = false;\n };\n }, []);\n\n const markRead = useCallback(\n async (id: string) => {\n const item = await client.notifications.markRead(id);\n if (mounted.current) {\n setData((prev) => {\n if (!prev) return prev;\n const wasUnread = prev.items.some((n) => n.id === id && n.read_at === null);\n return {\n ...prev,\n items: prev.items.map((n) => (n.id === id ? item : n)),\n unread_count: Math.max(0, prev.unread_count - (wasUnread ? 1 : 0)),\n };\n });\n }\n return item;\n },\n [client, setData],\n );\n\n const markAllRead = useCallback(async () => {\n const out = await client.notifications.markAllRead();\n if (mounted.current) {\n const now = new Date().toISOString();\n setData((prev) =>\n prev\n ? {\n ...prev,\n items: prev.items.map((n) => (n.read_at === null ? { ...n, read_at: now } : n)),\n unread_count: 0,\n }\n : prev,\n );\n }\n return out;\n }, [client, setData]);\n\n const loadMore = useCallback(async () => {\n const cursor = cursorRef.current;\n if (!cursor || loadingMore) return;\n setLoadingMore(true);\n try {\n const page = await client.notifications.list({\n cursor,\n ...(unreadOnly !== undefined ? { unreadOnly } : {}),\n ...(category !== undefined ? { category } : {}),\n ...(limit !== undefined ? { limit } : {}),\n });\n if (!mounted.current) return;\n setData((prev) =>\n prev\n ? {\n items: [...prev.items, ...page.items],\n next_cursor: page.next_cursor,\n unread_count: page.unread_count,\n }\n : page,\n );\n } finally {\n if (mounted.current) setLoadingMore(false);\n }\n }, [client, setData, unreadOnly, category, limit, loadingMore]);\n\n return { ...publicState(state), markRead, markAllRead, loadMore, loadingMore };\n}\n\nexport interface UseUnreadCountOptions {\n /** Re-fetch every this many milliseconds. Default 30000; `0` disables\n * polling. */\n pollMs?: number;\n}\n\n/** Message a service worker posts to open clients when a push arrives, so\n * badges refresh without waiting for the next poll. */\nexport const PUSH_MESSAGE_TYPE = \"takeal:push\";\n\n/**\n * Unread inbox items (`client.notifications.unreadCount()`) for a badge.\n * Refreshes silently (no `loading` flip) on an interval and whenever the\n * page's service worker posts `{ type: \"takeal:push\" }`, which your\n * `push` handler should do for every open client.\n */\nexport function useUnreadCount(opts: UseUnreadCountOptions = {}): AsyncState<number> {\n const client = useClient();\n const pollMs = opts.pollMs ?? 30_000;\n const state = useAsyncResource<number>(() => client.notifications.unreadCount(), [client]);\n const { setData } = state;\n\n useEffect(() => {\n let cancelled = false;\n const refresh = () => {\n client.notifications\n .unreadCount()\n .then((n) => {\n if (!cancelled) setData(n);\n })\n .catch(() => {\n // A failed background refresh keeps the last known value.\n });\n };\n\n const timer = pollMs > 0 ? setInterval(refresh, pollMs) : undefined;\n\n const sw = serviceWorkerContainer();\n const onMessage = (event: { data?: unknown }) => {\n const data = event.data as { type?: unknown } | null | undefined;\n if (data && data.type === PUSH_MESSAGE_TYPE) refresh();\n };\n sw?.addEventListener(\"message\", onMessage);\n\n return () => {\n cancelled = true;\n if (timer !== undefined) clearInterval(timer);\n sw?.removeEventListener(\"message\", onMessage);\n };\n }, [client, pollMs, setData]);\n\n return publicState(state);\n}\n\ninterface MessageTarget {\n addEventListener(type: \"message\", listener: (event: { data?: unknown }) => void): void;\n removeEventListener(type: \"message\", listener: (event: { data?: unknown }) => void): void;\n}\n\n/** `navigator.serviceWorker` when the runtime has one; null on the server\n * and in browsers without service workers. */\nfunction serviceWorkerContainer(): MessageTarget | null {\n const nav = (globalThis as { navigator?: { serviceWorker?: unknown } }).navigator;\n const sw = nav?.serviceWorker as MessageTarget | undefined;\n if (!sw || typeof sw.addEventListener !== \"function\") return null;\n return sw;\n}\n"]}
1
+ {"version":3,"sources":["../../src/react/context.ts","../../src/react/hooks.ts"],"names":["createContext","createElement","useContext","useState","useCallback","useEffect","useRef"],"mappings":";;;;;AAiBA,IAAM,aAAA,GAAgBA,oBAAqC,IAAI,CAAA;AAC/D,aAAA,CAAc,WAAA,GAAc,uBAAA;AAyBrB,SAAS,eAAe,KAAA,EAA4B;AACzD,EAAA,OAAOC,mBAAA,CAAc,cAAc,QAAA,EAAU,EAAE,OAAO,KAAA,CAAM,MAAA,EAAO,EAAG,KAAA,CAAM,QAAQ,CAAA;AACtF;AAOO,SAAS,SAAA,GAA4B;AAC1C,EAAA,MAAM,MAAA,GAASC,iBAAW,aAAa,CAAA;AACvC,EAAA,IAAI,WAAW,IAAA,EAAM;AACnB,IAAA,MAAM,IAAI,KAAA;AAAA,MACR;AAAA,KAGF;AAAA,EACF;AACA,EAAA,OAAO,MAAA;AACT;ACKA,SAAS,gBAAA,CACP,SACA,IAAA,EACyB;AACzB,EAAA,MAAM,CAAC,IAAA,EAAM,OAAO,CAAA,GAAIC,eAAmB,IAAI,CAAA;AAC/C,EAAA,MAAM,CAAC,KAAA,EAAO,QAAQ,CAAA,GAAIA,eAAkB,IAAI,CAAA;AAChD,EAAA,MAAM,CAAC,OAAA,EAAS,UAAU,CAAA,GAAIA,eAAkB,IAAI,CAAA;AAGpD,EAAA,MAAM,CAAC,KAAA,EAAO,QAAQ,CAAA,GAAIA,eAAS,CAAC,CAAA;AAEpC,EAAA,MAAM,OAAA,GAAUC,kBAAY,YAAY;AACtC,IAAA,QAAA,CAAS,CAAC,CAAA,KAAM,CAAA,GAAI,CAAC,CAAA;AAAA,EACvB,CAAA,EAAG,EAAE,CAAA;AAEL,EAAAC,eAAA,CAAU,MAAM;AACd,IAAA,IAAI,SAAA,GAAY,KAAA;AAChB,IAAA,MAAM,UAAA,GAAa,IAAI,eAAA,EAAgB;AAEvC,IAAA,UAAA,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QAAQ,MAAA,GAAS,CAAA,GAAI,WAAA,CAAY,OAAA,EAAS,MAAM,CAAA,GAAI,MAAA;AAE1D,IAAA,MAAM,KAAK,sBAAA,EAAuB;AAClC,IAAA,MAAM,SAAA,GAAY,CAAC,KAAA,KAA8B;AAC/C,MAAA,MAAM,OAAO,KAAA,CAAM,IAAA;AACnB,MAAA,IAAI,IAAA,IAAQ,IAAA,CAAK,IAAA,KAAS,iBAAA,EAAmB,OAAA,EAAQ;AAAA,IACvD,CAAA;AACA,IAAA,EAAA,EAAI,gBAAA,CAAiB,WAAW,SAAS,CAAA;AAEzC,IAAA,OAAO,MAAM;AACX,MAAA,SAAA,GAAY,IAAA;AACZ,MAAA,IAAI,KAAA,KAAU,MAAA,EAAW,aAAA,CAAc,KAAK,CAAA;AAC5C,MAAA,EAAA,EAAI,mBAAA,CAAoB,WAAW,SAAS,CAAA;AAAA,IAC9C,CAAA;AAAA,EACF,CAAA,EAAG,CAAC,MAAA,EAAQ,MAAA,EAAQ,OAAO,CAAC,CAAA;AAE5B,EAAA,OAAO,YAAY,KAAK,CAAA;AAC1B;AASA,SAAS,sBAAA,GAA+C;AACtD,EAAA,MAAM,MAAO,UAAA,CAA2D,SAAA;AACxE,EAAA,MAAM,KAAK,GAAA,EAAK,aAAA;AAChB,EAAA,IAAI,CAAC,EAAA,IAAM,OAAO,EAAA,CAAG,gBAAA,KAAqB,YAAY,OAAO,IAAA;AAC7D,EAAA,OAAO,EAAA;AACT","file":"index.cjs","sourcesContent":["import { createContext, createElement, useContext, type ReactNode } from \"react\";\nimport type { CusfrontClient } from \"../index.js\";\n\n/**\n * React context carrying a single {@link CusfrontClient} instance.\n *\n * The client is created once by the consumer (via `createClient`) and\n * handed to {@link ClientProvider}; every hook in this entry point\n * reads it back through {@link useClient}. Keeping the client in\n * context (rather than module state) means multiple deployments /\n * brands can coexist in one tree, and the SDK ships no global\n * singleton.\n *\n * SSR-safe: nothing here touches `window` / `document`, and the\n * context default is `null` so a missing provider fails loudly\n * instead of silently using a stale client.\n */\nconst ClientContext = createContext<CusfrontClient | null>(null);\nClientContext.displayName = \"CusfrontClientContext\";\n\nexport interface ClientProviderProps {\n /** The client built by `createClient(...)`. Create it once (e.g. in\n * a module-level `const` or a `useMemo`) and pass it here — do not\n * rebuild it on every render. */\n client: CusfrontClient;\n children?: ReactNode;\n}\n\n/**\n * Provides a {@link CusfrontClient} to the subtree. Place it near the\n * root of your app:\n *\n * ```tsx\n * const client = createClient({ baseUrl: \"https://api.example.com\" });\n *\n * <ClientProvider client={client}>\n * <App />\n * </ClientProvider>\n * ```\n *\n * Authored with `createElement` rather than JSX so the SDK's build\n * needs no JSX transform configured.\n */\nexport function ClientProvider(props: ClientProviderProps) {\n return createElement(ClientContext.Provider, { value: props.client }, props.children);\n}\n\n/**\n * Read the {@link CusfrontClient} from context. Throws a clear error\n * when used outside a {@link ClientProvider} — surfacing the missing\n * wiring at the call site instead of a confusing null-deref later.\n */\nexport function useClient(): CusfrontClient {\n const client = useContext(ClientContext);\n if (client === null) {\n throw new Error(\n \"@takeal/cusfront-sdk/react: useClient() (or a data hook) was called \" +\n \"outside of a <ClientProvider>. Wrap your app in \" +\n \"<ClientProvider client={createClient(...)}>.\",\n );\n }\n return client;\n}\n","import { useCallback, useEffect, useRef, useState } from \"react\";\nimport { useClient } from \"./context.js\";\nimport type { User } from \"../resources/auth.js\";\nimport type { Deposit } from \"../resources/deposits.js\";\nimport type { Card, CardProduct } from \"../resources/cards.js\";\nimport type { Balance } from \"../resources/balance.js\";\nimport type {\n InboxItem,\n NotificationCategory,\n NotificationPage,\n} from \"../resources/notifications.js\";\n\n/**\n * Data-fetching hooks for the React entry point.\n *\n * Each hook wraps one resource call and exposes the same small,\n * predictable shape:\n *\n * ```ts\n * const { data, error, loading, refetch } = useDeposits();\n * ```\n *\n * Design notes:\n * - Pure React (`useState` + `useEffect` + `useCallback`); no external\n * data-fetching library, so the React entry stays tiny and the\n * consumer keeps full control of caching.\n * - The effect is cancellation-guarded: if the component unmounts (or\n * the inputs change) before the request settles, the stale result is\n * dropped instead of writing to an unmounted component.\n * - SSR-safe: the fetch only runs inside `useEffect`, which never\n * executes during server render.\n * - `error` holds whatever the resource threw — typically the SDK's\n * `ApiError` / `NetworkError` (branch with `isApiError` /\n * `isNetworkError`).\n */\n\n/** Common return shape for every data hook. */\nexport interface AsyncState<T> {\n /** The resolved value, or `null` before the first success / on error. */\n data: T | null;\n /** The thrown error, or `null` while loading / on success. */\n error: unknown;\n /** True from mount (and from each `refetch`) until the call settles. */\n loading: boolean;\n /** Re-run the underlying resource call. Returns a promise that\n * resolves once the refetch settles (useful for pull-to-refresh). */\n refetch: () => Promise<void>;\n}\n\n/**\n * Internal engine shared by every public hook.\n *\n * `fetcher` is invoked on mount and whenever the caller's `deps`\n * change. It is handed an `AbortSignal` so resource calls that accept\n * one can cancel in-flight work; results are additionally gated behind\n * a `cancelled` flag so a late resolve never lands after teardown.\n *\n * The caller passes a stable `fetcher` (memoise it with `useCallback`)\n * — `useAsyncResource` does not re-subscribe on identity changes alone,\n * only on the explicit `deps` array, mirroring `useEffect` semantics.\n */\ninterface AsyncStateWithSetter<T> extends AsyncState<T> {\n /** Replace `data` without a round-trip (optimistic updates, silent\n * refreshes). Internal: never exposed on a public hook. */\n setData: (update: T | null | ((prev: T | null) => T | null)) => void;\n}\n\nfunction useAsyncResource<T>(\n fetcher: (signal: AbortSignal) => Promise<T>,\n deps: ReadonlyArray<unknown>,\n): AsyncStateWithSetter<T> {\n const [data, setData] = useState<T | null>(null);\n const [error, setError] = useState<unknown>(null);\n const [loading, setLoading] = useState<boolean>(true);\n // Bumping this re-runs the effect on demand, reusing the exact same\n // cancellation machinery a dependency change would.\n const [nonce, setNonce] = useState(0);\n\n const refetch = useCallback(async () => {\n setNonce((n) => n + 1);\n }, []);\n\n useEffect(() => {\n let cancelled = false;\n const controller = new AbortController();\n\n setLoading(true);\n setError(null);\n\n fetcher(controller.signal)\n .then((result) => {\n if (cancelled) return;\n setData(result);\n })\n .catch((e: unknown) => {\n if (cancelled) return;\n // Ignore the abort we triggered ourselves on teardown.\n if (controller.signal.aborted) return;\n setError(e);\n })\n .finally(() => {\n if (cancelled) return;\n setLoading(false);\n });\n\n return () => {\n cancelled = true;\n controller.abort();\n };\n // `fetcher` is intentionally omitted from the dep list: callers\n // memoise it, and re-runs are driven by `deps` + `nonce` so that an\n // unstable inline fetcher can't cause an effect loop.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [...deps, nonce]);\n\n return { data, error, loading, refetch, setData };\n}\n\n/** Strip the internal setter so public hooks return exactly {@link AsyncState}. */\nfunction publicState<T>(state: AsyncStateWithSetter<T>): AsyncState<T> {\n const { data, error, loading, refetch } = state;\n return { data, error, loading, refetch };\n}\n\n/** Current authenticated user (`client.auth.me()`). 401 surfaces as\n * the thrown `ApiError` in `error` — treat it as \"no session\". */\nexport function useMe(): AsyncState<User> {\n const client = useClient();\n return publicState(useAsyncResource<User>(() => client.auth.me(), [client]));\n}\n\n/** The caller's deposits, most recent first (`client.deposits.list()`). */\nexport function useDeposits(): AsyncState<Deposit[]> {\n const client = useClient();\n return publicState(useAsyncResource<Deposit[]>(() => client.deposits.list(), [client]));\n}\n\n/** The caller's cards, most recent first (`client.cards.list()`). */\nexport function useCards(): AsyncState<Card[]> {\n const client = useClient();\n return publicState(useAsyncResource<Card[]>(() => client.cards.list(), [client]));\n}\n\n/**\n * The cards the user can order, default product first\n * (`client.cards.listProducts()`). Render each item's artwork through\n * `client.assetUrl(product.design.image_url)`.\n */\nexport function useCardProducts(): AsyncState<CardProduct[]> {\n const client = useClient();\n return publicState(useAsyncResource<CardProduct[]>(() => client.cards.listProducts(), [client]));\n}\n\n/**\n * The user's wallet balance for one currency\n * (`client.balance.get(currency)`). Re-fetches when `currency`\n * changes.\n */\nexport function useBalance(currency: string): AsyncState<Balance> {\n const client = useClient();\n return publicState(\n useAsyncResource<Balance>(() => client.balance.get(currency), [client, currency]),\n );\n}\n\nexport interface UseNotificationsOptions {\n /** Only unread items. */\n unreadOnly?: boolean;\n category?: NotificationCategory;\n /** Page size. */\n limit?: number;\n}\n\nexport interface NotificationsState extends AsyncState<NotificationPage> {\n /** Mark one item read on the server and in `data` right away. */\n markRead: (id: string) => Promise<InboxItem>;\n /** Mark everything read on the server and in `data` right away. */\n markAllRead: () => Promise<{ marked: number }>;\n /** Fetch the next page (`data.next_cursor`) and append its items.\n * Resolves at once when there is no next page or a load is running. */\n loadMore: () => Promise<void>;\n /** True while `loadMore` is in flight. */\n loadingMore: boolean;\n}\n\n/**\n * The user's inbox (`client.notifications.list(opts)`), newest first, with\n * paging and read-state helpers. `data.items` grows as `loadMore` is\n * called; `refetch` starts over from the first page.\n *\n * ```tsx\n * const inbox = useNotifications({ limit: 20 });\n * inbox.data?.items.map((n) => (\n * <Row key={n.id} onClick={() => inbox.markRead(n.id)} unread={!n.read_at}>\n * {n.title}\n * </Row>\n * ));\n * ```\n */\nexport function useNotifications(opts: UseNotificationsOptions = {}): NotificationsState {\n const client = useClient();\n const { unreadOnly, category, limit } = opts;\n const state = useAsyncResource<NotificationPage>(\n () =>\n client.notifications.list({\n ...(unreadOnly !== undefined ? { unreadOnly } : {}),\n ...(category !== undefined ? { category } : {}),\n ...(limit !== undefined ? { limit } : {}),\n }),\n [client, unreadOnly, category, limit],\n );\n const { setData } = state;\n const [loadingMore, setLoadingMore] = useState(false);\n // The cursor lives in a ref too, so `loadMore` doesn't change identity\n // (and re-trigger consumer effects) on every page.\n const cursorRef = useRef<string | null>(null);\n cursorRef.current = state.data?.next_cursor ?? null;\n const mounted = useRef(true);\n useEffect(() => {\n mounted.current = true;\n return () => {\n mounted.current = false;\n };\n }, []);\n\n const markRead = useCallback(\n async (id: string) => {\n const item = await client.notifications.markRead(id);\n if (mounted.current) {\n setData((prev) => {\n if (!prev) return prev;\n const wasUnread = prev.items.some((n) => n.id === id && n.read_at === null);\n return {\n ...prev,\n items: prev.items.map((n) => (n.id === id ? item : n)),\n unread_count: Math.max(0, prev.unread_count - (wasUnread ? 1 : 0)),\n };\n });\n }\n return item;\n },\n [client, setData],\n );\n\n const markAllRead = useCallback(async () => {\n const out = await client.notifications.markAllRead();\n if (mounted.current) {\n const now = new Date().toISOString();\n setData((prev) =>\n prev\n ? {\n ...prev,\n items: prev.items.map((n) => (n.read_at === null ? { ...n, read_at: now } : n)),\n unread_count: 0,\n }\n : prev,\n );\n }\n return out;\n }, [client, setData]);\n\n const loadMore = useCallback(async () => {\n const cursor = cursorRef.current;\n if (!cursor || loadingMore) return;\n setLoadingMore(true);\n try {\n const page = await client.notifications.list({\n cursor,\n ...(unreadOnly !== undefined ? { unreadOnly } : {}),\n ...(category !== undefined ? { category } : {}),\n ...(limit !== undefined ? { limit } : {}),\n });\n if (!mounted.current) return;\n setData((prev) =>\n prev\n ? {\n items: [...prev.items, ...page.items],\n next_cursor: page.next_cursor,\n unread_count: page.unread_count,\n }\n : page,\n );\n } finally {\n if (mounted.current) setLoadingMore(false);\n }\n }, [client, setData, unreadOnly, category, limit, loadingMore]);\n\n return { ...publicState(state), markRead, markAllRead, loadMore, loadingMore };\n}\n\nexport interface UseUnreadCountOptions {\n /** Re-fetch every this many milliseconds. Default 30000; `0` disables\n * polling. */\n pollMs?: number;\n}\n\n/** Message a service worker posts to open clients when a push arrives, so\n * badges refresh without waiting for the next poll. */\nexport const PUSH_MESSAGE_TYPE = \"takeal:push\";\n\n/**\n * Unread inbox items (`client.notifications.unreadCount()`) for a badge.\n * Refreshes silently (no `loading` flip) on an interval and whenever the\n * page's service worker posts `{ type: \"takeal:push\" }`, which your\n * `push` handler should do for every open client.\n */\nexport function useUnreadCount(opts: UseUnreadCountOptions = {}): AsyncState<number> {\n const client = useClient();\n const pollMs = opts.pollMs ?? 30_000;\n const state = useAsyncResource<number>(() => client.notifications.unreadCount(), [client]);\n const { setData } = state;\n\n useEffect(() => {\n let cancelled = false;\n const refresh = () => {\n client.notifications\n .unreadCount()\n .then((n) => {\n if (!cancelled) setData(n);\n })\n .catch(() => {\n // A failed background refresh keeps the last known value.\n });\n };\n\n const timer = pollMs > 0 ? setInterval(refresh, pollMs) : undefined;\n\n const sw = serviceWorkerContainer();\n const onMessage = (event: { data?: unknown }) => {\n const data = event.data as { type?: unknown } | null | undefined;\n if (data && data.type === PUSH_MESSAGE_TYPE) refresh();\n };\n sw?.addEventListener(\"message\", onMessage);\n\n return () => {\n cancelled = true;\n if (timer !== undefined) clearInterval(timer);\n sw?.removeEventListener(\"message\", onMessage);\n };\n }, [client, pollMs, setData]);\n\n return publicState(state);\n}\n\ninterface MessageTarget {\n addEventListener(type: \"message\", listener: (event: { data?: unknown }) => void): void;\n removeEventListener(type: \"message\", listener: (event: { data?: unknown }) => void): void;\n}\n\n/** `navigator.serviceWorker` when the runtime has one; null on the server\n * and in browsers without service workers. */\nfunction serviceWorkerContainer(): MessageTarget | null {\n const nav = (globalThis as { navigator?: { serviceWorker?: unknown } }).navigator;\n const sw = nav?.serviceWorker as MessageTarget | undefined;\n if (!sw || typeof sw.addEventListener !== \"function\") return null;\n return sw;\n}\n"]}
@@ -4,11 +4,7 @@ import { createContext, createElement, useContext, useState, useRef, useEffect,
4
4
  var ClientContext = createContext(null);
5
5
  ClientContext.displayName = "CusfrontClientContext";
6
6
  function ClientProvider(props) {
7
- return createElement(
8
- ClientContext.Provider,
9
- { value: props.client },
10
- props.children
11
- );
7
+ return createElement(ClientContext.Provider, { value: props.client }, props.children);
12
8
  }
13
9
  function useClient() {
14
10
  const client = useContext(ClientContext);
@@ -68,9 +64,7 @@ function useCards() {
68
64
  }
69
65
  function useCardProducts() {
70
66
  const client = useClient();
71
- return publicState(
72
- useAsyncResource(() => client.cards.listProducts(), [client])
73
- );
67
+ return publicState(useAsyncResource(() => client.cards.listProducts(), [client]));
74
68
  }
75
69
  function useBalance(currency) {
76
70
  const client = useClient();
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/react/context.ts","../../src/react/hooks.ts"],"names":[],"mappings":";;;AAiBA,IAAM,aAAA,GAAgB,c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M,OAAO,KAAA,CAAM,IAAA;AACnB,MAAA,IAAI,IAAA,IAAQ,IAAA,CAAK,IAAA,KAAS,iBAAA,EAAmB,OAAA,EAAQ;AAAA,IACvD,CAAA;AACA,IAAA,EAAA,EAAI,gBAAA,CAAiB,WAAW,SAAS,CAAA;AAEzC,IAAA,OAAO,MAAM;AACX,MAAA,SAAA,GAAY,IAAA;AACZ,MAAA,IAAI,KAAA,KAAU,MAAA,EAAW,aAAA,CAAc,KAAK,CAAA;AAC5C,MAAA,EAAA,EAAI,mBAAA,CAAoB,WAAW,SAAS,CAAA;AAAA,IAC9C,CAAA;AAAA,EACF,CAAA,EAAG,CAAC,MAAA,EAAQ,MAAA,EAAQ,OAAO,CAAC,CAAA;AAE5B,EAAA,OAAO,YAAY,KAAK,CAAA;AAC1B;AASA,SAAS,sBAAA,GAA+C;AACtD,EAAA,MAAM,MAAO,UAAA,CAA2D,SAAA;AACxE,EAAA,MAAM,KAAK,GAAA,EAAK,aAAA;AAChB,EAAA,IAAI,CAAC,EAAA,IAAM,OAAO,EAAA,CAAG,gBAAA,KAAqB,YAAY,OAAO,IAAA;AAC7D,EAAA,OAAO,EAAA;AACT","file":"index.js","sourcesContent":["import { createContext, createElement, useContext, type ReactNode } from \"react\";\nimport type { CusfrontClient } from \"../index.js\";\n\n/**\n * React context carrying a single {@link CusfrontClient} instance.\n *\n * The client is created once by the consumer (via `createClient`) and\n * handed to {@link ClientProvider}; every hook in this entry point\n * reads it back through {@link useClient}. Keeping the client in\n * context (rather than module state) means multiple deployments /\n * brands can coexist in one tree, and the SDK ships no global\n * singleton.\n *\n * SSR-safe: nothing here touches `window` / `document`, and the\n * context default is `null` so a missing provider fails loudly\n * instead of silently using a stale client.\n */\nconst ClientContext = createContext<CusfrontClient | null>(null);\nClientContext.displayName = \"CusfrontClientContext\";\n\nexport interface ClientProviderProps {\n /** The client built by `createClient(...)`. Create it once (e.g. in\n * a module-level `const` or a `useMemo`) and pass it here — do not\n * rebuild it on every render. */\n client: CusfrontClient;\n children?: ReactNode;\n}\n\n/**\n * Provides a {@link CusfrontClient} to the subtree. Place it near the\n * root of your app:\n *\n * ```tsx\n * const client = createClient({ baseUrl: \"https://api.example.com\" });\n *\n * <ClientProvider client={client}>\n * <App />\n * </ClientProvider>\n * ```\n *\n * Authored with `createElement` rather than JSX so the SDK's build\n * needs no JSX transform configured.\n */\nexport function ClientProvider(props: ClientProviderProps) {\n return createElement(\n ClientContext.Provider,\n { value: props.client },\n props.children,\n );\n}\n\n/**\n * Read the {@link CusfrontClient} from context. Throws a clear error\n * when used outside a {@link ClientProvider} — surfacing the missing\n * wiring at the call site instead of a confusing null-deref later.\n */\nexport function useClient(): CusfrontClient {\n const client = useContext(ClientContext);\n if (client === null) {\n throw new Error(\n \"@takeal/cusfront-sdk/react: useClient() (or a data hook) was called \" +\n \"outside of a <ClientProvider>. Wrap your app in \" +\n \"<ClientProvider client={createClient(...)}>.\",\n );\n }\n return client;\n}\n","import { useCallback, useEffect, useRef, useState } from \"react\";\nimport { useClient } from \"./context.js\";\nimport type { User } from \"../resources/auth.js\";\nimport type { Deposit } from \"../resources/deposits.js\";\nimport type { Card, CardProduct } from \"../resources/cards.js\";\nimport type { Balance } from \"../resources/balance.js\";\nimport type {\n InboxItem,\n NotificationCategory,\n NotificationPage,\n} from \"../resources/notifications.js\";\n\n/**\n * Data-fetching hooks for the React entry point.\n *\n * Each hook wraps one resource call and exposes the same small,\n * predictable shape:\n *\n * ```ts\n * const { data, error, loading, refetch } = useDeposits();\n * ```\n *\n * Design notes:\n * - Pure React (`useState` + `useEffect` + `useCallback`); no external\n * data-fetching library, so the React entry stays tiny and the\n * consumer keeps full control of caching.\n * - The effect is cancellation-guarded: if the component unmounts (or\n * the inputs change) before the request settles, the stale result is\n * dropped instead of writing to an unmounted component.\n * - SSR-safe: the fetch only runs inside `useEffect`, which never\n * executes during server render.\n * - `error` holds whatever the resource threw — typically the SDK's\n * `ApiError` / `NetworkError` (branch with `isApiError` /\n * `isNetworkError`).\n */\n\n/** Common return shape for every data hook. */\nexport interface AsyncState<T> {\n /** The resolved value, or `null` before the first success / on error. */\n data: T | null;\n /** The thrown error, or `null` while loading / on success. */\n error: unknown;\n /** True from mount (and from each `refetch`) until the call settles. */\n loading: boolean;\n /** Re-run the underlying resource call. Returns a promise that\n * resolves once the refetch settles (useful for pull-to-refresh). */\n refetch: () => Promise<void>;\n}\n\n/**\n * Internal engine shared by every public hook.\n *\n * `fetcher` is invoked on mount and whenever the caller's `deps`\n * change. It is handed an `AbortSignal` so resource calls that accept\n * one can cancel in-flight work; results are additionally gated behind\n * a `cancelled` flag so a late resolve never lands after teardown.\n *\n * The caller passes a stable `fetcher` (memoise it with `useCallback`)\n * — `useAsyncResource` does not re-subscribe on identity changes alone,\n * only on the explicit `deps` array, mirroring `useEffect` semantics.\n */\ninterface AsyncStateWithSetter<T> extends AsyncState<T> {\n /** Replace `data` without a round-trip (optimistic updates, silent\n * refreshes). Internal: never exposed on a public hook. */\n setData: (update: T | null | ((prev: T | null) => T | null)) => void;\n}\n\nfunction useAsyncResource<T>(\n fetcher: (signal: AbortSignal) => Promise<T>,\n deps: ReadonlyArray<unknown>,\n): AsyncStateWithSetter<T> {\n const [data, setData] = useState<T | null>(null);\n const [error, setError] = useState<unknown>(null);\n const [loading, setLoading] = useState<boolean>(true);\n // Bumping this re-runs the effect on demand, reusing the exact same\n // cancellation machinery a dependency change would.\n const [nonce, setNonce] = useState(0);\n\n const refetch = useCallback(async () => {\n setNonce((n) => n + 1);\n }, []);\n\n useEffect(() => {\n let cancelled = false;\n const controller = new AbortController();\n\n setLoading(true);\n setError(null);\n\n fetcher(controller.signal)\n .then((result) => {\n if (cancelled) return;\n setData(result);\n })\n .catch((e: unknown) => {\n if (cancelled) return;\n // Ignore the abort we triggered ourselves on teardown.\n if (controller.signal.aborted) return;\n setError(e);\n })\n .finally(() => {\n if (cancelled) return;\n setLoading(false);\n });\n\n return () => {\n cancelled = true;\n controller.abort();\n };\n // `fetcher` is intentionally omitted from the dep list: callers\n // memoise it, and re-runs are driven by `deps` + `nonce` so that an\n // unstable inline fetcher can't cause an effect loop.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [...deps, nonce]);\n\n return { data, error, loading, refetch, setData };\n}\n\n/** Strip the internal setter so public hooks return exactly {@link AsyncState}. */\nfunction publicState<T>(state: AsyncStateWithSetter<T>): AsyncState<T> {\n const { data, error, loading, refetch } = state;\n return { data, error, loading, refetch };\n}\n\n/** Current authenticated user (`client.auth.me()`). 401 surfaces as\n * the thrown `ApiError` in `error` — treat it as \"no session\". */\nexport function useMe(): AsyncState<User> {\n const client = useClient();\n return publicState(useAsyncResource<User>(() => client.auth.me(), [client]));\n}\n\n/** The caller's deposits, most recent first (`client.deposits.list()`). */\nexport function useDeposits(): AsyncState<Deposit[]> {\n const client = useClient();\n return publicState(useAsyncResource<Deposit[]>(() => client.deposits.list(), [client]));\n}\n\n/** The caller's cards, most recent first (`client.cards.list()`). */\nexport function useCards(): AsyncState<Card[]> {\n const client = useClient();\n return publicState(useAsyncResource<Card[]>(() => client.cards.list(), [client]));\n}\n\n/**\n * The cards the user can order, default product first\n * (`client.cards.listProducts()`). Render each item's artwork through\n * `client.assetUrl(product.design.image_url)`.\n */\nexport function useCardProducts(): AsyncState<CardProduct[]> {\n const client = useClient();\n return publicState(\n useAsyncResource<CardProduct[]>(() => client.cards.listProducts(), [client]),\n );\n}\n\n/**\n * The user's wallet balance for one currency\n * (`client.balance.get(currency)`). Re-fetches when `currency`\n * changes.\n */\nexport function useBalance(currency: string): AsyncState<Balance> {\n const client = useClient();\n return publicState(\n useAsyncResource<Balance>(() => client.balance.get(currency), [client, currency]),\n );\n}\n\nexport interface UseNotificationsOptions {\n /** Only unread items. */\n unreadOnly?: boolean;\n category?: NotificationCategory;\n /** Page size. */\n limit?: number;\n}\n\nexport interface NotificationsState extends AsyncState<NotificationPage> {\n /** Mark one item read on the server and in `data` right away. */\n markRead: (id: string) => Promise<InboxItem>;\n /** Mark everything read on the server and in `data` right away. */\n markAllRead: () => Promise<{ marked: number }>;\n /** Fetch the next page (`data.next_cursor`) and append its items.\n * Resolves at once when there is no next page or a load is running. */\n loadMore: () => Promise<void>;\n /** True while `loadMore` is in flight. */\n loadingMore: boolean;\n}\n\n/**\n * The user's inbox (`client.notifications.list(opts)`), newest first, with\n * paging and read-state helpers. `data.items` grows as `loadMore` is\n * called; `refetch` starts over from the first page.\n *\n * ```tsx\n * const inbox = useNotifications({ limit: 20 });\n * inbox.data?.items.map((n) => (\n * <Row key={n.id} onClick={() => inbox.markRead(n.id)} unread={!n.read_at}>\n * {n.title}\n * </Row>\n * ));\n * ```\n */\nexport function useNotifications(opts: UseNotificationsOptions = {}): NotificationsState {\n const client = useClient();\n const { unreadOnly, category, limit } = opts;\n const state = useAsyncResource<NotificationPage>(\n () =>\n client.notifications.list({\n ...(unreadOnly !== undefined ? { unreadOnly } : {}),\n ...(category !== undefined ? { category } : {}),\n ...(limit !== undefined ? { limit } : {}),\n }),\n [client, unreadOnly, category, limit],\n );\n const { setData } = state;\n const [loadingMore, setLoadingMore] = useState(false);\n // The cursor lives in a ref too, so `loadMore` doesn't change identity\n // (and re-trigger consumer effects) on every page.\n const cursorRef = useRef<string | null>(null);\n cursorRef.current = state.data?.next_cursor ?? null;\n const mounted = useRef(true);\n useEffect(() => {\n mounted.current = true;\n return () => {\n mounted.current = false;\n };\n }, []);\n\n const markRead = useCallback(\n async (id: string) => {\n const item = await client.notifications.markRead(id);\n if (mounted.current) {\n setData((prev) => {\n if (!prev) return prev;\n const wasUnread = prev.items.some((n) => n.id === id && n.read_at === null);\n return {\n ...prev,\n items: prev.items.map((n) => (n.id === id ? item : n)),\n unread_count: Math.max(0, prev.unread_count - (wasUnread ? 1 : 0)),\n };\n });\n }\n return item;\n },\n [client, setData],\n );\n\n const markAllRead = useCallback(async () => {\n const out = await client.notifications.markAllRead();\n if (mounted.current) {\n const now = new Date().toISOString();\n setData((prev) =>\n prev\n ? {\n ...prev,\n items: prev.items.map((n) => (n.read_at === null ? { ...n, read_at: now } : n)),\n unread_count: 0,\n }\n : prev,\n );\n }\n return out;\n }, [client, setData]);\n\n const loadMore = useCallback(async () => {\n const cursor = cursorRef.current;\n if (!cursor || loadingMore) return;\n setLoadingMore(true);\n try {\n const page = await client.notifications.list({\n cursor,\n ...(unreadOnly !== undefined ? { unreadOnly } : {}),\n ...(category !== undefined ? { category } : {}),\n ...(limit !== undefined ? { limit } : {}),\n });\n if (!mounted.current) return;\n setData((prev) =>\n prev\n ? {\n items: [...prev.items, ...page.items],\n next_cursor: page.next_cursor,\n unread_count: page.unread_count,\n }\n : page,\n );\n } finally {\n if (mounted.current) setLoadingMore(false);\n }\n }, [client, setData, unreadOnly, category, limit, loadingMore]);\n\n return { ...publicState(state), markRead, markAllRead, loadMore, loadingMore };\n}\n\nexport interface UseUnreadCountOptions {\n /** Re-fetch every this many milliseconds. Default 30000; `0` disables\n * polling. */\n pollMs?: number;\n}\n\n/** Message a service worker posts to open clients when a push arrives, so\n * badges refresh without waiting for the next poll. */\nexport const PUSH_MESSAGE_TYPE = \"takeal:push\";\n\n/**\n * Unread inbox items (`client.notifications.unreadCount()`) for a badge.\n * Refreshes silently (no `loading` flip) on an interval and whenever the\n * page's service worker posts `{ type: \"takeal:push\" }`, which your\n * `push` handler should do for every open client.\n */\nexport function useUnreadCount(opts: UseUnreadCountOptions = {}): AsyncState<number> {\n const client = useClient();\n const pollMs = opts.pollMs ?? 30_000;\n const state = useAsyncResource<number>(() => client.notifications.unreadCount(), [client]);\n const { setData } = state;\n\n useEffect(() => {\n let cancelled = false;\n const refresh = () => {\n client.notifications\n .unreadCount()\n .then((n) => {\n if (!cancelled) setData(n);\n })\n .catch(() => {\n // A failed background refresh keeps the last known value.\n });\n };\n\n const timer = pollMs > 0 ? setInterval(refresh, pollMs) : undefined;\n\n const sw = serviceWorkerContainer();\n const onMessage = (event: { data?: unknown }) => {\n const data = event.data as { type?: unknown } | null | undefined;\n if (data && data.type === PUSH_MESSAGE_TYPE) refresh();\n };\n sw?.addEventListener(\"message\", onMessage);\n\n return () => {\n cancelled = true;\n if (timer !== undefined) clearInterval(timer);\n sw?.removeEventListener(\"message\", onMessage);\n };\n }, [client, pollMs, setData]);\n\n return publicState(state);\n}\n\ninterface MessageTarget {\n addEventListener(type: \"message\", listener: (event: { data?: unknown }) => void): void;\n removeEventListener(type: \"message\", listener: (event: { data?: unknown }) => void): void;\n}\n\n/** `navigator.serviceWorker` when the runtime has one; null on the server\n * and in browsers without service workers. */\nfunction serviceWorkerContainer(): MessageTarget | null {\n const nav = (globalThis as { navigator?: { serviceWorker?: unknown } }).navigator;\n const sw = nav?.serviceWorker as MessageTarget | undefined;\n if (!sw || typeof sw.addEventListener !== \"function\") return null;\n return sw;\n}\n"]}
1
+ {"version":3,"sources":["../../src/react/context.ts","../../src/react/hooks.ts"],"names":[],"mappings":";;;AAiBA,IAAM,aAAA,GAAgB,cAAqC,IAAI,CAAA;AAC/D,aAAA,CAAc,WAAA,GAAc,uBAAA;AAyBrB,SAAS,eAAe,KAAA,EAA4B;AACzD,EAAA,OAAO,aAAA,CAAc,cAAc,QAAA,EAAU,EAAE,OAAO,KAAA,CAAM,MAAA,EAAO,EAAG,KAAA,CAAM,QAAQ,CAAA;AACtF;AAOO,SAAS,SAAA,GAA4B;AAC1C,EAAA,MAAM,MAAA,GAAS,WAAW,aAAa,CAAA;AACvC,EAAA,IAAI,WAAW,IAAA,EAAM;AACnB,IAAA,MAAM,IAAI,KAAA;AAAA,MACR;AAAA,KAGF;AAAA,EACF;AACA,EAAA,OAAO,MAAA;AACT;ACKA,SAAS,gBAAA,CACP,SACA,IAAA,EACyB;AACzB,EAAA,MAAM,CAAC,IAAA,EAAM,OAAO,CAAA,GAAI,SAAmB,IAAI,CAAA;AAC/C,EAAA,MAAM,CAAC,KAAA,EAAO,QAAQ,CAAA,GAAI,SAAkB,IAAI,CAAA;AAChD,EAAA,MAAM,CAAC,OAAA,EAAS,UAAU,CAAA,GAAI,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O,IAAA;AAC7D,EAAA,OAAO,EAAA;AACT","file":"index.js","sourcesContent":["import { createContext, createElement, useContext, type ReactNode } from \"react\";\nimport type { CusfrontClient } from \"../index.js\";\n\n/**\n * React context carrying a single {@link CusfrontClient} instance.\n *\n * The client is created once by the consumer (via `createClient`) and\n * handed to {@link ClientProvider}; every hook in this entry point\n * reads it back through {@link useClient}. Keeping the client in\n * context (rather than module state) means multiple deployments /\n * brands can coexist in one tree, and the SDK ships no global\n * singleton.\n *\n * SSR-safe: nothing here touches `window` / `document`, and the\n * context default is `null` so a missing provider fails loudly\n * instead of silently using a stale client.\n */\nconst ClientContext = createContext<CusfrontClient | null>(null);\nClientContext.displayName = \"CusfrontClientContext\";\n\nexport interface ClientProviderProps {\n /** The client built by `createClient(...)`. Create it once (e.g. in\n * a module-level `const` or a `useMemo`) and pass it here — do not\n * rebuild it on every render. */\n client: CusfrontClient;\n children?: ReactNode;\n}\n\n/**\n * Provides a {@link CusfrontClient} to the subtree. Place it near the\n * root of your app:\n *\n * ```tsx\n * const client = createClient({ baseUrl: \"https://api.example.com\" });\n *\n * <ClientProvider client={client}>\n * <App />\n * </ClientProvider>\n * ```\n *\n * Authored with `createElement` rather than JSX so the SDK's build\n * needs no JSX transform configured.\n */\nexport function ClientProvider(props: ClientProviderProps) {\n return createElement(ClientContext.Provider, { value: props.client }, props.children);\n}\n\n/**\n * Read the {@link CusfrontClient} from context. Throws a clear error\n * when used outside a {@link ClientProvider} — surfacing the missing\n * wiring at the call site instead of a confusing null-deref later.\n */\nexport function useClient(): CusfrontClient {\n const client = useContext(ClientContext);\n if (client === null) {\n throw new Error(\n \"@takeal/cusfront-sdk/react: useClient() (or a data hook) was called \" +\n \"outside of a <ClientProvider>. Wrap your app in \" +\n \"<ClientProvider client={createClient(...)}>.\",\n );\n }\n return client;\n}\n","import { useCallback, useEffect, useRef, useState } from \"react\";\nimport { useClient } from \"./context.js\";\nimport type { User } from \"../resources/auth.js\";\nimport type { Deposit } from \"../resources/deposits.js\";\nimport type { Card, CardProduct } from \"../resources/cards.js\";\nimport type { Balance } from \"../resources/balance.js\";\nimport type {\n InboxItem,\n NotificationCategory,\n NotificationPage,\n} from \"../resources/notifications.js\";\n\n/**\n * Data-fetching hooks for the React entry point.\n *\n * Each hook wraps one resource call and exposes the same small,\n * predictable shape:\n *\n * ```ts\n * const { data, error, loading, refetch } = useDeposits();\n * ```\n *\n * Design notes:\n * - Pure React (`useState` + `useEffect` + `useCallback`); no external\n * data-fetching library, so the React entry stays tiny and the\n * consumer keeps full control of caching.\n * - The effect is cancellation-guarded: if the component unmounts (or\n * the inputs change) before the request settles, the stale result is\n * dropped instead of writing to an unmounted component.\n * - SSR-safe: the fetch only runs inside `useEffect`, which never\n * executes during server render.\n * - `error` holds whatever the resource threw — typically the SDK's\n * `ApiError` / `NetworkError` (branch with `isApiError` /\n * `isNetworkError`).\n */\n\n/** Common return shape for every data hook. */\nexport interface AsyncState<T> {\n /** The resolved value, or `null` before the first success / on error. */\n data: T | null;\n /** The thrown error, or `null` while loading / on success. */\n error: unknown;\n /** True from mount (and from each `refetch`) until the call settles. */\n loading: boolean;\n /** Re-run the underlying resource call. Returns a promise that\n * resolves once the refetch settles (useful for pull-to-refresh). */\n refetch: () => Promise<void>;\n}\n\n/**\n * Internal engine shared by every public hook.\n *\n * `fetcher` is invoked on mount and whenever the caller's `deps`\n * change. It is handed an `AbortSignal` so resource calls that accept\n * one can cancel in-flight work; results are additionally gated behind\n * a `cancelled` flag so a late resolve never lands after teardown.\n *\n * The caller passes a stable `fetcher` (memoise it with `useCallback`)\n * — `useAsyncResource` does not re-subscribe on identity changes alone,\n * only on the explicit `deps` array, mirroring `useEffect` semantics.\n */\ninterface AsyncStateWithSetter<T> extends AsyncState<T> {\n /** Replace `data` without a round-trip (optimistic updates, silent\n * refreshes). Internal: never exposed on a public hook. */\n setData: (update: T | null | ((prev: T | null) => T | null)) => void;\n}\n\nfunction useAsyncResource<T>(\n fetcher: (signal: AbortSignal) => Promise<T>,\n deps: ReadonlyArray<unknown>,\n): AsyncStateWithSetter<T> {\n const [data, setData] = useState<T | null>(null);\n const [error, setError] = useState<unknown>(null);\n const [loading, setLoading] = useState<boolean>(true);\n // Bumping this re-runs the effect on demand, reusing the exact same\n // cancellation machinery a dependency change would.\n const [nonce, setNonce] = useState(0);\n\n const refetch = useCallback(async () => {\n setNonce((n) => n + 1);\n }, []);\n\n useEffect(() => {\n let cancelled = false;\n const controller = new AbortController();\n\n setLoading(true);\n setError(null);\n\n fetcher(controller.signal)\n .then((result) => {\n if (cancelled) return;\n setData(result);\n })\n .catch((e: unknown) => {\n if (cancelled) return;\n // Ignore the abort we triggered ourselves on teardown.\n if (controller.signal.aborted) return;\n setError(e);\n })\n .finally(() => {\n if (cancelled) return;\n setLoading(false);\n });\n\n return () => {\n cancelled = true;\n controller.abort();\n };\n // `fetcher` is intentionally omitted from the dep list: callers\n // memoise it, and re-runs are driven by `deps` + `nonce` so that an\n // unstable inline fetcher can't cause an effect loop.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [...deps, nonce]);\n\n return { data, error, loading, refetch, setData };\n}\n\n/** Strip the internal setter so public hooks return exactly {@link AsyncState}. */\nfunction publicState<T>(state: AsyncStateWithSetter<T>): AsyncState<T> {\n const { data, error, loading, refetch } = state;\n return { data, error, loading, refetch };\n}\n\n/** Current authenticated user (`client.auth.me()`). 401 surfaces as\n * the thrown `ApiError` in `error` — treat it as \"no session\". */\nexport function useMe(): AsyncState<User> {\n const client = useClient();\n return publicState(useAsyncResource<User>(() => client.auth.me(), [client]));\n}\n\n/** The caller's deposits, most recent first (`client.deposits.list()`). */\nexport function useDeposits(): AsyncState<Deposit[]> {\n const client = useClient();\n return publicState(useAsyncResource<Deposit[]>(() => client.deposits.list(), [client]));\n}\n\n/** The caller's cards, most recent first (`client.cards.list()`). */\nexport function useCards(): AsyncState<Card[]> {\n const client = useClient();\n return publicState(useAsyncResource<Card[]>(() => client.cards.list(), [client]));\n}\n\n/**\n * The cards the user can order, default product first\n * (`client.cards.listProducts()`). Render each item's artwork through\n * `client.assetUrl(product.design.image_url)`.\n */\nexport function useCardProducts(): AsyncState<CardProduct[]> {\n const client = useClient();\n return publicState(useAsyncResource<CardProduct[]>(() => client.cards.listProducts(), [client]));\n}\n\n/**\n * The user's wallet balance for one currency\n * (`client.balance.get(currency)`). Re-fetches when `currency`\n * changes.\n */\nexport function useBalance(currency: string): AsyncState<Balance> {\n const client = useClient();\n return publicState(\n useAsyncResource<Balance>(() => client.balance.get(currency), [client, currency]),\n );\n}\n\nexport interface UseNotificationsOptions {\n /** Only unread items. */\n unreadOnly?: boolean;\n category?: NotificationCategory;\n /** Page size. */\n limit?: number;\n}\n\nexport interface NotificationsState extends AsyncState<NotificationPage> {\n /** Mark one item read on the server and in `data` right away. */\n markRead: (id: string) => Promise<InboxItem>;\n /** Mark everything read on the server and in `data` right away. */\n markAllRead: () => Promise<{ marked: number }>;\n /** Fetch the next page (`data.next_cursor`) and append its items.\n * Resolves at once when there is no next page or a load is running. */\n loadMore: () => Promise<void>;\n /** True while `loadMore` is in flight. */\n loadingMore: boolean;\n}\n\n/**\n * The user's inbox (`client.notifications.list(opts)`), newest first, with\n * paging and read-state helpers. `data.items` grows as `loadMore` is\n * called; `refetch` starts over from the first page.\n *\n * ```tsx\n * const inbox = useNotifications({ limit: 20 });\n * inbox.data?.items.map((n) => (\n * <Row key={n.id} onClick={() => inbox.markRead(n.id)} unread={!n.read_at}>\n * {n.title}\n * </Row>\n * ));\n * ```\n */\nexport function useNotifications(opts: UseNotificationsOptions = {}): NotificationsState {\n const client = useClient();\n const { unreadOnly, category, limit } = opts;\n const state = useAsyncResource<NotificationPage>(\n () =>\n client.notifications.list({\n ...(unreadOnly !== undefined ? { unreadOnly } : {}),\n ...(category !== undefined ? { category } : {}),\n ...(limit !== undefined ? { limit } : {}),\n }),\n [client, unreadOnly, category, limit],\n );\n const { setData } = state;\n const [loadingMore, setLoadingMore] = useState(false);\n // The cursor lives in a ref too, so `loadMore` doesn't change identity\n // (and re-trigger consumer effects) on every page.\n const cursorRef = useRef<string | null>(null);\n cursorRef.current = state.data?.next_cursor ?? null;\n const mounted = useRef(true);\n useEffect(() => {\n mounted.current = true;\n return () => {\n mounted.current = false;\n };\n }, []);\n\n const markRead = useCallback(\n async (id: string) => {\n const item = await client.notifications.markRead(id);\n if (mounted.current) {\n setData((prev) => {\n if (!prev) return prev;\n const wasUnread = prev.items.some((n) => n.id === id && n.read_at === null);\n return {\n ...prev,\n items: prev.items.map((n) => (n.id === id ? item : n)),\n unread_count: Math.max(0, prev.unread_count - (wasUnread ? 1 : 0)),\n };\n });\n }\n return item;\n },\n [client, setData],\n );\n\n const markAllRead = useCallback(async () => {\n const out = await client.notifications.markAllRead();\n if (mounted.current) {\n const now = new Date().toISOString();\n setData((prev) =>\n prev\n ? {\n ...prev,\n items: prev.items.map((n) => (n.read_at === null ? { ...n, read_at: now } : n)),\n unread_count: 0,\n }\n : prev,\n );\n }\n return out;\n }, [client, setData]);\n\n const loadMore = useCallback(async () => {\n const cursor = cursorRef.current;\n if (!cursor || loadingMore) return;\n setLoadingMore(true);\n try {\n const page = await client.notifications.list({\n cursor,\n ...(unreadOnly !== undefined ? { unreadOnly } : {}),\n ...(category !== undefined ? { category } : {}),\n ...(limit !== undefined ? { limit } : {}),\n });\n if (!mounted.current) return;\n setData((prev) =>\n prev\n ? {\n items: [...prev.items, ...page.items],\n next_cursor: page.next_cursor,\n unread_count: page.unread_count,\n }\n : page,\n );\n } finally {\n if (mounted.current) setLoadingMore(false);\n }\n }, [client, setData, unreadOnly, category, limit, loadingMore]);\n\n return { ...publicState(state), markRead, markAllRead, loadMore, loadingMore };\n}\n\nexport interface UseUnreadCountOptions {\n /** Re-fetch every this many milliseconds. Default 30000; `0` disables\n * polling. */\n pollMs?: number;\n}\n\n/** Message a service worker posts to open clients when a push arrives, so\n * badges refresh without waiting for the next poll. */\nexport const PUSH_MESSAGE_TYPE = \"takeal:push\";\n\n/**\n * Unread inbox items (`client.notifications.unreadCount()`) for a badge.\n * Refreshes silently (no `loading` flip) on an interval and whenever the\n * page's service worker posts `{ type: \"takeal:push\" }`, which your\n * `push` handler should do for every open client.\n */\nexport function useUnreadCount(opts: UseUnreadCountOptions = {}): AsyncState<number> {\n const client = useClient();\n const pollMs = opts.pollMs ?? 30_000;\n const state = useAsyncResource<number>(() => client.notifications.unreadCount(), [client]);\n const { setData } = state;\n\n useEffect(() => {\n let cancelled = false;\n const refresh = () => {\n client.notifications\n .unreadCount()\n .then((n) => {\n if (!cancelled) setData(n);\n })\n .catch(() => {\n // A failed background refresh keeps the last known value.\n });\n };\n\n const timer = pollMs > 0 ? setInterval(refresh, pollMs) : undefined;\n\n const sw = serviceWorkerContainer();\n const onMessage = (event: { data?: unknown }) => {\n const data = event.data as { type?: unknown } | null | undefined;\n if (data && data.type === PUSH_MESSAGE_TYPE) refresh();\n };\n sw?.addEventListener(\"message\", onMessage);\n\n return () => {\n cancelled = true;\n if (timer !== undefined) clearInterval(timer);\n sw?.removeEventListener(\"message\", onMessage);\n };\n }, [client, pollMs, setData]);\n\n return publicState(state);\n}\n\ninterface MessageTarget {\n addEventListener(type: \"message\", listener: (event: { data?: unknown }) => void): void;\n removeEventListener(type: \"message\", listener: (event: { data?: unknown }) => void): void;\n}\n\n/** `navigator.serviceWorker` when the runtime has one; null on the server\n * and in browsers without service workers. */\nfunction serviceWorkerContainer(): MessageTarget | null {\n const nav = (globalThis as { navigator?: { serviceWorker?: unknown } }).navigator;\n const sw = nav?.serviceWorker as MessageTarget | undefined;\n if (!sw || typeof sw.addEventListener !== \"function\") return null;\n return sw;\n}\n"]}
@@ -1 +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,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AAG,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"]}
1
+ {"version":3,"sources":["../../src/resources/attribution.ts"],"names":[],"mappings":";;;AA6EO,IAAM,sBAAN,MAA0B;AAAA,EAC/B,YAA6B,IAAA,EAAkB;AAAlB,IAAA,IAAA,CAAA,IAAA,GAAA,IAAA;AAAA,EAAmB;AAAA;A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AE,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\" | \"telegram_channel\" | \"search\" | \"ads\" | \"review\" | \"other\" | \"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 =\n g.crypto?.randomUUID?.() ??\n `${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"]}
@@ -1 +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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K,EAAA;AACrE,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.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"]}
1
+ {"version":3,"sources":["../../src/resources/attribution.ts"],"names":[],"mappings":";AA6EO,IAAM,sBAAN,MAA0B;AAAA,EAC/B,YAA6B,IAAA,EAAkB;AAAlB,IAA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K,YAAY,CAAA,CAAA,GAAK,EAAA;AACrE,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.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\" | \"telegram_channel\" | \"search\" | \"ads\" | \"review\" | \"other\" | \"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 =\n g.crypto?.randomUUID?.() ??\n `${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"]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/error.ts","../../src/resources/auth.ts"],"names":[],"mappings":";;;AAwCO,SAAS,WAAW,CAAA,EAA2B;AAC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AAA,EAAyC;AACvD,IAAA,OAAO,IAAA,CAAK,IAAA,CAAK,IAAA,CAAW,WAAA,EAAa,EAAE,IAAA,EAAM,EAAE,KAAA,EAAO,KAAA,CAAM,KAAA,EAAM,EAAG,CAAA;AAAA,EAC3E;AAAA;AAAA;AAAA,EAIA,MAAM,EAAA,GAAoB;AACxB,IAAA,OAAO,IAAA,CAAK,IAAA,CAAK,GAAA,CAAU,UAAU,CAAA;AAAA,EACvC;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,OAAA,GAAyB;AAC7B,IAAA,MAAM,QAAA,GAAW,IAAA,CAAK,UAAA,GAAa,MAAM,OAAA,CAAQ,QAAQ,IAAA,CAAK,UAAA,CAAW,GAAA,EAAK,CAAA,GAAI,IAAA;AAClF,IAAA,IAAI;AACF,MAAA,MAAM,IAAA,CAAK,IAAA,CAAK,IAAA,CAAW,cAAA,EAAgB;AAAA,QACzC,MAAM,QAAA,GAAW,EAAE,cAAA,EAAgB,QAAA,KAAa,EAAC;AAAA,QACjD,OAAA,EAAS;AAAA,OACV,CAAA;AAAA,IACH,CAAA,CAAA,MAAQ;AAAA,IAER;AACA,IAAA,MAAM,OAAA,CAAQ,OAAA,CAAQ,IAAA,CAAK,MAAA,CAAO,OAAO,CAAA;AACzC,IAAA,IAAI,IAAA,CAAK,YAAY,MAAM,OAAA,CAAQ,QAAQ,IAAA,CAAK,UAAA,CAAW,OAAO,CAAA;AAAA,EACpE;AACF","file":"auth.cjs","sourcesContent":["/**\n * Errors surfaced by the SDK. All HTTP failures map onto `ApiError`;\n * network-level / abort / serialisation failures get the generic\n * `NetworkError`. Consumers catch on the discriminator field\n * (`isApiError` / `isNetworkError`) rather than `instanceof` — works\n * across bundler boundaries where multiple copies of the class can\n * coexist.\n */\nexport class ApiError extends Error {\n readonly isApiError = true as const;\n\n constructor(\n /** HTTP status code returned by the Takeal API. */\n public readonly status: number,\n /** Stable machine-readable code (e.g. `\"insufficient_funds\"`,\n * `\"permission_required\"`, `\"validation\"`). Same enum the\n * TypeScript types pin via openapi-typescript. */\n public readonly code: string,\n /** Human-readable message. English; the consumer maps to its\n * own i18n layer before showing to end-users. */\n message: string,\n /** Full parsed response body when available. Carries field-level\n * validation details for `code = \"validation\"`. */\n public readonly body?: unknown,\n ) {\n super(message);\n this.name = \"ApiError\";\n }\n}\n\nexport class NetworkError extends Error {\n readonly isNetworkError = true as const;\n\n constructor(message: string, public readonly cause?: unknown) {\n super(message);\n this.name = \"NetworkError\";\n }\n}\n\n/** Type guard — preferred over `instanceof` (bundler-safe). */\nexport function isApiError(e: unknown): e is ApiError {\n return (\n typeof e === \"object\" && e !== null && (e as { isApiError?: boolean }).isApiError === true\n );\n}\n\nexport function isNetworkError(e: unknown): e is NetworkError {\n return (\n typeof e === \"object\" &&\n e !== null &&\n (e as { isNetworkError?: boolean }).isNetworkError === true\n );\n}\n","import type { HttpClient } from \"../http.js\";\nimport type { TokenStore } from \"../token-store.js\";\nimport { isApiError } from \"../error.js\";\nimport type { SignupAttribution } from \"./attribution.js\";\nimport type { CodeResult } from \"./codes.js\";\n\n/**\n * Auth resource — `client.auth.*`.\n *\n * Covers the end-user-facing staged auth flow: password login\n * with optional TOTP/OTP step-up. The shape mirrors the responses\n * the Takeal API returns from `/auth/login`, `/auth/login/totp`,\n * `/auth/login/otp/verify`, `/auth/login/2fa/switch`, and `/auth/me`.\n *\n * The login methods stash the JWT in the configured `TokenStore` on\n * success so subsequent `client.*` calls authenticate automatically.\n * Step-up responses (TotpRequired / OtpSent) carry their own short-\n * lived challenge token which the caller passes to the next method\n * — those tokens DO NOT go through the TokenStore (they're not the\n * end-state JWT).\n */\n\nexport interface User {\n id: string;\n email: string;\n role: string;\n is_active: boolean;\n /** True for users auto-provisioned via the Telegram Mini App who still hold\n * a synthetic placeholder email. The client should prompt for a real email\n * and attach it via `auth.linkEmail` — this flips the flag to false. */\n email_pending?: boolean;\n created_at: string;\n updated_at: string;\n /** ISO 4217 code the user's wallet is held in (their own choice, else the\n * deployment default). Present on `GET /auth/me`. */\n wallet_currency?: string;\n /** The Telegram account linked to this user, or `null` when none is.\n * Present on `GET /auth/me` and inside every `stage: \"jwt\"` envelope. */\n telegram?: TelegramLink | null;\n}\n\n/** A Telegram account attached to a user. One Telegram per account and one\n * account per Telegram. */\nexport interface TelegramLink {\n /** Telegram username without the `@`, or `null` when the user has none. */\n username: string | null;\n /** When the link was made, ISO-8601. */\n linked_at: string;\n}\n\nexport interface ExchangeTelegramInput {\n /** Raw `window.Telegram.WebApp.initData`, passed to the server verbatim. */\n initData: string;\n /** Analytics ids for a new account. The Telegram id is the anonymous key\n * here, and a `startapp` code in `initData` is read by the server. */\n attribution?: SignupAttribution;\n /** Create an account for a Telegram id the deployment has not seen before.\n * Default `true`. With `false` the exchange resolves to\n * `{ stage: \"unknown\" }` instead, so the app can offer \"create an account\"\n * or \"I already have one\". */\n provision?: boolean;\n /** A promo or referral code for a new account. Without it the server\n * reads the `startapp` of the link the Mini App was opened with, when\n * that is a code. The result comes back as `code_result`. */\n code?: string;\n}\n\n/** `exchangeTelegram({ provision: false })` for a Telegram id nobody has\n * signed in with yet. No account was created and no JWT was stored. */\nexport interface TelegramUnknown {\n stage: \"unknown\";\n}\n\nexport interface LinkTelegramInput {\n /** Raw `window.Telegram.WebApp.initData`, passed to the server verbatim. */\n initData: string;\n email: string;\n password: string;\n}\n\nexport interface LoginInput {\n email: string;\n password: string;\n /** Keep this browser signed in: the SDK stores the remember token it gets\n * and renews the session by itself when it ends. For accounts with a\n * second factor, pass it again to `verifyTotp` / `verifyOtp` /\n * `completeTotpSetup`. */\n remember?: boolean;\n}\n\n/** Discriminated union — `stage` is the discriminator. */\nexport type LoginResponse = JwtIssued | TotpRequired | TotpSetupRequired;\n\nexport interface JwtIssued {\n stage: \"jwt\";\n access_token: string;\n expires_at: string;\n user: User;\n /** `exchangeTelegram` for a new account opened with a code (`startapp`\n * or `code`): whether it was applied and what it gave. */\n code_result?: CodeResult;\n /** Present when the sign-in was remembered. The SDK keeps it in the\n * remember store; you don't need to. */\n remember_token?: string;\n remember_expires_at?: string;\n /** True iff the user's role grants `system.view_hub`.\n * Cusfront ignores this; the operator console uses it to gate `/dashboard`. */\n hub_access?: boolean;\n}\n\nexport interface TotpRequired {\n stage: \"totp_required\";\n challenge_token: string;\n expires_at: string;\n /** Alternate second factors. Pick one with `/2fa/switch`. */\n available_methods: AvailableMethod[];\n}\n\nexport interface TotpSetupRequired {\n stage: \"totp_setup_required\";\n challenge_token: string;\n expires_at: string;\n /** OTPAuth URI rendered as a QR by the consumer. */\n otpauth_url: string;\n /** Same secret base32-encoded — for manual entry alongside QR. */\n secret_base32: string;\n}\n\nexport interface AvailableMethod {\n kind: \"totp\" | \"telegram_otp\" | \"email_otp\";\n /** Short user-facing hint, e.g. `\"Telegram (@user)\"` or `\"e****@example.com\"`. */\n hint?: string;\n}\n\nexport interface TotpVerifyInput {\n challenge_token: string;\n /** 6-digit TOTP code OR `XXXX-XXXX` backup code. */\n code: string;\n /** Keep this browser signed in, as in `login`. */\n remember?: boolean;\n}\n\nexport interface OtpVerifyInput {\n challenge_token: string;\n /** 6-digit one-time code delivered via the selected channel. */\n code: string;\n /** Keep this browser signed in, as in `login`. */\n remember?: boolean;\n}\n\nexport interface SwitchMethodInput {\n challenge_token: string;\n method: AvailableMethod[\"kind\"];\n}\n\nexport interface RegisterInput {\n email: string;\n password: string;\n /** ISO 4217 code for the new wallet; must be offered by the deployment. */\n wallet_currency?: string;\n /** Keep this browser signed in, as in `login`. */\n remember?: boolean;\n /** Where the new user came from: the anonymous key their visits were\n * sent with (`client.attribution.touch`) and the analytics ids. Without\n * it the account is recorded with an unknown source. */\n attribution?: SignupAttribution;\n /** A promo or referral code. An unknown or expired code doesn't stop the\n * sign-up: the account is created and `code_result` says why the code\n * was not applied, so the app can show it. */\n code?: string;\n}\n\n/** A signed-in session without the login `stage` marker — what\n * `register` returns. With a `code`, `code_result` is set. */\nexport type Session = Omit<JwtIssued, \"stage\">;\n\nexport interface TotpSetupComplete extends Session {\n /** Ten one-time `XXXX-XXXX` codes, returned only this once. */\n backup_codes: string[];\n}\n\nexport interface ChangePasswordInput {\n current_password: string;\n /** At least 12 characters with a lower-case letter, an upper-case letter\n * and a digit; must differ from the current password. */\n new_password: string;\n}\n\nexport interface OtpSentResponse {\n stage: \"otp_sent\";\n challenge_token: string;\n expires_at: string;\n method: AvailableMethod[\"kind\"];\n hint?: string;\n available_methods: AvailableMethod[];\n}\n\n/** Send `remember` as the API's `remember_me`. */\nfunction withRemember<T extends { remember?: boolean }>(input: T): Omit<T, \"remember\"> & { remember_me?: boolean } {\n const { remember, ...rest } = input;\n return remember ? { ...rest, remember_me: true } : rest;\n}\n\nexport class AuthResource {\n constructor(\n private readonly http: HttpClient,\n private readonly tokens: TokenStore,\n private readonly remembered?: TokenStore,\n ) {\n if (remembered) http.setRefresher(() => this.renew().then((r) => r.kind !== \"gone\"));\n }\n\n /** Store what a finished sign-in returned. */\n private async keep(resp: { access_token: string; remember_token?: string }): Promise<void> {\n await Promise.resolve(this.tokens.set(resp.access_token));\n if (resp.remember_token && this.remembered) {\n await Promise.resolve(this.remembered.set(resp.remember_token));\n }\n }\n\n /** Renew a remembered sign-in: a new session and a new remember token,\n * both stored. Resolves `null` (and forgets the remember token) when there\n * is none or it no longer works; the app then shows the sign-in form.\n * The SDK does this by itself on a 401; call it on app start to resume a\n * session without a request failing first. */\n async refresh(): Promise<JwtIssued | null> {\n const r = await this.renew();\n if (r.kind === \"renewed\") return r.resp;\n if (r.kind === \"taken_over\") {\n // Another tab renewed first: its session is already stored.\n const access = await Promise.resolve(this.tokens.get());\n const user = await this.me();\n return { stage: \"jwt\", access_token: access ?? \"\", expires_at: \"\", user };\n }\n return null;\n }\n\n /** The renewal itself, for the 401 path: it must not call the API again\n * through the client, or a second 401 would wait on this very renewal. */\n private async renew(): Promise<\n { kind: \"renewed\"; resp: JwtIssued } | { kind: \"taken_over\" } | { kind: \"gone\" }\n > {\n const token = this.remembered ? await Promise.resolve(this.remembered.get()) : null;\n if (!token) return { kind: \"gone\" };\n try {\n const resp = await this.http.post<JwtIssued>(\"/auth/refresh\", {\n body: { remember_token: token },\n skipAuth: true,\n });\n await this.keep(resp);\n return { kind: \"renewed\", resp };\n } catch (e) {\n if (isApiError(e) && e.status === 401) {\n // Another tab of the same browser may have renewed first; its\n // tokens are then already in the (shared) stores.\n const now = await Promise.resolve(this.remembered!.get());\n if (now && now !== token && (await Promise.resolve(this.tokens.get()))) {\n return { kind: \"taken_over\" };\n }\n await Promise.resolve(this.remembered!.clear());\n await Promise.resolve(this.tokens.clear());\n return { kind: \"gone\" };\n }\n throw e;\n }\n }\n\n /** Password-auth entry. May resolve to a JWT, or to a step-up\n * challenge that needs `verifyTotp` / `verifyOtp` next. */\n async login(input: LoginInput): Promise<LoginResponse> {\n const resp = await this.http.post<LoginResponse>(\"/auth/login\", {\n body: withRemember(input),\n skipAuth: true,\n });\n if (resp.stage === \"jwt\") {\n await this.keep(resp);\n }\n return resp;\n }\n\n /** Verify a TOTP code (or XXXX-XXXX backup code) against a\n * `totp_required` challenge. On success the JWT is stored. */\n async verifyTotp(input: TotpVerifyInput): Promise<JwtIssued> {\n const resp = await this.http.post<JwtIssued>(\"/auth/login/totp\", {\n body: withRemember(input),\n skipAuth: true,\n });\n await this.keep(resp);\n return resp;\n }\n\n /** Verify a 6-digit OTP code (Telegram / email) against an\n * `otp_sent` challenge. */\n async verifyOtp(input: OtpVerifyInput): Promise<JwtIssued> {\n const resp = await this.http.post<JwtIssued>(\"/auth/login/otp/verify\", {\n body: withRemember(input),\n skipAuth: true,\n });\n await this.keep(resp);\n return resp;\n }\n\n /** Create an end-user account and sign it in. The JWT is stored.\n * `wallet_currency` must be one the deployment offers; omit it to take\n * the deployment default (it can be switched later via `client.wallet`\n * while the wallet is empty).\n * Errors: 400 `validation` / `currency_not_allowed`, 409 email taken. */\n async register(input: RegisterInput): Promise<Session> {\n const resp = await this.http.post<Session>(\"/auth/register\", {\n body: withRemember(input),\n skipAuth: true,\n });\n await this.keep(resp);\n return resp;\n }\n\n /** Finish a `totp_setup_required` login: send the first code from the\n * authenticator app. The JWT is stored. The response carries ten\n * one-time `backup_codes` that are never returned again, so show them to\n * the user right away and don't keep them on the device. */\n async completeTotpSetup(input: TotpVerifyInput): Promise<TotpSetupComplete> {\n const resp = await this.http.post<TotpSetupComplete>(\"/auth/login/totp-setup\", {\n body: withRemember(input),\n skipAuth: true,\n });\n await this.keep(resp);\n return resp;\n }\n\n /** Change the signed-in user's password. Every other session of the\n * account is signed out; this one stays valid.\n * Errors: 400 when the new password fails the policy, 401 when the\n * current one is wrong. */\n async changePassword(input: ChangePasswordInput): Promise<{ revoked_sessions: number }> {\n return this.http.post<{ revoked_sessions: number }>(\"/auth/password\", {\n body: input,\n });\n }\n\n /** Swap the 2FA method mid-flow. Resolves to `otp_sent` for\n * telegram/email; for TOTP it short-circuits back to the challenge. */\n async switchMethod(input: SwitchMethodInput): Promise<OtpSentResponse> {\n return this.http.post<OtpSentResponse>(\"/auth/login/2fa/switch\", {\n body: input,\n skipAuth: true,\n });\n }\n\n /** Exchange a signed Telegram Mini App `initData` payload for a session\n * JWT. The server validates the initData HMAC against the deployment's bot\n * token, then looks the Telegram id up. A known id signs in. An unknown id\n * gets a fresh account (`user.email_pending === true` — prompt for a real\n * email and call {@link linkEmail}) unless `provision: false` is passed, in\n * which case the call resolves to `{ stage: \"unknown\" }`, nothing is\n * created and nothing is stored; the app then offers to create the account\n * (call again with `provision: true`) or to attach the Telegram to an\n * existing one ({@link linkTelegram}). Stores the JWT on `stage: \"jwt\"`.\n *\n * Every other error still throws an `ApiError` (401 `invalid_init_data`,\n * 503 `telegram_not_configured`, …).\n *\n * Most consumers use the higher-level `fromInitData` / `fromTelegramWebApp`\n * helpers in `@takeal/cusfront-sdk/telegram`; reach for this directly when\n * you already hold a configured client. */\n exchangeTelegram(input: { initData: string; provision?: true }): Promise<JwtIssued>;\n exchangeTelegram(input: ExchangeTelegramInput): Promise<JwtIssued | TelegramUnknown>;\n async exchangeTelegram(input: ExchangeTelegramInput): Promise<JwtIssued | TelegramUnknown> {\n const body: {\n init_data: string;\n provision?: boolean;\n attribution?: SignupAttribution;\n code?: string;\n } = {\n init_data: input.initData,\n };\n if (input.provision !== undefined) body.provision = input.provision;\n if (input.attribution !== undefined) body.attribution = input.attribution;\n if (input.code !== undefined) body.code = input.code;\n let resp: JwtIssued;\n try {\n resp = await this.http.post<JwtIssued>(\"/auth/telegram/exchange\", {\n body,\n skipAuth: true,\n });\n } catch (e) {\n if (isApiError(e) && e.status === 404 && e.code === \"telegram_unknown\") {\n return { stage: \"unknown\" };\n }\n throw e;\n }\n await Promise.resolve(this.tokens.set(resp.access_token));\n return resp;\n }\n\n /** Attach the Telegram account behind `initData` to an existing email +\n * password account and sign in as that account. No bearer needed; the\n * password is checked the same way `login` checks it. The JWT is stored.\n *\n * Errors: 401 `unauthenticated` (wrong email or password, as with\n * `login`) / `invalid_init_data`; 403\n * `user_disabled` / `second_factor_required` (accounts that sign in with\n * a second factor can't be linked from a Mini App); 409\n * `telegram_already_linked_other` (this account already has a different\n * Telegram; unlink it first) / `telegram_in_use` (this Telegram belongs to\n * another account); 503 `telegram_not_configured`. */\n async linkTelegram(input: LinkTelegramInput): Promise<JwtIssued> {\n const resp = await this.http.post<JwtIssued>(\"/auth/telegram/link\", {\n body: { init_data: input.initData, email: input.email, password: input.password },\n skipAuth: true,\n });\n await Promise.resolve(this.tokens.set(resp.access_token));\n return resp;\n }\n\n /** Attach a real email to the current user (and clear `email_pending`).\n * Used after a Telegram exchange to satisfy the email requirement; also\n * works for a password user changing their address. 409 if taken. */\n async linkEmail(input: { email: string }): Promise<User> {\n return this.http.post<User>(\"/me/email\", { body: { email: input.email } });\n }\n\n /** Current user — fails 401 when the stored JWT is expired or\n * missing. Useful as a \"do I have a session\" probe on app boot. */\n async me(): Promise<User> {\n return this.http.get<User>(\"/auth/me\");\n }\n\n /** Sign out: ends this session and the remembered sign-in on the\n * server (best effort: a network failure still signs out locally), then\n * forgets both tokens. */\n async signOut(): Promise<void> {\n const remember = this.remembered ? await Promise.resolve(this.remembered.get()) : null;\n try {\n await this.http.post<void>(\"/auth/logout\", {\n body: remember ? { remember_token: remember } : {},\n retried: true,\n });\n } catch {\n // Signed out locally either way.\n }\n await Promise.resolve(this.tokens.clear());\n if (this.remembered) await Promise.resolve(this.remembered.clear());\n }\n}\n"]}
1
+ {"version":3,"sources":["../../src/error.ts","../../src/resources/auth.ts"],"names":[],"mappings":";;;AA2CO,SAAS,WAAW,CAAA,EAA2B;AACpD,EAAA,OAAO,OAAO,CAAA,KAAM,QAAA,IAAY,CAAA,KAAM,IAAA,IAAS,EAA+B,UAAA,KAAe,IAAA;AAC/F;;;ACyJA,SAAS,aACP,KAAA,EACiD;AACjD,EAAA,MAAM,EAAE,QAAA,EAAU,GAAG,IAAA,EAAK,GAAI,KAAA;AAC9B,EAAA,OAAO,WAAW,EAAE,GAAG,IAAA,EAAM,WAAA,EAAa,MAAK,GAAI,IAAA;AACrD;AAEO,IAAM,eAAN,MAAmB;AAAA,EACxB,WAAA,CACmB,IAAA,EACA,MAAA,EACA,UAAA,EACjB;AAHiB,IAAA,IAAA,CAAA,IAAA,GAAA,IAAA;AACA,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA;AACA,IAAA,IAAA,CAAA,UAAA,GAAA,UAAA;AAEjB,IAAA,IAAI,UAAA,EAAY,IAAA,CAAK,YAAA,CAAa,MAAM,IAAA,CAAK,KAAA,EAAM,CAAE,IAAA,CAAK,CAAC,CAAA,KAAM,CAAA,CAAE,IAAA,KAAS,MAAM,CAAC,CAAA;AAAA,EACrF;AAAA;AAAA,EAGA,MAAc,KAAK,IAAA,EAAwE;AACzF,IAAA,MAAM,QAAQ,OAAA,CAAQ,IAAA,CAAK,OAAO,GAAA,CAAI,IAAA,CAAK,YAAY,CAAC,CAAA;AACxD,IAAA,IAAI,IAAA,CAAK,cAAA,IAAkB,IAAA,CAAK,UAAA,EAAY;AAC1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,EACpE;AACF","file":"auth.cjs","sourcesContent":["/**\n * Errors surfaced by the SDK. All HTTP failures map onto `ApiError`;\n * network-level / abort / serialisation failures get the generic\n * `NetworkError`. Consumers catch on the discriminator field\n * (`isApiError` / `isNetworkError`) rather than `instanceof` — works\n * across bundler boundaries where multiple copies of the class can\n * coexist.\n */\nexport class ApiError extends Error {\n readonly isApiError = true as const;\n\n constructor(\n /** HTTP status code returned by the Takeal API. */\n public readonly status: number,\n /** Stable machine-readable code (e.g. `\"insufficient_funds\"`,\n * `\"permission_required\"`, `\"validation\"`). Same enum the\n * TypeScript types pin via openapi-typescript. */\n public readonly code: string,\n /** Human-readable message. English; the consumer maps to its\n * own i18n layer before showing to end-users. */\n message: string,\n /** Full parsed response body when available. Carries field-level\n * validation details for `code = \"validation\"`. */\n public readonly body?: unknown,\n ) {\n super(message);\n this.name = \"ApiError\";\n }\n}\n\nexport class NetworkError extends Error {\n readonly isNetworkError = true as const;\n\n constructor(\n message: string,\n public readonly cause?: unknown,\n ) {\n super(message);\n this.name = \"NetworkError\";\n }\n}\n\n/** Type guard — preferred over `instanceof` (bundler-safe). */\nexport function isApiError(e: unknown): e is ApiError {\n return typeof e === \"object\" && e !== null && (e as { isApiError?: boolean }).isApiError === true;\n}\n\nexport function isNetworkError(e: unknown): e is NetworkError {\n return (\n typeof e === \"object\" &&\n e !== null &&\n (e as { isNetworkError?: boolean }).isNetworkError === true\n );\n}\n","import type { HttpClient } from \"../http.js\";\nimport type { TokenStore } from \"../token-store.js\";\nimport { isApiError } from \"../error.js\";\nimport type { SignupAttribution } from \"./attribution.js\";\nimport type { CodeResult } from \"./codes.js\";\n\n/**\n * Auth resource — `client.auth.*`.\n *\n * Covers the end-user-facing staged auth flow: password login\n * with optional TOTP/OTP step-up. The shape mirrors the responses\n * the Takeal API returns from `/auth/login`, `/auth/login/totp`,\n * `/auth/login/otp/verify`, `/auth/login/2fa/switch`, and `/auth/me`.\n *\n * The login methods stash the JWT in the configured `TokenStore` on\n * success so subsequent `client.*` calls authenticate automatically.\n * Step-up responses (TotpRequired / OtpSent) carry their own short-\n * lived challenge token which the caller passes to the next method\n * — those tokens DO NOT go through the TokenStore (they're not the\n * end-state JWT).\n */\n\nexport interface User {\n id: string;\n email: string;\n role: string;\n is_active: boolean;\n /** True for users auto-provisioned via the Telegram Mini App who still hold\n * a synthetic placeholder email. The client should prompt for a real email\n * and attach it via `auth.linkEmail` — this flips the flag to false. */\n email_pending?: boolean;\n created_at: string;\n updated_at: string;\n /** ISO 4217 code the user's wallet is held in (their own choice, else the\n * deployment default). Present on `GET /auth/me`. */\n wallet_currency?: string;\n /** The Telegram account linked to this user, or `null` when none is.\n * Present on `GET /auth/me` and inside every `stage: \"jwt\"` envelope. */\n telegram?: TelegramLink | null;\n}\n\n/** A Telegram account attached to a user. One Telegram per account and one\n * account per Telegram. */\nexport interface TelegramLink {\n /** Telegram username without the `@`, or `null` when the user has none. */\n username: string | null;\n /** When the link was made, ISO-8601. */\n linked_at: string;\n}\n\nexport interface ExchangeTelegramInput {\n /** Raw `window.Telegram.WebApp.initData`, passed to the server verbatim. */\n initData: string;\n /** Analytics ids for a new account. The Telegram id is the anonymous key\n * here, and a `startapp` code in `initData` is read by the server. */\n attribution?: SignupAttribution;\n /** Create an account for a Telegram id the deployment has not seen before.\n * Default `true`. With `false` the exchange resolves to\n * `{ stage: \"unknown\" }` instead, so the app can offer \"create an account\"\n * or \"I already have one\". */\n provision?: boolean;\n /** A promo or referral code for a new account. Without it the server\n * reads the `startapp` of the link the Mini App was opened with, when\n * that is a code. The result comes back as `code_result`. */\n code?: string;\n}\n\n/** `exchangeTelegram({ provision: false })` for a Telegram id nobody has\n * signed in with yet. No account was created and no JWT was stored. */\nexport interface TelegramUnknown {\n stage: \"unknown\";\n}\n\nexport interface LinkTelegramInput {\n /** Raw `window.Telegram.WebApp.initData`, passed to the server verbatim. */\n initData: string;\n email: string;\n password: string;\n}\n\nexport interface LoginInput {\n email: string;\n password: string;\n /** Keep this browser signed in: the SDK stores the remember token it gets\n * and renews the session by itself when it ends. For accounts with a\n * second factor, pass it again to `verifyTotp` / `verifyOtp` /\n * `completeTotpSetup`. */\n remember?: boolean;\n}\n\n/** Discriminated union — `stage` is the discriminator. */\nexport type LoginResponse = JwtIssued | TotpRequired | TotpSetupRequired;\n\nexport interface JwtIssued {\n stage: \"jwt\";\n access_token: string;\n expires_at: string;\n user: User;\n /** `exchangeTelegram` for a new account opened with a code (`startapp`\n * or `code`): whether it was applied and what it gave. */\n code_result?: CodeResult;\n /** Present when the sign-in was remembered. The SDK keeps it in the\n * remember store; you don't need to. */\n remember_token?: string;\n remember_expires_at?: string;\n /** True iff the user's role grants `system.view_hub`.\n * Cusfront ignores this; the operator console uses it to gate `/dashboard`. */\n hub_access?: boolean;\n}\n\nexport interface TotpRequired {\n stage: \"totp_required\";\n challenge_token: string;\n expires_at: string;\n /** Alternate second factors. Pick one with `/2fa/switch`. */\n available_methods: AvailableMethod[];\n}\n\nexport interface TotpSetupRequired {\n stage: \"totp_setup_required\";\n challenge_token: string;\n expires_at: string;\n /** OTPAuth URI rendered as a QR by the consumer. */\n otpauth_url: string;\n /** Same secret base32-encoded — for manual entry alongside QR. */\n secret_base32: string;\n}\n\nexport interface AvailableMethod {\n kind: \"totp\" | \"telegram_otp\" | \"email_otp\";\n /** Short user-facing hint, e.g. `\"Telegram (@user)\"` or `\"e****@example.com\"`. */\n hint?: string;\n}\n\nexport interface TotpVerifyInput {\n challenge_token: string;\n /** 6-digit TOTP code OR `XXXX-XXXX` backup code. */\n code: string;\n /** Keep this browser signed in, as in `login`. */\n remember?: boolean;\n}\n\nexport interface OtpVerifyInput {\n challenge_token: string;\n /** 6-digit one-time code delivered via the selected channel. */\n code: string;\n /** Keep this browser signed in, as in `login`. */\n remember?: boolean;\n}\n\nexport interface SwitchMethodInput {\n challenge_token: string;\n method: AvailableMethod[\"kind\"];\n}\n\nexport interface RegisterInput {\n email: string;\n password: string;\n /** ISO 4217 code for the new wallet; must be offered by the deployment. */\n wallet_currency?: string;\n /** Keep this browser signed in, as in `login`. */\n remember?: boolean;\n /** Where the new user came from: the anonymous key their visits were\n * sent with (`client.attribution.touch`) and the analytics ids. Without\n * it the account is recorded with an unknown source. */\n attribution?: SignupAttribution;\n /** A promo or referral code. An unknown or expired code doesn't stop the\n * sign-up: the account is created and `code_result` says why the code\n * was not applied, so the app can show it. */\n code?: string;\n}\n\n/** A signed-in session without the login `stage` marker — what\n * `register` returns. With a `code`, `code_result` is set. */\nexport type Session = Omit<JwtIssued, \"stage\">;\n\nexport interface TotpSetupComplete extends Session {\n /** Ten one-time `XXXX-XXXX` codes, returned only this once. */\n backup_codes: string[];\n}\n\nexport interface ChangePasswordInput {\n current_password: string;\n /** At least 12 characters with a lower-case letter, an upper-case letter\n * and a digit; must differ from the current password. */\n new_password: string;\n}\n\nexport interface OtpSentResponse {\n stage: \"otp_sent\";\n challenge_token: string;\n expires_at: string;\n method: AvailableMethod[\"kind\"];\n hint?: string;\n available_methods: AvailableMethod[];\n}\n\n/** Send `remember` as the API's `remember_me`. */\nfunction withRemember<T extends { remember?: boolean }>(\n input: T,\n): Omit<T, \"remember\"> & { remember_me?: boolean } {\n const { remember, ...rest } = input;\n return remember ? { ...rest, remember_me: true } : rest;\n}\n\nexport class AuthResource {\n constructor(\n private readonly http: HttpClient,\n private readonly tokens: TokenStore,\n private readonly remembered?: TokenStore,\n ) {\n if (remembered) http.setRefresher(() => this.renew().then((r) => r.kind !== \"gone\"));\n }\n\n /** Store what a finished sign-in returned. */\n private async keep(resp: { access_token: string; remember_token?: string }): Promise<void> {\n await Promise.resolve(this.tokens.set(resp.access_token));\n if (resp.remember_token && this.remembered) {\n await Promise.resolve(this.remembered.set(resp.remember_token));\n }\n }\n\n /** Renew a remembered sign-in: a new session and a new remember token,\n * both stored. Resolves `null` (and forgets the remember token) when there\n * is none or it no longer works; the app then shows the sign-in form.\n * The SDK does this by itself on a 401; call it on app start to resume a\n * session without a request failing first. */\n async refresh(): Promise<JwtIssued | null> {\n const r = await this.renew();\n if (r.kind === \"renewed\") return r.resp;\n if (r.kind === \"taken_over\") {\n // Another tab renewed first: its session is already stored.\n const access = await Promise.resolve(this.tokens.get());\n const user = await this.me();\n return { stage: \"jwt\", access_token: access ?? \"\", expires_at: \"\", user };\n }\n return null;\n }\n\n /** The renewal itself, for the 401 path: it must not call the API again\n * through the client, or a second 401 would wait on this very renewal. */\n private async renew(): Promise<\n { kind: \"renewed\"; resp: JwtIssued } | { kind: \"taken_over\" } | { kind: \"gone\" }\n > {\n const token = this.remembered ? await Promise.resolve(this.remembered.get()) : null;\n if (!token) return { kind: \"gone\" };\n try {\n const resp = await this.http.post<JwtIssued>(\"/auth/refresh\", {\n body: { remember_token: token },\n skipAuth: true,\n });\n await this.keep(resp);\n return { kind: \"renewed\", resp };\n } catch (e) {\n if (isApiError(e) && e.status === 401) {\n // Another tab of the same browser may have renewed first; its\n // tokens are then already in the (shared) stores.\n const now = await Promise.resolve(this.remembered!.get());\n if (now && now !== token && (await Promise.resolve(this.tokens.get()))) {\n return { kind: \"taken_over\" };\n }\n await Promise.resolve(this.remembered!.clear());\n await Promise.resolve(this.tokens.clear());\n return { kind: \"gone\" };\n }\n throw e;\n }\n }\n\n /** Password-auth entry. May resolve to a JWT, or to a step-up\n * challenge that needs `verifyTotp` / `verifyOtp` next. */\n async login(input: LoginInput): Promise<LoginResponse> {\n const resp = await this.http.post<LoginResponse>(\"/auth/login\", {\n body: withRemember(input),\n skipAuth: true,\n });\n if (resp.stage === \"jwt\") {\n await this.keep(resp);\n }\n return resp;\n }\n\n /** Verify a TOTP code (or XXXX-XXXX backup code) against a\n * `totp_required` challenge. On success the JWT is stored. */\n async verifyTotp(input: TotpVerifyInput): Promise<JwtIssued> {\n const resp = await this.http.post<JwtIssued>(\"/auth/login/totp\", {\n body: withRemember(input),\n skipAuth: true,\n });\n await this.keep(resp);\n return resp;\n }\n\n /** Verify a 6-digit OTP code (Telegram / email) against an\n * `otp_sent` challenge. */\n async verifyOtp(input: OtpVerifyInput): Promise<JwtIssued> {\n const resp = await this.http.post<JwtIssued>(\"/auth/login/otp/verify\", {\n body: withRemember(input),\n skipAuth: true,\n });\n await this.keep(resp);\n return resp;\n }\n\n /** Create an end-user account and sign it in. The JWT is stored.\n * `wallet_currency` must be one the deployment offers; omit it to take\n * the deployment default (it can be switched later via `client.wallet`\n * while the wallet is empty).\n * Errors: 400 `validation` / `currency_not_allowed`, 409 email taken. */\n async register(input: RegisterInput): Promise<Session> {\n const resp = await this.http.post<Session>(\"/auth/register\", {\n body: withRemember(input),\n skipAuth: true,\n });\n await this.keep(resp);\n return resp;\n }\n\n /** Finish a `totp_setup_required` login: send the first code from the\n * authenticator app. The JWT is stored. The response carries ten\n * one-time `backup_codes` that are never returned again, so show them to\n * the user right away and don't keep them on the device. */\n async completeTotpSetup(input: TotpVerifyInput): Promise<TotpSetupComplete> {\n const resp = await this.http.post<TotpSetupComplete>(\"/auth/login/totp-setup\", {\n body: withRemember(input),\n skipAuth: true,\n });\n await this.keep(resp);\n return resp;\n }\n\n /** Change the signed-in user's password. Every other session of the\n * account is signed out; this one stays valid.\n * Errors: 400 when the new password fails the policy, 401 when the\n * current one is wrong. */\n async changePassword(input: ChangePasswordInput): Promise<{ revoked_sessions: number }> {\n return this.http.post<{ revoked_sessions: number }>(\"/auth/password\", {\n body: input,\n });\n }\n\n /** Swap the 2FA method mid-flow. Resolves to `otp_sent` for\n * telegram/email; for TOTP it short-circuits back to the challenge. */\n async switchMethod(input: SwitchMethodInput): Promise<OtpSentResponse> {\n return this.http.post<OtpSentResponse>(\"/auth/login/2fa/switch\", {\n body: input,\n skipAuth: true,\n });\n }\n\n /** Exchange a signed Telegram Mini App `initData` payload for a session\n * JWT. The server validates the initData HMAC against the deployment's bot\n * token, then looks the Telegram id up. A known id signs in. An unknown id\n * gets a fresh account (`user.email_pending === true` — prompt for a real\n * email and call {@link linkEmail}) unless `provision: false` is passed, in\n * which case the call resolves to `{ stage: \"unknown\" }`, nothing is\n * created and nothing is stored; the app then offers to create the account\n * (call again with `provision: true`) or to attach the Telegram to an\n * existing one ({@link linkTelegram}). Stores the JWT on `stage: \"jwt\"`.\n *\n * Every other error still throws an `ApiError` (401 `invalid_init_data`,\n * 503 `telegram_not_configured`, …).\n *\n * Most consumers use the higher-level `fromInitData` / `fromTelegramWebApp`\n * helpers in `@takeal/cusfront-sdk/telegram`; reach for this directly when\n * you already hold a configured client. */\n exchangeTelegram(input: { initData: string; provision?: true }): Promise<JwtIssued>;\n exchangeTelegram(input: ExchangeTelegramInput): Promise<JwtIssued | TelegramUnknown>;\n async exchangeTelegram(input: ExchangeTelegramInput): Promise<JwtIssued | TelegramUnknown> {\n const body: {\n init_data: string;\n provision?: boolean;\n attribution?: SignupAttribution;\n code?: string;\n } = {\n init_data: input.initData,\n };\n if (input.provision !== undefined) body.provision = input.provision;\n if (input.attribution !== undefined) body.attribution = input.attribution;\n if (input.code !== undefined) body.code = input.code;\n let resp: JwtIssued;\n try {\n resp = await this.http.post<JwtIssued>(\"/auth/telegram/exchange\", {\n body,\n skipAuth: true,\n });\n } catch (e) {\n if (isApiError(e) && e.status === 404 && e.code === \"telegram_unknown\") {\n return { stage: \"unknown\" };\n }\n throw e;\n }\n await Promise.resolve(this.tokens.set(resp.access_token));\n return resp;\n }\n\n /** Attach the Telegram account behind `initData` to an existing email +\n * password account and sign in as that account. No bearer needed; the\n * password is checked the same way `login` checks it. The JWT is stored.\n *\n * Errors: 401 `unauthenticated` (wrong email or password, as with\n * `login`) / `invalid_init_data`; 403\n * `user_disabled` / `second_factor_required` (accounts that sign in with\n * a second factor can't be linked from a Mini App); 409\n * `telegram_already_linked_other` (this account already has a different\n * Telegram; unlink it first) / `telegram_in_use` (this Telegram belongs to\n * another account); 503 `telegram_not_configured`. */\n async linkTelegram(input: LinkTelegramInput): Promise<JwtIssued> {\n const resp = await this.http.post<JwtIssued>(\"/auth/telegram/link\", {\n body: { init_data: input.initData, email: input.email, password: input.password },\n skipAuth: true,\n });\n await Promise.resolve(this.tokens.set(resp.access_token));\n return resp;\n }\n\n /** Attach a real email to the current user (and clear `email_pending`).\n * Used after a Telegram exchange to satisfy the email requirement; also\n * works for a password user changing their address. 409 if taken. */\n async linkEmail(input: { email: string }): Promise<User> {\n return this.http.post<User>(\"/me/email\", { body: { email: input.email } });\n }\n\n /** Current user — fails 401 when the stored JWT is expired or\n * missing. Useful as a \"do I have a session\" probe on app boot. */\n async me(): Promise<User> {\n return this.http.get<User>(\"/auth/me\");\n }\n\n /** Sign out: ends this session and the remembered sign-in on the\n * server (best effort: a network failure still signs out locally), then\n * forgets both tokens. */\n async signOut(): Promise<void> {\n const remember = this.remembered ? await Promise.resolve(this.remembered.get()) : null;\n try {\n await this.http.post<void>(\"/auth/logout\", {\n body: remember ? { remember_token: remember } : {},\n retried: true,\n });\n } catch {\n // Signed out locally either way.\n }\n await Promise.resolve(this.tokens.clear());\n if (this.remembered) await Promise.resolve(this.remembered.clear());\n }\n}\n"]}