@takeal/cusfront-sdk 0.1.0 → 0.3.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.
- package/CHANGELOG.md +104 -2
- package/README.md +393 -14
- package/dist/devices-C3JHi2Hi.d.cts +165 -0
- package/dist/devices-DP_hxwmW.d.ts +165 -0
- package/dist/{http-BkZZZI8K.d.cts → http-B-OQwMYn.d.cts} +13 -2
- package/dist/{http-BkZZZI8K.d.ts → http-B-OQwMYn.d.ts} +13 -2
- package/dist/index.cjs +425 -25
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +77 -8
- package/dist/index.d.ts +77 -8
- package/dist/index.js +422 -26
- package/dist/index.js.map +1 -1
- package/dist/react/index.cjs +133 -6
- package/dist/react/index.cjs.map +1 -1
- package/dist/react/index.d.cts +65 -3
- package/dist/react/index.d.ts +65 -3
- package/dist/react/index.js +131 -8
- package/dist/react/index.js.map +1 -1
- package/dist/resources/auth.cjs +73 -15
- package/dist/resources/auth.cjs.map +1 -1
- package/dist/resources/auth.d.cts +100 -9
- package/dist/resources/auth.d.ts +100 -9
- package/dist/resources/auth.js +73 -15
- package/dist/resources/auth.js.map +1 -1
- package/dist/resources/balance.cjs +4 -3
- package/dist/resources/balance.cjs.map +1 -1
- package/dist/resources/balance.d.cts +8 -9
- package/dist/resources/balance.d.ts +8 -9
- package/dist/resources/balance.js +4 -3
- package/dist/resources/balance.js.map +1 -1
- package/dist/resources/blog.d.cts +1 -1
- package/dist/resources/blog.d.ts +1 -1
- package/dist/resources/branding.cjs.map +1 -1
- package/dist/resources/branding.d.cts +8 -2
- package/dist/resources/branding.d.ts +8 -2
- package/dist/resources/branding.js.map +1 -1
- package/dist/resources/cards.cjs +33 -1
- package/dist/resources/cards.cjs.map +1 -1
- package/dist/resources/cards.d.cts +105 -4
- package/dist/resources/cards.d.ts +105 -4
- package/dist/resources/cards.js +33 -1
- package/dist/resources/cards.js.map +1 -1
- package/dist/resources/deposits.d.cts +1 -1
- package/dist/resources/deposits.d.ts +1 -1
- package/dist/resources/devices.cjs +92 -0
- package/dist/resources/devices.cjs.map +1 -0
- package/dist/resources/devices.d.cts +3 -0
- package/dist/resources/devices.d.ts +3 -0
- package/dist/resources/devices.js +89 -0
- package/dist/resources/devices.js.map +1 -0
- package/dist/resources/me.cjs +32 -0
- package/dist/resources/me.cjs.map +1 -0
- package/dist/resources/me.d.cts +40 -0
- package/dist/resources/me.d.ts +40 -0
- package/dist/resources/me.js +30 -0
- package/dist/resources/me.js.map +1 -0
- package/dist/resources/notifications.cjs +53 -0
- package/dist/resources/notifications.cjs.map +1 -0
- package/dist/resources/notifications.d.cts +109 -0
- package/dist/resources/notifications.d.ts +109 -0
- package/dist/resources/notifications.js +51 -0
- package/dist/resources/notifications.js.map +1 -0
- package/dist/resources/push.cjs +65 -0
- package/dist/resources/push.cjs.map +1 -0
- package/dist/resources/push.d.cts +76 -0
- package/dist/resources/push.d.ts +76 -0
- package/dist/resources/push.js +62 -0
- package/dist/resources/push.js.map +1 -0
- package/dist/resources/sessions.cjs +26 -0
- package/dist/resources/sessions.cjs.map +1 -0
- package/dist/resources/sessions.d.cts +43 -0
- package/dist/resources/sessions.d.ts +43 -0
- package/dist/resources/sessions.js +24 -0
- package/dist/resources/sessions.js.map +1 -0
- package/dist/resources/subscriptions.cjs.map +1 -1
- package/dist/resources/subscriptions.d.cts +8 -1
- package/dist/resources/subscriptions.d.ts +8 -1
- package/dist/resources/subscriptions.js.map +1 -1
- package/dist/resources/wallet.cjs +24 -0
- package/dist/resources/wallet.cjs.map +1 -0
- package/dist/resources/wallet.d.cts +39 -0
- package/dist/resources/wallet.d.ts +39 -0
- package/dist/resources/wallet.js +22 -0
- package/dist/resources/wallet.js.map +1 -0
- package/dist/telegram.cjs +466 -28
- package/dist/telegram.cjs.map +1 -1
- package/dist/telegram.d.cts +65 -7
- package/dist/telegram.d.ts +65 -7
- package/dist/telegram.js +465 -29
- package/dist/telegram.js.map +1 -1
- package/package.json +37 -3
package/dist/react/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/react/context.ts","../../src/react/hooks.ts"],"names":["createContext","createElement","useContext","useState","useCallback","useEffect"],"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;ACVA,SAAS,gBAAA,CACP,SACA,IAAA,EACe;AACf,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,EAA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CAAO,KAAA,CAAM,MAAK,EAAG,CAAC,MAAM,CAAC,CAAA;AACrE;AAOO,SAAS,WAAW,QAAA,EAAuC;AAChE,EAAA,MAAM,SAAS,SAAA,EAAU;AACzB,EAAA,OAAO,gBAAA;AAAA,IACL,MAAM,MAAA,CAAO,OAAA,CAAQ,GAAA,CAAI,QAAQ,CAAA;AAAA,IACjC,CAAC,QAAQ,QAAQ;AAAA,GACnB;AACF","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, 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 } from \"../resources/cards.js\";\nimport type { Balance } from \"../resources/balance.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 */\nfunction useAsyncResource<T>(\n fetcher: (signal: AbortSignal) => Promise<T>,\n deps: ReadonlyArray<unknown>,\n): AsyncState<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 };\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 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 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 useAsyncResource<Card[]>(() => client.cards.list(), [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 useAsyncResource<Balance>(\n () => client.balance.get(currency),\n [client, currency],\n );\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;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,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,IAA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,IAAA,MAAM,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(\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"]}
|
package/dist/react/index.d.cts
CHANGED
|
@@ -3,12 +3,18 @@ import { ReactNode } from 'react';
|
|
|
3
3
|
import { CusfrontClient } from '../index.cjs';
|
|
4
4
|
import { User } from '../resources/auth.cjs';
|
|
5
5
|
import { Deposit } from '../resources/deposits.cjs';
|
|
6
|
-
import { Card } from '../resources/cards.cjs';
|
|
6
|
+
import { CardProduct, Card } from '../resources/cards.cjs';
|
|
7
7
|
import { Balance } from '../resources/balance.cjs';
|
|
8
|
-
import '../
|
|
8
|
+
import { NotificationPage, InboxItem, NotificationCategory } from '../resources/notifications.cjs';
|
|
9
|
+
import '../http-B-OQwMYn.cjs';
|
|
9
10
|
import '../resources/branding.cjs';
|
|
11
|
+
import '../resources/wallet.cjs';
|
|
10
12
|
import '../resources/blog.cjs';
|
|
11
13
|
import '../resources/subscriptions.cjs';
|
|
14
|
+
import '../resources/sessions.cjs';
|
|
15
|
+
import '../resources/push.cjs';
|
|
16
|
+
import '../resources/me.cjs';
|
|
17
|
+
import '../devices-C3JHi2Hi.cjs';
|
|
12
18
|
import '../customer-CoxPwe5o.cjs';
|
|
13
19
|
|
|
14
20
|
interface ClientProviderProps {
|
|
@@ -83,11 +89,67 @@ declare function useMe(): AsyncState<User>;
|
|
|
83
89
|
declare function useDeposits(): AsyncState<Deposit[]>;
|
|
84
90
|
/** The caller's cards, most recent first (`client.cards.list()`). */
|
|
85
91
|
declare function useCards(): AsyncState<Card[]>;
|
|
92
|
+
/**
|
|
93
|
+
* The cards the user can order, default product first
|
|
94
|
+
* (`client.cards.listProducts()`). Render each item's artwork through
|
|
95
|
+
* `client.assetUrl(product.design.image_url)`.
|
|
96
|
+
*/
|
|
97
|
+
declare function useCardProducts(): AsyncState<CardProduct[]>;
|
|
86
98
|
/**
|
|
87
99
|
* The user's wallet balance for one currency
|
|
88
100
|
* (`client.balance.get(currency)`). Re-fetches when `currency`
|
|
89
101
|
* changes.
|
|
90
102
|
*/
|
|
91
103
|
declare function useBalance(currency: string): AsyncState<Balance>;
|
|
104
|
+
interface UseNotificationsOptions {
|
|
105
|
+
/** Only unread items. */
|
|
106
|
+
unreadOnly?: boolean;
|
|
107
|
+
category?: NotificationCategory;
|
|
108
|
+
/** Page size. */
|
|
109
|
+
limit?: number;
|
|
110
|
+
}
|
|
111
|
+
interface NotificationsState extends AsyncState<NotificationPage> {
|
|
112
|
+
/** Mark one item read on the server and in `data` right away. */
|
|
113
|
+
markRead: (id: string) => Promise<InboxItem>;
|
|
114
|
+
/** Mark everything read on the server and in `data` right away. */
|
|
115
|
+
markAllRead: () => Promise<{
|
|
116
|
+
marked: number;
|
|
117
|
+
}>;
|
|
118
|
+
/** Fetch the next page (`data.next_cursor`) and append its items.
|
|
119
|
+
* Resolves at once when there is no next page or a load is running. */
|
|
120
|
+
loadMore: () => Promise<void>;
|
|
121
|
+
/** True while `loadMore` is in flight. */
|
|
122
|
+
loadingMore: boolean;
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* The user's inbox (`client.notifications.list(opts)`), newest first, with
|
|
126
|
+
* paging and read-state helpers. `data.items` grows as `loadMore` is
|
|
127
|
+
* called; `refetch` starts over from the first page.
|
|
128
|
+
*
|
|
129
|
+
* ```tsx
|
|
130
|
+
* const inbox = useNotifications({ limit: 20 });
|
|
131
|
+
* inbox.data?.items.map((n) => (
|
|
132
|
+
* <Row key={n.id} onClick={() => inbox.markRead(n.id)} unread={!n.read_at}>
|
|
133
|
+
* {n.title}
|
|
134
|
+
* </Row>
|
|
135
|
+
* ));
|
|
136
|
+
* ```
|
|
137
|
+
*/
|
|
138
|
+
declare function useNotifications(opts?: UseNotificationsOptions): NotificationsState;
|
|
139
|
+
interface UseUnreadCountOptions {
|
|
140
|
+
/** Re-fetch every this many milliseconds. Default 30000; `0` disables
|
|
141
|
+
* polling. */
|
|
142
|
+
pollMs?: number;
|
|
143
|
+
}
|
|
144
|
+
/** Message a service worker posts to open clients when a push arrives, so
|
|
145
|
+
* badges refresh without waiting for the next poll. */
|
|
146
|
+
declare const PUSH_MESSAGE_TYPE = "takeal:push";
|
|
147
|
+
/**
|
|
148
|
+
* Unread inbox items (`client.notifications.unreadCount()`) for a badge.
|
|
149
|
+
* Refreshes silently (no `loading` flip) on an interval and whenever the
|
|
150
|
+
* page's service worker posts `{ type: "takeal:push" }`, which your
|
|
151
|
+
* `push` handler should do for every open client.
|
|
152
|
+
*/
|
|
153
|
+
declare function useUnreadCount(opts?: UseUnreadCountOptions): AsyncState<number>;
|
|
92
154
|
|
|
93
|
-
export { type AsyncState, ClientProvider, type ClientProviderProps, useBalance, useCards, useClient, useDeposits, useMe };
|
|
155
|
+
export { type AsyncState, ClientProvider, type ClientProviderProps, type NotificationsState, PUSH_MESSAGE_TYPE, type UseNotificationsOptions, type UseUnreadCountOptions, useBalance, useCardProducts, useCards, useClient, useDeposits, useMe, useNotifications, useUnreadCount };
|
package/dist/react/index.d.ts
CHANGED
|
@@ -3,12 +3,18 @@ import { ReactNode } from 'react';
|
|
|
3
3
|
import { CusfrontClient } from '../index.js';
|
|
4
4
|
import { User } from '../resources/auth.js';
|
|
5
5
|
import { Deposit } from '../resources/deposits.js';
|
|
6
|
-
import { Card } from '../resources/cards.js';
|
|
6
|
+
import { CardProduct, Card } from '../resources/cards.js';
|
|
7
7
|
import { Balance } from '../resources/balance.js';
|
|
8
|
-
import '../
|
|
8
|
+
import { NotificationPage, InboxItem, NotificationCategory } from '../resources/notifications.js';
|
|
9
|
+
import '../http-B-OQwMYn.js';
|
|
9
10
|
import '../resources/branding.js';
|
|
11
|
+
import '../resources/wallet.js';
|
|
10
12
|
import '../resources/blog.js';
|
|
11
13
|
import '../resources/subscriptions.js';
|
|
14
|
+
import '../resources/sessions.js';
|
|
15
|
+
import '../resources/push.js';
|
|
16
|
+
import '../resources/me.js';
|
|
17
|
+
import '../devices-DP_hxwmW.js';
|
|
12
18
|
import '../customer-CoxPwe5o.js';
|
|
13
19
|
|
|
14
20
|
interface ClientProviderProps {
|
|
@@ -83,11 +89,67 @@ declare function useMe(): AsyncState<User>;
|
|
|
83
89
|
declare function useDeposits(): AsyncState<Deposit[]>;
|
|
84
90
|
/** The caller's cards, most recent first (`client.cards.list()`). */
|
|
85
91
|
declare function useCards(): AsyncState<Card[]>;
|
|
92
|
+
/**
|
|
93
|
+
* The cards the user can order, default product first
|
|
94
|
+
* (`client.cards.listProducts()`). Render each item's artwork through
|
|
95
|
+
* `client.assetUrl(product.design.image_url)`.
|
|
96
|
+
*/
|
|
97
|
+
declare function useCardProducts(): AsyncState<CardProduct[]>;
|
|
86
98
|
/**
|
|
87
99
|
* The user's wallet balance for one currency
|
|
88
100
|
* (`client.balance.get(currency)`). Re-fetches when `currency`
|
|
89
101
|
* changes.
|
|
90
102
|
*/
|
|
91
103
|
declare function useBalance(currency: string): AsyncState<Balance>;
|
|
104
|
+
interface UseNotificationsOptions {
|
|
105
|
+
/** Only unread items. */
|
|
106
|
+
unreadOnly?: boolean;
|
|
107
|
+
category?: NotificationCategory;
|
|
108
|
+
/** Page size. */
|
|
109
|
+
limit?: number;
|
|
110
|
+
}
|
|
111
|
+
interface NotificationsState extends AsyncState<NotificationPage> {
|
|
112
|
+
/** Mark one item read on the server and in `data` right away. */
|
|
113
|
+
markRead: (id: string) => Promise<InboxItem>;
|
|
114
|
+
/** Mark everything read on the server and in `data` right away. */
|
|
115
|
+
markAllRead: () => Promise<{
|
|
116
|
+
marked: number;
|
|
117
|
+
}>;
|
|
118
|
+
/** Fetch the next page (`data.next_cursor`) and append its items.
|
|
119
|
+
* Resolves at once when there is no next page or a load is running. */
|
|
120
|
+
loadMore: () => Promise<void>;
|
|
121
|
+
/** True while `loadMore` is in flight. */
|
|
122
|
+
loadingMore: boolean;
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* The user's inbox (`client.notifications.list(opts)`), newest first, with
|
|
126
|
+
* paging and read-state helpers. `data.items` grows as `loadMore` is
|
|
127
|
+
* called; `refetch` starts over from the first page.
|
|
128
|
+
*
|
|
129
|
+
* ```tsx
|
|
130
|
+
* const inbox = useNotifications({ limit: 20 });
|
|
131
|
+
* inbox.data?.items.map((n) => (
|
|
132
|
+
* <Row key={n.id} onClick={() => inbox.markRead(n.id)} unread={!n.read_at}>
|
|
133
|
+
* {n.title}
|
|
134
|
+
* </Row>
|
|
135
|
+
* ));
|
|
136
|
+
* ```
|
|
137
|
+
*/
|
|
138
|
+
declare function useNotifications(opts?: UseNotificationsOptions): NotificationsState;
|
|
139
|
+
interface UseUnreadCountOptions {
|
|
140
|
+
/** Re-fetch every this many milliseconds. Default 30000; `0` disables
|
|
141
|
+
* polling. */
|
|
142
|
+
pollMs?: number;
|
|
143
|
+
}
|
|
144
|
+
/** Message a service worker posts to open clients when a push arrives, so
|
|
145
|
+
* badges refresh without waiting for the next poll. */
|
|
146
|
+
declare const PUSH_MESSAGE_TYPE = "takeal:push";
|
|
147
|
+
/**
|
|
148
|
+
* Unread inbox items (`client.notifications.unreadCount()`) for a badge.
|
|
149
|
+
* Refreshes silently (no `loading` flip) on an interval and whenever the
|
|
150
|
+
* page's service worker posts `{ type: "takeal:push" }`, which your
|
|
151
|
+
* `push` handler should do for every open client.
|
|
152
|
+
*/
|
|
153
|
+
declare function useUnreadCount(opts?: UseUnreadCountOptions): AsyncState<number>;
|
|
92
154
|
|
|
93
|
-
export { type AsyncState, ClientProvider, type ClientProviderProps, useBalance, useCards, useClient, useDeposits, useMe };
|
|
155
|
+
export { type AsyncState, ClientProvider, type ClientProviderProps, type NotificationsState, PUSH_MESSAGE_TYPE, type UseNotificationsOptions, type UseUnreadCountOptions, useBalance, useCardProducts, useCards, useClient, useDeposits, useMe, useNotifications, useUnreadCount };
|
package/dist/react/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { createContext, createElement, useContext, useState,
|
|
1
|
+
import { createContext, createElement, useContext, useState, useRef, useEffect, useCallback } from 'react';
|
|
2
2
|
|
|
3
3
|
// src/react/context.ts
|
|
4
4
|
var ClientContext = createContext(null);
|
|
@@ -48,28 +48,151 @@ function useAsyncResource(fetcher, deps) {
|
|
|
48
48
|
controller.abort();
|
|
49
49
|
};
|
|
50
50
|
}, [...deps, nonce]);
|
|
51
|
+
return { data, error, loading, refetch, setData };
|
|
52
|
+
}
|
|
53
|
+
function publicState(state) {
|
|
54
|
+
const { data, error, loading, refetch } = state;
|
|
51
55
|
return { data, error, loading, refetch };
|
|
52
56
|
}
|
|
53
57
|
function useMe() {
|
|
54
58
|
const client = useClient();
|
|
55
|
-
return useAsyncResource(() => client.auth.me(), [client]);
|
|
59
|
+
return publicState(useAsyncResource(() => client.auth.me(), [client]));
|
|
56
60
|
}
|
|
57
61
|
function useDeposits() {
|
|
58
62
|
const client = useClient();
|
|
59
|
-
return useAsyncResource(() => client.deposits.list(), [client]);
|
|
63
|
+
return publicState(useAsyncResource(() => client.deposits.list(), [client]));
|
|
60
64
|
}
|
|
61
65
|
function useCards() {
|
|
62
66
|
const client = useClient();
|
|
63
|
-
return useAsyncResource(() => client.cards.list(), [client]);
|
|
67
|
+
return publicState(useAsyncResource(() => client.cards.list(), [client]));
|
|
68
|
+
}
|
|
69
|
+
function useCardProducts() {
|
|
70
|
+
const client = useClient();
|
|
71
|
+
return publicState(
|
|
72
|
+
useAsyncResource(() => client.cards.listProducts(), [client])
|
|
73
|
+
);
|
|
64
74
|
}
|
|
65
75
|
function useBalance(currency) {
|
|
66
76
|
const client = useClient();
|
|
67
|
-
return
|
|
68
|
-
() => client.balance.get(currency),
|
|
69
|
-
|
|
77
|
+
return publicState(
|
|
78
|
+
useAsyncResource(() => client.balance.get(currency), [client, currency])
|
|
79
|
+
);
|
|
80
|
+
}
|
|
81
|
+
function useNotifications(opts = {}) {
|
|
82
|
+
const client = useClient();
|
|
83
|
+
const { unreadOnly, category, limit } = opts;
|
|
84
|
+
const state = useAsyncResource(
|
|
85
|
+
() => client.notifications.list({
|
|
86
|
+
...unreadOnly !== void 0 ? { unreadOnly } : {},
|
|
87
|
+
...category !== void 0 ? { category } : {},
|
|
88
|
+
...limit !== void 0 ? { limit } : {}
|
|
89
|
+
}),
|
|
90
|
+
[client, unreadOnly, category, limit]
|
|
91
|
+
);
|
|
92
|
+
const { setData } = state;
|
|
93
|
+
const [loadingMore, setLoadingMore] = useState(false);
|
|
94
|
+
const cursorRef = useRef(null);
|
|
95
|
+
cursorRef.current = state.data?.next_cursor ?? null;
|
|
96
|
+
const mounted = useRef(true);
|
|
97
|
+
useEffect(() => {
|
|
98
|
+
mounted.current = true;
|
|
99
|
+
return () => {
|
|
100
|
+
mounted.current = false;
|
|
101
|
+
};
|
|
102
|
+
}, []);
|
|
103
|
+
const markRead = useCallback(
|
|
104
|
+
async (id) => {
|
|
105
|
+
const item = await client.notifications.markRead(id);
|
|
106
|
+
if (mounted.current) {
|
|
107
|
+
setData((prev) => {
|
|
108
|
+
if (!prev) return prev;
|
|
109
|
+
const wasUnread = prev.items.some((n) => n.id === id && n.read_at === null);
|
|
110
|
+
return {
|
|
111
|
+
...prev,
|
|
112
|
+
items: prev.items.map((n) => n.id === id ? item : n),
|
|
113
|
+
unread_count: Math.max(0, prev.unread_count - (wasUnread ? 1 : 0))
|
|
114
|
+
};
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
return item;
|
|
118
|
+
},
|
|
119
|
+
[client, setData]
|
|
70
120
|
);
|
|
121
|
+
const markAllRead = useCallback(async () => {
|
|
122
|
+
const out = await client.notifications.markAllRead();
|
|
123
|
+
if (mounted.current) {
|
|
124
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
125
|
+
setData(
|
|
126
|
+
(prev) => prev ? {
|
|
127
|
+
...prev,
|
|
128
|
+
items: prev.items.map((n) => n.read_at === null ? { ...n, read_at: now } : n),
|
|
129
|
+
unread_count: 0
|
|
130
|
+
} : prev
|
|
131
|
+
);
|
|
132
|
+
}
|
|
133
|
+
return out;
|
|
134
|
+
}, [client, setData]);
|
|
135
|
+
const loadMore = useCallback(async () => {
|
|
136
|
+
const cursor = cursorRef.current;
|
|
137
|
+
if (!cursor || loadingMore) return;
|
|
138
|
+
setLoadingMore(true);
|
|
139
|
+
try {
|
|
140
|
+
const page = await client.notifications.list({
|
|
141
|
+
cursor,
|
|
142
|
+
...unreadOnly !== void 0 ? { unreadOnly } : {},
|
|
143
|
+
...category !== void 0 ? { category } : {},
|
|
144
|
+
...limit !== void 0 ? { limit } : {}
|
|
145
|
+
});
|
|
146
|
+
if (!mounted.current) return;
|
|
147
|
+
setData(
|
|
148
|
+
(prev) => prev ? {
|
|
149
|
+
items: [...prev.items, ...page.items],
|
|
150
|
+
next_cursor: page.next_cursor,
|
|
151
|
+
unread_count: page.unread_count
|
|
152
|
+
} : page
|
|
153
|
+
);
|
|
154
|
+
} finally {
|
|
155
|
+
if (mounted.current) setLoadingMore(false);
|
|
156
|
+
}
|
|
157
|
+
}, [client, setData, unreadOnly, category, limit, loadingMore]);
|
|
158
|
+
return { ...publicState(state), markRead, markAllRead, loadMore, loadingMore };
|
|
159
|
+
}
|
|
160
|
+
var PUSH_MESSAGE_TYPE = "takeal:push";
|
|
161
|
+
function useUnreadCount(opts = {}) {
|
|
162
|
+
const client = useClient();
|
|
163
|
+
const pollMs = opts.pollMs ?? 3e4;
|
|
164
|
+
const state = useAsyncResource(() => client.notifications.unreadCount(), [client]);
|
|
165
|
+
const { setData } = state;
|
|
166
|
+
useEffect(() => {
|
|
167
|
+
let cancelled = false;
|
|
168
|
+
const refresh = () => {
|
|
169
|
+
client.notifications.unreadCount().then((n) => {
|
|
170
|
+
if (!cancelled) setData(n);
|
|
171
|
+
}).catch(() => {
|
|
172
|
+
});
|
|
173
|
+
};
|
|
174
|
+
const timer = pollMs > 0 ? setInterval(refresh, pollMs) : void 0;
|
|
175
|
+
const sw = serviceWorkerContainer();
|
|
176
|
+
const onMessage = (event) => {
|
|
177
|
+
const data = event.data;
|
|
178
|
+
if (data && data.type === PUSH_MESSAGE_TYPE) refresh();
|
|
179
|
+
};
|
|
180
|
+
sw?.addEventListener("message", onMessage);
|
|
181
|
+
return () => {
|
|
182
|
+
cancelled = true;
|
|
183
|
+
if (timer !== void 0) clearInterval(timer);
|
|
184
|
+
sw?.removeEventListener("message", onMessage);
|
|
185
|
+
};
|
|
186
|
+
}, [client, pollMs, setData]);
|
|
187
|
+
return publicState(state);
|
|
188
|
+
}
|
|
189
|
+
function serviceWorkerContainer() {
|
|
190
|
+
const nav = globalThis.navigator;
|
|
191
|
+
const sw = nav?.serviceWorker;
|
|
192
|
+
if (!sw || typeof sw.addEventListener !== "function") return null;
|
|
193
|
+
return sw;
|
|
71
194
|
}
|
|
72
195
|
|
|
73
|
-
export { ClientProvider, useBalance, useCards, useClient, useDeposits, useMe };
|
|
196
|
+
export { ClientProvider, PUSH_MESSAGE_TYPE, useBalance, useCardProducts, useCards, useClient, useDeposits, useMe, useNotifications, useUnreadCount };
|
|
74
197
|
//# sourceMappingURL=index.js.map
|
|
75
198
|
//# sourceMappingURL=index.js.map
|
package/dist/react/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
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;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,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;ACVA,SAAS,gBAAA,CACP,SACA,IAAA,EACe;AACf,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,SAAkB,IAAI,CAAA;AAGpD,EAAA,MAAM,CAAC,KAAA,EAAO,QAAQ,CAAA,GAAI,SAAS,CAAC,CAAA;AAEpC,EAAA,MAAM,OAAA,GAAU,YAAY,YAAY;AACtC,IAAA,QAAA,CAAS,CAAC,CAAA,KAAM,CAAA,GAAI,CAAC,CAAA;AAAA,EACvB,CAAA,EAAG,EAAE,CAAA;AAEL,EAAA,SAAA,CAAU,MAAM;AACd,IAAA,IAAI,SAAA,GAAY,KAAA;AAChB,IAAA,MAAM,UAAA,GAAa,IAAI,eAAA,EAAgB;AAEvC,IAAA,UAAA,CAAW,IAAI,CA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AAM,CAAC,CAAA;AACrE;AAOO,SAAS,WAAW,QAAA,EAAuC;AAChE,EAAA,MAAM,SAAS,SAAA,EAAU;AACzB,EAAA,OAAO,gBAAA;AAAA,IACL,MAAM,MAAA,CAAO,OAAA,CAAQ,GAAA,CAAI,QAAQ,CAAA;AAAA,IACjC,CAAC,QAAQ,QAAQ;AAAA,GACnB;AACF","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, 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 } from \"../resources/cards.js\";\nimport type { Balance } from \"../resources/balance.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 */\nfunction useAsyncResource<T>(\n fetcher: (signal: AbortSignal) => Promise<T>,\n deps: ReadonlyArray<unknown>,\n): AsyncState<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 };\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 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 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 useAsyncResource<Card[]>(() => client.cards.list(), [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 useAsyncResource<Balance>(\n () => client.balance.get(currency),\n [client, currency],\n );\n}\n"]}
|
|
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,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.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"]}
|
package/dist/resources/auth.cjs
CHANGED
|
@@ -1,5 +1,10 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
+
// src/error.ts
|
|
4
|
+
function isApiError(e) {
|
|
5
|
+
return typeof e === "object" && e !== null && e.isApiError === true;
|
|
6
|
+
}
|
|
7
|
+
|
|
3
8
|
// src/resources/auth.ts
|
|
4
9
|
var AuthResource = class {
|
|
5
10
|
constructor(http, tokens) {
|
|
@@ -38,6 +43,40 @@ var AuthResource = class {
|
|
|
38
43
|
await Promise.resolve(this.tokens.set(resp.access_token));
|
|
39
44
|
return resp;
|
|
40
45
|
}
|
|
46
|
+
/** Create an end-user account and sign it in. The JWT is stored.
|
|
47
|
+
* `wallet_currency` must be one the deployment offers; omit it to take
|
|
48
|
+
* the deployment default (it can be switched later via `client.wallet`
|
|
49
|
+
* while the wallet is empty).
|
|
50
|
+
* Errors: 400 `validation` / `currency_not_allowed`, 409 email taken. */
|
|
51
|
+
async register(input) {
|
|
52
|
+
const resp = await this.http.post("/auth/register", {
|
|
53
|
+
body: input,
|
|
54
|
+
skipAuth: true
|
|
55
|
+
});
|
|
56
|
+
await Promise.resolve(this.tokens.set(resp.access_token));
|
|
57
|
+
return resp;
|
|
58
|
+
}
|
|
59
|
+
/** Finish a `totp_setup_required` login: send the first code from the
|
|
60
|
+
* authenticator app. The JWT is stored. The response carries ten
|
|
61
|
+
* one-time `backup_codes` that are never returned again, so show them to
|
|
62
|
+
* the user right away and don't keep them on the device. */
|
|
63
|
+
async completeTotpSetup(input) {
|
|
64
|
+
const resp = await this.http.post("/auth/login/totp-setup", {
|
|
65
|
+
body: input,
|
|
66
|
+
skipAuth: true
|
|
67
|
+
});
|
|
68
|
+
await Promise.resolve(this.tokens.set(resp.access_token));
|
|
69
|
+
return resp;
|
|
70
|
+
}
|
|
71
|
+
/** Change the signed-in user's password. Every other session of the
|
|
72
|
+
* account is signed out; this one stays valid.
|
|
73
|
+
* Errors: 400 when the new password fails the policy, 401 when the
|
|
74
|
+
* current one is wrong. */
|
|
75
|
+
async changePassword(input) {
|
|
76
|
+
return this.http.post("/auth/password", {
|
|
77
|
+
body: input
|
|
78
|
+
});
|
|
79
|
+
}
|
|
41
80
|
/** Swap the 2FA method mid-flow. Resolves to `otp_sent` for
|
|
42
81
|
* telegram/email; for TOTP it short-circuits back to the challenge. */
|
|
43
82
|
async switchMethod(input) {
|
|
@@ -46,18 +85,38 @@ var AuthResource = class {
|
|
|
46
85
|
skipAuth: true
|
|
47
86
|
});
|
|
48
87
|
}
|
|
49
|
-
/** Exchange a signed Telegram Mini App `initData` payload for a session
|
|
50
|
-
* JWT. The server validates the initData HMAC against the deployment's bot
|
|
51
|
-
* token, then find-or-creates the end-user. First-time Telegram users are
|
|
52
|
-
* auto-provisioned with `user.email_pending === true` — prompt them for a
|
|
53
|
-
* real email and call {@link linkEmail}. Stores the JWT on success.
|
|
54
|
-
*
|
|
55
|
-
* Most consumers use the higher-level `fromInitData` / `fromTelegramWebApp`
|
|
56
|
-
* helpers in `@takeal/cusfront-sdk/telegram`; reach for this directly when
|
|
57
|
-
* you already hold a configured client. */
|
|
58
88
|
async exchangeTelegram(input) {
|
|
59
|
-
const
|
|
60
|
-
|
|
89
|
+
const body = { init_data: input.initData };
|
|
90
|
+
if (input.provision !== void 0) body.provision = input.provision;
|
|
91
|
+
let resp;
|
|
92
|
+
try {
|
|
93
|
+
resp = await this.http.post("/auth/telegram/exchange", {
|
|
94
|
+
body,
|
|
95
|
+
skipAuth: true
|
|
96
|
+
});
|
|
97
|
+
} catch (e) {
|
|
98
|
+
if (isApiError(e) && e.status === 404 && e.code === "telegram_unknown") {
|
|
99
|
+
return { stage: "unknown" };
|
|
100
|
+
}
|
|
101
|
+
throw e;
|
|
102
|
+
}
|
|
103
|
+
await Promise.resolve(this.tokens.set(resp.access_token));
|
|
104
|
+
return resp;
|
|
105
|
+
}
|
|
106
|
+
/** Attach the Telegram account behind `initData` to an existing email +
|
|
107
|
+
* password account and sign in as that account. No bearer needed; the
|
|
108
|
+
* password is checked the same way `login` checks it. The JWT is stored.
|
|
109
|
+
*
|
|
110
|
+
* Errors: 401 `unauthenticated` (wrong email or password, as with
|
|
111
|
+
* `login`) / `invalid_init_data`; 403
|
|
112
|
+
* `user_disabled` / `second_factor_required` (accounts that sign in with
|
|
113
|
+
* a second factor can't be linked from a Mini App); 409
|
|
114
|
+
* `telegram_already_linked_other` (this account already has a different
|
|
115
|
+
* Telegram; unlink it first) / `telegram_in_use` (this Telegram belongs to
|
|
116
|
+
* another account); 503 `telegram_not_configured`. */
|
|
117
|
+
async linkTelegram(input) {
|
|
118
|
+
const resp = await this.http.post("/auth/telegram/link", {
|
|
119
|
+
body: { init_data: input.initData, email: input.email, password: input.password },
|
|
61
120
|
skipAuth: true
|
|
62
121
|
});
|
|
63
122
|
await Promise.resolve(this.tokens.set(resp.access_token));
|
|
@@ -74,10 +133,9 @@ var AuthResource = class {
|
|
|
74
133
|
async me() {
|
|
75
134
|
return this.http.get("/auth/me");
|
|
76
135
|
}
|
|
77
|
-
/** Local sign-out.
|
|
78
|
-
*
|
|
79
|
-
*
|
|
80
|
-
* with a future session table. */
|
|
136
|
+
/** Local sign-out: forgets the stored JWT. To end the session on the
|
|
137
|
+
* server as well, revoke it first with `client.sessions.revoke(jti)`
|
|
138
|
+
* (the current one is marked `current: true` in `client.sessions.list()`). */
|
|
81
139
|
async signOut() {
|
|
82
140
|
await Promise.resolve(this.tokens.clear());
|
|
83
141
|
}
|