@kheopskit/core 6.0.0-rc.3 → 6.0.0-rc.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/MIGRATING_TO_V6.md +78 -17
  3. package/README.md +138 -34
  4. package/dist/ethereum.d.mts +2 -2
  5. package/dist/ethereum.d.ts +2 -2
  6. package/dist/ethereum.js +4 -4
  7. package/dist/ethereum.js.map +1 -1
  8. package/dist/ethereum.mjs +4 -4
  9. package/dist/ethereum.mjs.map +1 -1
  10. package/dist/index.d.mts +12 -27
  11. package/dist/index.d.ts +12 -27
  12. package/dist/index.js +9 -921
  13. package/dist/index.mjs +4 -916
  14. package/dist/{injectedWallets-BQBgS-f0.js → injectedWallets-D7wzBr_f.js} +2 -2
  15. package/dist/{injectedWallets-BQBgS-f0.js.map → injectedWallets-D7wzBr_f.js.map} +1 -1
  16. package/dist/{injectedWallets-5GL1Jder.mjs → injectedWallets-DHf2lYVb.mjs} +2 -2
  17. package/dist/{injectedWallets-5GL1Jder.mjs.map → injectedWallets-DHf2lYVb.mjs.map} +1 -1
  18. package/dist/instance-1BgEld17.d.ts +109 -0
  19. package/dist/instance-BPAvq0v7.mjs +1457 -0
  20. package/dist/instance-BPAvq0v7.mjs.map +1 -0
  21. package/dist/instance-CCP7uJV3.js +1528 -0
  22. package/dist/instance-CCP7uJV3.js.map +1 -0
  23. package/dist/instance-DDvZiq1L.d.mts +109 -0
  24. package/dist/internal.d.mts +3 -3
  25. package/dist/internal.d.ts +3 -3
  26. package/dist/internal.js +8 -6
  27. package/dist/internal.mjs +3 -3
  28. package/dist/{platformAccounts-yyRUrnel.mjs → platformAccounts-BeMDbmUT.mjs} +2 -2
  29. package/dist/{platformAccounts-yyRUrnel.mjs.map → platformAccounts-BeMDbmUT.mjs.map} +1 -1
  30. package/dist/{platformAccounts-BjIeRcFN.js → platformAccounts-FE7oA3-Y.js} +2 -2
  31. package/dist/{platformAccounts-BjIeRcFN.js.map → platformAccounts-FE7oA3-Y.js.map} +1 -1
  32. package/dist/polkadot.d.mts +2 -2
  33. package/dist/polkadot.d.ts +2 -2
  34. package/dist/polkadot.js +6 -7
  35. package/dist/polkadot.js.map +1 -1
  36. package/dist/polkadot.mjs +5 -6
  37. package/dist/polkadot.mjs.map +1 -1
  38. package/dist/{polkadotExtensions-BoVKhNU_.mjs → registryReads-30CCkmHe.js} +43 -2
  39. package/dist/registryReads-30CCkmHe.js.map +1 -0
  40. package/dist/{polkadotExtensions-y4J9UzYl.js → registryReads-HvSaXRWX.mjs} +30 -5
  41. package/dist/registryReads-HvSaXRWX.mjs.map +1 -0
  42. package/dist/solana.d.mts +2 -2
  43. package/dist/solana.d.ts +2 -2
  44. package/dist/solana.js +4 -4
  45. package/dist/solana.js.map +1 -1
  46. package/dist/solana.mjs +4 -4
  47. package/dist/solana.mjs.map +1 -1
  48. package/dist/testing.d.mts +1 -1
  49. package/dist/testing.d.ts +1 -1
  50. package/dist/{types-C3I3w0jb.d.ts → types-BGeGUtxz.d.mts} +14 -4
  51. package/dist/{types-C3I3w0jb.d.mts → types-BGeGUtxz.d.ts} +14 -4
  52. package/dist/{types-BWHvNFlN.js → types-BrMtrjs9.js} +8 -1
  53. package/dist/types-BrMtrjs9.js.map +1 -0
  54. package/dist/{types-Yor672md.mjs → types-D7OWi0Td.mjs} +3 -2
  55. package/dist/types-D7OWi0Td.mjs.map +1 -0
  56. package/dist/walletconnect.d.mts +13 -2
  57. package/dist/walletconnect.d.ts +13 -2
  58. package/dist/walletconnect.js +19 -13
  59. package/dist/walletconnect.js.map +1 -1
  60. package/dist/walletconnect.mjs +19 -13
  61. package/dist/walletconnect.mjs.map +1 -1
  62. package/package.json +1 -1
  63. package/dist/getCachedObservable-LUq9IfEx.d.mts +0 -23
  64. package/dist/getCachedObservable-LUq9IfEx.d.ts +0 -23
  65. package/dist/iconCache-C-U3IEbP.mjs +0 -324
  66. package/dist/iconCache-C-U3IEbP.mjs.map +0 -1
  67. package/dist/iconCache-FR4iy6go.js +0 -377
  68. package/dist/iconCache-FR4iy6go.js.map +0 -1
  69. package/dist/index.js.map +0 -1
  70. package/dist/index.mjs.map +0 -1
  71. package/dist/polkadotExtensions-BoVKhNU_.mjs.map +0 -1
  72. package/dist/polkadotExtensions-y4J9UzYl.js.map +0 -1
  73. package/dist/registryReads-BpHsWLd7.js +0 -38
  74. package/dist/registryReads-BpHsWLd7.js.map +0 -1
  75. package/dist/registryReads-BvtznSo3.mjs +0 -33
  76. package/dist/registryReads-BvtznSo3.mjs.map +0 -1
  77. package/dist/types-BWHvNFlN.js.map +0 -1
  78. package/dist/types-Yor672md.mjs.map +0 -1
@@ -0,0 +1,1528 @@
1
+ const require_types = require("./types-BrMtrjs9.js");
2
+ const require_platformAccounts = require("./platformAccounts-FE7oA3-Y.js");
3
+ const require_registryReads = require("./registryReads-30CCkmHe.js");
4
+ let lodash_es = require("lodash-es");
5
+ let rxjs = require("rxjs");
6
+ //#region src/api/config.ts
7
+ /**
8
+ * Default storage key for persisting wallet connection state.
9
+ * Can be overridden via config.storageKey to avoid conflicts
10
+ * when running multiple dapps on the same domain.
11
+ */
12
+ const DEFAULT_STORAGE_KEY = "kheopskit";
13
+ const DEFAULTS = {
14
+ autoReconnect: true,
15
+ debug: false,
16
+ storageKey: DEFAULT_STORAGE_KEY,
17
+ hydrationGracePeriod: 500,
18
+ hydrationTimeout: 3e3
19
+ };
20
+ const resolveConfig = (config) => {
21
+ const platforms = config?.platforms ?? [];
22
+ const invalidPlatforms = platforms.filter((p) => typeof p !== "object" || p === null || typeof p.getWallets$ !== "function");
23
+ if (invalidPlatforms.length > 0) throw new Error(`[kheopskit] config.platforms must contain plugin instances created by the per-platform factories (e.g. platforms: [polkadot(), ethereum(), solana()] imported from "@kheopskit/core/<platform>"). Invalid entries: ${JSON.stringify(invalidPlatforms)}. String platform names like "polkadot" were removed in v4 — see MIGRATING_TO_V4.md.`);
24
+ if (config?.walletConnect !== void 0 && typeof config.walletConnect?.getWallet$ !== "function") throw new require_types.KheopskitError("INVALID_CONFIG", "config.walletConnect must be created by walletConnect() imported from \"@kheopskit/core/walletconnect\", e.g. walletConnect: walletConnect({ projectId, metadata, networks }). Raw WalletConnect options were removed in v6, see MIGRATING_TO_V6.md.");
25
+ if (platforms.length === 0) console.warn("[kheopskit] No platforms configured; wallets and accounts will be empty. Pass e.g. platforms: [polkadot()] from \"@kheopskit/core/polkadot\".");
26
+ return Object.assign({}, DEFAULTS, config, { platforms });
27
+ };
28
+ //#endregion
29
+ //#region src/utils/hydrateState.ts
30
+ /**
31
+ * Looks up the icon for a wallet from known Polkadot extensions only.
32
+ * Ethereum icons will be populated from the localStorage icon cache via the merge function.
33
+ *
34
+ * Note: We DON'T use localStorage icon cache here because hydrateWallet is called
35
+ * during SSR (server) and client hydration. localStorage isn't available on server,
36
+ * so using it would cause a hydration mismatch. Icons for Ethereum wallets will be
37
+ * populated when the hydration buffer merges cached wallets with live wallets.
38
+ */
39
+ const lookupWalletIcon = (platform, identifier) => {
40
+ if (platform === "polkadot") return require_registryReads.POLKADOT_EXTENSIONS[identifier]?.icon ?? "";
41
+ return "";
42
+ };
43
+ const hydrateWallet = (cached) => {
44
+ const connect = async () => {
45
+ throw require_types.walletPendingError(cached.id);
46
+ };
47
+ const disconnect = async () => {};
48
+ if (cached.type === "walletconnect") return {
49
+ id: cached.id,
50
+ type: "walletconnect",
51
+ platforms: [],
52
+ name: cached.name,
53
+ icon: "",
54
+ status: cached.isConnected ? "connecting" : "disconnected",
55
+ isPlaceholder: true,
56
+ isConnected: false,
57
+ connect,
58
+ disconnect
59
+ };
60
+ const { platform, identifier } = require_types.parseWalletId(cached.id);
61
+ return {
62
+ id: cached.id,
63
+ platform: cached.platform,
64
+ type: cached.type,
65
+ name: cached.name,
66
+ icon: lookupWalletIcon(platform, identifier),
67
+ status: cached.isConnected ? "connecting" : "disconnected",
68
+ isPlaceholder: true,
69
+ isConnected: false,
70
+ connect,
71
+ disconnect
72
+ };
73
+ };
74
+ const hydrateAccount = (cached) => ({
75
+ id: cached.id,
76
+ isPlaceholder: true,
77
+ platform: cached.platform,
78
+ address: cached.address,
79
+ name: cached.name,
80
+ walletId: cached.walletId,
81
+ walletName: cached.walletName,
82
+ ...cached.platform === "ethereum" && { chainId: cached.chainId },
83
+ ...cached.platform === "polkadot" && { type: cached.polkadotAccountType },
84
+ ...cached.platform === "solana" && { chains: [] }
85
+ });
86
+ /**
87
+ * Converts a wallet to a CachedWallet for storage.
88
+ * Only extracts the serializable properties needed for hydration.
89
+ */
90
+ const serializeWallet = (wallet) => ({
91
+ id: wallet.id,
92
+ platform: require_types.isWalletConnectWallet(wallet) ? void 0 : wallet.platform,
93
+ type: wallet.type,
94
+ name: wallet.name,
95
+ isConnected: wallet.isConnected
96
+ });
97
+ /**
98
+ * Converts an account to a CachedAccount for storage.
99
+ * Only extracts the serializable properties needed for hydration. Platform-only
100
+ * fields (Ethereum chainId, Polkadot key type) are read defensively so this
101
+ * stays SDK-free.
102
+ */
103
+ const serializeAccount = (account) => ({
104
+ id: account.id,
105
+ platform: account.platform,
106
+ address: account.address,
107
+ name: account.name,
108
+ chainId: account.platform === "ethereum" ? account.chainId : void 0,
109
+ polkadotAccountType: account.platform === "polkadot" ? account.type : void 0,
110
+ walletId: account.walletId,
111
+ walletName: account.walletName
112
+ });
113
+ //#endregion
114
+ //#region src/utils/storage.ts
115
+ /**
116
+ * A no-op storage implementation that does nothing.
117
+ * Useful for testing or SSR environments where no storage is needed.
118
+ */
119
+ const noopStorage = {
120
+ getItem: () => null,
121
+ setItem: () => {},
122
+ removeItem: () => {}
123
+ };
124
+ /**
125
+ * Cached localStorage wrapper instance.
126
+ * Lazily initialized on first access to avoid SSR issues.
127
+ */
128
+ let _safeLocalStorage = null;
129
+ /**
130
+ * Creates the localStorage wrapper, testing for availability.
131
+ * Returns noopStorage if localStorage is unavailable (SSR, private browsing, etc.)
132
+ */
133
+ const createSafeLocalStorage = () => {
134
+ if (typeof window === "undefined") return noopStorage;
135
+ try {
136
+ const testKey = "__kheopskit_test__";
137
+ window.localStorage.setItem(testKey, testKey);
138
+ window.localStorage.removeItem(testKey);
139
+ return {
140
+ getItem: (key) => window.localStorage.getItem(key),
141
+ setItem: (key, value) => window.localStorage.setItem(key, value),
142
+ removeItem: (key) => window.localStorage.removeItem(key),
143
+ subscribe: (key, callback) => {
144
+ const handler = (event) => {
145
+ if (event.key === key) callback(event.newValue);
146
+ };
147
+ window.addEventListener("storage", handler);
148
+ return () => window.removeEventListener("storage", handler);
149
+ }
150
+ };
151
+ } catch {
152
+ return noopStorage;
153
+ }
154
+ };
155
+ /**
156
+ * A safe localStorage wrapper that falls back to noopStorage
157
+ * when localStorage is not available (e.g., during SSR).
158
+ * Includes cross-tab sync via the native 'storage' event.
159
+ *
160
+ * Lazily initialized on first access to be SSR-safe.
161
+ */
162
+ const getSafeLocalStorage = () => {
163
+ if (_safeLocalStorage === null) _safeLocalStorage = createSafeLocalStorage();
164
+ return _safeLocalStorage;
165
+ };
166
+ /**
167
+ * @deprecated Use getSafeLocalStorage() instead. This is kept for backward compatibility.
168
+ * Returns a proxy that lazily initializes on first use.
169
+ */
170
+ const safeLocalStorage = {
171
+ getItem: (key) => getSafeLocalStorage().getItem(key),
172
+ setItem: (key, value) => getSafeLocalStorage().setItem(key, value),
173
+ removeItem: (key) => getSafeLocalStorage().removeItem(key),
174
+ get subscribe() {
175
+ return getSafeLocalStorage().subscribe;
176
+ }
177
+ };
178
+ /**
179
+ * Parse a cookie string to extract the value for a specific key.
180
+ * @param cookieString - The full cookie header string (e.g., document.cookie or req.headers.cookie)
181
+ * @param key - The cookie key to find
182
+ * @returns The cookie value or null if not found
183
+ */
184
+ const parseCookie = (cookieString, key) => {
185
+ if (!cookieString) return null;
186
+ for (const cookie of cookieString.split(";")) {
187
+ const [k, ...v] = cookie.split("=");
188
+ if (k?.trim() === key) try {
189
+ return decodeURIComponent(v.join("=").trim());
190
+ } catch {
191
+ return null;
192
+ }
193
+ }
194
+ return null;
195
+ };
196
+ /**
197
+ * Maximum recommended size for cookie storage (3KB to stay well under 4KB limit).
198
+ *
199
+ * @remarks
200
+ * Cookie storage is subject to browser limits (typically 4KB per cookie).
201
+ * When users connect many wallets, the auto-reconnect list may exceed this limit.
202
+ * If this happens:
203
+ * - A console warning will be logged
204
+ * - Some browsers may silently reject the cookie
205
+ * - Consider using fewer simultaneous wallet connections
206
+ *
207
+ * The stored data includes wallet IDs in format `platform:identifier`
208
+ * (e.g., `polkadot:talisman`, `ethereum:io.metamask`).
209
+ */
210
+ const COOKIE_MAX_SIZE = 3072;
211
+ /**
212
+ * BroadcastChannel name for cross-tab cookie sync.
213
+ */
214
+ const BROADCAST_CHANNEL_NAME = "kheopskit-storage-sync";
215
+ /**
216
+ * Singleton BroadcastChannel for cross-tab cookie sync.
217
+ * Created once and shared across all cookieStorage instances.
218
+ */
219
+ let sharedBroadcastChannel = null;
220
+ const getBroadcastChannel = () => {
221
+ if (sharedBroadcastChannel) return sharedBroadcastChannel;
222
+ if (typeof BroadcastChannel === "undefined") return null;
223
+ try {
224
+ sharedBroadcastChannel = new BroadcastChannel(BROADCAST_CHANNEL_NAME);
225
+ } catch {}
226
+ return sharedBroadcastChannel;
227
+ };
228
+ /**
229
+ * Check if the current connection is secure (HTTPS).
230
+ * Must be called at runtime (inside methods) to work correctly after SSR hydration.
231
+ */
232
+ const isSecureConnection = () => typeof window !== "undefined" && window.location.protocol === "https:";
233
+ /**
234
+ * A cookie-based storage implementation for SSR environments.
235
+ * Reads cookies from an optional initial cookie string (for SSR hydration),
236
+ * writes to document.cookie on the client.
237
+ *
238
+ * Features:
239
+ * - Secure flag automatically added for HTTPS connections
240
+ * - Cross-tab synchronization via BroadcastChannel API
241
+ * - Size limit warning when data exceeds recommended limits
242
+ *
243
+ * @param initialCookies - Optional cookie string for server-side hydration
244
+ */
245
+ const cookieStorage = (initialCookies) => {
246
+ return {
247
+ getItem: (key) => {
248
+ const cookieString = typeof document !== "undefined" ? document.cookie : initialCookies;
249
+ return parseCookie(cookieString, key);
250
+ },
251
+ setItem: (key, value) => {
252
+ if (typeof document === "undefined") return;
253
+ const encodedValue = encodeURIComponent(value);
254
+ if (encodedValue.length > 3072) console.warn(`[kheopskit] Cookie value for "${key}" exceeds recommended size limit (${encodedValue.length} > ${COOKIE_MAX_SIZE} bytes). This may cause issues with cookie storage. Consider reducing the number of connected wallets.`);
255
+ const expires = /* @__PURE__ */ new Date();
256
+ expires.setFullYear(expires.getFullYear() + 1);
257
+ let cookieStr = `${key}=${encodedValue};expires=${expires.toUTCString()};path=/;SameSite=Lax`;
258
+ if (isSecureConnection()) cookieStr += ";Secure";
259
+ document.cookie = cookieStr;
260
+ getBroadcastChannel()?.postMessage({
261
+ type: "set",
262
+ key,
263
+ value
264
+ });
265
+ },
266
+ removeItem: (key) => {
267
+ if (typeof document === "undefined") return;
268
+ let cookieStr = `${key}=;expires=Thu, 01 Jan 1970 00:00:01 GMT;path=/;SameSite=Lax`;
269
+ if (isSecureConnection()) cookieStr += ";Secure";
270
+ document.cookie = cookieStr;
271
+ getBroadcastChannel()?.postMessage({
272
+ type: "remove",
273
+ key
274
+ });
275
+ },
276
+ subscribe: (key, callback) => {
277
+ const channel = getBroadcastChannel();
278
+ if (!channel) return () => {};
279
+ const handler = (event) => {
280
+ const data = event.data;
281
+ if (data.key === key) {
282
+ if (data.type === "set") callback(data.value ?? null);
283
+ else if (data.type === "remove") callback(null);
284
+ }
285
+ };
286
+ channel.addEventListener("message", handler);
287
+ return () => {
288
+ channel.removeEventListener("message", handler);
289
+ };
290
+ }
291
+ };
292
+ };
293
+ //#endregion
294
+ //#region src/utils/iconCache.ts
295
+ /**
296
+ * Storage key for the icon cache in localStorage.
297
+ */
298
+ const ICON_CACHE_KEY = "kheopskit-icons";
299
+ /**
300
+ * In-memory cache to avoid repeated localStorage reads.
301
+ */
302
+ let memoryCache = null;
303
+ /**
304
+ * Loads the icon cache from localStorage.
305
+ */
306
+ const loadCache = () => {
307
+ if (memoryCache !== null) return memoryCache;
308
+ try {
309
+ const stored = safeLocalStorage.getItem(ICON_CACHE_KEY);
310
+ memoryCache = stored ? JSON.parse(stored) : {};
311
+ } catch {
312
+ memoryCache = {};
313
+ }
314
+ return memoryCache;
315
+ };
316
+ /**
317
+ * Saves the icon cache to localStorage.
318
+ */
319
+ const saveCache = (cache) => {
320
+ try {
321
+ safeLocalStorage.setItem(ICON_CACHE_KEY, JSON.stringify(cache));
322
+ memoryCache = cache;
323
+ } catch {}
324
+ };
325
+ /**
326
+ * Gets a cached icon for a wallet.
327
+ * @param walletId - The wallet ID (e.g., "ethereum:io.talisman")
328
+ * @returns The cached icon data URI, or undefined if not cached
329
+ */
330
+ const getCachedIcon = (walletId) => {
331
+ return loadCache()[walletId] || void 0;
332
+ };
333
+ /**
334
+ * Sets multiple cached icons at once.
335
+ * More efficient than calling setCachedIcon multiple times.
336
+ * @param icons - Map of wallet ID to icon
337
+ */
338
+ const setCachedIcons = (icons) => {
339
+ const cache = loadCache();
340
+ let changed = false;
341
+ for (const [walletId, icon] of Object.entries(icons)) if (icon && cache[walletId] !== icon) {
342
+ cache[walletId] = icon;
343
+ changed = true;
344
+ }
345
+ if (changed) saveCache(cache);
346
+ };
347
+ //#endregion
348
+ //#region src/utils/sortAccounts.ts
349
+ const PLATFORM_ORDER$1 = {
350
+ polkadot: 0,
351
+ ethereum: 1,
352
+ solana: 2
353
+ };
354
+ const byPlatform = (a1, a2) => PLATFORM_ORDER$1[a1.platform] - PLATFORM_ORDER$1[a2.platform];
355
+ const byWalletName = (a1, a2) => {
356
+ if (a1.walletName === a2.walletName) return 0;
357
+ if (a1.walletName.toLowerCase() === "talisman") return -1;
358
+ if (a2.walletName.toLowerCase() === "talisman") return 1;
359
+ return a1.walletName.localeCompare(a2.walletName);
360
+ };
361
+ const sortAccounts = (a1, a2) => byPlatform(a1, a2) || byWalletName(a1, a2);
362
+ //#endregion
363
+ //#region src/utils/sortWallets.ts
364
+ const PLATFORM_ORDER = {
365
+ polkadot: 0,
366
+ ethereum: 1,
367
+ solana: 2
368
+ };
369
+ const orderOf = (wallet) => require_types.isWalletConnectWallet(wallet) ? 3 : PLATFORM_ORDER[wallet.platform];
370
+ const sortWallets = (w1, w2) => {
371
+ const o1 = orderOf(w1);
372
+ const o2 = orderOf(w2);
373
+ if (o1 !== o2) return o1 - o2;
374
+ if (w1.name.toLowerCase() === "talisman") return -1;
375
+ if (w2.name.toLowerCase() === "talisman") return 1;
376
+ return w1.name.localeCompare(w2.name);
377
+ };
378
+ //#endregion
379
+ //#region src/api/platform.ts
380
+ const acceptsCachedWallet = (cached, config) => cached.type === "walletconnect" ? config.walletConnect !== void 0 : config.platforms.some((p) => p.platform === cached.platform);
381
+ const acceptsCachedAccount = (cached, platforms) => {
382
+ const plugin = platforms.find((p) => p.platform === cached.platform);
383
+ return plugin !== void 0 && (plugin.acceptsCachedAccount?.(cached) ?? true);
384
+ };
385
+ //#endregion
386
+ //#region src/api/reconnectPolicy.ts
387
+ const createReconnectPolicy = ({ maxAttempts = 3 } = {}) => {
388
+ const states = /* @__PURE__ */ new Map();
389
+ const shouldAttempt = (walletId) => {
390
+ const state = states.get(walletId);
391
+ if (!state) return true;
392
+ return state.kind === "failed" && state.attempts < maxAttempts;
393
+ };
394
+ const attempt = async (walletId, connect) => {
395
+ if (!shouldAttempt(walletId)) return false;
396
+ const before = states.get(walletId);
397
+ states.set(walletId, { kind: "pending" });
398
+ const recordOutcome = (outcome) => {
399
+ if (states.get(walletId)?.kind !== "settled") states.set(walletId, outcome);
400
+ };
401
+ try {
402
+ await connect();
403
+ recordOutcome({ kind: "reconnected" });
404
+ return true;
405
+ } catch (err) {
406
+ recordOutcome({
407
+ kind: "failed",
408
+ attempts: before?.kind === "failed" ? before.attempts + 1 : 1
409
+ });
410
+ throw err;
411
+ }
412
+ };
413
+ const settle = (walletId) => {
414
+ states.set(walletId, { kind: "settled" });
415
+ };
416
+ return {
417
+ shouldAttempt,
418
+ attempt,
419
+ settle
420
+ };
421
+ };
422
+ const reconnectAccepts = (autoReconnect, wallet) => typeof autoReconnect === "function" ? autoReconnect(wallet) : autoReconnect;
423
+ const reconnectCandidates$ = (store) => {
424
+ const remembered$ = store.observable.pipe((0, rxjs.map)((s) => s.remembered ?? []));
425
+ return remembered$.pipe((0, rxjs.take)(1), (0, rxjs.switchMap)((initial) => remembered$.pipe((0, rxjs.scan)((remaining, current) => remaining.filter((id) => current.includes(id)), initial))), (0, rxjs.distinctUntilChanged)(lodash_es.isEqual));
426
+ };
427
+ //#endregion
428
+ //#region src/api/hydration.ts
429
+ /**
430
+ * Builds placeholder wallets and accounts from the store's cached state,
431
+ * sorted like the live pipeline. Omits wallets of platforms missing from
432
+ * `config.platforms`, the WalletConnect row when `config.walletConnect` is
433
+ * unset, and every account of a platform missing from `config.platforms` or
434
+ * whose wallet is not among the returned wallets. A cached connected injected
435
+ * wallet that `autoReconnect` rejects comes back `disconnected`, and a wallet
436
+ * that comes back `disconnected` has no accounts. Each remaining account must
437
+ * pass its platform plugin's `acceptsCachedAccount` hook.
438
+ *
439
+ * This is the single implementation behind the observable's initial seed and
440
+ * both React snapshot sources (`serverValue`/`initialValue`). They must produce
441
+ * the same shape in the same order or the UI flickers/reorders on reload — by
442
+ * sharing this helper, that agreement holds by construction.
443
+ */
444
+ const getHydratedSnapshot = (store, config, options = {}) => {
445
+ const cached = store.getCachedState();
446
+ const wallets = cached.wallets.filter((wallet) => acceptsCachedWallet(wallet, config)).map(hydrateWallet).map((wallet) => wallet.status === "connecting" && require_types.isInjectedWallet(wallet) && !reconnectAccepts(config.autoReconnect, wallet) ? {
447
+ ...wallet,
448
+ status: "disconnected"
449
+ } : wallet).map((wallet) => {
450
+ if (!options.icons || wallet.icon) return wallet;
451
+ const icon = getCachedIcon(wallet.id);
452
+ return icon ? {
453
+ ...wallet,
454
+ icon
455
+ } : wallet;
456
+ }).sort(sortWallets);
457
+ const walletsWithAccounts = new Set(wallets.filter((w) => w.status !== "disconnected").map((w) => w.id));
458
+ return {
459
+ wallets,
460
+ accounts: cached.accounts.filter((account) => walletsWithAccounts.has(account.walletId)).filter((account) => acceptsCachedAccount(account, config.platforms)).map(hydrateAccount).sort(sortAccounts)
461
+ };
462
+ };
463
+ //#endregion
464
+ //#region src/utils/createHydrationBuffer.ts
465
+ const createBufferCore = (cachedItems, liveItems$, gracePeriodMs, timeoutMs, mergeFn, settled$) => {
466
+ if (gracePeriodMs <= 0 || cachedItems.length === 0) return liveItems$.pipe((0, rxjs.map)((items) => ({
467
+ items,
468
+ isHydrating: false
469
+ })));
470
+ return new rxjs.Observable((subscriber) => {
471
+ const subscriptions = new rxjs.Subscription();
472
+ const isHydrating$ = new rxjs.BehaviorSubject(true);
473
+ const endHydration = () => {
474
+ if (isHydrating$.value) isHydrating$.next(false);
475
+ };
476
+ const graceElapsed$ = (0, rxjs.timer)(gracePeriodMs).pipe((0, rxjs.map)(() => true), (0, rxjs.startWith)(false));
477
+ const ended$ = settled$ ? (0, rxjs.combineLatest)([graceElapsed$, settled$]).pipe((0, rxjs.filter)(([graceElapsed, settled]) => graceElapsed && settled), (0, rxjs.take)(1)) : (0, rxjs.timer)(gracePeriodMs);
478
+ subscriptions.add(ended$.subscribe(endHydration));
479
+ subscriptions.add((0, rxjs.timer)(timeoutMs).subscribe(endHydration));
480
+ subscriptions.add((0, rxjs.combineLatest)([liveItems$.pipe((0, rxjs.startWith)([])), isHydrating$]).pipe((0, rxjs.map)(([liveItems, isHydrating]) => isHydrating ? {
481
+ items: mergeFn(liveItems, cachedItems),
482
+ isHydrating
483
+ } : {
484
+ items: liveItems,
485
+ isHydrating
486
+ })).subscribe(subscriber));
487
+ return () => {
488
+ subscriptions.unsubscribe();
489
+ isHydrating$.complete();
490
+ };
491
+ });
492
+ };
493
+ /**
494
+ * Creates a hydration buffer that merges cached items with live items.
495
+ *
496
+ * During hydration, cached items take precedence over live items with the same key.
497
+ * This preserves the cached connected state (e.g., isConnected: true) while
498
+ * auto-reconnect is still in progress. New live items not in the cache are added.
499
+ *
500
+ * @param cachedItems - Initial cached items from storage
501
+ * @param liveItems$ - Observable of live items as they become available
502
+ * @param gracePeriodMs - Minimum time in ms the cached items are shown
503
+ * @param timeoutMs - Upper bound in ms on hydration
504
+ * @param getKey - Function to extract a unique key from an item
505
+ * @param settled$ - Whether the live state has caught up with the cache
506
+ * @param mergeItem - Optional function to merge a live item with its cached counterpart
507
+ * @param transformCachedOnly - Optional function to transform cached items not yet in the live stream
508
+ */
509
+ const createHydrationBuffer = (cachedItems, liveItems$, gracePeriodMs, timeoutMs, getKey, settled$, mergeItem, transformCachedOnly) => {
510
+ return createBufferCore(cachedItems, liveItems$, gracePeriodMs, timeoutMs, (liveItems, cached) => {
511
+ const cachedByKey = new Map(cached.map((item) => [getKey(item), item]));
512
+ const liveKeys = new Set(liveItems.map(getKey));
513
+ const mergedItems = liveItems.map((liveItem) => {
514
+ const key = getKey(liveItem);
515
+ const cachedItem = cachedByKey.get(key);
516
+ if (!cachedItem) return liveItem;
517
+ return mergeItem ? mergeItem(liveItem, cachedItem) : cachedItem;
518
+ });
519
+ for (const cachedItem of cached) if (!liveKeys.has(getKey(cachedItem))) {
520
+ const transformed = transformCachedOnly ? transformCachedOnly(cachedItem) : cachedItem;
521
+ mergedItems.push(transformed);
522
+ }
523
+ return mergedItems;
524
+ }, settled$);
525
+ };
526
+ /**
527
+ * Creates a hydration buffer specifically for accounts, which need special handling.
528
+ *
529
+ * Accounts are grouped by wallet - when a wallet provides its account list,
530
+ * we replace all cached accounts for that wallet with the live ones.
531
+ * Cached accounts for wallets that haven't provided accounts yet are preserved.
532
+ *
533
+ * @param cachedAccounts - Initial cached accounts from storage
534
+ * @param liveAccounts$ - Observable of live accounts as they become available
535
+ * @param gracePeriodMs - Minimum time in ms the cached accounts are shown
536
+ * @param timeoutMs - Upper bound in ms on hydration
537
+ * @param getWalletId - Function to extract the wallet ID from an account
538
+ * @param settled$ - Whether the live state has caught up with the cache
539
+ */
540
+ const createAccountHydrationBuffer = (cachedAccounts, liveAccounts$, gracePeriodMs, timeoutMs, getWalletId, settled$) => {
541
+ return createBufferCore(cachedAccounts, liveAccounts$, gracePeriodMs, timeoutMs, (liveAccounts, cached) => {
542
+ const walletsWithLiveAccounts = new Set(liveAccounts.map(getWalletId));
543
+ const mergedAccounts = [...liveAccounts];
544
+ for (const cachedAccount of cached) if (!walletsWithLiveAccounts.has(getWalletId(cachedAccount))) mergedAccounts.push(cachedAccount);
545
+ return mergedAccounts;
546
+ }, settled$);
547
+ };
548
+ //#endregion
549
+ //#region src/utils/logObservable.ts
550
+ const logObservable = (label, opts) => (0, rxjs.tap)((value) => {
551
+ const { printValue = false, enabled = true } = opts || {};
552
+ if (!label || !enabled) return;
553
+ const text = `[kheopskit] observable ${label} emit`;
554
+ if (printValue) console.debug(text, value);
555
+ else console.debug(text);
556
+ });
557
+ //#endregion
558
+ //#region src/api/accounts.ts
559
+ const getAccounts$ = (config, wallets) => {
560
+ return new rxjs.Observable((subscriber) => {
561
+ const sources = config.platforms.map((plugin) => require_platformAccounts.framesOf(plugin.getAccounts$(wallets.pipe((0, rxjs.map)((ws) => ws.filter((w) => require_types.isWalletConnectWallet(w) || w.platform === plugin.platform))))));
562
+ const sub = (sources.length ? (0, rxjs.combineLatest)(sources).pipe((0, rxjs.map)((frames) => ({
563
+ accounts: frames.flatMap((frame) => frame.accounts).sort(sortAccounts),
564
+ answered: frames.flatMap((frame) => frame.answered)
565
+ }))) : (0, rxjs.of)({
566
+ accounts: [],
567
+ answered: []
568
+ })).subscribe(subscriber);
569
+ return () => {
570
+ sub.unsubscribe();
571
+ };
572
+ }).pipe((0, rxjs.shareReplay)({
573
+ refCount: true,
574
+ bufferSize: 1
575
+ }));
576
+ };
577
+ //#endregion
578
+ //#region src/utils/createStore.ts
579
+ const createStore = (key, defaultValue, storage = safeLocalStorage, normalize = (value) => value) => {
580
+ const read = (str) => normalize(parseData(str, defaultValue));
581
+ const syncsAcrossTabs = typeof window !== "undefined" && storage.subscribe !== void 0;
582
+ const subject = new rxjs.BehaviorSubject(read(storage.getItem(key)));
583
+ let observers = 0;
584
+ let stopSync;
585
+ const latestValue = () => {
586
+ if (syncsAcrossTabs && observers === 0) subject.next(read(storage.getItem(key)));
587
+ return subject.getValue();
588
+ };
589
+ const observable = new rxjs.Observable((subscriber) => {
590
+ if (observers === 0 && syncsAcrossTabs) {
591
+ latestValue();
592
+ stopSync = storage.subscribe?.(key, (newValue) => {
593
+ subject.next(read(newValue));
594
+ });
595
+ }
596
+ observers++;
597
+ const subscription = subject.subscribe(subscriber);
598
+ return () => {
599
+ subscription.unsubscribe();
600
+ observers--;
601
+ if (observers === 0) stopSync?.();
602
+ };
603
+ });
604
+ const update = (val) => {
605
+ persistBestEffort(key, val, storage);
606
+ subject.next(val);
607
+ };
608
+ return {
609
+ observable,
610
+ set: (val) => update(val),
611
+ mutate: (transform) => update(transform(latestValue())),
612
+ get: () => structuredClone(latestValue()),
613
+ destroy: () => subject.complete()
614
+ };
615
+ };
616
+ const parseData = (str, defaultValue) => {
617
+ try {
618
+ if (str) return JSON.parse(str);
619
+ } catch {}
620
+ return defaultValue;
621
+ };
622
+ const persistBestEffort = (key, val, storage) => {
623
+ const str = JSON.stringify(val);
624
+ try {
625
+ storage.setItem(key, str);
626
+ } catch {}
627
+ };
628
+ //#endregion
629
+ //#region src/api/compactStore.ts
630
+ const EMPTY_STORE_DATA = {};
631
+ const migratePreV6StoreData = (data) => {
632
+ if (data?.autoReconnect === void 0) return data;
633
+ const { autoReconnect, ...rest } = data;
634
+ return rest.remembered === void 0 && Array.isArray(autoReconnect) ? {
635
+ ...rest,
636
+ remembered: autoReconnect
637
+ } : rest;
638
+ };
639
+ const toCompactPolkadotAccountType = (type) => {
640
+ switch (type) {
641
+ case "sr25519": return 0;
642
+ case "ed25519": return 1;
643
+ case "ecdsa": return 2;
644
+ case "ethereum": return 3;
645
+ default: return null;
646
+ }
647
+ };
648
+ const fromCompactPolkadotAccountType = (type) => {
649
+ switch (type) {
650
+ case 0: return "sr25519";
651
+ case 1: return "ed25519";
652
+ case 2: return "ecdsa";
653
+ case 3: return "ethereum";
654
+ default: return;
655
+ }
656
+ };
657
+ const toCompactPlatform = (platform) => {
658
+ switch (platform) {
659
+ case "polkadot": return 0;
660
+ case "ethereum": return 1;
661
+ case "solana": return 2;
662
+ }
663
+ };
664
+ const fromCompactPlatform = (code) => {
665
+ switch (code) {
666
+ case 0: return "polkadot";
667
+ case 1: return "ethereum";
668
+ case 2: return "solana";
669
+ default: return;
670
+ }
671
+ };
672
+ const isCompactStore = (value) => {
673
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
674
+ if ("cachedWallets" in value || "cachedAccounts" in value) return false;
675
+ return "v" in value || "w" in value || "a" in value || "r" in value;
676
+ };
677
+ const toCompactStore = (data) => {
678
+ const wallets = data.cachedWallets?.map((wallet) => [
679
+ wallet.id,
680
+ wallet.name,
681
+ wallet.isConnected ? 1 : 0,
682
+ wallet.type === "walletconnect" ? 1 : 0
683
+ ]);
684
+ const accounts = data.cachedAccounts?.map((account) => [
685
+ account.walletId,
686
+ account.address,
687
+ account.name ?? null,
688
+ account.chainId ?? null,
689
+ toCompactPolkadotAccountType(account.polkadotAccountType),
690
+ toCompactPlatform(account.platform)
691
+ ]);
692
+ return {
693
+ v: 1,
694
+ r: data.remembered,
695
+ w: wallets?.length ? wallets : void 0,
696
+ a: accounts?.length ? accounts : void 0
697
+ };
698
+ };
699
+ const fromCompactStore = (data) => {
700
+ const walletNameMap = /* @__PURE__ */ new Map();
701
+ const wallets = [];
702
+ for (const item of Array.isArray(data.w) ? data.w : []) {
703
+ if (!Array.isArray(item)) continue;
704
+ const [id, name, isConnected, type] = item;
705
+ if (!require_types.isValidWalletId(id)) continue;
706
+ const isWalletConnect = id === require_types.WALLET_CONNECT_WALLET_ID;
707
+ const walletType = type === 1 ? "walletconnect" : "injected";
708
+ if (isWalletConnect !== (walletType === "walletconnect")) continue;
709
+ walletNameMap.set(id, name);
710
+ wallets.push({
711
+ id,
712
+ platform: isWalletConnect ? void 0 : require_types.parseWalletId(id).platform,
713
+ type: walletType,
714
+ name,
715
+ isConnected: isConnected === 1
716
+ });
717
+ }
718
+ const accounts = [];
719
+ for (const item of Array.isArray(data.a) ? data.a : []) {
720
+ if (!Array.isArray(item)) continue;
721
+ const [walletId, address, name, chainId, polkadotAccountType, platformCode] = item;
722
+ if (!require_types.isValidWalletId(walletId) || typeof address !== "string" || !address) continue;
723
+ const platform = platformCode != null ? fromCompactPlatform(platformCode) : walletId === "walletconnect" ? void 0 : require_types.parseWalletId(walletId).platform;
724
+ if (!require_types.isWalletPlatform(platform)) continue;
725
+ accounts.push({
726
+ id: require_platformAccounts.getWalletAccountId(walletId, address),
727
+ platform,
728
+ address,
729
+ name: name ?? void 0,
730
+ chainId: chainId ?? void 0,
731
+ polkadotAccountType: platform === "polkadot" ? fromCompactPolkadotAccountType(polkadotAccountType) : void 0,
732
+ walletId,
733
+ walletName: walletNameMap.get(walletId) ?? walletId
734
+ });
735
+ }
736
+ return {
737
+ remembered: data.r,
738
+ cachedWallets: wallets,
739
+ cachedAccounts: accounts
740
+ };
741
+ };
742
+ const decodeStore = (raw, fallback) => {
743
+ try {
744
+ const parsed = JSON.parse(raw);
745
+ if (isCompactStore(parsed)) return fromCompactStore(parsed);
746
+ return migratePreV6StoreData(parsed);
747
+ } catch {
748
+ return fallback;
749
+ }
750
+ };
751
+ const encodeStore = (data) => JSON.stringify(toCompactStore(data));
752
+ /**
753
+ * Cookie storage that transparently encodes/decodes {@link CompactStoreV1},
754
+ * migrating legacy verbose-JSON cookies to the compact format on first read.
755
+ */
756
+ const createCompactCookieStorage = (initialCookies) => {
757
+ const base = cookieStorage(initialCookies);
758
+ return {
759
+ getItem: (key) => {
760
+ const raw = base.getItem(key);
761
+ if (!raw) return null;
762
+ const expanded = decodeStore(raw, EMPTY_STORE_DATA);
763
+ if (typeof document !== "undefined") try {
764
+ const parsed = JSON.parse(raw);
765
+ if (!isCompactStore(parsed)) base.setItem(key, encodeStore(expanded));
766
+ } catch {}
767
+ return JSON.stringify(expanded);
768
+ },
769
+ setItem: (key, value) => {
770
+ const expanded = decodeStore(value, EMPTY_STORE_DATA);
771
+ base.setItem(key, encodeStore(expanded));
772
+ },
773
+ removeItem: base.removeItem,
774
+ subscribe: (key, callback) => {
775
+ const unsubscribe = base.subscribe?.(key, (value) => {
776
+ if (!value) {
777
+ callback(null);
778
+ return;
779
+ }
780
+ const expanded = decodeStore(value, EMPTY_STORE_DATA);
781
+ callback(JSON.stringify(expanded));
782
+ });
783
+ return () => {
784
+ unsubscribe?.();
785
+ };
786
+ }
787
+ };
788
+ };
789
+ //#endregion
790
+ //#region src/api/store.ts
791
+ const DEFAULT_SETTINGS = {};
792
+ /**
793
+ * Validates a cached wallet read from persisted storage. Cached state may have
794
+ * been written by an older (or corrupted) version with a different shape, so we
795
+ * drop anything that wouldn't survive hydration/sort rather than letting it
796
+ * throw at render time. Only the fields downstream code relies on are checked.
797
+ */
798
+ const isValidCachedWallet = (value) => {
799
+ if (!value || typeof value !== "object") return false;
800
+ const w = value;
801
+ if (!require_types.isValidWalletId(w.id)) return false;
802
+ if (typeof w.name !== "string" || typeof w.isConnected !== "boolean") return false;
803
+ if (w.type === "walletconnect") return w.id === "walletconnect" && w.platform === void 0;
804
+ return w.type === "injected" && require_types.isWalletPlatform(w.platform);
805
+ };
806
+ /** Validates a cached account read from persisted storage. See {@link isValidCachedWallet}. */
807
+ const isValidCachedAccount = (value) => {
808
+ if (!value || typeof value !== "object") return false;
809
+ const a = value;
810
+ return typeof a.id === "string" && !!a.id && require_types.isWalletPlatform(a.platform) && typeof a.address === "string" && !!a.address && require_types.isValidWalletId(a.walletId) && typeof a.walletName === "string";
811
+ };
812
+ /**
813
+ * Creates a kheopskit store with the appropriate storage backend.
814
+ * Uses the given `storage` when provided, else cookieStorage when ssrCookies is
815
+ * provided (for SSR hydration), otherwise safeLocalStorage.
816
+ *
817
+ * @param options - Configuration options for the store
818
+ */
819
+ const createKheopskitStore = (options = {}) => {
820
+ const { ssrCookies, storageKey = DEFAULT_STORAGE_KEY } = options;
821
+ const storage = options.storage ?? (ssrCookies !== void 0 ? createCompactCookieStorage(ssrCookies) : safeLocalStorage);
822
+ const store = createStore(storageKey, DEFAULT_SETTINGS, storage, migratePreV6StoreData);
823
+ const rememberWallet = (walletId) => {
824
+ require_types.parseWalletId(walletId);
825
+ store.mutate((prev) => ({
826
+ ...prev,
827
+ remembered: (0, lodash_es.uniq)((prev.remembered ?? []).concat(walletId))
828
+ }));
829
+ };
830
+ const forgetWallet = (walletId) => {
831
+ store.mutate((prev) => ({
832
+ ...prev,
833
+ remembered: (0, lodash_es.uniq)((prev.remembered ?? []).filter((id) => id !== walletId))
834
+ }));
835
+ };
836
+ const getCachedState = () => {
837
+ const data = store.get();
838
+ const cachedWallets = Array.isArray(data?.cachedWallets) ? data.cachedWallets : [];
839
+ const cachedAccounts = Array.isArray(data?.cachedAccounts) ? data.cachedAccounts : [];
840
+ return {
841
+ wallets: cachedWallets.filter(isValidCachedWallet),
842
+ accounts: cachedAccounts.filter(isValidCachedAccount)
843
+ };
844
+ };
845
+ const setCachedState = (wallets, accounts) => {
846
+ store.mutate((prev) => ({
847
+ ...prev,
848
+ cachedWallets: wallets,
849
+ cachedAccounts: accounts
850
+ }));
851
+ };
852
+ return {
853
+ observable: store.observable,
854
+ rememberWallet,
855
+ forgetWallet,
856
+ getCachedState,
857
+ setCachedState,
858
+ destroy: store.destroy
859
+ };
860
+ };
861
+ /**
862
+ * Cached default store instance, anchored on globalThis so it stays a single
863
+ * instance even if this module is duplicated across bundle chunks (e.g. CJS
864
+ * subpath entries). Lazily initialized on first access to be SSR-safe.
865
+ */
866
+ const DEFAULT_STORE_SYMBOL = Symbol.for("kheopskit.defaultStore");
867
+ /**
868
+ * Gets the default store, creating it on first access.
869
+ * Uses localStorage on client, noop on server.
870
+ * Lazily initialized to avoid SSR issues with module-level code.
871
+ */
872
+ const getDefaultStore = () => {
873
+ const g = globalThis;
874
+ if (!g[DEFAULT_STORE_SYMBOL]) g[DEFAULT_STORE_SYMBOL] = createKheopskitStore();
875
+ return g[DEFAULT_STORE_SYMBOL];
876
+ };
877
+ //#endregion
878
+ //#region src/api/wallets.ts
879
+ const getWallets$ = (config, store, registryReads$, walletConnect$ = config.walletConnect?.getWallet$({
880
+ config,
881
+ store,
882
+ registryReads$
883
+ })) => {
884
+ return new rxjs.Observable((subscriber) => {
885
+ const ctx = {
886
+ config,
887
+ store,
888
+ registryReads$
889
+ };
890
+ const observables = config.platforms.map((plugin) => plugin.getWallets$(ctx));
891
+ const reconnectPolicy = createReconnectPolicy();
892
+ const settleOnUserCall = (wallet) => ({
893
+ ...wallet,
894
+ connect: (options) => {
895
+ reconnectPolicy.settle(wallet.id);
896
+ return wallet.connect(options);
897
+ },
898
+ disconnect: () => {
899
+ reconnectPolicy.settle(wallet.id);
900
+ return wallet.disconnect();
901
+ }
902
+ });
903
+ const platformWallets$ = observables.length ? (0, rxjs.combineLatest)(observables).pipe((0, rxjs.map)((wallets) => wallets.flat())) : (0, rxjs.of)([]);
904
+ const rawWallets$ = (walletConnect$ ? (0, rxjs.combineLatest)([platformWallets$, walletConnect$.pipe((0, rxjs.startWith)(null))]).pipe((0, rxjs.map)(([platformWallets, walletConnect]) => walletConnect ? [...platformWallets, walletConnect] : platformWallets)) : platformWallets$).pipe((0, rxjs.map)((all) => all.sort(sortWallets)));
905
+ const wallets$ = rawWallets$.pipe((0, rxjs.map)((wallets) => wallets.map((wallet) => require_types.isInjectedWallet(wallet) ? settleOnUserCall(wallet) : wallet)));
906
+ const reconnect = async (wallet) => {
907
+ try {
908
+ await reconnectPolicy.attempt(wallet.id, () => wallet.connect());
909
+ } catch (err) {
910
+ if (subscriber.closed) return;
911
+ if (err instanceof require_types.KheopskitError) {
912
+ if (err.code === "USER_REJECTED") store.forgetWallet(wallet.id);
913
+ if (err.code === "USER_REJECTED" || err.code === "ABORTED") reconnectPolicy.settle(wallet.id);
914
+ }
915
+ if (config.debug) console.debug("[kheopskit] reconnect of %s failed", wallet.id, err);
916
+ }
917
+ };
918
+ const subWallets = wallets$.subscribe(subscriber);
919
+ if (subscriber.closed) return subWallets;
920
+ const subAutoReconnect = rawWallets$.pipe((0, rxjs.withLatestFrom)(reconnectCandidates$(store)), (0, rxjs.filter)(([, walletIds]) => config.autoReconnect !== false && walletIds.length > 0), (0, rxjs.mergeMap)(([wallets, walletIds]) => wallets.filter(require_types.isInjectedWallet).filter((wallet) => walletIds.includes(wallet.id))), (0, rxjs.tap)((wallet) => {
921
+ if (wallet.status === "connected") reconnectPolicy.settle(wallet.id);
922
+ }), (0, rxjs.filter)((wallet) => wallet.status === "disconnected" && reconnectAccepts(config.autoReconnect, wallet))).subscribe(reconnect);
923
+ return () => {
924
+ subAutoReconnect.unsubscribe();
925
+ subWallets.unsubscribe();
926
+ };
927
+ }).pipe((0, rxjs.shareReplay)({
928
+ refCount: true,
929
+ bufferSize: 1
930
+ }));
931
+ };
932
+ //#endregion
933
+ //#region src/api/kheopskit.ts
934
+ const kheopskitRun$ = (config, options = {}) => {
935
+ const { ssrCookies, store: existingStore } = options;
936
+ const kc = resolveConfig(config);
937
+ const store = existingStore ?? createKheopskitStore({
938
+ ssrCookies,
939
+ storageKey: kc.storageKey
940
+ });
941
+ if (kc.debug) console.debug("[kheopskit] config", kc);
942
+ if (kc.debug && typeof window === "undefined" && ssrCookies === void 0) console.warn("[kheopskit] Running on server without `ssrCookies`. Wallet state will not be hydrated. Pass cookies for SSR support.");
943
+ const { wallets: cachedWallets, accounts: cachedAccounts } = getHydratedSnapshot(store, kc, { icons: true });
944
+ if (kc.debug && cachedWallets.length > 0) console.debug("[kheopskit] hydrating from cache:", {
945
+ wallets: cachedWallets.length,
946
+ accounts: cachedAccounts.length
947
+ });
948
+ return new rxjs.Observable((subscriber) => {
949
+ let latest;
950
+ let closed = false;
951
+ const waiters = /* @__PURE__ */ new Set();
952
+ const liveWaiters = /* @__PURE__ */ new Set();
953
+ const wrapped = /* @__PURE__ */ new WeakMap();
954
+ const abandon = (waiter) => {
955
+ waiters.delete(waiter);
956
+ if (waiter.isConnected) waiter.reject(require_types.abortedError(waiter.walletId, "connect"));
957
+ else waiter.resolve();
958
+ };
959
+ const settleIn = (waiter, state) => {
960
+ const wallet = state.wallets.find((w) => w.id === waiter.walletId);
961
+ if (!wallet || wallet.isConnected === waiter.isConnected) {
962
+ waiters.delete(waiter);
963
+ waiter.resolve();
964
+ }
965
+ };
966
+ const supersede = (walletId, isConnected) => {
967
+ for (const waiter of waiters) if (waiter.walletId === walletId && waiter.isConnected !== isConnected) abandon(waiter);
968
+ };
969
+ const whenState = (walletId, isConnected) => new Promise((resolve, reject) => {
970
+ const waiter = {
971
+ walletId,
972
+ isConnected,
973
+ resolve,
974
+ reject
975
+ };
976
+ waiters.add(waiter);
977
+ if (latest) settleIn(waiter, latest);
978
+ if (closed && waiters.has(waiter)) abandon(waiter);
979
+ });
980
+ const whenLive = (walletId, signal) => new Promise((resolve, reject) => {
981
+ const settle = (finish) => {
982
+ liveWaiters.delete(check);
983
+ signal?.removeEventListener("abort", onAbort);
984
+ finish();
985
+ };
986
+ const onAbort = () => settle(() => reject(require_types.abortedError(walletId, "connect")));
987
+ const check = (state) => {
988
+ if (!state) return onAbort();
989
+ const live = state.wallets.find((w) => w.id === walletId && !w.isPlaceholder);
990
+ if (live) settle(() => resolve(live));
991
+ else if (!state.isHydrating) settle(() => reject(require_types.walletPendingError(walletId)));
992
+ };
993
+ if (closed || signal?.aborted) return onAbort();
994
+ signal?.addEventListener("abort", onAbort, { once: true });
995
+ liveWaiters.add(check);
996
+ if (latest) check(latest);
997
+ });
998
+ const deferToLive = (placeholder) => ({
999
+ ...placeholder,
1000
+ connect: async (options) => {
1001
+ const live = await whenLive(placeholder.id, options?.signal);
1002
+ if (closed) throw require_types.abortedError(placeholder.id, "connect");
1003
+ await live.connect(options);
1004
+ },
1005
+ disconnect: async () => {
1006
+ if (closed) return;
1007
+ const live = latest?.wallets.find((w) => w.id === placeholder.id && !w.isPlaceholder);
1008
+ if (live) return live.disconnect();
1009
+ store.forgetWallet(placeholder.id);
1010
+ }
1011
+ });
1012
+ const settleWithState = (wallet) => {
1013
+ const existing = wrapped.get(wallet);
1014
+ if (existing) return existing;
1015
+ if (wallet.isPlaceholder) {
1016
+ const deferred = deferToLive(wallet);
1017
+ wrapped.set(wallet, deferred);
1018
+ return deferred;
1019
+ }
1020
+ if (!require_types.isInjectedWallet(wallet)) return wallet;
1021
+ const settled = {
1022
+ ...wallet,
1023
+ connect: async (options) => {
1024
+ if (closed) throw require_types.abortedError(wallet.id, "connect");
1025
+ await wallet.connect(options);
1026
+ supersede(wallet.id, true);
1027
+ await whenState(wallet.id, true);
1028
+ },
1029
+ disconnect: async () => {
1030
+ if (closed) throw require_types.abortedError(wallet.id, "disconnect");
1031
+ await wallet.disconnect();
1032
+ supersede(wallet.id, false);
1033
+ await whenState(wallet.id, false);
1034
+ }
1035
+ };
1036
+ wrapped.set(wallet, settled);
1037
+ return settled;
1038
+ };
1039
+ const registryReads$ = require_registryReads.createRegistryReads$().pipe((0, rxjs.shareReplay)({
1040
+ bufferSize: 1,
1041
+ refCount: true
1042
+ }));
1043
+ const walletConnect$ = kc.walletConnect?.getWallet$({
1044
+ config: kc,
1045
+ store,
1046
+ registryReads$
1047
+ }).pipe((0, rxjs.shareReplay)({
1048
+ bufferSize: 1,
1049
+ refCount: true
1050
+ }));
1051
+ const liveWallets$ = getWallets$(kc, store, registryReads$, walletConnect$);
1052
+ const accountFrames$ = getAccounts$(kc, liveWallets$);
1053
+ const liveAccounts$ = accountFrames$.pipe((0, rxjs.map)(({ accounts }) => accounts.map(asLive)));
1054
+ const isDiscovering$ = (0, rxjs.concat)((0, rxjs.of)(true), registryReads$.pipe((0, rxjs.ignoreElements)()), (walletConnect$ ?? rxjs.EMPTY).pipe((0, rxjs.take)(1), (0, rxjs.ignoreElements)()), liveWallets$.pipe((0, rxjs.take)(1), (0, rxjs.map)(() => false))).pipe((0, rxjs.shareReplay)({
1055
+ bufferSize: 1,
1056
+ refCount: true
1057
+ }));
1058
+ const hydrationSettled$ = (0, rxjs.combineLatest)([
1059
+ liveWallets$,
1060
+ accountFrames$.pipe((0, rxjs.startWith)(noAnswerYet)),
1061
+ isDiscovering$,
1062
+ reconnectCandidates$(store)
1063
+ ]).pipe((0, rxjs.map)(([wallets, { accounts, answered }, isDiscovering, remembered]) => cachedWallets.every((cached) => {
1064
+ const wallet = wallets.find((w) => w.id === cached.id);
1065
+ if (!wallet) return !isDiscovering;
1066
+ return cached.status !== "connecting" || reconnectSettled(cached, wallet, {
1067
+ accounts,
1068
+ answered,
1069
+ cachedAccounts,
1070
+ remembered
1071
+ });
1072
+ })), (0, rxjs.debounceTime)(0, rxjs.asapScheduler), (0, rxjs.distinctUntilChanged)());
1073
+ const bufferedWallets$ = createHydrationBuffer(cachedWallets, liveWallets$.pipe((0, rxjs.map)((wallets) => wallets.map(asLive))), kc.hydrationGracePeriod, kc.hydrationTimeout, (w) => w.id, hydrationSettled$, (live, cached) => {
1074
+ const status = sessionRestoring(live, cached) ? "connecting" : live.status;
1075
+ return {
1076
+ ...live,
1077
+ status,
1078
+ isConnected: status === "connected",
1079
+ icon: cached.icon || getCachedIcon(cached.id) || live.icon
1080
+ };
1081
+ }, (cached) => ({
1082
+ ...cached,
1083
+ icon: cached.icon || getCachedIcon(cached.id) || ""
1084
+ }));
1085
+ const bufferedAccounts$ = createAccountHydrationBuffer(cachedAccounts, liveAccounts$, kc.hydrationGracePeriod, kc.hydrationTimeout, (a) => a.walletId, hydrationSettled$);
1086
+ const sharedWallets$ = bufferedWallets$.pipe((0, rxjs.shareReplay)({
1087
+ bufferSize: 1,
1088
+ refCount: true
1089
+ }));
1090
+ const sharedAccounts$ = bufferedAccounts$.pipe((0, rxjs.shareReplay)({
1091
+ bufferSize: 1,
1092
+ refCount: true
1093
+ }));
1094
+ const subscription = (0, rxjs.combineLatest)({
1095
+ wallets: sharedWallets$,
1096
+ accounts: sharedAccounts$,
1097
+ isDiscovering: isDiscovering$
1098
+ }).pipe((0, rxjs.map)(({ wallets, accounts, isDiscovering }) => {
1099
+ if (kc.debug) console.debug("[kheopskit] hydration state", {
1100
+ walletsHydrating: wallets.isHydrating,
1101
+ accountsHydrating: accounts.isHydrating,
1102
+ isDiscovering,
1103
+ walletsConnected: wallets.items.filter((w) => w.isConnected).length,
1104
+ walletsTotal: wallets.items.length
1105
+ });
1106
+ return {
1107
+ config: kc,
1108
+ wallets: [...wallets.items].sort(sortWallets).map(settleWithState),
1109
+ accounts: [...accounts.items].sort(sortAccounts),
1110
+ isHydrating: wallets.isHydrating || accounts.isHydrating,
1111
+ isDiscovering
1112
+ };
1113
+ }), (0, rxjs.debounceTime)(0, rxjs.asapScheduler), (0, rxjs.distinctUntilChanged)(statesEqual), (0, rxjs.tap)((state) => {
1114
+ latest = state;
1115
+ for (const check of liveWaiters) check(state);
1116
+ for (const waiter of waiters) settleIn(waiter, state);
1117
+ })).subscribe(subscriber);
1118
+ const persistSub = (0, rxjs.combineLatest)({
1119
+ wallets: sharedWallets$,
1120
+ accounts: sharedAccounts$
1121
+ }).pipe((0, rxjs.filter)(({ wallets, accounts }) => !wallets.isHydrating && !accounts.isHydrating), (0, rxjs.debounceTime)(1e3), (0, rxjs.distinctUntilChanged)((prev, curr) => {
1122
+ const prevWalletKeys = prev.wallets.items.map(persistedWalletKey);
1123
+ const currWalletKeys = curr.wallets.items.map(persistedWalletKey);
1124
+ const prevAccountKeys = prev.accounts.items.map(accountChangeKey);
1125
+ const currAccountKeys = curr.accounts.items.map(accountChangeKey);
1126
+ return arraysEqual(prevWalletKeys, currWalletKeys) && arraysEqual(prevAccountKeys, currAccountKeys);
1127
+ })).subscribe(({ wallets, accounts }) => {
1128
+ const snapshot = persistedSnapshot(wallets.items, accounts.items, store.getCachedState());
1129
+ if (kc.debug) console.debug("[kheopskit] persisting state snapshot:", {
1130
+ wallets: snapshot.wallets.length,
1131
+ accounts: snapshot.accounts.length
1132
+ });
1133
+ store.setCachedState(snapshot.wallets, snapshot.accounts);
1134
+ const icons = {};
1135
+ for (const wallet of wallets.items) if (wallet.icon) icons[wallet.id] = wallet.icon;
1136
+ setCachedIcons(icons);
1137
+ });
1138
+ return () => {
1139
+ subscription.unsubscribe();
1140
+ persistSub.unsubscribe();
1141
+ closed = true;
1142
+ for (const waiter of waiters) abandon(waiter);
1143
+ for (const check of liveWaiters) check(void 0);
1144
+ };
1145
+ }).pipe(logObservable("kheopskit$", {
1146
+ enabled: kc.debug,
1147
+ printValue: true
1148
+ }), (0, rxjs.shareReplay)({
1149
+ bufferSize: 1,
1150
+ refCount: true
1151
+ }));
1152
+ };
1153
+ const sessionRestoring = (live, cached) => require_types.isWalletConnectWallet(live) && live.status === "disconnected" && cached.status === "connecting";
1154
+ const flagged = /* @__PURE__ */ new WeakMap();
1155
+ const asLive = (item) => {
1156
+ const existing = flagged.get(item);
1157
+ if (existing) return existing;
1158
+ const live = {
1159
+ ...item,
1160
+ isPlaceholder: false
1161
+ };
1162
+ flagged.set(item, live);
1163
+ return live;
1164
+ };
1165
+ const noAnswerYet = {
1166
+ accounts: [],
1167
+ answered: []
1168
+ };
1169
+ /**
1170
+ * A remembered wallet that reads disconnected without an error is still
1171
+ * waiting for its reconnect: getWallets$ emits the wallet list before its
1172
+ * connect() flips the status to connecting.
1173
+ */
1174
+ const reconnectSettled = (cached, wallet, live) => {
1175
+ const status = sessionRestoring(wallet, cached) ? "connecting" : wallet.status;
1176
+ if (status === "connecting") return false;
1177
+ if (status === "disconnected") return wallet.error !== void 0 || !live.remembered.includes(cached.id);
1178
+ return live.answered.includes(cached.id) || !live.cachedAccounts.some((a) => a.walletId === cached.id) || live.accounts.some((a) => a.walletId === cached.id);
1179
+ };
1180
+ /**
1181
+ * A wallet still connecting keeps its previous cache entry and accounts:
1182
+ * written live it would read isConnected: false with no accounts, and the
1183
+ * next load would hydrate it as disconnected without placeholders while its
1184
+ * reconnect runs.
1185
+ */
1186
+ const persistedSnapshot = (wallets, accounts, previous) => {
1187
+ const connecting = new Set(wallets.filter((w) => w.status === "connecting").map((w) => w.id));
1188
+ const connected = new Set(wallets.filter((w) => w.isConnected).map((w) => w.id));
1189
+ const previousWallets = new Map(previous.wallets.map((w) => [w.id, w]));
1190
+ return {
1191
+ wallets: wallets.map((w) => connecting.has(w.id) && previousWallets.get(w.id) || serializeWallet(w)),
1192
+ accounts: [...accounts.filter((a) => connected.has(a.walletId)).map(serializeAccount), ...previous.accounts.filter((a) => connecting.has(a.walletId))]
1193
+ };
1194
+ };
1195
+ const arraysEqual = (a, b) => a.length === b.length && a.every((v, i) => v === b[i]);
1196
+ /**
1197
+ * A signature of an account covering its id, its name, plus the
1198
+ * platform-specific fields that can change without the id changing (Ethereum
1199
+ * chainId, Polkadot key type, Solana clusters). Used to detect both UI-relevant
1200
+ * changes and changes worth re-persisting, so the two comparators can't drift
1201
+ * apart.
1202
+ */
1203
+ const accountChangeKey = (account) => `${account.name ?? ""}|${accountPlatformKey(account)}`;
1204
+ const accountPlatformKey = (account) => {
1205
+ switch (account.platform) {
1206
+ case "ethereum": return `${account.id}|${account.chainId ?? ""}`;
1207
+ case "polkadot": return `${account.id}|${account.type ?? ""}`;
1208
+ case "solana": return `${account.id}|${(account.chains ?? []).join(",")}`;
1209
+ default: return account.id;
1210
+ }
1211
+ };
1212
+ /** Platforms a wallet's live session carries (only the WalletConnect connector). */
1213
+ const walletPlatforms = (wallet) => require_types.isWalletConnectWallet(wallet) ? wallet.platforms.join(",") : "";
1214
+ /** Fields persisted to the cache for a wallet (icon is stored separately). */
1215
+ const walletPersistKey = (wallet) => `${wallet.id}|${wallet.isConnected ? 1 : 0}|${wallet.name}`;
1216
+ /**
1217
+ * What decides a cache write: the persisted fields plus `status`, because a
1218
+ * wallet whose kept entry was written while connecting must be rewritten live
1219
+ * once its reconnect fails, and `isConnected` reads false on both sides.
1220
+ */
1221
+ const persistedWalletKey = (wallet) => `${walletPersistKey(wallet)}|${wallet.status}`;
1222
+ /**
1223
+ * UI-significant signature of a wallet: the persisted fields plus icon and the
1224
+ * WalletConnect connector's `platforms` array, which drive what the UI shows but
1225
+ * aren't part of the id (icon and platforms can arrive asynchronously after
1226
+ * connect without isConnected flipping).
1227
+ */
1228
+ const walletUiKey = (wallet) => `${walletPersistKey(wallet)}|${wallet.status}|${wallet.error?.code ?? ""}|${wallet.icon}|${walletPlatforms(wallet)}`;
1229
+ /**
1230
+ * Equality check for KheopskitState to prevent unnecessary emissions. Compares
1231
+ * the UI-significant signature of every wallet and account, in order.
1232
+ */
1233
+ const statesEqual = (a, b) => a.isHydrating === b.isHydrating && a.isDiscovering === b.isDiscovering && a.wallets.length === b.wallets.length && a.accounts.length === b.accounts.length && a.wallets.every((w, i) => {
1234
+ const other = b.wallets[i];
1235
+ return !!other && w.isPlaceholder === other.isPlaceholder && walletUiKey(w) === walletUiKey(other);
1236
+ }) && a.accounts.every((acc, i) => {
1237
+ const other = b.accounts[i];
1238
+ return !!other && acc.isPlaceholder === other.isPlaceholder && accountChangeKey(acc) === accountChangeKey(other);
1239
+ });
1240
+ //#endregion
1241
+ //#region src/api/liveActions.ts
1242
+ const didNotRun = {
1243
+ aborted: "was aborted",
1244
+ unheld: "was called while nothing subscribes this kheopskit instance's kheopskit$ (a mounted, visible KheopskitProvider subscribes it)",
1245
+ errored: "did not run because the pipeline stopped with an error",
1246
+ completed: "did not run because the pipeline completed"
1247
+ };
1248
+ const abortedError = (walletId, operation, end) => new require_types.KheopskitError("ABORTED", `${operation} of wallet ${walletId} ${didNotRun[end]}`, { walletId });
1249
+ const whenLiveAfterTheCallersTask = async (pipeline, signal) => {
1250
+ await Promise.resolve();
1251
+ return pipeline.whenLive(signal);
1252
+ };
1253
+ const walletActions = (pipeline, walletId) => {
1254
+ const liveWallet = async (operation, signal) => {
1255
+ const liveness = await whenLiveAfterTheCallersTask(pipeline, signal);
1256
+ if (liveness.end) throw abortedError(walletId, operation, liveness.end);
1257
+ const wallet = liveness.state.wallets.find((candidate) => candidate.id === walletId);
1258
+ if (!wallet) throw new Error(`[kheopskit] no wallet ${walletId}`);
1259
+ return wallet;
1260
+ };
1261
+ return {
1262
+ connect: async (options) => (await liveWallet("connect", options?.signal)).connect(options),
1263
+ disconnect: async () => (await liveWallet("disconnect")).disconnect()
1264
+ };
1265
+ };
1266
+ const createPresenter = (pipeline) => {
1267
+ const presentedStates = /* @__PURE__ */ new WeakMap();
1268
+ const presentedWallets = /* @__PURE__ */ new WeakMap();
1269
+ const presentWallet = (wallet) => {
1270
+ let live = presentedWallets.get(wallet);
1271
+ if (!live) {
1272
+ live = {
1273
+ ...wallet,
1274
+ ...walletActions(pipeline, wallet.id)
1275
+ };
1276
+ presentedWallets.set(wallet, live);
1277
+ }
1278
+ return live;
1279
+ };
1280
+ return (state) => {
1281
+ let live = presentedStates.get(state);
1282
+ if (!live) {
1283
+ live = {
1284
+ ...state,
1285
+ wallets: state.wallets.map(presentWallet)
1286
+ };
1287
+ presentedStates.set(state, live);
1288
+ }
1289
+ return live;
1290
+ };
1291
+ };
1292
+ //#endregion
1293
+ //#region src/api/livePipeline.ts
1294
+ const createLivePipeline = (source$) => {
1295
+ let holders = 0;
1296
+ let run = 0;
1297
+ let emittedRun = 0;
1298
+ let latestValue;
1299
+ let ended;
1300
+ const waiters = /* @__PURE__ */ new Set();
1301
+ const notifyWaiters = (liveness) => {
1302
+ for (const waiter of waiters) waiter(liveness);
1303
+ };
1304
+ const observable$ = new rxjs.Observable((subscriber) => {
1305
+ if (holders++ === 0) {
1306
+ run++;
1307
+ ended = void 0;
1308
+ }
1309
+ const thisRun = run;
1310
+ const subscription = source$.subscribe({
1311
+ next: (value) => {
1312
+ latestValue = value;
1313
+ emittedRun = thisRun;
1314
+ notifyWaiters({ state: value });
1315
+ subscriber.next(value);
1316
+ },
1317
+ error: (error) => {
1318
+ ended = "errored";
1319
+ subscriber.error(error);
1320
+ },
1321
+ complete: () => {
1322
+ ended = "completed";
1323
+ subscriber.complete();
1324
+ }
1325
+ });
1326
+ return () => {
1327
+ subscription.unsubscribe();
1328
+ if (--holders === 0) notifyWaiters({ end: ended ?? "unheld" });
1329
+ };
1330
+ });
1331
+ const whenLivePicks = async (pick, signal) => {
1332
+ if (signal?.aborted) return { end: "aborted" };
1333
+ if (ended) return { end: ended };
1334
+ if (holders === 0) return { end: "unheld" };
1335
+ const current = emittedRun === run ? pick(latestValue) : void 0;
1336
+ if (current !== void 0) return { state: current };
1337
+ return new Promise((resolve) => {
1338
+ const settle = (liveness) => {
1339
+ waiters.delete(observe);
1340
+ signal?.removeEventListener("abort", onAbort);
1341
+ resolve(liveness);
1342
+ };
1343
+ const observe = (liveness) => {
1344
+ if (liveness.end) return settle({ end: liveness.end });
1345
+ const picked = pick(liveness.state);
1346
+ if (picked !== void 0) settle({ state: picked });
1347
+ };
1348
+ const onAbort = () => settle({ end: "aborted" });
1349
+ signal?.addEventListener("abort", onAbort, { once: true });
1350
+ waiters.add(observe);
1351
+ });
1352
+ };
1353
+ const whenLive = (signal) => whenLivePicks((state) => state, signal);
1354
+ return {
1355
+ observable$,
1356
+ whenLivePicks,
1357
+ whenLive
1358
+ };
1359
+ };
1360
+ //#endregion
1361
+ //#region src/api/instance.ts
1362
+ const lookUpAccount = (state, accountId, walletId) => {
1363
+ const account = state.accounts.find((candidate) => candidate.id === accountId && !candidate.isPlaceholder);
1364
+ if (account) return {
1365
+ status: "live",
1366
+ account
1367
+ };
1368
+ return mayStillList(state, walletId) ? void 0 : { status: "unavailable" };
1369
+ };
1370
+ const mayStillList = (state, walletId) => {
1371
+ if (state.isHydrating) return true;
1372
+ const wallet = state.wallets.find((candidate) => candidate.id === walletId);
1373
+ if (!wallet) return state.isDiscovering;
1374
+ if (wallet.status === "connecting") return true;
1375
+ return wallet.isConnected && !state.accounts.some((candidate) => candidate.walletId === walletId);
1376
+ };
1377
+ const didNotWait = {
1378
+ aborted: "was aborted",
1379
+ unheld: "was called while nothing subscribes this kheopskit instance's kheopskit$ (a mounted, visible KheopskitProvider subscribes it)",
1380
+ errored: "did not run because the pipeline stopped with an error",
1381
+ completed: "did not run because the pipeline completed"
1382
+ };
1383
+ const internals = /* @__PURE__ */ new WeakMap();
1384
+ const createInstance = (run$, store) => {
1385
+ const pipeline = createLivePipeline((0, rxjs.defer)(run$).pipe((0, rxjs.share)({
1386
+ connector: () => new rxjs.ReplaySubject(1),
1387
+ resetOnError: true,
1388
+ resetOnComplete: true,
1389
+ resetOnRefCountZero: true
1390
+ })));
1391
+ const present = createPresenter(pipeline);
1392
+ const waitForAccount = async (accountId, { signal } = {}) => {
1393
+ const { walletId } = require_platformAccounts.parseWalletAccountId(accountId);
1394
+ await Promise.resolve();
1395
+ const found = await pipeline.whenLivePicks((state) => lookUpAccount(state, accountId, walletId), signal);
1396
+ if (found.end) throw new require_types.KheopskitError("ABORTED", `waitForAccount of account ${accountId} ${didNotWait[found.end]}`, { walletId });
1397
+ if (found.state.status === "unavailable") throw require_types.accountUnavailableError(accountId, walletId);
1398
+ return found.state.account;
1399
+ };
1400
+ const kit = {
1401
+ kheopskit$: pipeline.observable$.pipe((0, rxjs.map)(present)),
1402
+ store,
1403
+ waitForAccount
1404
+ };
1405
+ internals.set(kit, {
1406
+ present,
1407
+ walletActions: (walletId) => walletActions(pipeline, walletId)
1408
+ });
1409
+ return kit;
1410
+ };
1411
+ const kheopskitInternals = (kit) => {
1412
+ const found = internals.get(kit);
1413
+ if (!found) throw new Error("[kheopskit] not a kheopskit instance");
1414
+ return found;
1415
+ };
1416
+ const lazyStore = (create) => ({
1417
+ observable: (0, rxjs.defer)(() => create().observable),
1418
+ rememberWallet: (walletId) => create().rememberWallet(walletId),
1419
+ forgetWallet: (walletId) => create().forgetWallet(walletId),
1420
+ getCachedState: () => create().getCachedState(),
1421
+ setCachedState: (wallets, accounts) => create().setCachedState(wallets, accounts),
1422
+ destroy: () => create().destroy()
1423
+ });
1424
+ const inertOnTheServer = (store) => typeof window === "undefined" ? {
1425
+ ...store,
1426
+ rememberWallet: () => {},
1427
+ forgetWallet: () => {},
1428
+ setCachedState: () => {}
1429
+ } : store;
1430
+ /**
1431
+ * Creates one kheopskit instance: `kheopskit$`, the state stream every
1432
+ * subscriber shares, and `store`, which it reads the cache from and persists
1433
+ * into. Subscribe once at app start to keep it running for the page's
1434
+ * lifetime.
1435
+ *
1436
+ * @example
1437
+ * ```ts
1438
+ * export const { kheopskit$, store } = createKheopskit({ platforms: [polkadot()] });
1439
+ * kheopskit$.subscribe(render);
1440
+ * ```
1441
+ */
1442
+ const createKheopskit = (config, options = {}) => {
1443
+ const { storageKey } = resolveConfig(config);
1444
+ let created;
1445
+ const store = () => {
1446
+ created ?? (created = options.store ?? inertOnTheServer(createKheopskitStore({
1447
+ ssrCookies: options.ssr ? "" : void 0,
1448
+ storageKey
1449
+ })));
1450
+ return created;
1451
+ };
1452
+ return createInstance(() => kheopskitRun$(config, { store: store() }), options.store ?? lazyStore(store));
1453
+ };
1454
+ //#endregion
1455
+ Object.defineProperty(exports, "DEFAULT_STORAGE_KEY", {
1456
+ enumerable: true,
1457
+ get: function() {
1458
+ return DEFAULT_STORAGE_KEY;
1459
+ }
1460
+ });
1461
+ Object.defineProperty(exports, "createInstance", {
1462
+ enumerable: true,
1463
+ get: function() {
1464
+ return createInstance;
1465
+ }
1466
+ });
1467
+ Object.defineProperty(exports, "createKheopskit", {
1468
+ enumerable: true,
1469
+ get: function() {
1470
+ return createKheopskit;
1471
+ }
1472
+ });
1473
+ Object.defineProperty(exports, "createKheopskitStore", {
1474
+ enumerable: true,
1475
+ get: function() {
1476
+ return createKheopskitStore;
1477
+ }
1478
+ });
1479
+ Object.defineProperty(exports, "getDefaultStore", {
1480
+ enumerable: true,
1481
+ get: function() {
1482
+ return getDefaultStore;
1483
+ }
1484
+ });
1485
+ Object.defineProperty(exports, "getHydratedSnapshot", {
1486
+ enumerable: true,
1487
+ get: function() {
1488
+ return getHydratedSnapshot;
1489
+ }
1490
+ });
1491
+ Object.defineProperty(exports, "getSafeLocalStorage", {
1492
+ enumerable: true,
1493
+ get: function() {
1494
+ return getSafeLocalStorage;
1495
+ }
1496
+ });
1497
+ Object.defineProperty(exports, "kheopskitInternals", {
1498
+ enumerable: true,
1499
+ get: function() {
1500
+ return kheopskitInternals;
1501
+ }
1502
+ });
1503
+ Object.defineProperty(exports, "resolveConfig", {
1504
+ enumerable: true,
1505
+ get: function() {
1506
+ return resolveConfig;
1507
+ }
1508
+ });
1509
+ Object.defineProperty(exports, "serializeAccount", {
1510
+ enumerable: true,
1511
+ get: function() {
1512
+ return serializeAccount;
1513
+ }
1514
+ });
1515
+ Object.defineProperty(exports, "serializeWallet", {
1516
+ enumerable: true,
1517
+ get: function() {
1518
+ return serializeWallet;
1519
+ }
1520
+ });
1521
+ Object.defineProperty(exports, "setCachedIcons", {
1522
+ enumerable: true,
1523
+ get: function() {
1524
+ return setCachedIcons;
1525
+ }
1526
+ });
1527
+
1528
+ //# sourceMappingURL=instance-CCP7uJV3.js.map