@kheopskit/react 5.1.0 → 5.1.1

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/dist/index.d.mts CHANGED
@@ -1,10 +1,9 @@
1
- import * as _kheopskit_core from '@kheopskit/core';
2
- import { KheopskitPlatform, KheopskitConfig, KheopskitState } from '@kheopskit/core';
3
- import { FC, PropsWithChildren } from 'react';
4
-
1
+ import { KheopskitConfig, KheopskitPlatform, KheopskitState as KheopskitState$1 } from "@kheopskit/core";
2
+ import { FC, PropsWithChildren } from "react";
3
+ //#region src/createKheopskit.d.ts
5
4
  type CreateKheopskitConfig<P extends readonly KheopskitPlatform[]> = Omit<Partial<KheopskitConfig<P>>, "platforms"> & {
6
- /** Platform plugins, e.g. `[polkadot(), solana()]`. Required. */
7
- platforms: P;
5
+ /** Platform plugins, e.g. `[polkadot(), solana()]`. Required. */
6
+ platforms: P;
8
7
  };
9
8
  /**
10
9
  * Binds a platform tuple once and returns a `KheopskitProvider` plus hooks
@@ -23,55 +22,58 @@ type CreateKheopskitConfig<P extends readonly KheopskitPlatform[]> = Omit<Partia
23
22
  * ```
24
23
  */
25
24
  declare const createKheopskit: <const P extends readonly [KheopskitPlatform, ...KheopskitPlatform[]]>(config: CreateKheopskitConfig<P>) => {
26
- KheopskitProvider: FC<PropsWithChildren<{
27
- ssrCookies?: string;
28
- }>>;
29
- /** Current state, typed to the bound platform tuple. */
30
- useWallets: () => _kheopskit_core.KheopskitState<P>;
31
- /** Current accounts, typed to the bound platform tuple. */
32
- useAccounts: () => _kheopskit_core.AccountOf<P[number]>[];
25
+ KheopskitProvider: FC<PropsWithChildren<{
26
+ ssrCookies?: string;
27
+ }>>;
28
+ /** Current state, typed to the bound platform tuple. */
29
+ useWallets: () => KheopskitState<P_1>;
30
+ /** Current accounts, typed to the bound platform tuple. */
31
+ useAccounts: () => any;
33
32
  };
34
-
33
+ //#endregion
34
+ //#region src/KheopskitProvider.d.ts
35
35
  type KheopskitProviderProps = PropsWithChildren & {
36
- /**
37
- * Kheopskit configuration.
38
- *
39
- * @remarks
40
- * Must be a **referentially stable** value — define it once (module scope, a
41
- * `useMemo`, or via {@link createKheopskit}) and pass the same reference. A
42
- * new object literal on every render (`config={{ platforms: [...] }}` inline)
43
- * recreates the underlying store and re-subscribes each render.
44
- */
45
- config?: Partial<KheopskitConfig>;
46
- /**
47
- * Cookie string for SSR hydration.
48
- * Pass the request cookie header (e.g., from Next.js headers or TanStack Start)
49
- * to hydrate wallet state on the server.
50
- *
51
- * @remarks
52
- * This value should be stable per render to avoid unnecessary store recreation.
53
- * Compute it once in your server component or layout and pass it down.
54
- *
55
- * @example
56
- * ```tsx
57
- * // Next.js App Router
58
- * const cookieStore = await cookies();
59
- * const ssrCookies = cookieStore.getAll().map(c => `${c.name}=${c.value}`).join('; ');
60
- * return <Providers ssrCookies={ssrCookies}>{children}</Providers>
61
- * ```
62
- */
63
- ssrCookies?: string;
36
+ /**
37
+ * Kheopskit configuration.
38
+ *
39
+ * @remarks
40
+ * Must be a **referentially stable** value — define it once (module scope, a
41
+ * `useMemo`, or via {@link createKheopskit}) and pass the same reference. A
42
+ * new object literal on every render (`config={{ platforms: [...] }}` inline)
43
+ * recreates the underlying store and re-subscribes each render.
44
+ */
45
+ config?: Partial<KheopskitConfig>;
46
+ /**
47
+ * Cookie string for SSR hydration.
48
+ * Pass the request cookie header (e.g., from Next.js headers or TanStack Start)
49
+ * to hydrate wallet state on the server.
50
+ *
51
+ * @remarks
52
+ * This value should be stable per render to avoid unnecessary store recreation.
53
+ * Compute it once in your server component or layout and pass it down.
54
+ *
55
+ * @example
56
+ * ```tsx
57
+ * // Next.js App Router
58
+ * const cookieStore = await cookies();
59
+ * const ssrCookies = cookieStore.getAll().map(c => `${c.name}=${c.value}`).join('; ');
60
+ * return <Providers ssrCookies={ssrCookies}>{children}</Providers>
61
+ * ```
62
+ */
63
+ ssrCookies?: string;
64
64
  };
65
65
  declare const KheopskitProvider: FC<KheopskitProviderProps>;
66
-
66
+ //#endregion
67
+ //#region src/useAccounts.d.ts
67
68
  /**
68
69
  * Convenience hook returning just the accounts from kheopskit state. Pass the
69
70
  * platform tuple as a type argument to recover SDK-precise account types —
70
71
  * `useAccounts<typeof platforms>()` — or use the pre-typed hook from
71
72
  * {@link createKheopskit}.
72
73
  */
73
- declare const useAccounts: <P extends readonly KheopskitPlatform[] = readonly KheopskitPlatform[]>() => _kheopskit_core.AccountOf<P[number]>[];
74
-
74
+ declare const useAccounts: <P extends readonly KheopskitPlatform[] = readonly KheopskitPlatform[]>() => any;
75
+ //#endregion
76
+ //#region src/useWallets.d.ts
75
77
  /**
76
78
  * Returns the current kheopskit state (wallets, accounts, config, isHydrating).
77
79
  *
@@ -80,6 +82,7 @@ declare const useAccounts: <P extends readonly KheopskitPlatform[] = readonly Kh
80
82
  * generic, so without the argument the state is typed with the base
81
83
  * (SDK-free) wallet/account shapes.
82
84
  */
83
- declare const useWallets: <P extends readonly KheopskitPlatform[] = readonly KheopskitPlatform[]>() => KheopskitState<P>;
84
-
85
- export { type CreateKheopskitConfig, KheopskitProvider, type KheopskitProviderProps, createKheopskit, useAccounts, useWallets };
85
+ declare const useWallets: <P extends readonly KheopskitPlatform[] = readonly KheopskitPlatform[]>() => KheopskitState$1<P>;
86
+ //#endregion
87
+ export { CreateKheopskitConfig, KheopskitProvider, KheopskitProviderProps, createKheopskit, useAccounts, useWallets };
88
+ //# sourceMappingURL=index.d.mts.map
package/dist/index.d.ts CHANGED
@@ -1,10 +1,9 @@
1
- import * as _kheopskit_core from '@kheopskit/core';
2
- import { KheopskitPlatform, KheopskitConfig, KheopskitState } from '@kheopskit/core';
3
- import { FC, PropsWithChildren } from 'react';
4
-
1
+ import { KheopskitConfig, KheopskitPlatform, KheopskitState as KheopskitState$1 } from "@kheopskit/core";
2
+ import { FC, PropsWithChildren } from "react";
3
+ //#region src/createKheopskit.d.ts
5
4
  type CreateKheopskitConfig<P extends readonly KheopskitPlatform[]> = Omit<Partial<KheopskitConfig<P>>, "platforms"> & {
6
- /** Platform plugins, e.g. `[polkadot(), solana()]`. Required. */
7
- platforms: P;
5
+ /** Platform plugins, e.g. `[polkadot(), solana()]`. Required. */
6
+ platforms: P;
8
7
  };
9
8
  /**
10
9
  * Binds a platform tuple once and returns a `KheopskitProvider` plus hooks
@@ -23,55 +22,58 @@ type CreateKheopskitConfig<P extends readonly KheopskitPlatform[]> = Omit<Partia
23
22
  * ```
24
23
  */
25
24
  declare const createKheopskit: <const P extends readonly [KheopskitPlatform, ...KheopskitPlatform[]]>(config: CreateKheopskitConfig<P>) => {
26
- KheopskitProvider: FC<PropsWithChildren<{
27
- ssrCookies?: string;
28
- }>>;
29
- /** Current state, typed to the bound platform tuple. */
30
- useWallets: () => _kheopskit_core.KheopskitState<P>;
31
- /** Current accounts, typed to the bound platform tuple. */
32
- useAccounts: () => _kheopskit_core.AccountOf<P[number]>[];
25
+ KheopskitProvider: FC<PropsWithChildren<{
26
+ ssrCookies?: string;
27
+ }>>;
28
+ /** Current state, typed to the bound platform tuple. */
29
+ useWallets: () => KheopskitState<P_1>;
30
+ /** Current accounts, typed to the bound platform tuple. */
31
+ useAccounts: () => any;
33
32
  };
34
-
33
+ //#endregion
34
+ //#region src/KheopskitProvider.d.ts
35
35
  type KheopskitProviderProps = PropsWithChildren & {
36
- /**
37
- * Kheopskit configuration.
38
- *
39
- * @remarks
40
- * Must be a **referentially stable** value — define it once (module scope, a
41
- * `useMemo`, or via {@link createKheopskit}) and pass the same reference. A
42
- * new object literal on every render (`config={{ platforms: [...] }}` inline)
43
- * recreates the underlying store and re-subscribes each render.
44
- */
45
- config?: Partial<KheopskitConfig>;
46
- /**
47
- * Cookie string for SSR hydration.
48
- * Pass the request cookie header (e.g., from Next.js headers or TanStack Start)
49
- * to hydrate wallet state on the server.
50
- *
51
- * @remarks
52
- * This value should be stable per render to avoid unnecessary store recreation.
53
- * Compute it once in your server component or layout and pass it down.
54
- *
55
- * @example
56
- * ```tsx
57
- * // Next.js App Router
58
- * const cookieStore = await cookies();
59
- * const ssrCookies = cookieStore.getAll().map(c => `${c.name}=${c.value}`).join('; ');
60
- * return <Providers ssrCookies={ssrCookies}>{children}</Providers>
61
- * ```
62
- */
63
- ssrCookies?: string;
36
+ /**
37
+ * Kheopskit configuration.
38
+ *
39
+ * @remarks
40
+ * Must be a **referentially stable** value — define it once (module scope, a
41
+ * `useMemo`, or via {@link createKheopskit}) and pass the same reference. A
42
+ * new object literal on every render (`config={{ platforms: [...] }}` inline)
43
+ * recreates the underlying store and re-subscribes each render.
44
+ */
45
+ config?: Partial<KheopskitConfig>;
46
+ /**
47
+ * Cookie string for SSR hydration.
48
+ * Pass the request cookie header (e.g., from Next.js headers or TanStack Start)
49
+ * to hydrate wallet state on the server.
50
+ *
51
+ * @remarks
52
+ * This value should be stable per render to avoid unnecessary store recreation.
53
+ * Compute it once in your server component or layout and pass it down.
54
+ *
55
+ * @example
56
+ * ```tsx
57
+ * // Next.js App Router
58
+ * const cookieStore = await cookies();
59
+ * const ssrCookies = cookieStore.getAll().map(c => `${c.name}=${c.value}`).join('; ');
60
+ * return <Providers ssrCookies={ssrCookies}>{children}</Providers>
61
+ * ```
62
+ */
63
+ ssrCookies?: string;
64
64
  };
65
65
  declare const KheopskitProvider: FC<KheopskitProviderProps>;
66
-
66
+ //#endregion
67
+ //#region src/useAccounts.d.ts
67
68
  /**
68
69
  * Convenience hook returning just the accounts from kheopskit state. Pass the
69
70
  * platform tuple as a type argument to recover SDK-precise account types —
70
71
  * `useAccounts<typeof platforms>()` — or use the pre-typed hook from
71
72
  * {@link createKheopskit}.
72
73
  */
73
- declare const useAccounts: <P extends readonly KheopskitPlatform[] = readonly KheopskitPlatform[]>() => _kheopskit_core.AccountOf<P[number]>[];
74
-
74
+ declare const useAccounts: <P extends readonly KheopskitPlatform[] = readonly KheopskitPlatform[]>() => any;
75
+ //#endregion
76
+ //#region src/useWallets.d.ts
75
77
  /**
76
78
  * Returns the current kheopskit state (wallets, accounts, config, isHydrating).
77
79
  *
@@ -80,6 +82,7 @@ declare const useAccounts: <P extends readonly KheopskitPlatform[] = readonly Kh
80
82
  * generic, so without the argument the state is typed with the base
81
83
  * (SDK-free) wallet/account shapes.
82
84
  */
83
- declare const useWallets: <P extends readonly KheopskitPlatform[] = readonly KheopskitPlatform[]>() => KheopskitState<P>;
84
-
85
- export { type CreateKheopskitConfig, KheopskitProvider, type KheopskitProviderProps, createKheopskit, useAccounts, useWallets };
85
+ declare const useWallets: <P extends readonly KheopskitPlatform[] = readonly KheopskitPlatform[]>() => KheopskitState$1<P>;
86
+ //#endregion
87
+ export { CreateKheopskitConfig, KheopskitProvider, KheopskitProviderProps, createKheopskit, useAccounts, useWallets };
88
+ //# sourceMappingURL=index.d.ts.map
package/dist/index.js CHANGED
@@ -1,186 +1,174 @@
1
1
  "use client";
2
- "use strict";
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __hasOwnProp = Object.prototype.hasOwnProperty;
7
- var __export = (target, all) => {
8
- for (var name in all)
9
- __defProp(target, name, { get: all[name], enumerable: true });
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ let _kheopskit_core = require("@kheopskit/core");
4
+ let react = require("react");
5
+ let react_jsx_runtime = require("react/jsx-runtime");
6
+ //#region src/context.ts
7
+ const KheopskitContext = (0, react.createContext)(null);
8
+ //#endregion
9
+ //#region src/createExternalStore.ts
10
+ const createExternalStore = (observable$, initialValue, serverValue) => {
11
+ let latestValue = null;
12
+ let subscription = null;
13
+ let subscriberCount = 0;
14
+ const listeners = /* @__PURE__ */ new Set();
15
+ const ensureSubscription = () => {
16
+ if (!subscription || subscription.closed) subscription = observable$.subscribe((value) => {
17
+ latestValue = value;
18
+ for (const listener of listeners) listener(value);
19
+ });
20
+ };
21
+ const getSnapshot = () => latestValue ?? initialValue;
22
+ /**
23
+ * Returns the server-side snapshot for SSR hydration.
24
+ * This prevents hydration mismatches by providing a consistent
25
+ * value during server rendering. Must return the same value as
26
+ * what the server rendered.
27
+ */
28
+ const getServerSnapshot = () => serverValue ?? initialValue;
29
+ const subscribe = (callback) => {
30
+ subscriberCount++;
31
+ ensureSubscription();
32
+ listeners.add(callback);
33
+ callback(getSnapshot());
34
+ return () => {
35
+ subscriberCount--;
36
+ listeners.delete(callback);
37
+ };
38
+ };
39
+ const destroy = () => {
40
+ if (subscriberCount === 0 && subscription) {
41
+ subscription.unsubscribe();
42
+ subscription = null;
43
+ }
44
+ };
45
+ return {
46
+ getSnapshot,
47
+ getServerSnapshot,
48
+ subscribe,
49
+ destroy
50
+ };
10
51
  };
11
- var __copyProps = (to, from, except, desc) => {
12
- if (from && typeof from === "object" || typeof from === "function") {
13
- for (let key of __getOwnPropNames(from))
14
- if (!__hasOwnProp.call(to, key) && key !== except)
15
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
- }
17
- return to;
52
+ //#endregion
53
+ //#region src/KheopskitProvider.tsx
54
+ const KheopskitProvider = ({ children, config, ssrCookies }) => {
55
+ const resolvedConfig = (0, react.useMemo)(() => (0, _kheopskit_core.resolveConfig)(config), [config]);
56
+ const lastConfigRef = (0, react.useRef)(config);
57
+ const hasMountedRef = (0, react.useRef)(false);
58
+ (0, react.useEffect)(() => {
59
+ if (hasMountedRef.current && lastConfigRef.current !== config && (typeof process === "undefined" || process.env?.NODE_ENV !== "production")) console.warn("[kheopskit] KheopskitProvider received a new `config` reference; this recreates the store and re-subscribes on every render. Pass a referentially stable config (module scope, useMemo, or createKheopskit()).");
60
+ hasMountedRef.current = true;
61
+ lastConfigRef.current = config;
62
+ }, [config]);
63
+ const kheopskitStore = (0, react.useMemo)(() => (0, _kheopskit_core.createKheopskitStore)({
64
+ ssrCookies,
65
+ storageKey: resolvedConfig.storageKey
66
+ }), [ssrCookies, resolvedConfig.storageKey]);
67
+ const serverValue = (0, react.useMemo)(() => {
68
+ if (ssrCookies === void 0) return {
69
+ wallets: [],
70
+ accounts: [],
71
+ config: resolvedConfig,
72
+ isHydrating: true
73
+ };
74
+ return {
75
+ ...(0, _kheopskit_core.getHydratedSnapshot)(kheopskitStore, resolvedConfig.platforms),
76
+ config: resolvedConfig,
77
+ isHydrating: true
78
+ };
79
+ }, [
80
+ ssrCookies,
81
+ kheopskitStore,
82
+ resolvedConfig
83
+ ]);
84
+ const initialValue = (0, react.useMemo)(() => {
85
+ return {
86
+ ...(0, _kheopskit_core.getHydratedSnapshot)(kheopskitStore, resolvedConfig.platforms, { icons: true }),
87
+ config: resolvedConfig,
88
+ isHydrating: true
89
+ };
90
+ }, [kheopskitStore, resolvedConfig]);
91
+ const store = (0, react.useMemo)(() => createExternalStore((0, _kheopskit_core.getKheopskit$)(config, {
92
+ ssrCookies,
93
+ store: kheopskitStore
94
+ }), initialValue, serverValue), [
95
+ config,
96
+ ssrCookies,
97
+ kheopskitStore,
98
+ initialValue,
99
+ serverValue
100
+ ]);
101
+ (0, react.useEffect)(() => {
102
+ return () => store.destroy();
103
+ }, [store]);
104
+ const state = (0, react.useSyncExternalStore)(store.subscribe, store.getSnapshot, store.getServerSnapshot);
105
+ const value = (0, react.useMemo)(() => ({ state }), [state]);
106
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(KheopskitContext.Provider, {
107
+ value,
108
+ children
109
+ });
18
110
  };
19
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
20
-
21
- // src/index.ts
22
- var index_exports = {};
23
- __export(index_exports, {
24
- KheopskitProvider: () => KheopskitProvider,
25
- createKheopskit: () => createKheopskit,
26
- useAccounts: () => useAccounts,
27
- useWallets: () => useWallets
28
- });
29
- module.exports = __toCommonJS(index_exports);
30
-
31
- // src/KheopskitProvider.tsx
32
- var import_core = require("@kheopskit/core");
33
- var import_react2 = require("react");
34
-
35
- // src/context.ts
36
- var import_react = require("react");
37
- var KheopskitContext = (0, import_react.createContext)(null);
38
-
39
- // src/createExternalStore.ts
40
- var createExternalStore = (observable$, initialValue, serverValue) => {
41
- let latestValue = null;
42
- let subscription = null;
43
- let subscriberCount = 0;
44
- const listeners = /* @__PURE__ */ new Set();
45
- const ensureSubscription = () => {
46
- if (!subscription || subscription.closed) {
47
- subscription = observable$.subscribe((value) => {
48
- latestValue = value;
49
- for (const listener of listeners) {
50
- listener(value);
51
- }
52
- });
53
- }
54
- };
55
- const getSnapshot = () => latestValue ?? initialValue;
56
- const getServerSnapshot = () => serverValue ?? initialValue;
57
- const subscribe = (callback) => {
58
- subscriberCount++;
59
- ensureSubscription();
60
- listeners.add(callback);
61
- callback(getSnapshot());
62
- return () => {
63
- subscriberCount--;
64
- listeners.delete(callback);
65
- };
66
- };
67
- const destroy = () => {
68
- if (subscriberCount === 0 && subscription) {
69
- subscription.unsubscribe();
70
- subscription = null;
71
- }
72
- };
73
- return {
74
- getSnapshot,
75
- getServerSnapshot,
76
- subscribe,
77
- destroy
78
- };
111
+ //#endregion
112
+ //#region src/useWallets.ts
113
+ /**
114
+ * Returns the current kheopskit state (wallets, accounts, config, isHydrating).
115
+ *
116
+ * Pass the platform tuple as a type argument to recover SDK-precise account and
117
+ * wallet types — `useWallets<typeof platforms>()`. React contexts can't be
118
+ * generic, so without the argument the state is typed with the base
119
+ * (SDK-free) wallet/account shapes.
120
+ */
121
+ const useWallets = () => {
122
+ const ctx = (0, react.useContext)(KheopskitContext);
123
+ if (!ctx) throw new Error("useWallets can't be used without a KheopskitProvider");
124
+ return ctx.state;
79
125
  };
80
-
81
- // src/KheopskitProvider.tsx
82
- var import_jsx_runtime = require("react/jsx-runtime");
83
- var KheopskitProvider = ({
84
- children,
85
- config,
86
- ssrCookies
87
- }) => {
88
- const resolvedConfig = (0, import_react2.useMemo)(() => (0, import_core.resolveConfig)(config), [config]);
89
- const lastConfigRef = (0, import_react2.useRef)(config);
90
- const hasMountedRef = (0, import_react2.useRef)(false);
91
- (0, import_react2.useEffect)(() => {
92
- if (hasMountedRef.current && lastConfigRef.current !== config && (typeof process === "undefined" || process.env?.NODE_ENV !== "production")) {
93
- console.warn(
94
- "[kheopskit] KheopskitProvider received a new `config` reference; this recreates the store and re-subscribes on every render. Pass a referentially stable config (module scope, useMemo, or createKheopskit())."
95
- );
96
- }
97
- hasMountedRef.current = true;
98
- lastConfigRef.current = config;
99
- }, [config]);
100
- const kheopskitStore = (0, import_react2.useMemo)(
101
- () => (0, import_core.createKheopskitStore)({
102
- ssrCookies,
103
- storageKey: resolvedConfig.storageKey
104
- }),
105
- [ssrCookies, resolvedConfig.storageKey]
106
- );
107
- const serverValue = (0, import_react2.useMemo)(() => {
108
- if (ssrCookies === void 0) {
109
- return {
110
- wallets: [],
111
- accounts: [],
112
- config: resolvedConfig,
113
- isHydrating: true
114
- };
115
- }
116
- return {
117
- ...(0, import_core.getHydratedSnapshot)(kheopskitStore, resolvedConfig.platforms),
118
- config: resolvedConfig,
119
- isHydrating: true
120
- };
121
- }, [ssrCookies, kheopskitStore, resolvedConfig]);
122
- const initialValue = (0, import_react2.useMemo)(() => {
123
- return {
124
- ...(0, import_core.getHydratedSnapshot)(kheopskitStore, resolvedConfig.platforms, {
125
- icons: true
126
- }),
127
- config: resolvedConfig,
128
- isHydrating: true
129
- };
130
- }, [kheopskitStore, resolvedConfig]);
131
- const store = (0, import_react2.useMemo)(
132
- () => createExternalStore(
133
- (0, import_core.getKheopskit$)(config, { ssrCookies, store: kheopskitStore }),
134
- initialValue,
135
- serverValue
136
- ),
137
- [config, ssrCookies, kheopskitStore, initialValue, serverValue]
138
- );
139
- (0, import_react2.useEffect)(() => {
140
- return () => store.destroy();
141
- }, [store]);
142
- const state = (0, import_react2.useSyncExternalStore)(
143
- store.subscribe,
144
- store.getSnapshot,
145
- store.getServerSnapshot
146
- );
147
- const value = (0, import_react2.useMemo)(() => ({ state }), [state]);
148
- return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(KheopskitContext.Provider, { value, children });
149
- };
150
-
151
- // src/useWallets.ts
152
- var import_react3 = require("react");
153
- var useWallets = () => {
154
- const ctx = (0, import_react3.useContext)(KheopskitContext);
155
- if (!ctx)
156
- throw new Error("useWallets can't be used without a KheopskitProvider");
157
- return ctx.state;
158
- };
159
-
160
- // src/createKheopskit.tsx
161
- var import_jsx_runtime2 = require("react/jsx-runtime");
162
- var createKheopskit = (config) => {
163
- const Provider = ({
164
- children,
165
- ssrCookies
166
- }) => /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(KheopskitProvider, { config, ssrCookies, children });
167
- Provider.displayName = "KheopskitProvider";
168
- return {
169
- KheopskitProvider: Provider,
170
- /** Current state, typed to the bound platform tuple. */
171
- useWallets: () => useWallets(),
172
- /** Current accounts, typed to the bound platform tuple. */
173
- useAccounts: () => useWallets().accounts
174
- };
126
+ //#endregion
127
+ //#region src/createKheopskit.tsx
128
+ /**
129
+ * Binds a platform tuple once and returns a `KheopskitProvider` plus hooks
130
+ * (`useWallets`, `useAccounts`) already typed to those platforms — so you don't
131
+ * repeat `useWallets<typeof platforms>()` in every component.
132
+ *
133
+ * @example
134
+ * ```tsx
135
+ * // kheopskit.ts
136
+ * export const { KheopskitProvider, useWallets, useAccounts } = createKheopskit({
137
+ * platforms: [polkadot(), ethereum(), solana()],
138
+ * });
139
+ *
140
+ * // anywhere
141
+ * const { accounts } = useWallets(); // accounts are platform-precise, no generic
142
+ * ```
143
+ */
144
+ const createKheopskit = (config) => {
145
+ const Provider = ({ children, ssrCookies }) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)(KheopskitProvider, {
146
+ config,
147
+ ssrCookies,
148
+ children
149
+ });
150
+ Provider.displayName = "KheopskitProvider";
151
+ return {
152
+ KheopskitProvider: Provider,
153
+ /** Current state, typed to the bound platform tuple. */
154
+ useWallets: () => useWallets(),
155
+ /** Current accounts, typed to the bound platform tuple. */
156
+ useAccounts: () => useWallets().accounts
157
+ };
175
158
  };
159
+ //#endregion
160
+ //#region src/useAccounts.ts
161
+ /**
162
+ * Convenience hook returning just the accounts from kheopskit state. Pass the
163
+ * platform tuple as a type argument to recover SDK-precise account types —
164
+ * `useAccounts<typeof platforms>()` — or use the pre-typed hook from
165
+ * {@link createKheopskit}.
166
+ */
167
+ const useAccounts = () => useWallets().accounts;
168
+ //#endregion
169
+ exports.KheopskitProvider = KheopskitProvider;
170
+ exports.createKheopskit = createKheopskit;
171
+ exports.useAccounts = useAccounts;
172
+ exports.useWallets = useWallets;
176
173
 
177
- // src/useAccounts.ts
178
- var useAccounts = () => useWallets().accounts;
179
- // Annotate the CommonJS export names for ESM import in node:
180
- 0 && (module.exports = {
181
- KheopskitProvider,
182
- createKheopskit,
183
- useAccounts,
184
- useWallets
185
- });
186
174
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/KheopskitProvider.tsx","../src/context.ts","../src/createExternalStore.ts","../src/useWallets.ts","../src/createKheopskit.tsx","../src/useAccounts.ts"],"sourcesContent":["export * from \"./createKheopskit\";\nexport * from \"./KheopskitProvider\";\nexport * from \"./useAccounts\";\nexport * from \"./useWallets\";\n","import {\n\tcreateKheopskitStore,\n\tgetHydratedSnapshot,\n\tgetKheopskit$,\n\ttype KheopskitConfig,\n\ttype KheopskitState,\n\tresolveConfig,\n} from \"@kheopskit/core\";\nimport {\n\ttype FC,\n\ttype PropsWithChildren,\n\tuseEffect,\n\tuseMemo,\n\tuseRef,\n\tuseSyncExternalStore,\n} from \"react\";\nimport { KheopskitContext } from \"./context\";\nimport { createExternalStore } from \"./createExternalStore\";\n\nexport type KheopskitProviderProps = PropsWithChildren & {\n\t/**\n\t * Kheopskit configuration.\n\t *\n\t * @remarks\n\t * Must be a **referentially stable** value — define it once (module scope, a\n\t * `useMemo`, or via {@link createKheopskit}) and pass the same reference. A\n\t * new object literal on every render (`config={{ platforms: [...] }}` inline)\n\t * recreates the underlying store and re-subscribes each render.\n\t */\n\tconfig?: Partial<KheopskitConfig>;\n\t/**\n\t * Cookie string for SSR hydration.\n\t * Pass the request cookie header (e.g., from Next.js headers or TanStack Start)\n\t * to hydrate wallet state on the server.\n\t *\n\t * @remarks\n\t * This value should be stable per render to avoid unnecessary store recreation.\n\t * Compute it once in your server component or layout and pass it down.\n\t *\n\t * @example\n\t * ```tsx\n\t * // Next.js App Router\n\t * const cookieStore = await cookies();\n\t * const ssrCookies = cookieStore.getAll().map(c => `${c.name}=${c.value}`).join('; ');\n\t * return <Providers ssrCookies={ssrCookies}>{children}</Providers>\n\t * ```\n\t */\n\tssrCookies?: string;\n};\n\nexport const KheopskitProvider: FC<KheopskitProviderProps> = ({\n\tchildren,\n\tconfig,\n\tssrCookies,\n}) => {\n\tconst resolvedConfig = useMemo(() => resolveConfig(config), [config]);\n\n\t// Dev-only: warn if the `config` prop reference changes between renders. A new\n\t// object each render recreates the store and re-subscribes the whole pipeline\n\t// (re-hydrating, dropping live connection state) on every render. `config` must\n\t// be referentially stable — define it at module scope, memoize it, or use\n\t// createKheopskit() (which passes a stable reference for you).\n\tconst lastConfigRef = useRef(config);\n\tconst hasMountedRef = useRef(false);\n\tuseEffect(() => {\n\t\tif (\n\t\t\thasMountedRef.current &&\n\t\t\tlastConfigRef.current !== config &&\n\t\t\t(typeof process === \"undefined\" || process.env?.NODE_ENV !== \"production\")\n\t\t) {\n\t\t\tconsole.warn(\n\t\t\t\t\"[kheopskit] KheopskitProvider received a new `config` reference; this \" +\n\t\t\t\t\t\"recreates the store and re-subscribes on every render. Pass a \" +\n\t\t\t\t\t\"referentially stable config (module scope, useMemo, or createKheopskit()).\",\n\t\t\t);\n\t\t}\n\t\thasMountedRef.current = true;\n\t\tlastConfigRef.current = config;\n\t}, [config]);\n\n\t// Create a single store for both reading cached state and powering the observable\n\tconst kheopskitStore = useMemo(\n\t\t() =>\n\t\t\tcreateKheopskitStore({\n\t\t\t\tssrCookies,\n\t\t\t\tstorageKey: resolvedConfig.storageKey,\n\t\t\t}),\n\t\t[ssrCookies, resolvedConfig.storageKey],\n\t);\n\n\t// Read cached state from the store for SSR hydration.\n\t// Icons stay OFF: this snapshot must match the server-rendered markup, and the\n\t// server never sees the localStorage icon cache (see GetHydratedSnapshotOptions).\n\tconst serverValue = useMemo<KheopskitState>(() => {\n\t\tif (ssrCookies === undefined) {\n\t\t\treturn {\n\t\t\t\twallets: [],\n\t\t\t\taccounts: [],\n\t\t\t\tconfig: resolvedConfig,\n\t\t\t\tisHydrating: true,\n\t\t\t};\n\t\t}\n\t\treturn {\n\t\t\t...getHydratedSnapshot(kheopskitStore, resolvedConfig.platforms),\n\t\t\tconfig: resolvedConfig,\n\t\t\tisHydrating: true,\n\t\t};\n\t}, [ssrCookies, kheopskitStore, resolvedConfig]);\n\n\t// Client-only initial snapshot, read straight from the client cache so a hard\n\t// reload paints the cached wallet/account list on the very first frame instead\n\t// of flashing empty until the live observable produces its first emission —\n\t// which can be asynchronous (e.g. WalletConnect's AppKit is loaded via dynamic\n\t// import, so the underlying combineLatest can't emit synchronously).\n\t//\n\t// We can't derive this from `serverValue`: without SSR cookies that stays empty\n\t// (to keep the server/client hydration markup identical), so the SPA case would\n\t// otherwise render nothing. This snapshot is only ever read on the client via\n\t// getSnapshot, so reading the cache here is safe — and getCachedIcon returns \"\"\n\t// on the server, making the icon enrichment a no-op there.\n\tconst initialValue = useMemo<KheopskitState>(() => {\n\t\treturn {\n\t\t\t...getHydratedSnapshot(kheopskitStore, resolvedConfig.platforms, {\n\t\t\t\ticons: true,\n\t\t\t}),\n\t\t\tconfig: resolvedConfig,\n\t\t\tisHydrating: true,\n\t\t};\n\t}, [kheopskitStore, resolvedConfig]);\n\n\tconst store = useMemo(\n\t\t() =>\n\t\t\tcreateExternalStore(\n\t\t\t\tgetKheopskit$(config, { ssrCookies, store: kheopskitStore }),\n\t\t\t\tinitialValue,\n\t\t\t\tserverValue,\n\t\t\t),\n\t\t[config, ssrCookies, kheopskitStore, initialValue, serverValue],\n\t);\n\n\t// Cleanup store subscriptions when store changes or component unmounts\n\tuseEffect(() => {\n\t\treturn () => store.destroy();\n\t}, [store]);\n\n\tconst state = useSyncExternalStore(\n\t\tstore.subscribe,\n\t\tstore.getSnapshot,\n\t\tstore.getServerSnapshot,\n\t);\n\n\tconst value = useMemo(() => ({ state }), [state]);\n\n\treturn (\n\t\t<KheopskitContext.Provider value={value}>\n\t\t\t{children}\n\t\t</KheopskitContext.Provider>\n\t);\n};\n","import type { KheopskitState } from \"@kheopskit/core\";\nimport { createContext } from \"react\";\n\nexport const KheopskitContext = createContext<{\n\tstate: KheopskitState;\n} | null>(null);\n","import type { Observable, Subscription } from \"rxjs\";\n\nexport const createExternalStore = <T>(\n\tobservable$: Observable<T>,\n\tinitialValue: T,\n\tserverValue?: T,\n) => {\n\t// Use null as sentinel to indicate we haven't received first emission yet\n\tlet latestValue: T | null = null;\n\tlet subscription: Subscription | null = null;\n\tlet subscriberCount = 0;\n\tconst listeners = new Set<(value: T) => void>();\n\n\tconst ensureSubscription = () => {\n\t\tif (!subscription || subscription.closed) {\n\t\t\tsubscription = observable$.subscribe((value) => {\n\t\t\t\tlatestValue = value;\n\t\t\t\tfor (const listener of listeners) {\n\t\t\t\t\tlistener(value);\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t};\n\n\t// The subscription is created lazily by subscribe() (which React calls from a\n\t// committed passive effect), never during render. React may render a tree and\n\t// throw it away without committing — StrictMode double-invokes the initial\n\t// render, and concurrent/Suspense can discard renders — so subscribing eagerly\n\t// here (createExternalStore runs inside the Provider's render-phase useMemo) would leak\n\t// the discarded store's observable subscription. Until the first emission,\n\t// getSnapshot falls back to initialValue.\n\tconst getSnapshot = () => latestValue ?? initialValue;\n\n\t/**\n\t * Returns the server-side snapshot for SSR hydration.\n\t * This prevents hydration mismatches by providing a consistent\n\t * value during server rendering. Must return the same value as\n\t * what the server rendered.\n\t */\n\tconst getServerSnapshot = () => serverValue ?? initialValue;\n\n\tconst subscribe = (callback: (value: T) => void) => {\n\t\tsubscriberCount++;\n\t\t// Subscribe to the observable BEFORE registering this listener, so a\n\t\t// synchronous replay (BehaviorSubject / shareReplay) updates latestValue\n\t\t// without double-invoking this callback — the current value is emitted once,\n\t\t// explicitly, just below.\n\t\tensureSubscription();\n\t\tlisteners.add(callback);\n\n\t\t// Immediately emit current value (BehaviorSubject semantics)\n\t\tcallback(getSnapshot());\n\n\t\treturn () => {\n\t\t\tsubscriberCount--;\n\t\t\tlisteners.delete(callback);\n\t\t\t// Don't close the observable subscription on unsubscribe\n\t\t\t// Let destroy() handle that when the store is truly being disposed\n\t\t};\n\t};\n\n\tconst destroy = () => {\n\t\t// Only unsubscribe if no one is listening\n\t\t// React StrictMode may call destroy and then immediately resubscribe\n\t\tif (subscriberCount === 0 && subscription) {\n\t\t\tsubscription.unsubscribe();\n\t\t\tsubscription = null;\n\t\t}\n\t};\n\n\treturn {\n\t\tgetSnapshot,\n\t\tgetServerSnapshot,\n\t\tsubscribe,\n\t\tdestroy,\n\t};\n};\n","import type { KheopskitPlatform, KheopskitState } from \"@kheopskit/core\";\nimport { useContext } from \"react\";\nimport { KheopskitContext } from \"./context\";\n\n/**\n * Returns the current kheopskit state (wallets, accounts, config, isHydrating).\n *\n * Pass the platform tuple as a type argument to recover SDK-precise account and\n * wallet types — `useWallets<typeof platforms>()`. React contexts can't be\n * generic, so without the argument the state is typed with the base\n * (SDK-free) wallet/account shapes.\n */\nexport const useWallets = <\n\tP extends readonly KheopskitPlatform[] = readonly KheopskitPlatform[],\n>(): KheopskitState<P> => {\n\tconst ctx = useContext(KheopskitContext);\n\n\tif (!ctx)\n\t\tthrow new Error(\"useWallets can't be used without a KheopskitProvider\");\n\n\treturn ctx.state as unknown as KheopskitState<P>;\n};\n","import type { KheopskitConfig, KheopskitPlatform } from \"@kheopskit/core\";\nimport type { FC, PropsWithChildren } from \"react\";\nimport { KheopskitProvider } from \"./KheopskitProvider\";\nimport { useWallets } from \"./useWallets\";\n\nexport type CreateKheopskitConfig<P extends readonly KheopskitPlatform[]> =\n\tOmit<Partial<KheopskitConfig<P>>, \"platforms\"> & {\n\t\t/** Platform plugins, e.g. `[polkadot(), solana()]`. Required. */\n\t\tplatforms: P;\n\t};\n\n/**\n * Binds a platform tuple once and returns a `KheopskitProvider` plus hooks\n * (`useWallets`, `useAccounts`) already typed to those platforms — so you don't\n * repeat `useWallets<typeof platforms>()` in every component.\n *\n * @example\n * ```tsx\n * // kheopskit.ts\n * export const { KheopskitProvider, useWallets, useAccounts } = createKheopskit({\n * platforms: [polkadot(), ethereum(), solana()],\n * });\n *\n * // anywhere\n * const { accounts } = useWallets(); // accounts are platform-precise, no generic\n * ```\n */\nexport const createKheopskit = <\n\tconst P extends readonly [KheopskitPlatform, ...KheopskitPlatform[]],\n>(\n\tconfig: CreateKheopskitConfig<P>,\n) => {\n\tconst Provider: FC<PropsWithChildren<{ ssrCookies?: string }>> = ({\n\t\tchildren,\n\t\tssrCookies,\n\t}) => (\n\t\t<KheopskitProvider config={config} ssrCookies={ssrCookies}>\n\t\t\t{children}\n\t\t</KheopskitProvider>\n\t);\n\tProvider.displayName = \"KheopskitProvider\";\n\n\treturn {\n\t\tKheopskitProvider: Provider,\n\t\t/** Current state, typed to the bound platform tuple. */\n\t\tuseWallets: () => useWallets<P>(),\n\t\t/** Current accounts, typed to the bound platform tuple. */\n\t\tuseAccounts: () => useWallets<P>().accounts,\n\t};\n};\n","import type { KheopskitPlatform } from \"@kheopskit/core\";\nimport { useWallets } from \"./useWallets\";\n\n/**\n * Convenience hook returning just the accounts from kheopskit state. Pass the\n * platform tuple as a type argument to recover SDK-precise account types —\n * `useAccounts<typeof platforms>()` — or use the pre-typed hook from\n * {@link createKheopskit}.\n */\nexport const useAccounts = <\n\tP extends readonly KheopskitPlatform[] = readonly KheopskitPlatform[],\n>() => useWallets<P>().accounts;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,kBAOO;AACP,IAAAA,gBAOO;;;ACdP,mBAA8B;AAEvB,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aAAa,MAEA;AACzB,QAAM,UAAM,0BAAW,gBAAgB;AAEvC,MAAI,CAAC;AACJ,UAAM,IAAI,MAAM,sDAAsD;AAEvE,SAAO,IAAI;AACZ;;;ACeE,IAAAC,sBAAA;AATK,IAAM,kBAAkB,CAG9B,WACI;AACJ,QAAM,WAA2D,CAAC;AAAA,IACjE;AAAA,IACA;AAAA,EACD,MACC,6CAAC,qBAAkB,QAAgB,YACjC,UACF;AAED,WAAS,cAAc;AAEvB,SAAO;AAAA,IACN,mBAAmB;AAAA;AAAA,IAEnB,YAAY,MAAM,WAAc;AAAA;AAAA,IAEhC,aAAa,MAAM,WAAc,EAAE;AAAA,EACpC;AACD;;;ACxCO,IAAM,cAAc,MAEpB,WAAc,EAAE;","names":["import_react","import_react","import_jsx_runtime"]}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/context.ts","../src/createExternalStore.ts","../src/KheopskitProvider.tsx","../src/useWallets.ts","../src/createKheopskit.tsx","../src/useAccounts.ts"],"sourcesContent":["import type { KheopskitState } from \"@kheopskit/core\";\nimport { createContext } from \"react\";\n\nexport const KheopskitContext = createContext<{\n\tstate: KheopskitState;\n} | null>(null);\n","import type { Observable, Subscription } from \"rxjs\";\n\nexport const createExternalStore = <T>(\n\tobservable$: Observable<T>,\n\tinitialValue: T,\n\tserverValue?: T,\n) => {\n\t// Use null as sentinel to indicate we haven't received first emission yet\n\tlet latestValue: T | null = null;\n\tlet subscription: Subscription | null = null;\n\tlet subscriberCount = 0;\n\tconst listeners = new Set<(value: T) => void>();\n\n\tconst ensureSubscription = () => {\n\t\tif (!subscription || subscription.closed) {\n\t\t\tsubscription = observable$.subscribe((value) => {\n\t\t\t\tlatestValue = value;\n\t\t\t\tfor (const listener of listeners) {\n\t\t\t\t\tlistener(value);\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t};\n\n\t// The subscription is created lazily by subscribe() (which React calls from a\n\t// committed passive effect), never during render. React may render a tree and\n\t// throw it away without committing — StrictMode double-invokes the initial\n\t// render, and concurrent/Suspense can discard renders — so subscribing eagerly\n\t// here (createExternalStore runs inside the Provider's render-phase useMemo) would leak\n\t// the discarded store's observable subscription. Until the first emission,\n\t// getSnapshot falls back to initialValue.\n\tconst getSnapshot = () => latestValue ?? initialValue;\n\n\t/**\n\t * Returns the server-side snapshot for SSR hydration.\n\t * This prevents hydration mismatches by providing a consistent\n\t * value during server rendering. Must return the same value as\n\t * what the server rendered.\n\t */\n\tconst getServerSnapshot = () => serverValue ?? initialValue;\n\n\tconst subscribe = (callback: (value: T) => void) => {\n\t\tsubscriberCount++;\n\t\t// Subscribe to the observable BEFORE registering this listener, so a\n\t\t// synchronous replay (BehaviorSubject / shareReplay) updates latestValue\n\t\t// without double-invoking this callback — the current value is emitted once,\n\t\t// explicitly, just below.\n\t\tensureSubscription();\n\t\tlisteners.add(callback);\n\n\t\t// Immediately emit current value (BehaviorSubject semantics)\n\t\tcallback(getSnapshot());\n\n\t\treturn () => {\n\t\t\tsubscriberCount--;\n\t\t\tlisteners.delete(callback);\n\t\t\t// Don't close the observable subscription on unsubscribe\n\t\t\t// Let destroy() handle that when the store is truly being disposed\n\t\t};\n\t};\n\n\tconst destroy = () => {\n\t\t// Only unsubscribe if no one is listening\n\t\t// React StrictMode may call destroy and then immediately resubscribe\n\t\tif (subscriberCount === 0 && subscription) {\n\t\t\tsubscription.unsubscribe();\n\t\t\tsubscription = null;\n\t\t}\n\t};\n\n\treturn {\n\t\tgetSnapshot,\n\t\tgetServerSnapshot,\n\t\tsubscribe,\n\t\tdestroy,\n\t};\n};\n","import {\n\tcreateKheopskitStore,\n\tgetHydratedSnapshot,\n\tgetKheopskit$,\n\ttype KheopskitConfig,\n\ttype KheopskitState,\n\tresolveConfig,\n} from \"@kheopskit/core\";\nimport {\n\ttype FC,\n\ttype PropsWithChildren,\n\tuseEffect,\n\tuseMemo,\n\tuseRef,\n\tuseSyncExternalStore,\n} from \"react\";\nimport { KheopskitContext } from \"./context\";\nimport { createExternalStore } from \"./createExternalStore\";\n\nexport type KheopskitProviderProps = PropsWithChildren & {\n\t/**\n\t * Kheopskit configuration.\n\t *\n\t * @remarks\n\t * Must be a **referentially stable** value — define it once (module scope, a\n\t * `useMemo`, or via {@link createKheopskit}) and pass the same reference. A\n\t * new object literal on every render (`config={{ platforms: [...] }}` inline)\n\t * recreates the underlying store and re-subscribes each render.\n\t */\n\tconfig?: Partial<KheopskitConfig>;\n\t/**\n\t * Cookie string for SSR hydration.\n\t * Pass the request cookie header (e.g., from Next.js headers or TanStack Start)\n\t * to hydrate wallet state on the server.\n\t *\n\t * @remarks\n\t * This value should be stable per render to avoid unnecessary store recreation.\n\t * Compute it once in your server component or layout and pass it down.\n\t *\n\t * @example\n\t * ```tsx\n\t * // Next.js App Router\n\t * const cookieStore = await cookies();\n\t * const ssrCookies = cookieStore.getAll().map(c => `${c.name}=${c.value}`).join('; ');\n\t * return <Providers ssrCookies={ssrCookies}>{children}</Providers>\n\t * ```\n\t */\n\tssrCookies?: string;\n};\n\nexport const KheopskitProvider: FC<KheopskitProviderProps> = ({\n\tchildren,\n\tconfig,\n\tssrCookies,\n}) => {\n\tconst resolvedConfig = useMemo(() => resolveConfig(config), [config]);\n\n\t// Dev-only: warn if the `config` prop reference changes between renders. A new\n\t// object each render recreates the store and re-subscribes the whole pipeline\n\t// (re-hydrating, dropping live connection state) on every render. `config` must\n\t// be referentially stable — define it at module scope, memoize it, or use\n\t// createKheopskit() (which passes a stable reference for you).\n\tconst lastConfigRef = useRef(config);\n\tconst hasMountedRef = useRef(false);\n\tuseEffect(() => {\n\t\tif (\n\t\t\thasMountedRef.current &&\n\t\t\tlastConfigRef.current !== config &&\n\t\t\t(typeof process === \"undefined\" || process.env?.NODE_ENV !== \"production\")\n\t\t) {\n\t\t\tconsole.warn(\n\t\t\t\t\"[kheopskit] KheopskitProvider received a new `config` reference; this \" +\n\t\t\t\t\t\"recreates the store and re-subscribes on every render. Pass a \" +\n\t\t\t\t\t\"referentially stable config (module scope, useMemo, or createKheopskit()).\",\n\t\t\t);\n\t\t}\n\t\thasMountedRef.current = true;\n\t\tlastConfigRef.current = config;\n\t}, [config]);\n\n\t// Create a single store for both reading cached state and powering the observable\n\tconst kheopskitStore = useMemo(\n\t\t() =>\n\t\t\tcreateKheopskitStore({\n\t\t\t\tssrCookies,\n\t\t\t\tstorageKey: resolvedConfig.storageKey,\n\t\t\t}),\n\t\t[ssrCookies, resolvedConfig.storageKey],\n\t);\n\n\t// Read cached state from the store for SSR hydration.\n\t// Icons stay OFF: this snapshot must match the server-rendered markup, and the\n\t// server never sees the localStorage icon cache (see GetHydratedSnapshotOptions).\n\tconst serverValue = useMemo<KheopskitState>(() => {\n\t\tif (ssrCookies === undefined) {\n\t\t\treturn {\n\t\t\t\twallets: [],\n\t\t\t\taccounts: [],\n\t\t\t\tconfig: resolvedConfig,\n\t\t\t\tisHydrating: true,\n\t\t\t};\n\t\t}\n\t\treturn {\n\t\t\t...getHydratedSnapshot(kheopskitStore, resolvedConfig.platforms),\n\t\t\tconfig: resolvedConfig,\n\t\t\tisHydrating: true,\n\t\t};\n\t}, [ssrCookies, kheopskitStore, resolvedConfig]);\n\n\t// Client-only initial snapshot, read straight from the client cache so a hard\n\t// reload paints the cached wallet/account list on the very first frame instead\n\t// of flashing empty until the live observable produces its first emission —\n\t// which can be asynchronous (e.g. WalletConnect's AppKit is loaded via dynamic\n\t// import, so the underlying combineLatest can't emit synchronously).\n\t//\n\t// We can't derive this from `serverValue`: without SSR cookies that stays empty\n\t// (to keep the server/client hydration markup identical), so the SPA case would\n\t// otherwise render nothing. This snapshot is only ever read on the client via\n\t// getSnapshot, so reading the cache here is safe — and getCachedIcon returns \"\"\n\t// on the server, making the icon enrichment a no-op there.\n\tconst initialValue = useMemo<KheopskitState>(() => {\n\t\treturn {\n\t\t\t...getHydratedSnapshot(kheopskitStore, resolvedConfig.platforms, {\n\t\t\t\ticons: true,\n\t\t\t}),\n\t\t\tconfig: resolvedConfig,\n\t\t\tisHydrating: true,\n\t\t};\n\t}, [kheopskitStore, resolvedConfig]);\n\n\tconst store = useMemo(\n\t\t() =>\n\t\t\tcreateExternalStore(\n\t\t\t\tgetKheopskit$(config, { ssrCookies, store: kheopskitStore }),\n\t\t\t\tinitialValue,\n\t\t\t\tserverValue,\n\t\t\t),\n\t\t[config, ssrCookies, kheopskitStore, initialValue, serverValue],\n\t);\n\n\t// Cleanup store subscriptions when store changes or component unmounts\n\tuseEffect(() => {\n\t\treturn () => store.destroy();\n\t}, [store]);\n\n\tconst state = useSyncExternalStore(\n\t\tstore.subscribe,\n\t\tstore.getSnapshot,\n\t\tstore.getServerSnapshot,\n\t);\n\n\tconst value = useMemo(() => ({ state }), [state]);\n\n\treturn (\n\t\t<KheopskitContext.Provider value={value}>\n\t\t\t{children}\n\t\t</KheopskitContext.Provider>\n\t);\n};\n","import type { KheopskitPlatform, KheopskitState } from \"@kheopskit/core\";\nimport { useContext } from \"react\";\nimport { KheopskitContext } from \"./context\";\n\n/**\n * Returns the current kheopskit state (wallets, accounts, config, isHydrating).\n *\n * Pass the platform tuple as a type argument to recover SDK-precise account and\n * wallet types — `useWallets<typeof platforms>()`. React contexts can't be\n * generic, so without the argument the state is typed with the base\n * (SDK-free) wallet/account shapes.\n */\nexport const useWallets = <\n\tP extends readonly KheopskitPlatform[] = readonly KheopskitPlatform[],\n>(): KheopskitState<P> => {\n\tconst ctx = useContext(KheopskitContext);\n\n\tif (!ctx)\n\t\tthrow new Error(\"useWallets can't be used without a KheopskitProvider\");\n\n\treturn ctx.state as unknown as KheopskitState<P>;\n};\n","import type { KheopskitConfig, KheopskitPlatform } from \"@kheopskit/core\";\nimport type { FC, PropsWithChildren } from \"react\";\nimport { KheopskitProvider } from \"./KheopskitProvider\";\nimport { useWallets } from \"./useWallets\";\n\nexport type CreateKheopskitConfig<P extends readonly KheopskitPlatform[]> =\n\tOmit<Partial<KheopskitConfig<P>>, \"platforms\"> & {\n\t\t/** Platform plugins, e.g. `[polkadot(), solana()]`. Required. */\n\t\tplatforms: P;\n\t};\n\n/**\n * Binds a platform tuple once and returns a `KheopskitProvider` plus hooks\n * (`useWallets`, `useAccounts`) already typed to those platforms — so you don't\n * repeat `useWallets<typeof platforms>()` in every component.\n *\n * @example\n * ```tsx\n * // kheopskit.ts\n * export const { KheopskitProvider, useWallets, useAccounts } = createKheopskit({\n * platforms: [polkadot(), ethereum(), solana()],\n * });\n *\n * // anywhere\n * const { accounts } = useWallets(); // accounts are platform-precise, no generic\n * ```\n */\nexport const createKheopskit = <\n\tconst P extends readonly [KheopskitPlatform, ...KheopskitPlatform[]],\n>(\n\tconfig: CreateKheopskitConfig<P>,\n) => {\n\tconst Provider: FC<PropsWithChildren<{ ssrCookies?: string }>> = ({\n\t\tchildren,\n\t\tssrCookies,\n\t}) => (\n\t\t<KheopskitProvider config={config} ssrCookies={ssrCookies}>\n\t\t\t{children}\n\t\t</KheopskitProvider>\n\t);\n\tProvider.displayName = \"KheopskitProvider\";\n\n\treturn {\n\t\tKheopskitProvider: Provider,\n\t\t/** Current state, typed to the bound platform tuple. */\n\t\tuseWallets: () => useWallets<P>(),\n\t\t/** Current accounts, typed to the bound platform tuple. */\n\t\tuseAccounts: () => useWallets<P>().accounts,\n\t};\n};\n","import type { KheopskitPlatform } from \"@kheopskit/core\";\nimport { useWallets } from \"./useWallets\";\n\n/**\n * Convenience hook returning just the accounts from kheopskit state. Pass the\n * platform tuple as a type argument to recover SDK-precise account types —\n * `useAccounts<typeof platforms>()` — or use the pre-typed hook from\n * {@link createKheopskit}.\n */\nexport const useAccounts = <\n\tP extends readonly KheopskitPlatform[] = readonly KheopskitPlatform[],\n>() => useWallets<P>().accounts;\n"],"mappings":";;;;;;AAGA,MAAa,oBAAA,GAAA,MAAA,cAAA,CAEH,IAAI;;;ACHd,MAAa,uBACZ,aACA,cACA,gBACI;CAEJ,IAAI,cAAwB;CAC5B,IAAI,eAAoC;CACxC,IAAI,kBAAkB;CACtB,MAAM,4BAAY,IAAI,IAAwB;CAE9C,MAAM,2BA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,kBAAkB,WAAc;;EAEhC,mBAAmB,WAAc,CAAC,CAAC;CACpC;AACD;;;;;;;;;ACxCA,MAAa,oBAEN,WAAc,CAAC,CAAC"}
package/dist/index.mjs CHANGED
@@ -1,167 +1,170 @@
1
1
  "use client";
2
-
3
- // src/KheopskitProvider.tsx
4
- import {
5
- createKheopskitStore,
6
- getHydratedSnapshot,
7
- getKheopskit$,
8
- resolveConfig
9
- } from "@kheopskit/core";
10
- import {
11
- useEffect,
12
- useMemo,
13
- useRef,
14
- useSyncExternalStore
15
- } from "react";
16
-
17
- // src/context.ts
18
- import { createContext } from "react";
19
- var KheopskitContext = createContext(null);
20
-
21
- // src/createExternalStore.ts
22
- var createExternalStore = (observable$, initialValue, serverValue) => {
23
- let latestValue = null;
24
- let subscription = null;
25
- let subscriberCount = 0;
26
- const listeners = /* @__PURE__ */ new Set();
27
- const ensureSubscription = () => {
28
- if (!subscription || subscription.closed) {
29
- subscription = observable$.subscribe((value) => {
30
- latestValue = value;
31
- for (const listener of listeners) {
32
- listener(value);
33
- }
34
- });
35
- }
36
- };
37
- const getSnapshot = () => latestValue ?? initialValue;
38
- const getServerSnapshot = () => serverValue ?? initialValue;
39
- const subscribe = (callback) => {
40
- subscriberCount++;
41
- ensureSubscription();
42
- listeners.add(callback);
43
- callback(getSnapshot());
44
- return () => {
45
- subscriberCount--;
46
- listeners.delete(callback);
47
- };
48
- };
49
- const destroy = () => {
50
- if (subscriberCount === 0 && subscription) {
51
- subscription.unsubscribe();
52
- subscription = null;
53
- }
54
- };
55
- return {
56
- getSnapshot,
57
- getServerSnapshot,
58
- subscribe,
59
- destroy
60
- };
61
- };
62
-
63
- // src/KheopskitProvider.tsx
2
+ import { createKheopskitStore, getHydratedSnapshot, getKheopskit$, resolveConfig } from "@kheopskit/core";
3
+ import { createContext, useContext, useEffect, useMemo, useRef, useSyncExternalStore } from "react";
64
4
  import { jsx } from "react/jsx-runtime";
65
- var KheopskitProvider = ({
66
- children,
67
- config,
68
- ssrCookies
69
- }) => {
70
- const resolvedConfig = useMemo(() => resolveConfig(config), [config]);
71
- const lastConfigRef = useRef(config);
72
- const hasMountedRef = useRef(false);
73
- useEffect(() => {
74
- if (hasMountedRef.current && lastConfigRef.current !== config && (typeof process === "undefined" || process.env?.NODE_ENV !== "production")) {
75
- console.warn(
76
- "[kheopskit] KheopskitProvider received a new `config` reference; this recreates the store and re-subscribes on every render. Pass a referentially stable config (module scope, useMemo, or createKheopskit())."
77
- );
78
- }
79
- hasMountedRef.current = true;
80
- lastConfigRef.current = config;
81
- }, [config]);
82
- const kheopskitStore = useMemo(
83
- () => createKheopskitStore({
84
- ssrCookies,
85
- storageKey: resolvedConfig.storageKey
86
- }),
87
- [ssrCookies, resolvedConfig.storageKey]
88
- );
89
- const serverValue = useMemo(() => {
90
- if (ssrCookies === void 0) {
91
- return {
92
- wallets: [],
93
- accounts: [],
94
- config: resolvedConfig,
95
- isHydrating: true
96
- };
97
- }
98
- return {
99
- ...getHydratedSnapshot(kheopskitStore, resolvedConfig.platforms),
100
- config: resolvedConfig,
101
- isHydrating: true
102
- };
103
- }, [ssrCookies, kheopskitStore, resolvedConfig]);
104
- const initialValue = useMemo(() => {
105
- return {
106
- ...getHydratedSnapshot(kheopskitStore, resolvedConfig.platforms, {
107
- icons: true
108
- }),
109
- config: resolvedConfig,
110
- isHydrating: true
111
- };
112
- }, [kheopskitStore, resolvedConfig]);
113
- const store = useMemo(
114
- () => createExternalStore(
115
- getKheopskit$(config, { ssrCookies, store: kheopskitStore }),
116
- initialValue,
117
- serverValue
118
- ),
119
- [config, ssrCookies, kheopskitStore, initialValue, serverValue]
120
- );
121
- useEffect(() => {
122
- return () => store.destroy();
123
- }, [store]);
124
- const state = useSyncExternalStore(
125
- store.subscribe,
126
- store.getSnapshot,
127
- store.getServerSnapshot
128
- );
129
- const value = useMemo(() => ({ state }), [state]);
130
- return /* @__PURE__ */ jsx(KheopskitContext.Provider, { value, children });
5
+ //#region src/context.ts
6
+ const KheopskitContext = createContext(null);
7
+ //#endregion
8
+ //#region src/createExternalStore.ts
9
+ const createExternalStore = (observable$, initialValue, serverValue) => {
10
+ let latestValue = null;
11
+ let subscription = null;
12
+ let subscriberCount = 0;
13
+ const listeners = /* @__PURE__ */ new Set();
14
+ const ensureSubscription = () => {
15
+ if (!subscription || subscription.closed) subscription = observable$.subscribe((value) => {
16
+ latestValue = value;
17
+ for (const listener of listeners) listener(value);
18
+ });
19
+ };
20
+ const getSnapshot = () => latestValue ?? initialValue;
21
+ /**
22
+ * Returns the server-side snapshot for SSR hydration.
23
+ * This prevents hydration mismatches by providing a consistent
24
+ * value during server rendering. Must return the same value as
25
+ * what the server rendered.
26
+ */
27
+ const getServerSnapshot = () => serverValue ?? initialValue;
28
+ const subscribe = (callback) => {
29
+ subscriberCount++;
30
+ ensureSubscription();
31
+ listeners.add(callback);
32
+ callback(getSnapshot());
33
+ return () => {
34
+ subscriberCount--;
35
+ listeners.delete(callback);
36
+ };
37
+ };
38
+ const destroy = () => {
39
+ if (subscriberCount === 0 && subscription) {
40
+ subscription.unsubscribe();
41
+ subscription = null;
42
+ }
43
+ };
44
+ return {
45
+ getSnapshot,
46
+ getServerSnapshot,
47
+ subscribe,
48
+ destroy
49
+ };
131
50
  };
132
-
133
- // src/useWallets.ts
134
- import { useContext } from "react";
135
- var useWallets = () => {
136
- const ctx = useContext(KheopskitContext);
137
- if (!ctx)
138
- throw new Error("useWallets can't be used without a KheopskitProvider");
139
- return ctx.state;
51
+ //#endregion
52
+ //#region src/KheopskitProvider.tsx
53
+ const KheopskitProvider = ({ children, config, ssrCookies }) => {
54
+ const resolvedConfig = useMemo(() => resolveConfig(config), [config]);
55
+ const lastConfigRef = useRef(config);
56
+ const hasMountedRef = useRef(false);
57
+ useEffect(() => {
58
+ if (hasMountedRef.current && lastConfigRef.current !== config && (typeof process === "undefined" || process.env?.NODE_ENV !== "production")) console.warn("[kheopskit] KheopskitProvider received a new `config` reference; this recreates the store and re-subscribes on every render. Pass a referentially stable config (module scope, useMemo, or createKheopskit()).");
59
+ hasMountedRef.current = true;
60
+ lastConfigRef.current = config;
61
+ }, [config]);
62
+ const kheopskitStore = useMemo(() => createKheopskitStore({
63
+ ssrCookies,
64
+ storageKey: resolvedConfig.storageKey
65
+ }), [ssrCookies, resolvedConfig.storageKey]);
66
+ const serverValue = useMemo(() => {
67
+ if (ssrCookies === void 0) return {
68
+ wallets: [],
69
+ accounts: [],
70
+ config: resolvedConfig,
71
+ isHydrating: true
72
+ };
73
+ return {
74
+ ...getHydratedSnapshot(kheopskitStore, resolvedConfig.platforms),
75
+ config: resolvedConfig,
76
+ isHydrating: true
77
+ };
78
+ }, [
79
+ ssrCookies,
80
+ kheopskitStore,
81
+ resolvedConfig
82
+ ]);
83
+ const initialValue = useMemo(() => {
84
+ return {
85
+ ...getHydratedSnapshot(kheopskitStore, resolvedConfig.platforms, { icons: true }),
86
+ config: resolvedConfig,
87
+ isHydrating: true
88
+ };
89
+ }, [kheopskitStore, resolvedConfig]);
90
+ const store = useMemo(() => createExternalStore(getKheopskit$(config, {
91
+ ssrCookies,
92
+ store: kheopskitStore
93
+ }), initialValue, serverValue), [
94
+ config,
95
+ ssrCookies,
96
+ kheopskitStore,
97
+ initialValue,
98
+ serverValue
99
+ ]);
100
+ useEffect(() => {
101
+ return () => store.destroy();
102
+ }, [store]);
103
+ const state = useSyncExternalStore(store.subscribe, store.getSnapshot, store.getServerSnapshot);
104
+ const value = useMemo(() => ({ state }), [state]);
105
+ return /* @__PURE__ */ jsx(KheopskitContext.Provider, {
106
+ value,
107
+ children
108
+ });
140
109
  };
141
-
142
- // src/createKheopskit.tsx
143
- import { jsx as jsx2 } from "react/jsx-runtime";
144
- var createKheopskit = (config) => {
145
- const Provider = ({
146
- children,
147
- ssrCookies
148
- }) => /* @__PURE__ */ jsx2(KheopskitProvider, { config, ssrCookies, children });
149
- Provider.displayName = "KheopskitProvider";
150
- return {
151
- KheopskitProvider: Provider,
152
- /** Current state, typed to the bound platform tuple. */
153
- useWallets: () => useWallets(),
154
- /** Current accounts, typed to the bound platform tuple. */
155
- useAccounts: () => useWallets().accounts
156
- };
110
+ //#endregion
111
+ //#region src/useWallets.ts
112
+ /**
113
+ * Returns the current kheopskit state (wallets, accounts, config, isHydrating).
114
+ *
115
+ * Pass the platform tuple as a type argument to recover SDK-precise account and
116
+ * wallet types — `useWallets<typeof platforms>()`. React contexts can't be
117
+ * generic, so without the argument the state is typed with the base
118
+ * (SDK-free) wallet/account shapes.
119
+ */
120
+ const useWallets = () => {
121
+ const ctx = useContext(KheopskitContext);
122
+ if (!ctx) throw new Error("useWallets can't be used without a KheopskitProvider");
123
+ return ctx.state;
157
124
  };
158
-
159
- // src/useAccounts.ts
160
- var useAccounts = () => useWallets().accounts;
161
- export {
162
- KheopskitProvider,
163
- createKheopskit,
164
- useAccounts,
165
- useWallets
125
+ //#endregion
126
+ //#region src/createKheopskit.tsx
127
+ /**
128
+ * Binds a platform tuple once and returns a `KheopskitProvider` plus hooks
129
+ * (`useWallets`, `useAccounts`) already typed to those platforms — so you don't
130
+ * repeat `useWallets<typeof platforms>()` in every component.
131
+ *
132
+ * @example
133
+ * ```tsx
134
+ * // kheopskit.ts
135
+ * export const { KheopskitProvider, useWallets, useAccounts } = createKheopskit({
136
+ * platforms: [polkadot(), ethereum(), solana()],
137
+ * });
138
+ *
139
+ * // anywhere
140
+ * const { accounts } = useWallets(); // accounts are platform-precise, no generic
141
+ * ```
142
+ */
143
+ const createKheopskit = (config) => {
144
+ const Provider = ({ children, ssrCookies }) => /* @__PURE__ */ jsx(KheopskitProvider, {
145
+ config,
146
+ ssrCookies,
147
+ children
148
+ });
149
+ Provider.displayName = "KheopskitProvider";
150
+ return {
151
+ KheopskitProvider: Provider,
152
+ /** Current state, typed to the bound platform tuple. */
153
+ useWallets: () => useWallets(),
154
+ /** Current accounts, typed to the bound platform tuple. */
155
+ useAccounts: () => useWallets().accounts
156
+ };
166
157
  };
158
+ //#endregion
159
+ //#region src/useAccounts.ts
160
+ /**
161
+ * Convenience hook returning just the accounts from kheopskit state. Pass the
162
+ * platform tuple as a type argument to recover SDK-precise account types —
163
+ * `useAccounts<typeof platforms>()` — or use the pre-typed hook from
164
+ * {@link createKheopskit}.
165
+ */
166
+ const useAccounts = () => useWallets().accounts;
167
+ //#endregion
168
+ export { KheopskitProvider, createKheopskit, useAccounts, useWallets };
169
+
167
170
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/KheopskitProvider.tsx","../src/context.ts","../src/createExternalStore.ts","../src/useWallets.ts","../src/createKheopskit.tsx","../src/useAccounts.ts"],"sourcesContent":["import {\n\tcreateKheopskitStore,\n\tgetHydratedSnapshot,\n\tgetKheopskit$,\n\ttype KheopskitConfig,\n\ttype KheopskitState,\n\tresolveConfig,\n} from \"@kheopskit/core\";\nimport {\n\ttype FC,\n\ttype PropsWithChildren,\n\tuseEffect,\n\tuseMemo,\n\tuseRef,\n\tuseSyncExternalStore,\n} from \"react\";\nimport { KheopskitContext } from \"./context\";\nimport { createExternalStore } from \"./createExternalStore\";\n\nexport type KheopskitProviderProps = PropsWithChildren & {\n\t/**\n\t * Kheopskit configuration.\n\t *\n\t * @remarks\n\t * Must be a **referentially stable** value — define it once (module scope, a\n\t * `useMemo`, or via {@link createKheopskit}) and pass the same reference. A\n\t * new object literal on every render (`config={{ platforms: [...] }}` inline)\n\t * recreates the underlying store and re-subscribes each render.\n\t */\n\tconfig?: Partial<KheopskitConfig>;\n\t/**\n\t * Cookie string for SSR hydration.\n\t * Pass the request cookie header (e.g., from Next.js headers or TanStack Start)\n\t * to hydrate wallet state on the server.\n\t *\n\t * @remarks\n\t * This value should be stable per render to avoid unnecessary store recreation.\n\t * Compute it once in your server component or layout and pass it down.\n\t *\n\t * @example\n\t * ```tsx\n\t * // Next.js App Router\n\t * const cookieStore = await cookies();\n\t * const ssrCookies = cookieStore.getAll().map(c => `${c.name}=${c.value}`).join('; ');\n\t * return <Providers ssrCookies={ssrCookies}>{children}</Providers>\n\t * ```\n\t */\n\tssrCookies?: string;\n};\n\nexport const KheopskitProvider: FC<KheopskitProviderProps> = ({\n\tchildren,\n\tconfig,\n\tssrCookies,\n}) => {\n\tconst resolvedConfig = useMemo(() => resolveConfig(config), [config]);\n\n\t// Dev-only: warn if the `config` prop reference changes between renders. A new\n\t// object each render recreates the store and re-subscribes the whole pipeline\n\t// (re-hydrating, dropping live connection state) on every render. `config` must\n\t// be referentially stable — define it at module scope, memoize it, or use\n\t// createKheopskit() (which passes a stable reference for you).\n\tconst lastConfigRef = useRef(config);\n\tconst hasMountedRef = useRef(false);\n\tuseEffect(() => {\n\t\tif (\n\t\t\thasMountedRef.current &&\n\t\t\tlastConfigRef.current !== config &&\n\t\t\t(typeof process === \"undefined\" || process.env?.NODE_ENV !== \"production\")\n\t\t) {\n\t\t\tconsole.warn(\n\t\t\t\t\"[kheopskit] KheopskitProvider received a new `config` reference; this \" +\n\t\t\t\t\t\"recreates the store and re-subscribes on every render. Pass a \" +\n\t\t\t\t\t\"referentially stable config (module scope, useMemo, or createKheopskit()).\",\n\t\t\t);\n\t\t}\n\t\thasMountedRef.current = true;\n\t\tlastConfigRef.current = config;\n\t}, [config]);\n\n\t// Create a single store for both reading cached state and powering the observable\n\tconst kheopskitStore = useMemo(\n\t\t() =>\n\t\t\tcreateKheopskitStore({\n\t\t\t\tssrCookies,\n\t\t\t\tstorageKey: resolvedConfig.storageKey,\n\t\t\t}),\n\t\t[ssrCookies, resolvedConfig.storageKey],\n\t);\n\n\t// Read cached state from the store for SSR hydration.\n\t// Icons stay OFF: this snapshot must match the server-rendered markup, and the\n\t// server never sees the localStorage icon cache (see GetHydratedSnapshotOptions).\n\tconst serverValue = useMemo<KheopskitState>(() => {\n\t\tif (ssrCookies === undefined) {\n\t\t\treturn {\n\t\t\t\twallets: [],\n\t\t\t\taccounts: [],\n\t\t\t\tconfig: resolvedConfig,\n\t\t\t\tisHydrating: true,\n\t\t\t};\n\t\t}\n\t\treturn {\n\t\t\t...getHydratedSnapshot(kheopskitStore, resolvedConfig.platforms),\n\t\t\tconfig: resolvedConfig,\n\t\t\tisHydrating: true,\n\t\t};\n\t}, [ssrCookies, kheopskitStore, resolvedConfig]);\n\n\t// Client-only initial snapshot, read straight from the client cache so a hard\n\t// reload paints the cached wallet/account list on the very first frame instead\n\t// of flashing empty until the live observable produces its first emission —\n\t// which can be asynchronous (e.g. WalletConnect's AppKit is loaded via dynamic\n\t// import, so the underlying combineLatest can't emit synchronously).\n\t//\n\t// We can't derive this from `serverValue`: without SSR cookies that stays empty\n\t// (to keep the server/client hydration markup identical), so the SPA case would\n\t// otherwise render nothing. This snapshot is only ever read on the client via\n\t// getSnapshot, so reading the cache here is safe — and getCachedIcon returns \"\"\n\t// on the server, making the icon enrichment a no-op there.\n\tconst initialValue = useMemo<KheopskitState>(() => {\n\t\treturn {\n\t\t\t...getHydratedSnapshot(kheopskitStore, resolvedConfig.platforms, {\n\t\t\t\ticons: true,\n\t\t\t}),\n\t\t\tconfig: resolvedConfig,\n\t\t\tisHydrating: true,\n\t\t};\n\t}, [kheopskitStore, resolvedConfig]);\n\n\tconst store = useMemo(\n\t\t() =>\n\t\t\tcreateExternalStore(\n\t\t\t\tgetKheopskit$(config, { ssrCookies, store: kheopskitStore }),\n\t\t\t\tinitialValue,\n\t\t\t\tserverValue,\n\t\t\t),\n\t\t[config, ssrCookies, kheopskitStore, initialValue, serverValue],\n\t);\n\n\t// Cleanup store subscriptions when store changes or component unmounts\n\tuseEffect(() => {\n\t\treturn () => store.destroy();\n\t}, [store]);\n\n\tconst state = useSyncExternalStore(\n\t\tstore.subscribe,\n\t\tstore.getSnapshot,\n\t\tstore.getServerSnapshot,\n\t);\n\n\tconst value = useMemo(() => ({ state }), [state]);\n\n\treturn (\n\t\t<KheopskitContext.Provider value={value}>\n\t\t\t{children}\n\t\t</KheopskitContext.Provider>\n\t);\n};\n","import type { KheopskitState } from \"@kheopskit/core\";\nimport { createContext } from \"react\";\n\nexport const KheopskitContext = createContext<{\n\tstate: KheopskitState;\n} | null>(null);\n","import type { Observable, Subscription } from \"rxjs\";\n\nexport const createExternalStore = <T>(\n\tobservable$: Observable<T>,\n\tinitialValue: T,\n\tserverValue?: T,\n) => {\n\t// Use null as sentinel to indicate we haven't received first emission yet\n\tlet latestValue: T | null = null;\n\tlet subscription: Subscription | null = null;\n\tlet subscriberCount = 0;\n\tconst listeners = new Set<(value: T) => void>();\n\n\tconst ensureSubscription = () => {\n\t\tif (!subscription || subscription.closed) {\n\t\t\tsubscription = observable$.subscribe((value) => {\n\t\t\t\tlatestValue = value;\n\t\t\t\tfor (const listener of listeners) {\n\t\t\t\t\tlistener(value);\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t};\n\n\t// The subscription is created lazily by subscribe() (which React calls from a\n\t// committed passive effect), never during render. React may render a tree and\n\t// throw it away without committing — StrictMode double-invokes the initial\n\t// render, and concurrent/Suspense can discard renders — so subscribing eagerly\n\t// here (createExternalStore runs inside the Provider's render-phase useMemo) would leak\n\t// the discarded store's observable subscription. Until the first emission,\n\t// getSnapshot falls back to initialValue.\n\tconst getSnapshot = () => latestValue ?? initialValue;\n\n\t/**\n\t * Returns the server-side snapshot for SSR hydration.\n\t * This prevents hydration mismatches by providing a consistent\n\t * value during server rendering. Must return the same value as\n\t * what the server rendered.\n\t */\n\tconst getServerSnapshot = () => serverValue ?? initialValue;\n\n\tconst subscribe = (callback: (value: T) => void) => {\n\t\tsubscriberCount++;\n\t\t// Subscribe to the observable BEFORE registering this listener, so a\n\t\t// synchronous replay (BehaviorSubject / shareReplay) updates latestValue\n\t\t// without double-invoking this callback — the current value is emitted once,\n\t\t// explicitly, just below.\n\t\tensureSubscription();\n\t\tlisteners.add(callback);\n\n\t\t// Immediately emit current value (BehaviorSubject semantics)\n\t\tcallback(getSnapshot());\n\n\t\treturn () => {\n\t\t\tsubscriberCount--;\n\t\t\tlisteners.delete(callback);\n\t\t\t// Don't close the observable subscription on unsubscribe\n\t\t\t// Let destroy() handle that when the store is truly being disposed\n\t\t};\n\t};\n\n\tconst destroy = () => {\n\t\t// Only unsubscribe if no one is listening\n\t\t// React StrictMode may call destroy and then immediately resubscribe\n\t\tif (subscriberCount === 0 && subscription) {\n\t\t\tsubscription.unsubscribe();\n\t\t\tsubscription = null;\n\t\t}\n\t};\n\n\treturn {\n\t\tgetSnapshot,\n\t\tgetServerSnapshot,\n\t\tsubscribe,\n\t\tdestroy,\n\t};\n};\n","import type { KheopskitPlatform, KheopskitState } from \"@kheopskit/core\";\nimport { useContext } from \"react\";\nimport { KheopskitContext } from \"./context\";\n\n/**\n * Returns the current kheopskit state (wallets, accounts, config, isHydrating).\n *\n * Pass the platform tuple as a type argument to recover SDK-precise account and\n * wallet types — `useWallets<typeof platforms>()`. React contexts can't be\n * generic, so without the argument the state is typed with the base\n * (SDK-free) wallet/account shapes.\n */\nexport const useWallets = <\n\tP extends readonly KheopskitPlatform[] = readonly KheopskitPlatform[],\n>(): KheopskitState<P> => {\n\tconst ctx = useContext(KheopskitContext);\n\n\tif (!ctx)\n\t\tthrow new Error(\"useWallets can't be used without a KheopskitProvider\");\n\n\treturn ctx.state as unknown as KheopskitState<P>;\n};\n","import type { KheopskitConfig, KheopskitPlatform } from \"@kheopskit/core\";\nimport type { FC, PropsWithChildren } from \"react\";\nimport { KheopskitProvider } from \"./KheopskitProvider\";\nimport { useWallets } from \"./useWallets\";\n\nexport type CreateKheopskitConfig<P extends readonly KheopskitPlatform[]> =\n\tOmit<Partial<KheopskitConfig<P>>, \"platforms\"> & {\n\t\t/** Platform plugins, e.g. `[polkadot(), solana()]`. Required. */\n\t\tplatforms: P;\n\t};\n\n/**\n * Binds a platform tuple once and returns a `KheopskitProvider` plus hooks\n * (`useWallets`, `useAccounts`) already typed to those platforms — so you don't\n * repeat `useWallets<typeof platforms>()` in every component.\n *\n * @example\n * ```tsx\n * // kheopskit.ts\n * export const { KheopskitProvider, useWallets, useAccounts } = createKheopskit({\n * platforms: [polkadot(), ethereum(), solana()],\n * });\n *\n * // anywhere\n * const { accounts } = useWallets(); // accounts are platform-precise, no generic\n * ```\n */\nexport const createKheopskit = <\n\tconst P extends readonly [KheopskitPlatform, ...KheopskitPlatform[]],\n>(\n\tconfig: CreateKheopskitConfig<P>,\n) => {\n\tconst Provider: FC<PropsWithChildren<{ ssrCookies?: string }>> = ({\n\t\tchildren,\n\t\tssrCookies,\n\t}) => (\n\t\t<KheopskitProvider config={config} ssrCookies={ssrCookies}>\n\t\t\t{children}\n\t\t</KheopskitProvider>\n\t);\n\tProvider.displayName = \"KheopskitProvider\";\n\n\treturn {\n\t\tKheopskitProvider: Provider,\n\t\t/** Current state, typed to the bound platform tuple. */\n\t\tuseWallets: () => useWallets<P>(),\n\t\t/** Current accounts, typed to the bound platform tuple. */\n\t\tuseAccounts: () => useWallets<P>().accounts,\n\t};\n};\n","import type { KheopskitPlatform } from \"@kheopskit/core\";\nimport { useWallets } from \"./useWallets\";\n\n/**\n * Convenience hook returning just the accounts from kheopskit state. Pass the\n * platform tuple as a type argument to recover SDK-precise account types —\n * `useAccounts<typeof platforms>()` — or use the pre-typed hook from\n * {@link createKheopskit}.\n */\nexport const useAccounts = <\n\tP extends readonly KheopskitPlatform[] = readonly KheopskitPlatform[],\n>() => useWallets<P>().accounts;\n"],"mappings":";;;AAAA;AAAA,EACC;AAAA,EACA;AAAA,EACA;AAAA,EAGA;AAAA,OACM;AACP;AAAA,EAGC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACM;;;ACdP,SAAS,qBAAqB;AAEvB,IAAM,mBAAmB,cAEtB,IAAI;;;ACHP,IAAM,sBAAsB,CAClC,aACA,cACA,gBACI;AAEJ,MAAI,cAAwB;AAC5B,MAAI,eAAoC;AACxC,MAAI,kBAAkB;AACtB,QAAM,YAAY,oBAAI,IAAwB;AAE9C,QAAM,qBAAqB,MAAM;AAChC,QAAI,CAAC,gBAAgB,aAAa,QAAQ;AACzC,qBAAe,YAAY,UAAU,CAAC,UAAU;AAC/C,sBAAc;AACd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AAO;AAAA,IACN,mBAAmB;AAAA;AAAA,IAEnB,YAAY,MAAM,WAAc;AAAA;AAAA,IAEhC,aAAa,MAAM,WAAc,EAAE;AAAA,EACpC;AACD;;;ACxCO,IAAM,cAAc,MAEpB,WAAc,EAAE;","names":["jsx"]}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../src/context.ts","../src/createExternalStore.ts","../src/KheopskitProvider.tsx","../src/useWallets.ts","../src/createKheopskit.tsx","../src/useAccounts.ts"],"sourcesContent":["import type { KheopskitState } from \"@kheopskit/core\";\nimport { createContext } from \"react\";\n\nexport const KheopskitContext = createContext<{\n\tstate: KheopskitState;\n} | null>(null);\n","import type { Observable, Subscription } from \"rxjs\";\n\nexport const createExternalStore = <T>(\n\tobservable$: Observable<T>,\n\tinitialValue: T,\n\tserverValue?: T,\n) => {\n\t// Use null as sentinel to indicate we haven't received first emission yet\n\tlet latestValue: T | null = null;\n\tlet subscription: Subscription | null = null;\n\tlet subscriberCount = 0;\n\tconst listeners = new Set<(value: T) => void>();\n\n\tconst ensureSubscription = () => {\n\t\tif (!subscription || subscription.closed) {\n\t\t\tsubscription = observable$.subscribe((value) => {\n\t\t\t\tlatestValue = value;\n\t\t\t\tfor (const listener of listeners) {\n\t\t\t\t\tlistener(value);\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t};\n\n\t// The subscription is created lazily by subscribe() (which React calls from a\n\t// committed passive effect), never during render. React may render a tree and\n\t// throw it away without committing — StrictMode double-invokes the initial\n\t// render, and concurrent/Suspense can discard renders — so subscribing eagerly\n\t// here (createExternalStore runs inside the Provider's render-phase useMemo) would leak\n\t// the discarded store's observable subscription. Until the first emission,\n\t// getSnapshot falls back to initialValue.\n\tconst getSnapshot = () => latestValue ?? initialValue;\n\n\t/**\n\t * Returns the server-side snapshot for SSR hydration.\n\t * This prevents hydration mismatches by providing a consistent\n\t * value during server rendering. Must return the same value as\n\t * what the server rendered.\n\t */\n\tconst getServerSnapshot = () => serverValue ?? initialValue;\n\n\tconst subscribe = (callback: (value: T) => void) => {\n\t\tsubscriberCount++;\n\t\t// Subscribe to the observable BEFORE registering this listener, so a\n\t\t// synchronous replay (BehaviorSubject / shareReplay) updates latestValue\n\t\t// without double-invoking this callback — the current value is emitted once,\n\t\t// explicitly, just below.\n\t\tensureSubscription();\n\t\tlisteners.add(callback);\n\n\t\t// Immediately emit current value (BehaviorSubject semantics)\n\t\tcallback(getSnapshot());\n\n\t\treturn () => {\n\t\t\tsubscriberCount--;\n\t\t\tlisteners.delete(callback);\n\t\t\t// Don't close the observable subscription on unsubscribe\n\t\t\t// Let destroy() handle that when the store is truly being disposed\n\t\t};\n\t};\n\n\tconst destroy = () => {\n\t\t// Only unsubscribe if no one is listening\n\t\t// React StrictMode may call destroy and then immediately resubscribe\n\t\tif (subscriberCount === 0 && subscription) {\n\t\t\tsubscription.unsubscribe();\n\t\t\tsubscription = null;\n\t\t}\n\t};\n\n\treturn {\n\t\tgetSnapshot,\n\t\tgetServerSnapshot,\n\t\tsubscribe,\n\t\tdestroy,\n\t};\n};\n","import {\n\tcreateKheopskitStore,\n\tgetHydratedSnapshot,\n\tgetKheopskit$,\n\ttype KheopskitConfig,\n\ttype KheopskitState,\n\tresolveConfig,\n} from \"@kheopskit/core\";\nimport {\n\ttype FC,\n\ttype PropsWithChildren,\n\tuseEffect,\n\tuseMemo,\n\tuseRef,\n\tuseSyncExternalStore,\n} from \"react\";\nimport { KheopskitContext } from \"./context\";\nimport { createExternalStore } from \"./createExternalStore\";\n\nexport type KheopskitProviderProps = PropsWithChildren & {\n\t/**\n\t * Kheopskit configuration.\n\t *\n\t * @remarks\n\t * Must be a **referentially stable** value — define it once (module scope, a\n\t * `useMemo`, or via {@link createKheopskit}) and pass the same reference. A\n\t * new object literal on every render (`config={{ platforms: [...] }}` inline)\n\t * recreates the underlying store and re-subscribes each render.\n\t */\n\tconfig?: Partial<KheopskitConfig>;\n\t/**\n\t * Cookie string for SSR hydration.\n\t * Pass the request cookie header (e.g., from Next.js headers or TanStack Start)\n\t * to hydrate wallet state on the server.\n\t *\n\t * @remarks\n\t * This value should be stable per render to avoid unnecessary store recreation.\n\t * Compute it once in your server component or layout and pass it down.\n\t *\n\t * @example\n\t * ```tsx\n\t * // Next.js App Router\n\t * const cookieStore = await cookies();\n\t * const ssrCookies = cookieStore.getAll().map(c => `${c.name}=${c.value}`).join('; ');\n\t * return <Providers ssrCookies={ssrCookies}>{children}</Providers>\n\t * ```\n\t */\n\tssrCookies?: string;\n};\n\nexport const KheopskitProvider: FC<KheopskitProviderProps> = ({\n\tchildren,\n\tconfig,\n\tssrCookies,\n}) => {\n\tconst resolvedConfig = useMemo(() => resolveConfig(config), [config]);\n\n\t// Dev-only: warn if the `config` prop reference changes between renders. A new\n\t// object each render recreates the store and re-subscribes the whole pipeline\n\t// (re-hydrating, dropping live connection state) on every render. `config` must\n\t// be referentially stable — define it at module scope, memoize it, or use\n\t// createKheopskit() (which passes a stable reference for you).\n\tconst lastConfigRef = useRef(config);\n\tconst hasMountedRef = useRef(false);\n\tuseEffect(() => {\n\t\tif (\n\t\t\thasMountedRef.current &&\n\t\t\tlastConfigRef.current !== config &&\n\t\t\t(typeof process === \"undefined\" || process.env?.NODE_ENV !== \"production\")\n\t\t) {\n\t\t\tconsole.warn(\n\t\t\t\t\"[kheopskit] KheopskitProvider received a new `config` reference; this \" +\n\t\t\t\t\t\"recreates the store and re-subscribes on every render. Pass a \" +\n\t\t\t\t\t\"referentially stable config (module scope, useMemo, or createKheopskit()).\",\n\t\t\t);\n\t\t}\n\t\thasMountedRef.current = true;\n\t\tlastConfigRef.current = config;\n\t}, [config]);\n\n\t// Create a single store for both reading cached state and powering the observable\n\tconst kheopskitStore = useMemo(\n\t\t() =>\n\t\t\tcreateKheopskitStore({\n\t\t\t\tssrCookies,\n\t\t\t\tstorageKey: resolvedConfig.storageKey,\n\t\t\t}),\n\t\t[ssrCookies, resolvedConfig.storageKey],\n\t);\n\n\t// Read cached state from the store for SSR hydration.\n\t// Icons stay OFF: this snapshot must match the server-rendered markup, and the\n\t// server never sees the localStorage icon cache (see GetHydratedSnapshotOptions).\n\tconst serverValue = useMemo<KheopskitState>(() => {\n\t\tif (ssrCookies === undefined) {\n\t\t\treturn {\n\t\t\t\twallets: [],\n\t\t\t\taccounts: [],\n\t\t\t\tconfig: resolvedConfig,\n\t\t\t\tisHydrating: true,\n\t\t\t};\n\t\t}\n\t\treturn {\n\t\t\t...getHydratedSnapshot(kheopskitStore, resolvedConfig.platforms),\n\t\t\tconfig: resolvedConfig,\n\t\t\tisHydrating: true,\n\t\t};\n\t}, [ssrCookies, kheopskitStore, resolvedConfig]);\n\n\t// Client-only initial snapshot, read straight from the client cache so a hard\n\t// reload paints the cached wallet/account list on the very first frame instead\n\t// of flashing empty until the live observable produces its first emission —\n\t// which can be asynchronous (e.g. WalletConnect's AppKit is loaded via dynamic\n\t// import, so the underlying combineLatest can't emit synchronously).\n\t//\n\t// We can't derive this from `serverValue`: without SSR cookies that stays empty\n\t// (to keep the server/client hydration markup identical), so the SPA case would\n\t// otherwise render nothing. This snapshot is only ever read on the client via\n\t// getSnapshot, so reading the cache here is safe — and getCachedIcon returns \"\"\n\t// on the server, making the icon enrichment a no-op there.\n\tconst initialValue = useMemo<KheopskitState>(() => {\n\t\treturn {\n\t\t\t...getHydratedSnapshot(kheopskitStore, resolvedConfig.platforms, {\n\t\t\t\ticons: true,\n\t\t\t}),\n\t\t\tconfig: resolvedConfig,\n\t\t\tisHydrating: true,\n\t\t};\n\t}, [kheopskitStore, resolvedConfig]);\n\n\tconst store = useMemo(\n\t\t() =>\n\t\t\tcreateExternalStore(\n\t\t\t\tgetKheopskit$(config, { ssrCookies, store: kheopskitStore }),\n\t\t\t\tinitialValue,\n\t\t\t\tserverValue,\n\t\t\t),\n\t\t[config, ssrCookies, kheopskitStore, initialValue, serverValue],\n\t);\n\n\t// Cleanup store subscriptions when store changes or component unmounts\n\tuseEffect(() => {\n\t\treturn () => store.destroy();\n\t}, [store]);\n\n\tconst state = useSyncExternalStore(\n\t\tstore.subscribe,\n\t\tstore.getSnapshot,\n\t\tstore.getServerSnapshot,\n\t);\n\n\tconst value = useMemo(() => ({ state }), [state]);\n\n\treturn (\n\t\t<KheopskitContext.Provider value={value}>\n\t\t\t{children}\n\t\t</KheopskitContext.Provider>\n\t);\n};\n","import type { KheopskitPlatform, KheopskitState } from \"@kheopskit/core\";\nimport { useContext } from \"react\";\nimport { KheopskitContext } from \"./context\";\n\n/**\n * Returns the current kheopskit state (wallets, accounts, config, isHydrating).\n *\n * Pass the platform tuple as a type argument to recover SDK-precise account and\n * wallet types — `useWallets<typeof platforms>()`. React contexts can't be\n * generic, so without the argument the state is typed with the base\n * (SDK-free) wallet/account shapes.\n */\nexport const useWallets = <\n\tP extends readonly KheopskitPlatform[] = readonly KheopskitPlatform[],\n>(): KheopskitState<P> => {\n\tconst ctx = useContext(KheopskitContext);\n\n\tif (!ctx)\n\t\tthrow new Error(\"useWallets can't be used without a KheopskitProvider\");\n\n\treturn ctx.state as unknown as KheopskitState<P>;\n};\n","import type { KheopskitConfig, KheopskitPlatform } from \"@kheopskit/core\";\nimport type { FC, PropsWithChildren } from \"react\";\nimport { KheopskitProvider } from \"./KheopskitProvider\";\nimport { useWallets } from \"./useWallets\";\n\nexport type CreateKheopskitConfig<P extends readonly KheopskitPlatform[]> =\n\tOmit<Partial<KheopskitConfig<P>>, \"platforms\"> & {\n\t\t/** Platform plugins, e.g. `[polkadot(), solana()]`. Required. */\n\t\tplatforms: P;\n\t};\n\n/**\n * Binds a platform tuple once and returns a `KheopskitProvider` plus hooks\n * (`useWallets`, `useAccounts`) already typed to those platforms — so you don't\n * repeat `useWallets<typeof platforms>()` in every component.\n *\n * @example\n * ```tsx\n * // kheopskit.ts\n * export const { KheopskitProvider, useWallets, useAccounts } = createKheopskit({\n * platforms: [polkadot(), ethereum(), solana()],\n * });\n *\n * // anywhere\n * const { accounts } = useWallets(); // accounts are platform-precise, no generic\n * ```\n */\nexport const createKheopskit = <\n\tconst P extends readonly [KheopskitPlatform, ...KheopskitPlatform[]],\n>(\n\tconfig: CreateKheopskitConfig<P>,\n) => {\n\tconst Provider: FC<PropsWithChildren<{ ssrCookies?: string }>> = ({\n\t\tchildren,\n\t\tssrCookies,\n\t}) => (\n\t\t<KheopskitProvider config={config} ssrCookies={ssrCookies}>\n\t\t\t{children}\n\t\t</KheopskitProvider>\n\t);\n\tProvider.displayName = \"KheopskitProvider\";\n\n\treturn {\n\t\tKheopskitProvider: Provider,\n\t\t/** Current state, typed to the bound platform tuple. */\n\t\tuseWallets: () => useWallets<P>(),\n\t\t/** Current accounts, typed to the bound platform tuple. */\n\t\tuseAccounts: () => useWallets<P>().accounts,\n\t};\n};\n","import type { KheopskitPlatform } from \"@kheopskit/core\";\nimport { useWallets } from \"./useWallets\";\n\n/**\n * Convenience hook returning just the accounts from kheopskit state. Pass the\n * platform tuple as a type argument to recover SDK-precise account types —\n * `useAccounts<typeof platforms>()` — or use the pre-typed hook from\n * {@link createKheopskit}.\n */\nexport const useAccounts = <\n\tP extends readonly KheopskitPlatform[] = readonly KheopskitPlatform[],\n>() => useWallets<P>().accounts;\n"],"mappings":";;;;;AAGA,MAAa,mBAAmB,cAEtB,IAAI;;;ACHd,MAAa,uBACZ,aACA,cACA,gBACI;CAEJ,IAAI,cAAwB;CAC5B,IAAI,eAAoC;CACxC,IAAI,kBAAkB;CACtB,MAAM,4BAAY,IAAI,IAAwB;CAE9C,MAAM,2BAA2B;EAChC,IAAI,CAAC,gBAAgB,aAAa,QACjC,eAAe,YAAY,WAAW,UAAU;GAC/C,cAAc;GACd,KAAK,MAAM,YAAY,WACtB,SAAS,KAAK;EAEhB,CAAC;CAEH;CASA,MAAM,oBAAoB,eAAe;;;;;;;CAQzC,MAAM,0BAA0B,eAAe;CAE/C,MAAM,aAAa,aAAiC;EACnD;EAKA,mBAAmB;EACnB,UAAU,IAAI,QAAQ;EAGtB,SAAS,YAAY,CAAC;EAEtB,aAAa;GACZ;GACA,UAAU,OA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AC,KAAK,CAAC;CAEV,MAAM,QAAQ,qBACb,MAAM,WACN,MAAM,aACN,MAAM,iBACP;CAEA,MAAM,QAAQ,eAAe,EAAE,MAAM,IAAI,CAAC,KAAK,CAAC;CAEhD,OACC,oBAAC,iBAAiB,UAAlB;EAAkC;EAChC;CACyB,CAAA;AAE7B;;;;;;;;;;;AClJA,MAAa,mBAEa;CACzB,MAAM,MAAM,WAAW,gBAAgB;CAEvC,IAAI,CAAC,KACJ,MAAM,IAAI,MAAM,sDAAsD;CAEvE,OAAO,IAAI;AACZ;;;;;;;;;;;;;;;;;;;ACMA,MAAa,mBAGZ,WACI;CACJ,MAAM,YAA4D,EACjE,UACA,iBAEA,oBAAC,mBAAD;EAA2B;EAAoB;EAC7C;CACiB,CAAA;CAEpB,SAAS,cAAc;CAEvB,OAAO;EACN,mBAAmB;;EAEnB,kBAAkB,WAAc;;EAEhC,mBAAmB,WAAc,CAAC,CAAC;CACpC;AACD;;;;;;;;;ACxCA,MAAa,oBAEN,WAAc,CAAC,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kheopskit/react",
3
- "version": "5.1.0",
3
+ "version": "5.1.1",
4
4
  "description": "",
5
5
  "private": false,
6
6
  "sideEffects": false,
@@ -35,7 +35,7 @@
35
35
  },
36
36
  "license": "ISC",
37
37
  "peerDependencies": {
38
- "@kheopskit/core": "^5.1.0",
38
+ "@kheopskit/core": "^5.1.1",
39
39
  "react": ">=18.0.0",
40
40
  "react-dom": ">=18.0.0",
41
41
  "rxjs": ">=7.0.0"
@@ -43,17 +43,17 @@
43
43
  "devDependencies": {
44
44
  "@types/react": "^19.2.17",
45
45
  "@types/react-dom": "^19.2.3",
46
- "react": "^19.2.7",
47
- "react-dom": "^19.2.7",
46
+ "react": "^19.2.8",
47
+ "react-dom": "^19.2.8",
48
48
  "rxjs": "^7.8.2",
49
- "@kheopskit/core": "5.1.0"
49
+ "@kheopskit/core": "5.1.1"
50
50
  },
51
- "tsup": {
51
+ "tsdown": {
52
52
  "entry": [
53
53
  "src/index.ts"
54
54
  ],
55
55
  "tsconfig": "tsconfig.build.json",
56
- "splitting": false,
56
+ "fixedExtension": false,
57
57
  "sourcemap": true,
58
58
  "clean": true,
59
59
  "dts": true,
@@ -62,14 +62,14 @@
62
62
  "cjs"
63
63
  ],
64
64
  "target": "es2020",
65
- "banner": {
66
- "js": "\"use client\";"
65
+ "outputOptions": {
66
+ "banner": "\"use client\";"
67
67
  }
68
68
  },
69
69
  "scripts": {
70
70
  "test": "vitest run --root=../.. packages/react",
71
- "dev": "tsup --watch",
72
- "build": "tsup",
71
+ "dev": "tsdown --watch",
72
+ "build": "tsdown",
73
73
  "clean": "rm -rf ./dist && rm -rf ./node_modules",
74
74
  "typecheck": "tsc --noEmit"
75
75
  }