@kheopskit/core 5.2.1 → 6.0.0-rc.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/CHANGELOG.md +426 -0
  2. package/MIGRATING_TO_V6.md +837 -0
  3. package/README.md +628 -11
  4. package/dist/ethereum.d.mts +12 -6
  5. package/dist/ethereum.d.ts +12 -6
  6. package/dist/ethereum.js +13 -10
  7. package/dist/ethereum.js.map +1 -1
  8. package/dist/ethereum.mjs +7 -4
  9. package/dist/ethereum.mjs.map +1 -1
  10. package/dist/{iconCache-pP2ES4pJ.mjs → iconCache-C-U3IEbP.mjs} +21 -40
  11. package/dist/iconCache-C-U3IEbP.mjs.map +1 -0
  12. package/dist/{iconCache-DUtkJlaX.js → iconCache-FR4iy6go.js} +21 -40
  13. package/dist/iconCache-FR4iy6go.js.map +1 -0
  14. package/dist/index.d.mts +17 -63
  15. package/dist/index.d.ts +17 -63
  16. package/dist/index.js +387 -373
  17. package/dist/index.js.map +1 -1
  18. package/dist/index.mjs +384 -369
  19. package/dist/index.mjs.map +1 -1
  20. package/dist/injectedWallets-48L-AL1I.mjs +173 -0
  21. package/dist/injectedWallets-48L-AL1I.mjs.map +1 -0
  22. package/dist/injectedWallets-Dy8YGKL-.js +178 -0
  23. package/dist/injectedWallets-Dy8YGKL-.js.map +1 -0
  24. package/dist/internal.d.mts +3 -27
  25. package/dist/internal.d.ts +3 -27
  26. package/dist/internal.js +2 -2
  27. package/dist/internal.mjs +2 -2
  28. package/dist/pageLoad-BZ7o8p5R.mjs +24 -0
  29. package/dist/pageLoad-BZ7o8p5R.mjs.map +1 -0
  30. package/dist/pageLoad-D1wLeuFG.js +28 -0
  31. package/dist/pageLoad-D1wLeuFG.js.map +1 -0
  32. package/dist/platformAccounts-BjIeRcFN.js +321 -0
  33. package/dist/platformAccounts-BjIeRcFN.js.map +1 -0
  34. package/dist/platformAccounts-yyRUrnel.mjs +256 -0
  35. package/dist/platformAccounts-yyRUrnel.mjs.map +1 -0
  36. package/dist/polkadot.d.mts +127 -11
  37. package/dist/polkadot.d.ts +127 -11
  38. package/dist/polkadot.js +171 -107
  39. package/dist/polkadot.js.map +1 -1
  40. package/dist/polkadot.mjs +164 -100
  41. package/dist/polkadot.mjs.map +1 -1
  42. package/dist/solana.d.mts +11 -5
  43. package/dist/solana.d.ts +11 -5
  44. package/dist/solana.js +18 -15
  45. package/dist/solana.js.map +1 -1
  46. package/dist/solana.mjs +7 -4
  47. package/dist/solana.mjs.map +1 -1
  48. package/dist/storage-D3AwNgqc.d.mts +27 -0
  49. package/dist/storage-D3AwNgqc.d.ts +27 -0
  50. package/dist/testing.d.mts +71 -0
  51. package/dist/testing.d.ts +71 -0
  52. package/dist/testing.js +136 -0
  53. package/dist/testing.js.map +1 -0
  54. package/dist/testing.mjs +131 -0
  55. package/dist/testing.mjs.map +1 -0
  56. package/dist/{types-DKU-SNio.js → types-BWHvNFlN.js} +149 -2
  57. package/dist/types-BWHvNFlN.js.map +1 -0
  58. package/dist/types-Dkyt9bf4.d.mts +683 -0
  59. package/dist/types-Dkyt9bf4.d.ts +683 -0
  60. package/dist/types-Yor672md.mjs +215 -0
  61. package/dist/types-Yor672md.mjs.map +1 -0
  62. package/dist/walletconnect.d.mts +41 -0
  63. package/dist/walletconnect.d.ts +41 -0
  64. package/dist/walletconnect.js +219 -0
  65. package/dist/walletconnect.js.map +1 -0
  66. package/dist/walletconnect.mjs +216 -0
  67. package/dist/walletconnect.mjs.map +1 -0
  68. package/package.json +33 -9
  69. package/dist/errors-BLFP1dQI.mjs +0 -181
  70. package/dist/errors-BLFP1dQI.mjs.map +0 -1
  71. package/dist/errors-DYWVPHrR.js +0 -222
  72. package/dist/errors-DYWVPHrR.js.map +0 -1
  73. package/dist/iconCache-DUtkJlaX.js.map +0 -1
  74. package/dist/iconCache-pP2ES4pJ.mjs.map +0 -1
  75. package/dist/injectedWallets-BqR-_aAy.js +0 -148
  76. package/dist/injectedWallets-BqR-_aAy.js.map +0 -1
  77. package/dist/injectedWallets-Uz4hPuoW.mjs +0 -119
  78. package/dist/injectedWallets-Uz4hPuoW.mjs.map +0 -1
  79. package/dist/types-Cb-vuEru.d.mts +0 -330
  80. package/dist/types-Cb-vuEru.d.ts +0 -330
  81. package/dist/types-DKU-SNio.js.map +0 -1
  82. package/dist/types-jnifAAA0.mjs +0 -104
  83. package/dist/types-jnifAAA0.mjs.map +0 -1
@@ -1,222 +0,0 @@
1
- let _noble_hashes_sha3_js = require("@noble/hashes/sha3.js");
2
- let _scure_base = require("@scure/base");
3
- let _noble_hashes_blake2_js = require("@noble/hashes/blake2.js");
4
- //#region src/utils/isEthereumAddress.ts
5
- const HEX_ADDRESS = /^0x[0-9a-fA-F]{40}$/;
6
- const encoder = new TextEncoder();
7
- /**
8
- * Verifies the EIP-55 mixed-case checksum of an Ethereum address.
9
- * Dependency-free (keccak via @noble/hashes) so core stays decoupled from viem.
10
- */
11
- const isChecksumValid = (address) => {
12
- const hex = address.slice(2);
13
- const hash = (0, _noble_hashes_sha3_js.keccak_256)(encoder.encode(hex.toLowerCase()));
14
- for (let i = 0; i < 40; i++) {
15
- const char = hex.charAt(i);
16
- if (!(char >= "a" && char <= "f" || char >= "A" && char <= "F")) continue;
17
- const byte = hash[i >> 1] ?? 0;
18
- const nibble = i % 2 === 0 ? byte >> 4 : byte & 15;
19
- if (char <= "F" !== nibble >= 8) return false;
20
- }
21
- return true;
22
- };
23
- /**
24
- * Returns true if `address` is a valid Ethereum address.
25
- *
26
- * Mirrors viem's `isAddress` (strict): the shape must be `0x` + 40 hex, and a
27
- * mixed-case address must pass the EIP-55 checksum. All-lowercase addresses are
28
- * accepted as non-checksummed.
29
- */
30
- const isEthereumAddress = (address) => {
31
- if (!HEX_ADDRESS.test(address)) return false;
32
- if (address === address.toLowerCase()) return true;
33
- return isChecksumValid(address);
34
- };
35
- //#endregion
36
- //#region src/utils/isSolanaAddress.ts
37
- /**
38
- * Returns true if the value is a valid Solana address: a base58-encoded
39
- * 32-byte ed25519 public key.
40
- *
41
- * Solana addresses carry no checksum, so this is a pure base58 + length check.
42
- * Dependency-free (base58 via @scure/base) so core stays decoupled from
43
- * @solana/kit.
44
- */
45
- const isSolanaAddress = (address) => {
46
- if (!address) return false;
47
- try {
48
- return _scure_base.base58.decode(address).length === 32;
49
- } catch {
50
- return false;
51
- }
52
- };
53
- //#endregion
54
- //#region src/utils/isSs58Address.ts
55
- const SS58PRE = new Uint8Array([
56
- 83,
57
- 83,
58
- 53,
59
- 56,
60
- 80,
61
- 82,
62
- 69
63
- ]);
64
- /**
65
- * Returns true if `address` is a valid SS58-encoded 32-byte account id (the
66
- * only form Substrate wallets inject), verifying the blake2b-512 checksum.
67
- *
68
- * Dependency-free (base58 via @scure/base, blake2b via @noble/hashes) so core
69
- * stays decoupled from polkadot-api.
70
- */
71
- const isSs58Address = (address) => {
72
- if (!address) return false;
73
- let decoded;
74
- try {
75
- decoded = _scure_base.base58.decode(address);
76
- } catch {
77
- return false;
78
- }
79
- const firstByte = decoded[0];
80
- if (firstByte === void 0 || firstByte & 128) return false;
81
- const prefixLength = firstByte & 64 ? 2 : 1;
82
- if (decoded.length !== prefixLength + 32 + 2) return false;
83
- const body = decoded.subarray(0, decoded.length - 2);
84
- const preimage = new Uint8Array(SS58PRE.length + body.length);
85
- preimage.set(SS58PRE);
86
- preimage.set(body, SS58PRE.length);
87
- const hash = (0, _noble_hashes_blake2_js.blake2b)(preimage, { dkLen: 64 });
88
- return decoded[decoded.length - 2] === hash[0] && decoded[decoded.length - 1] === hash[1];
89
- };
90
- //#endregion
91
- //#region src/utils/isValidAddress.ts
92
- const isValidAddress = (address) => {
93
- if (address.startsWith("0x")) return isEthereumAddress(address);
94
- return isSs58Address(address) || isSolanaAddress(address);
95
- };
96
- //#endregion
97
- //#region src/utils/WalletAccountId.ts
98
- const getWalletAccountId = (walletId, address) => {
99
- if (!walletId) throw new Error("Missing walletId");
100
- if (!isValidAddress(address)) throw new Error("Invalid address");
101
- return `${walletId}::${address}`;
102
- };
103
- const parseWalletAccountId = (accountId) => {
104
- if (!accountId) throw new Error("Invalid walletAccountId");
105
- const [walletId, address] = accountId.split("::");
106
- if (!walletId) throw new Error("Missing walletId");
107
- if (!address || !isValidAddress(address)) throw new Error("Invalid address");
108
- return {
109
- walletId,
110
- address
111
- };
112
- };
113
- //#endregion
114
- //#region \0@oxc-project+runtime@0.149.0/helpers/esm/typeof.js
115
- function _typeof(o) {
116
- "@babel/helpers - typeof";
117
- return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o) {
118
- return typeof o;
119
- } : function(o) {
120
- return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
121
- }, _typeof(o);
122
- }
123
- //#endregion
124
- //#region \0@oxc-project+runtime@0.149.0/helpers/esm/toPrimitive.js
125
- function toPrimitive(t, r) {
126
- if ("object" != _typeof(t) || !t) return t;
127
- var e = t[Symbol.toPrimitive];
128
- if (void 0 !== e) {
129
- var i = e.call(t, r || "default");
130
- if ("object" != _typeof(i)) return i;
131
- throw new TypeError("@@toPrimitive must return a primitive value.");
132
- }
133
- return ("string" === r ? String : Number)(t);
134
- }
135
- //#endregion
136
- //#region \0@oxc-project+runtime@0.149.0/helpers/esm/toPropertyKey.js
137
- function toPropertyKey(t) {
138
- var i = toPrimitive(t, "string");
139
- return "symbol" == _typeof(i) ? i : i + "";
140
- }
141
- //#endregion
142
- //#region \0@oxc-project+runtime@0.149.0/helpers/esm/defineProperty.js
143
- function _defineProperty(e, r, t) {
144
- return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
145
- value: t,
146
- enumerable: !0,
147
- configurable: !0,
148
- writable: !0
149
- }) : e[r] = t, e;
150
- }
151
- //#endregion
152
- //#region src/api/errors.ts
153
- /**
154
- * Error thrown by kheopskit wallet/account operations. Carries a stable
155
- * {@link KheopskitErrorCode} and, when relevant, the offending wallet id.
156
- *
157
- * @example
158
- * ```ts
159
- * try {
160
- * await wallet.connect();
161
- * } catch (error) {
162
- * if (error instanceof KheopskitError && error.code === "WALLET_ALREADY_CONNECTED") {
163
- * // ignore
164
- * } else throw error;
165
- * }
166
- * ```
167
- */
168
- var KheopskitError = class extends Error {
169
- constructor(code, message, options) {
170
- super(`[kheopskit] ${message}`, { cause: options?.cause });
171
- _defineProperty(this, "code", void 0);
172
- _defineProperty(this, "walletId", void 0);
173
- this.name = "KheopskitError";
174
- this.code = code;
175
- this.walletId = options?.walletId;
176
- }
177
- };
178
- //#endregion
179
- Object.defineProperty(exports, "KheopskitError", {
180
- enumerable: true,
181
- get: function() {
182
- return KheopskitError;
183
- }
184
- });
185
- Object.defineProperty(exports, "getWalletAccountId", {
186
- enumerable: true,
187
- get: function() {
188
- return getWalletAccountId;
189
- }
190
- });
191
- Object.defineProperty(exports, "isEthereumAddress", {
192
- enumerable: true,
193
- get: function() {
194
- return isEthereumAddress;
195
- }
196
- });
197
- Object.defineProperty(exports, "isSolanaAddress", {
198
- enumerable: true,
199
- get: function() {
200
- return isSolanaAddress;
201
- }
202
- });
203
- Object.defineProperty(exports, "isSs58Address", {
204
- enumerable: true,
205
- get: function() {
206
- return isSs58Address;
207
- }
208
- });
209
- Object.defineProperty(exports, "isValidAddress", {
210
- enumerable: true,
211
- get: function() {
212
- return isValidAddress;
213
- }
214
- });
215
- Object.defineProperty(exports, "parseWalletAccountId", {
216
- enumerable: true,
217
- get: function() {
218
- return parseWalletAccountId;
219
- }
220
- });
221
-
222
- //# sourceMappingURL=errors-DYWVPHrR.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"errors-DYWVPHrR.js","names":["keccak_256","base58","base58","blake2b"],"sources":["../src/utils/isEthereumAddress.ts","../src/utils/isSolanaAddress.ts","../src/utils/isSs58Address.ts","../src/utils/isValidAddress.ts","../src/utils/WalletAccountId.ts","../src/api/errors.ts"],"sourcesContent":["import { keccak_256 } from \"@noble/hashes/sha3.js\";\n\nconst HEX_ADDRESS = /^0x[0-9a-fA-F]{40}$/;\nconst encoder = new TextEncoder();\n\n/**\n * Verifies the EIP-55 mixed-case checksum of an Ethereum address.\n * Dependency-free (keccak via @noble/hashes) so core stays decoupled from viem.\n */\nconst isChecksumValid = (address: string): boolean => {\n\tconst hex = address.slice(2);\n\tconst hash = keccak_256(encoder.encode(hex.toLowerCase()));\n\tfor (let i = 0; i < 40; i++) {\n\t\tconst char = hex.charAt(i);\n\t\tconst isLetter =\n\t\t\t(char >= \"a\" && char <= \"f\") || (char >= \"A\" && char <= \"F\");\n\t\tif (!isLetter) continue;\n\t\tconst byte = hash[i >> 1] ?? 0;\n\t\tconst nibble = i % 2 === 0 ? byte >> 4 : byte & 0x0f;\n\t\tconst isUpper = char <= \"F\";\n\t\tif (isUpper !== nibble >= 8) return false;\n\t}\n\treturn true;\n};\n\n/**\n * Returns true if `address` is a valid Ethereum address.\n *\n * Mirrors viem's `isAddress` (strict): the shape must be `0x` + 40 hex, and a\n * mixed-case address must pass the EIP-55 checksum. All-lowercase addresses are\n * accepted as non-checksummed.\n */\nexport const isEthereumAddress = (address: string): boolean => {\n\tif (!HEX_ADDRESS.test(address)) return false;\n\tif (address === address.toLowerCase()) return true;\n\treturn isChecksumValid(address);\n};\n","import { base58 } from \"@scure/base\";\n\n/**\n * Returns true if the value is a valid Solana address: a base58-encoded\n * 32-byte ed25519 public key.\n *\n * Solana addresses carry no checksum, so this is a pure base58 + length check.\n * Dependency-free (base58 via @scure/base) so core stays decoupled from\n * @solana/kit.\n */\nexport const isSolanaAddress = (address: string): boolean => {\n\tif (!address) return false;\n\ttry {\n\t\treturn base58.decode(address).length === 32;\n\t} catch {\n\t\treturn false;\n\t}\n};\n","import { blake2b } from \"@noble/hashes/blake2.js\";\nimport { base58 } from \"@scure/base\";\n\n// The \"SS58PRE\" prefix used in the SS58 checksum preimage.\nconst SS58PRE = new Uint8Array([0x53, 0x53, 0x35, 0x38, 0x50, 0x52, 0x45]);\n\n/**\n * Returns true if `address` is a valid SS58-encoded 32-byte account id (the\n * only form Substrate wallets inject), verifying the blake2b-512 checksum.\n *\n * Dependency-free (base58 via @scure/base, blake2b via @noble/hashes) so core\n * stays decoupled from polkadot-api.\n */\nexport const isSs58Address = (address: string): boolean => {\n\tif (!address) return false;\n\n\tlet decoded: Uint8Array;\n\ttry {\n\t\tdecoded = base58.decode(address);\n\t} catch {\n\t\treturn false;\n\t}\n\n\t// First byte encodes the network prefix; the high bit is reserved/invalid.\n\tconst firstByte = decoded[0];\n\tif (firstByte === undefined || firstByte & 0b1000_0000) return false;\n\t// The 0b0100_0000 bit marks a 2-byte prefix.\n\tconst prefixLength = firstByte & 0b0100_0000 ? 2 : 1;\n\n\t// AccountId32 layout: prefix + 32-byte pubkey + 2-byte checksum.\n\tif (decoded.length !== prefixLength + 32 + 2) return false;\n\n\tconst body = decoded.subarray(0, decoded.length - 2);\n\tconst preimage = new Uint8Array(SS58PRE.length + body.length);\n\tpreimage.set(SS58PRE);\n\tpreimage.set(body, SS58PRE.length);\n\tconst hash = blake2b(preimage, { dkLen: 64 });\n\n\treturn (\n\t\tdecoded[decoded.length - 2] === hash[0] &&\n\t\tdecoded[decoded.length - 1] === hash[1]\n\t);\n};\n","import { isEthereumAddress } from \"./isEthereumAddress\";\nimport { isSolanaAddress } from \"./isSolanaAddress\";\nimport { isSs58Address } from \"./isSs58Address\";\n\nexport const isValidAddress = (address: string): boolean => {\n\tif (address.startsWith(\"0x\")) return isEthereumAddress(address);\n\t// SS58 (checksummed) and Solana (base58, no checksum) are disjoint: a\n\t// 32-byte Solana pubkey fails SS58 decoding, and an SS58 address decodes to\n\t// more than 32 bytes so it fails the Solana length check.\n\treturn isSs58Address(address) || isSolanaAddress(address);\n};\n","import { isValidAddress } from \"./isValidAddress\";\n\nexport type WalletAccountId = string;\n\nexport const getWalletAccountId = (\n\twalletId: string,\n\taddress: string,\n): WalletAccountId => {\n\tif (!walletId) throw new Error(\"Missing walletId\");\n\tif (!isValidAddress(address)) throw new Error(\"Invalid address\");\n\treturn `${walletId}::${address}`;\n};\n\nexport const parseWalletAccountId = (accountId: string) => {\n\tif (!accountId) throw new Error(\"Invalid walletAccountId\");\n\tconst [walletId, address] = accountId.split(\"::\");\n\tif (!walletId) throw new Error(\"Missing walletId\");\n\tif (!address || !isValidAddress(address)) throw new Error(\"Invalid address\");\n\treturn { walletId, address };\n};\n","import type { WalletId } from \"../utils/WalletId\";\n\n/**\n * Stable error codes thrown by kheopskit. Catch a {@link KheopskitError} and\n * branch on `error.code` instead of matching message strings.\n */\nexport type KheopskitErrorCode =\n\t/** `connect()` called on a wallet that is already connected. */\n\t| \"WALLET_ALREADY_CONNECTED\"\n\t/** `disconnect()` called on a wallet that is not connected. */\n\t| \"WALLET_NOT_CONNECTED\"\n\t/** The wallet does not advertise a capability kheopskit needs to proceed. */\n\t| \"FEATURE_NOT_SUPPORTED\"\n\t/** No active WalletConnect session for the requested operation. */\n\t| \"NO_SESSION\"\n\t/** No provider available for the requested namespace. */\n\t| \"NO_PROVIDER\"\n\t/** The installed polkadot-api version exposes neither `getTxCreatorFromPjs` (v3) nor `getPolkadotSignerFromPjs` (v2). */\n\t| \"UNSUPPORTED_VERSION\"\n\t/** The requested chain cannot be used for this operation (e.g. a Solana cluster with no CAIP-2 id over WalletConnect). */\n\t| \"UNSUPPORTED_CHAIN\";\n\n/**\n * Error thrown by kheopskit wallet/account operations. Carries a stable\n * {@link KheopskitErrorCode} and, when relevant, the offending wallet id.\n *\n * @example\n * ```ts\n * try {\n * await wallet.connect();\n * } catch (error) {\n * if (error instanceof KheopskitError && error.code === \"WALLET_ALREADY_CONNECTED\") {\n * // ignore\n * } else throw error;\n * }\n * ```\n */\nexport class KheopskitError extends Error {\n\treadonly code: KheopskitErrorCode;\n\t/** The wallet id this error relates to, when applicable. */\n\treadonly walletId?: WalletId;\n\n\tconstructor(\n\t\tcode: KheopskitErrorCode,\n\t\tmessage: string,\n\t\toptions?: { walletId?: WalletId; cause?: unknown },\n\t) {\n\t\tsuper(`[kheopskit] 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AM,eAAe,WAAW,EAAE,OAAO,SAAS,MAAM,CAAC;EATjD,gBAAA,MAAA,QAAA,KAAA,CAAA;EAEA,gBAAA,MAAA,YAAA,KAAA,CAAA;EAQR,KAAK,OAAO;EACZ,KAAK,OAAO;EACZ,KAAK,WAAW,SAAS;CAC1B;AACD"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"iconCache-DUtkJlaX.js","names":["POLKADOT_EXTENSIONS","parseWalletId","isWalletConnectWallet"],"sources":["../src/utils/hydrateState.ts","../src/utils/storage.ts","../src/utils/iconCache.ts"],"sourcesContent":["import {\n\ttype BaseWallet,\n\ttype BaseWalletAccount,\n\ttype CachedAccount,\n\ttype CachedWallet,\n\tisWalletConnectWallet,\n\ttype PolkadotAccountType,\n\ttype WalletConnectWallet,\n} from \"../api/types\";\nimport { POLKADOT_EXTENSIONS } from \"./polkadotExtensions\";\nimport type { WalletAccountId } from \"./WalletAccountId\";\nimport { parseWalletId, type WalletId } from \"./WalletId\";\n\n/**\n * Looks up the icon for a wallet from known Polkadot extensions only.\n * Ethereum icons will be populated from the localStorage icon cache via the merge function.\n *\n * Note: We DON'T use localStorage icon cache here because hydrateWallet is called\n * during SSR (server) and client hydration. localStorage isn't available on server,\n * so using it would cause a hydration mismatch. Icons for Ethereum wallets will be\n * populated when the hydration buffer merges cached wallets with live wallets.\n */\nconst lookupWalletIcon = (platform: string, identifier: string): string => {\n\t// Only Polkadot extensions have hardcoded icons that are safe for SSR\n\tif (platform === \"polkadot\") {\n\t\treturn POLKADOT_EXTENSIONS[identifier]?.icon ?? \"\";\n\t}\n\t// Ethereum icons come from localStorage or live wallets - not here\n\treturn \"\";\n};\n\n/**\n * Error thrown when trying to use a placeholder wallet that hasn't fully loaded yet.\n */\nclass PendingWalletError extends Error {\n\tconstructor(walletId: string) {\n\t\tsuper(\n\t\t\t`Wallet ${walletId} is still loading. Wait for isHydrating to be false before calling connect/disconnect.`,\n\t\t);\n\t\tthis.name = \"PendingWalletError\";\n\t}\n}\n\n/**\n * Converts a CachedWallet to a placeholder wallet for SSR hydration display.\n *\n * The placeholder carries only the SDK-free {@link BaseWallet} fields; the real\n * wallet (with its injected provider/extension/standard-wallet handle) replaces\n * it once it loads. connect/disconnect throw until then.\n */\nexport const hydrateWallet = (\n\tcached: CachedWallet,\n): BaseWallet | WalletConnectWallet => {\n\tconst throwPending = () => {\n\t\tthrow new PendingWalletError(cached.id);\n\t};\n\n\t// The platform-less WalletConnect connector. `appKit`/`platforms` are SDK\n\t// state absent until the live connector loads (cast like other placeholder\n\t// SDK handles); icon is filled from the localStorage cache by the caller.\n\tif (cached.type === \"walletconnect\") {\n\t\treturn {\n\t\t\tid: cached.id,\n\t\t\ttype: \"walletconnect\",\n\t\t\tplatforms: [],\n\t\t\tname: cached.name,\n\t\t\ticon: \"\",\n\t\t\tisConnected: cached.isConnected,\n\t\t\tconnect: throwPending,\n\t\t\tdisconnect: throwPending,\n\t\t} as unknown as WalletConnectWallet;\n\t}\n\n\tconst { platform, identifier } = parseWalletId(cached.id);\n\n\treturn {\n\t\tid: cached.id,\n\t\tplatform: cached.platform as BaseWallet[\"platform\"],\n\t\ttype: cached.type,\n\t\tname: cached.name,\n\t\ticon: lookupWalletIcon(platform, identifier),\n\t\tisConnected: cached.isConnected,\n\t\tconnect: throwPending,\n\t\tdisconnect: throwPending,\n\t};\n};\n\n/**\n * Converts a CachedAccount to a placeholder account for SSR hydration display.\n *\n * The placeholder carries the SDK-free {@link BaseWalletAccount} fields plus the\n * plain, serializable platform data that lives in the cache — Ethereum `chainId`\n * and the Polkadot key `type`. Those render immediately on reload (no blank →\n * value flicker) and match what the live account will report. Only the SDK\n * handles (`client`/`signer`/`txCreator`) are absent until the real account\n * replaces this placeholder; signing stays gated on `isHydrating` until then.\n */\nexport const hydrateAccount = (cached: CachedAccount): BaseWalletAccount => ({\n\tid: cached.id as WalletAccountId,\n\tplatform: cached.platform,\n\taddress: cached.address,\n\tname: cached.name,\n\twalletId: cached.walletId,\n\twalletName: cached.walletName,\n\t// Spread (not direct keys) so the extra platform fields don't trip the\n\t// excess-property check against BaseWalletAccount; they're read back via the\n\t// platform-specific account types once narrowed by `platform`.\n\t...(cached.platform === \"ethereum\" && { chainId: cached.chainId }),\n\t...(cached.platform === \"polkadot\" && {\n\t\ttype: cached.polkadotAccountType,\n\t}),\n});\n\n/**\n * Converts a wallet to a CachedWallet for storage.\n * Only extracts the serializable properties needed for hydration.\n */\nexport const serializeWallet = (\n\twallet: BaseWallet | WalletConnectWallet,\n): CachedWallet => ({\n\tid: wallet.id,\n\t// The WalletConnect connector has no platform.\n\tplatform: isWalletConnectWallet(wallet) ? undefined : wallet.platform,\n\ttype: wallet.type,\n\tname: wallet.name,\n\t// Note: icon is NOT stored to save cookie space\n\tisConnected: wallet.isConnected,\n});\n\n/**\n * Converts an account to a CachedAccount for storage.\n * Only extracts the serializable properties needed for hydration. Platform-only\n * fields (Ethereum chainId, Polkadot key type) are read defensively so this\n * stays SDK-free.\n */\nexport const serializeAccount = (\n\taccount: BaseWalletAccount,\n): CachedAccount => ({\n\tid: account.id,\n\tplatform: account.platform,\n\taddress: account.address,\n\tname: account.name,\n\tchainId:\n\t\taccount.platform === \"ethereum\"\n\t\t\t? (account as { chainId?: number }).chainId\n\t\t\t: undefined,\n\tpolkadotAccountType:\n\t\taccount.platform === \"polkadot\"\n\t\t\t? (account as { type?: PolkadotAccountType }).type\n\t\t\t: undefined,\n\twalletId: account.walletId as WalletId,\n\twalletName: account.walletName,\n});\n","export type Storage = {\n\tgetItem: (key: string) => string | null;\n\tsetItem: (key: string, value: string) => void;\n\tremoveItem: (key: string) => void;\n};\n\n/**\n * Extended storage interface with cross-tab sync support.\n */\nexport type SyncableStorage = Storage & {\n\t/**\n\t * Subscribe to storage changes from other tabs.\n\t * Returns an unsubscribe function.\n\t */\n\tsubscribe?: (\n\t\tkey: string,\n\t\tcallback: (value: string | null) => void,\n\t) => () => void;\n};\n\n/**\n * A no-op storage implementation that does nothing.\n * Useful for testing or SSR environments where no storage is needed.\n */\nexport const noopStorage: SyncableStorage = {\n\tgetItem: () => null,\n\tsetItem: () => {},\n\tremoveItem: () => {},\n};\n\n/**\n * Cached localStorage wrapper instance.\n * Lazily initialized on first access to avoid SSR issues.\n */\nlet _safeLocalStorage: SyncableStorage | null = null;\n\n/**\n * Creates the localStorage wrapper, testing for availability.\n * Returns noopStorage if localStorage is unavailable (SSR, private browsing, etc.)\n */\nconst createSafeLocalStorage = (): SyncableStorage => {\n\tif (typeof window === \"undefined\") return noopStorage;\n\n\ttry {\n\t\t// Test that localStorage is accessible (may throw in private browsing)\n\t\tconst testKey = \"__kheopskit_test__\";\n\t\twindow.localStorage.setItem(testKey, testKey);\n\t\twindow.localStorage.removeItem(testKey);\n\n\t\treturn {\n\t\t\tgetItem: (key: string) => window.localStorage.getItem(key),\n\t\t\tsetItem: (key: string, value: string) =>\n\t\t\t\twindow.localStorage.setItem(key, value),\n\t\t\tremoveItem: (key: string) => window.localStorage.removeItem(key),\n\t\t\tsubscribe: (key: string, callback: (value: string | null) => void) => {\n\t\t\t\tconst handler = (event: StorageEvent) => {\n\t\t\t\t\tif (event.key === key) {\n\t\t\t\t\t\tcallback(event.newValue);\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t\twindow.addEventListener(\"storage\", handler);\n\t\t\t\treturn () => window.removeEventListener(\"storage\", handler);\n\t\t\t},\n\t\t};\n\t} catch {\n\t\treturn noopStorage;\n\t}\n};\n\n/**\n * A safe localStorage wrapper that falls back to noopStorage\n * when localStorage is not available (e.g., during SSR).\n * Includes cross-tab sync via the native 'storage' event.\n *\n * Lazily initialized on first access to be SSR-safe.\n */\nexport const getSafeLocalStorage = (): SyncableStorage => {\n\tif (_safeLocalStorage === null) {\n\t\t_safeLocalStorage = createSafeLocalStorage();\n\t}\n\treturn _safeLocalStorage;\n};\n\n/**\n * @deprecated Use getSafeLocalStorage() instead. This is kept for backward compatibility.\n * Returns a proxy that lazily initializes on first method call.\n */\nexport const safeLocalStorage: SyncableStorage = {\n\tgetItem: (key: string) => getSafeLocalStorage().getItem(key),\n\tsetItem: (key: string, value: string) =>\n\t\tgetSafeLocalStorage().setItem(key, value),\n\tremoveItem: (key: string) => getSafeLocalStorage().removeItem(key),\n\tsubscribe: (key: string, callback: (value: string | null) => void) => {\n\t\tconst storage = getSafeLocalStorage();\n\t\treturn storage.subscribe?.(key, callback) ?? (() => {});\n\t},\n};\n\n/**\n * Parse a cookie string to extract the value for a specific key.\n * @param cookieString - The full cookie header string (e.g., document.cookie or req.headers.cookie)\n * @param key - The cookie key to find\n * @returns The cookie value or null if not found\n */\nexport const parseCookie = (\n\tcookieString: string | undefined,\n\tkey: string,\n): string | null => {\n\tif (!cookieString) return null;\n\n\tfor (const cookie of cookieString.split(\";\")) {\n\t\tconst [k, ...v] = cookie.split(\"=\");\n\t\tconst cookieKey = k?.trim();\n\t\tif (cookieKey === key) {\n\t\t\ttry {\n\t\t\t\treturn decodeURIComponent(v.join(\"=\").trim());\n\t\t\t} catch {\n\t\t\t\treturn null; // Malformed cookie value\n\t\t\t}\n\t\t}\n\t}\n\n\treturn null;\n};\n\n/**\n * Maximum recommended size for cookie storage (3KB to stay well under 4KB limit).\n *\n * @remarks\n * Cookie storage is subject to browser limits (typically 4KB per cookie).\n * When users connect many wallets, the auto-reconnect list may exceed this limit.\n * If this happens:\n * - A console warning will be logged\n * - Some browsers may silently reject the cookie\n * - Consider using fewer simultaneous wallet connections\n *\n * The stored data includes wallet IDs in format `platform:identifier`\n * (e.g., `polkadot:talisman`, `ethereum:io.metamask`).\n */\nexport const COOKIE_MAX_SIZE = 3 * 1024;\n\n/**\n * BroadcastChannel name for cross-tab cookie sync.\n */\nconst BROADCAST_CHANNEL_NAME = \"kheopskit-storage-sync\";\n\n/**\n * Singleton BroadcastChannel for cross-tab cookie sync.\n * Created once and shared across all cookieStorage instances.\n */\nlet sharedBroadcastChannel: BroadcastChannel | null = null;\n\nconst getBroadcastChannel = (): BroadcastChannel | null => {\n\tif (sharedBroadcastChannel) return sharedBroadcastChannel;\n\tif (typeof BroadcastChannel === \"undefined\") return null;\n\n\ttry {\n\t\tsharedBroadcastChannel = new BroadcastChannel(BROADCAST_CHANNEL_NAME);\n\t} catch {\n\t\t// BroadcastChannel not supported or failed\n\t}\n\treturn sharedBroadcastChannel;\n};\n\n/**\n * Check if the current connection is secure (HTTPS).\n * Must be called at runtime (inside methods) to work correctly after SSR hydration.\n */\nconst isSecureConnection = (): boolean =>\n\ttypeof window !== \"undefined\" && window.location.protocol === \"https:\";\n\n/**\n * A cookie-based storage implementation for SSR environments.\n * Reads cookies from an optional initial cookie string (for SSR hydration),\n * writes to document.cookie on the client.\n *\n * Features:\n * - Secure flag automatically added for HTTPS connections\n * - Cross-tab synchronization via BroadcastChannel API\n * - Size limit warning when data exceeds recommended limits\n *\n * @param initialCookies - Optional cookie string for server-side hydration\n */\nexport const cookieStorage = (initialCookies?: string): SyncableStorage => {\n\treturn {\n\t\tgetItem: (key: string) => {\n\t\t\t// On server, use initialCookies. On client, read from document.cookie\n\t\t\tconst cookieString =\n\t\t\t\ttypeof document !== \"undefined\" ? document.cookie : initialCookies;\n\t\t\treturn parseCookie(cookieString, key);\n\t\t},\n\t\tsetItem: (key: string, value: string) => {\n\t\t\tif (typeof document === \"undefined\") return;\n\n\t\t\t// Warn if value exceeds recommended size\n\t\t\tconst encodedValue = encodeURIComponent(value);\n\t\t\tif (encodedValue.length > COOKIE_MAX_SIZE) {\n\t\t\t\tconsole.warn(\n\t\t\t\t\t`[kheopskit] Cookie value for \"${key}\" exceeds recommended size limit (${encodedValue.length} > ${COOKIE_MAX_SIZE} bytes). ` +\n\t\t\t\t\t\t\"This may cause issues with cookie storage. Consider reducing the number of connected wallets.\",\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// Set cookie with 1 year expiry\n\t\t\tconst expires = new Date();\n\t\t\texpires.setFullYear(expires.getFullYear() + 1);\n\n\t\t\t// Build cookie string with security attributes\n\t\t\tlet cookieStr = `${key}=${encodedValue};expires=${expires.toUTCString()};path=/;SameSite=Lax`;\n\t\t\tif (isSecureConnection()) {\n\t\t\t\tcookieStr += \";Secure\";\n\t\t\t}\n\n\t\t\t// biome-ignore lint: necessary for cookie storage - direct cookie assignment is the standard API\n\t\t\tdocument.cookie = cookieStr;\n\n\t\t\t// Broadcast change to other tabs\n\t\t\tgetBroadcastChannel()?.postMessage({ type: \"set\", key, value });\n\t\t},\n\t\tremoveItem: (key: string) => {\n\t\t\tif (typeof document === \"undefined\") return;\n\n\t\t\t// Build delete cookie string\n\t\t\tlet cookieStr = `${key}=;expires=Thu, 01 Jan 1970 00:00:01 GMT;path=/;SameSite=Lax`;\n\t\t\tif (isSecureConnection()) {\n\t\t\t\tcookieStr += \";Secure\";\n\t\t\t}\n\n\t\t\t// biome-ignore lint: necessary for cookie storage - direct cookie assignment is the standard API\n\t\t\tdocument.cookie = cookieStr;\n\n\t\t\t// Broadcast change to other tabs\n\t\t\tgetBroadcastChannel()?.postMessage({ type: \"remove\", key });\n\t\t},\n\t\tsubscribe: (key: string, callback: (value: string | null) => void) => {\n\t\t\tconst channel = getBroadcastChannel();\n\t\t\tif (!channel) return () => {};\n\n\t\t\tconst handler = (event: MessageEvent) => {\n\t\t\t\tconst data = event.data as {\n\t\t\t\t\ttype: string;\n\t\t\t\t\tkey: string;\n\t\t\t\t\tvalue?: string;\n\t\t\t\t};\n\t\t\t\tif (data.key === key) {\n\t\t\t\t\tif (data.type === \"set\") {\n\t\t\t\t\t\tcallback(data.value ?? null);\n\t\t\t\t\t} else if (data.type === \"remove\") {\n\t\t\t\t\t\tcallback(null);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tchannel.addEventListener(\"message\", handler);\n\t\t\treturn () => {\n\t\t\t\tchannel.removeEventListener(\"message\", handler);\n\t\t\t};\n\t\t},\n\t};\n};\n\n/**\n * Cleanup the shared BroadcastChannel used for cross-tab cookie sync.\n * Call this when you're done using cookie storage (e.g., in tests or when unmounting).\n *\n * @remarks\n * In normal browser usage, you typically don't need to call this -\n * the channel will be cleaned up when the page is closed.\n * This is primarily useful for testing environments where multiple\n * test runs may accumulate channels.\n */\nexport const cleanupBroadcastChannel = (): void => {\n\tif (sharedBroadcastChannel) {\n\t\tsharedBroadcastChannel.close();\n\t\tsharedBroadcastChannel = null;\n\t}\n};\n","import { safeLocalStorage } from \"./storage\";\n\n/**\n * Storage key for the icon cache in localStorage.\n */\nconst ICON_CACHE_KEY = \"kheopskit-icons\";\n\n/**\n * Icon cache type: a map of wallet ID to icon data URI or URL.\n */\ntype IconCache = Record<string, string>;\n\n/**\n * In-memory cache to avoid repeated localStorage reads.\n */\nlet memoryCache: IconCache | null = null;\n\n/**\n * Loads the icon cache from localStorage.\n */\nconst loadCache = (): IconCache => {\n\tif (memoryCache !== null) return memoryCache;\n\n\ttry {\n\t\tconst stored = safeLocalStorage.getItem(ICON_CACHE_KEY);\n\t\tmemoryCache = stored ? (JSON.parse(stored) as IconCache) : {};\n\t} catch {\n\t\tmemoryCache = {};\n\t}\n\treturn memoryCache;\n};\n\n/**\n * Saves the icon cache to localStorage.\n */\nconst saveCache = (cache: IconCache): void => {\n\ttry {\n\t\tsafeLocalStorage.setItem(ICON_CACHE_KEY, JSON.stringify(cache));\n\t\tmemoryCache = cache;\n\t} catch {\n\t\t// localStorage may be full or unavailable\n\t}\n};\n\n/**\n * Gets a cached icon for a wallet.\n * @param walletId - The wallet ID (e.g., \"ethereum:io.talisman\")\n * @returns The cached icon data URI, or undefined if not cached\n */\nexport const getCachedIcon = (walletId: string): string | undefined => {\n\tconst cache = loadCache();\n\treturn cache[walletId] || undefined;\n};\n\n/**\n * Sets multiple cached icons at once.\n * More efficient than calling setCachedIcon multiple times.\n * @param icons - Map of wallet ID to icon\n */\nexport const setCachedIcons = (icons: Record<string, string>): void => {\n\tconst cache = loadCache();\n\tlet changed = false;\n\n\tfor (const [walletId, icon] of Object.entries(icons)) {\n\t\tif (icon && cache[walletId] !== icon) {\n\t\t\tcache[walletId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Ed,KAAK,MAAM,CAAC,UAAU,SAAS,OAAO,QAAQ,KAAK,GAClD,IAAI,QAAQ,MAAM,cAAc,MAAM;EACrC,MAAM,YAAY;EAClB,UAAU;CACX;CAGD,IAAI,SACH,UAAU,KAAK;AAEjB"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"iconCache-pP2ES4pJ.mjs","names":[],"sources":["../src/utils/hydrateState.ts","../src/utils/storage.ts","../src/utils/iconCache.ts"],"sourcesContent":["import {\n\ttype BaseWallet,\n\ttype BaseWalletAccount,\n\ttype CachedAccount,\n\ttype CachedWallet,\n\tisWalletConnectWallet,\n\ttype PolkadotAccountType,\n\ttype WalletConnectWallet,\n} from \"../api/types\";\nimport { POLKADOT_EXTENSIONS } from \"./polkadotExtensions\";\nimport type { WalletAccountId } from \"./WalletAccountId\";\nimport { parseWalletId, type WalletId } from \"./WalletId\";\n\n/**\n * Looks up the icon for a wallet from known Polkadot extensions only.\n * Ethereum icons will be populated from the localStorage icon cache via the merge function.\n *\n * Note: We DON'T use localStorage icon cache here because hydrateWallet is called\n * during SSR (server) and client hydration. localStorage isn't available on server,\n * so using it would cause a hydration mismatch. Icons for Ethereum wallets will be\n * populated when the hydration buffer merges cached wallets with live wallets.\n */\nconst lookupWalletIcon = (platform: string, identifier: string): string => {\n\t// Only Polkadot extensions have hardcoded icons that are safe for SSR\n\tif (platform === \"polkadot\") {\n\t\treturn POLKADOT_EXTENSIONS[identifier]?.icon ?? \"\";\n\t}\n\t// Ethereum icons come from localStorage or live wallets - not here\n\treturn \"\";\n};\n\n/**\n * Error thrown when trying to use a placeholder wallet that hasn't fully loaded yet.\n */\nclass PendingWalletError extends Error {\n\tconstructor(walletId: string) {\n\t\tsuper(\n\t\t\t`Wallet ${walletId} is still loading. Wait for isHydrating to be false before calling connect/disconnect.`,\n\t\t);\n\t\tthis.name = \"PendingWalletError\";\n\t}\n}\n\n/**\n * Converts a CachedWallet to a placeholder wallet for SSR hydration display.\n *\n * The placeholder carries only the SDK-free {@link BaseWallet} fields; the real\n * wallet (with its injected provider/extension/standard-wallet handle) replaces\n * it once it loads. connect/disconnect throw until then.\n */\nexport const hydrateWallet = (\n\tcached: CachedWallet,\n): BaseWallet | WalletConnectWallet => {\n\tconst throwPending = () => {\n\t\tthrow new PendingWalletError(cached.id);\n\t};\n\n\t// The platform-less WalletConnect connector. `appKit`/`platforms` are SDK\n\t// state absent until the live connector loads (cast like other placeholder\n\t// SDK handles); icon is filled from the localStorage cache by the caller.\n\tif (cached.type === \"walletconnect\") {\n\t\treturn {\n\t\t\tid: cached.id,\n\t\t\ttype: \"walletconnect\",\n\t\t\tplatforms: [],\n\t\t\tname: cached.name,\n\t\t\ticon: \"\",\n\t\t\tisConnected: cached.isConnected,\n\t\t\tconnect: throwPending,\n\t\t\tdisconnect: throwPending,\n\t\t} as unknown as WalletConnectWallet;\n\t}\n\n\tconst { platform, identifier } = parseWalletId(cached.id);\n\n\treturn {\n\t\tid: cached.id,\n\t\tplatform: cached.platform as BaseWallet[\"platform\"],\n\t\ttype: cached.type,\n\t\tname: cached.name,\n\t\ticon: lookupWalletIcon(platform, identifier),\n\t\tisConnected: cached.isConnected,\n\t\tconnect: throwPending,\n\t\tdisconnect: throwPending,\n\t};\n};\n\n/**\n * Converts a CachedAccount to a placeholder account for SSR hydration display.\n *\n * The placeholder carries the SDK-free {@link BaseWalletAccount} fields plus the\n * plain, serializable platform data that lives in the cache — Ethereum `chainId`\n * and the Polkadot key `type`. Those render immediately on reload (no blank →\n * value flicker) and match what the live account will report. Only the SDK\n * handles (`client`/`signer`/`txCreator`) are absent until the real account\n * replaces this placeholder; signing stays gated on `isHydrating` until then.\n */\nexport const hydrateAccount = (cached: CachedAccount): BaseWalletAccount => ({\n\tid: cached.id as WalletAccountId,\n\tplatform: cached.platform,\n\taddress: cached.address,\n\tname: cached.name,\n\twalletId: cached.walletId,\n\twalletName: cached.walletName,\n\t// Spread (not direct keys) so the extra platform fields don't trip the\n\t// excess-property check against BaseWalletAccount; they're read back via the\n\t// platform-specific account types once narrowed by `platform`.\n\t...(cached.platform === \"ethereum\" && { chainId: cached.chainId }),\n\t...(cached.platform === \"polkadot\" && {\n\t\ttype: cached.polkadotAccountType,\n\t}),\n});\n\n/**\n * Converts a wallet to a CachedWallet for storage.\n * Only extracts the serializable properties needed for hydration.\n */\nexport const serializeWallet = (\n\twallet: BaseWallet | WalletConnectWallet,\n): CachedWallet => ({\n\tid: wallet.id,\n\t// The WalletConnect connector has no platform.\n\tplatform: isWalletConnectWallet(wallet) ? undefined : wallet.platform,\n\ttype: wallet.type,\n\tname: wallet.name,\n\t// Note: icon is NOT stored to save cookie space\n\tisConnected: wallet.isConnected,\n});\n\n/**\n * Converts an account to a CachedAccount for storage.\n * Only extracts the serializable properties needed for hydration. Platform-only\n * fields (Ethereum chainId, Polkadot key type) are read defensively so this\n * stays SDK-free.\n */\nexport const serializeAccount = (\n\taccount: BaseWalletAccount,\n): CachedAccount => ({\n\tid: account.id,\n\tplatform: account.platform,\n\taddress: account.address,\n\tname: account.name,\n\tchainId:\n\t\taccount.platform === \"ethereum\"\n\t\t\t? (account as { chainId?: number }).chainId\n\t\t\t: undefined,\n\tpolkadotAccountType:\n\t\taccount.platform === \"polkadot\"\n\t\t\t? (account as { type?: PolkadotAccountType }).type\n\t\t\t: undefined,\n\twalletId: account.walletId as WalletId,\n\twalletName: account.walletName,\n});\n","export type Storage = {\n\tgetItem: (key: string) => string | null;\n\tsetItem: (key: string, value: string) => void;\n\tremoveItem: (key: string) => void;\n};\n\n/**\n * Extended storage interface with cross-tab sync support.\n */\nexport type SyncableStorage = Storage & {\n\t/**\n\t * Subscribe to storage changes from other tabs.\n\t * Returns an unsubscribe function.\n\t */\n\tsubscribe?: (\n\t\tkey: string,\n\t\tcallback: (value: string | null) => void,\n\t) => () => void;\n};\n\n/**\n * A no-op storage implementation that does nothing.\n * Useful for testing or SSR environments where no storage is needed.\n */\nexport const noopStorage: SyncableStorage = {\n\tgetItem: () => null,\n\tsetItem: () => {},\n\tremoveItem: () => {},\n};\n\n/**\n * Cached localStorage wrapper instance.\n * Lazily initialized on first access to avoid SSR issues.\n */\nlet _safeLocalStorage: SyncableStorage | null = null;\n\n/**\n * Creates the localStorage wrapper, testing for availability.\n * Returns noopStorage if localStorage is unavailable (SSR, private browsing, etc.)\n */\nconst createSafeLocalStorage = (): SyncableStorage => {\n\tif (typeof window === \"undefined\") return noopStorage;\n\n\ttry {\n\t\t// Test that localStorage is accessible (may throw in private browsing)\n\t\tconst testKey = \"__kheopskit_test__\";\n\t\twindow.localStorage.setItem(testKey, testKey);\n\t\twindow.localStorage.removeItem(testKey);\n\n\t\treturn {\n\t\t\tgetItem: (key: string) => window.localStorage.getItem(key),\n\t\t\tsetItem: (key: string, value: string) =>\n\t\t\t\twindow.localStorage.setItem(key, value),\n\t\t\tremoveItem: (key: string) => window.localStorage.removeItem(key),\n\t\t\tsubscribe: (key: string, callback: (value: string | null) => void) => {\n\t\t\t\tconst handler = (event: StorageEvent) => {\n\t\t\t\t\tif (event.key === key) {\n\t\t\t\t\t\tcallback(event.newValue);\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t\twindow.addEventListener(\"storage\", handler);\n\t\t\t\treturn () => window.removeEventListener(\"storage\", handler);\n\t\t\t},\n\t\t};\n\t} catch {\n\t\treturn noopStorage;\n\t}\n};\n\n/**\n * A safe localStorage wrapper that falls back to noopStorage\n * when localStorage is not available (e.g., during SSR).\n * Includes cross-tab sync via the native 'storage' event.\n *\n * Lazily initialized on first access to be SSR-safe.\n */\nexport const getSafeLocalStorage = (): SyncableStorage => {\n\tif (_safeLocalStorage === null) {\n\t\t_safeLocalStorage = createSafeLocalStorage();\n\t}\n\treturn _safeLocalStorage;\n};\n\n/**\n * @deprecated Use getSafeLocalStorage() instead. This is kept for backward compatibility.\n * Returns a proxy that lazily initializes on first method call.\n */\nexport const safeLocalStorage: SyncableStorage = {\n\tgetItem: (key: string) => getSafeLocalStorage().getItem(key),\n\tsetItem: (key: string, value: string) =>\n\t\tgetSafeLocalStorage().setItem(key, value),\n\tremoveItem: (key: string) => getSafeLocalStorage().removeItem(key),\n\tsubscribe: (key: string, callback: (value: string | null) => void) => {\n\t\tconst storage = getSafeLocalStorage();\n\t\treturn storage.subscribe?.(key, callback) ?? (() => {});\n\t},\n};\n\n/**\n * Parse a cookie string to extract the value for a specific key.\n * @param cookieString - The full cookie header string (e.g., document.cookie or req.headers.cookie)\n * @param key - The cookie key to find\n * @returns The cookie value or null if not found\n */\nexport const parseCookie = (\n\tcookieString: string | undefined,\n\tkey: string,\n): string | null => {\n\tif (!cookieString) return null;\n\n\tfor (const cookie of cookieString.split(\";\")) {\n\t\tconst [k, ...v] = cookie.split(\"=\");\n\t\tconst cookieKey = k?.trim();\n\t\tif (cookieKey === key) {\n\t\t\ttry {\n\t\t\t\treturn decodeURIComponent(v.join(\"=\").trim());\n\t\t\t} catch {\n\t\t\t\treturn null; // Malformed cookie value\n\t\t\t}\n\t\t}\n\t}\n\n\treturn null;\n};\n\n/**\n * Maximum recommended size for cookie storage (3KB to stay well under 4KB limit).\n *\n * @remarks\n * Cookie storage is subject to browser limits (typically 4KB per cookie).\n * When users connect many wallets, the auto-reconnect list may exceed this limit.\n * If this happens:\n * - A console warning will be logged\n * - Some browsers may silently reject the cookie\n * - Consider using fewer simultaneous wallet connections\n *\n * The stored data includes wallet IDs in format `platform:identifier`\n * (e.g., `polkadot:talisman`, `ethereum:io.metamask`).\n */\nexport const COOKIE_MAX_SIZE = 3 * 1024;\n\n/**\n * BroadcastChannel name for cross-tab cookie sync.\n */\nconst BROADCAST_CHANNEL_NAME = \"kheopskit-storage-sync\";\n\n/**\n * Singleton BroadcastChannel for cross-tab cookie sync.\n * Created once and shared across all cookieStorage instances.\n */\nlet sharedBroadcastChannel: BroadcastChannel | null = null;\n\nconst getBroadcastChannel = (): BroadcastChannel | null => {\n\tif (sharedBroadcastChannel) return sharedBroadcastChannel;\n\tif (typeof BroadcastChannel === \"undefined\") return null;\n\n\ttry {\n\t\tsharedBroadcastChannel = new BroadcastChannel(BROADCAST_CHANNEL_NAME);\n\t} catch {\n\t\t// BroadcastChannel not supported or failed\n\t}\n\treturn sharedBroadcastChannel;\n};\n\n/**\n * Check if the current connection is secure (HTTPS).\n * Must be called at runtime (inside methods) to work correctly after SSR hydration.\n */\nconst isSecureConnection = (): boolean =>\n\ttypeof window !== \"undefined\" && window.location.protocol === \"https:\";\n\n/**\n * A cookie-based storage implementation for SSR environments.\n * Reads cookies from an optional initial cookie string (for SSR hydration),\n * writes to document.cookie on the client.\n *\n * Features:\n * - Secure flag automatically added for HTTPS connections\n * - Cross-tab synchronization via BroadcastChannel API\n * - Size limit warning when data exceeds recommended limits\n *\n * @param initialCookies - Optional cookie string for server-side hydration\n */\nexport const cookieStorage = (initialCookies?: string): SyncableStorage => {\n\treturn {\n\t\tgetItem: (key: string) => {\n\t\t\t// On server, use initialCookies. On client, read from document.cookie\n\t\t\tconst cookieString =\n\t\t\t\ttypeof document !== \"undefined\" ? document.cookie : initialCookies;\n\t\t\treturn parseCookie(cookieString, key);\n\t\t},\n\t\tsetItem: (key: string, value: string) => {\n\t\t\tif (typeof document === \"undefined\") return;\n\n\t\t\t// Warn if value exceeds recommended size\n\t\t\tconst encodedValue = encodeURIComponent(value);\n\t\t\tif (encodedValue.length > COOKIE_MAX_SIZE) {\n\t\t\t\tconsole.warn(\n\t\t\t\t\t`[kheopskit] Cookie value for \"${key}\" exceeds recommended size limit (${encodedValue.length} > ${COOKIE_MAX_SIZE} bytes). ` +\n\t\t\t\t\t\t\"This may cause issues with cookie storage. Consider reducing the number of connected wallets.\",\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// Set cookie with 1 year expiry\n\t\t\tconst expires = new Date();\n\t\t\texpires.setFullYear(expires.getFullYear() + 1);\n\n\t\t\t// Build cookie string with security attributes\n\t\t\tlet cookieStr = `${key}=${encodedValue};expires=${expires.toUTCString()};path=/;SameSite=Lax`;\n\t\t\tif (isSecureConnection()) {\n\t\t\t\tcookieStr += \";Secure\";\n\t\t\t}\n\n\t\t\t// biome-ignore lint: necessary for cookie storage - direct cookie assignment is the standard API\n\t\t\tdocument.cookie = cookieStr;\n\n\t\t\t// Broadcast change to other tabs\n\t\t\tgetBroadcastChannel()?.postMessage({ type: \"set\", key, value });\n\t\t},\n\t\tremoveItem: (key: string) => {\n\t\t\tif (typeof document === \"undefined\") return;\n\n\t\t\t// Build delete cookie string\n\t\t\tlet cookieStr = `${key}=;expires=Thu, 01 Jan 1970 00:00:01 GMT;path=/;SameSite=Lax`;\n\t\t\tif (isSecureConnection()) {\n\t\t\t\tcookieStr += \";Secure\";\n\t\t\t}\n\n\t\t\t// biome-ignore lint: necessary for cookie storage - direct cookie assignment is the standard API\n\t\t\tdocument.cookie = cookieStr;\n\n\t\t\t// Broadcast change to other tabs\n\t\t\tgetBroadcastChannel()?.postMessage({ type: \"remove\", key });\n\t\t},\n\t\tsubscribe: (key: string, callback: (value: string | null) => void) => {\n\t\t\tconst channel = getBroadcastChannel();\n\t\t\tif (!channel) return () => {};\n\n\t\t\tconst handler = (event: MessageEvent) => {\n\t\t\t\tconst data = event.data as {\n\t\t\t\t\ttype: string;\n\t\t\t\t\tkey: string;\n\t\t\t\t\tvalue?: string;\n\t\t\t\t};\n\t\t\t\tif (data.key === key) {\n\t\t\t\t\tif (data.type === \"set\") {\n\t\t\t\t\t\tcallback(data.value ?? null);\n\t\t\t\t\t} else if (data.type === \"remove\") {\n\t\t\t\t\t\tcallback(null);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tchannel.addEventListener(\"message\", handler);\n\t\t\treturn () => {\n\t\t\t\tchannel.removeEventListener(\"message\", handler);\n\t\t\t};\n\t\t},\n\t};\n};\n\n/**\n * Cleanup the shared BroadcastChannel used for cross-tab cookie sync.\n * Call this when you're done using cookie storage (e.g., in tests or when unmounting).\n *\n * @remarks\n * In normal browser usage, you typically don't need to call this -\n * the channel will be cleaned up when the page is closed.\n * This is primarily useful for testing environments where multiple\n * test runs may accumulate channels.\n */\nexport const cleanupBroadcastChannel = (): void => {\n\tif (sharedBroadcastChannel) {\n\t\tsharedBroadcastChannel.close();\n\t\tsharedBroadcastChannel = null;\n\t}\n};\n","import { safeLocalStorage } from \"./storage\";\n\n/**\n * Storage key for the icon cache in localStorage.\n */\nconst ICON_CACHE_KEY = \"kheopskit-icons\";\n\n/**\n * Icon cache type: a map of wallet ID to icon data URI or URL.\n */\ntype IconCache = Record<string, string>;\n\n/**\n * In-memory cache to avoid repeated localStorage reads.\n */\nlet memoryCache: IconCache | null = null;\n\n/**\n * Loads the icon cache from localStorage.\n */\nconst loadCache = (): IconCache => {\n\tif (memoryCache !== null) return memoryCache;\n\n\ttry {\n\t\tconst stored = safeLocalStorage.getItem(ICON_CACHE_KEY);\n\t\tmemoryCache = stored ? (JSON.parse(stored) as IconCache) : {};\n\t} catch {\n\t\tmemoryCache = {};\n\t}\n\treturn memoryCache;\n};\n\n/**\n * Saves the icon cache to localStorage.\n */\nconst saveCache = (cache: IconCache): void => {\n\ttry {\n\t\tsafeLocalStorage.setItem(ICON_CACHE_KEY, JSON.stringify(cache));\n\t\tmemoryCache = cache;\n\t} catch {\n\t\t// localStorage may be full or unavailable\n\t}\n};\n\n/**\n * Gets a cached icon for a wallet.\n * @param walletId - The wallet ID (e.g., \"ethereum:io.talisman\")\n * @returns The cached icon data URI, or undefined if not cached\n */\nexport const getCachedIcon = (walletId: string): string | undefined => {\n\tconst cache = loadCache();\n\treturn cache[walletId] || undefined;\n};\n\n/**\n * Sets multiple cached icons at once.\n * More efficient than calling setCachedIcon multiple times.\n * @param icons - Map of wallet ID to icon\n */\nexport const setCachedIcons = (icons: Record<string, string>): void => {\n\tconst cache = loadCache();\n\tlet changed = false;\n\n\tfor (const [walletId, icon] of Object.entries(icons)) {\n\t\tif (icon && cache[walletId] !== icon) {\n\t\t\tcache[walletId] = icon;\n\t\t\tchanged = true;\n\t\t}\n\t}\n\n\tif (changed) {\n\t\tsaveCache(cache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,MAAM,YAAY;EAClB,UAAU;CACX;CAGD,IAAI,SACH,UAAU,KAAK;AAEjB"}
@@ -1,148 +0,0 @@
1
- const require_types = require("./types-DKU-SNio.js");
2
- const require_errors = require("./errors-DYWVPHrR.js");
3
- let rxjs = require("rxjs");
4
- //#region src/api/platformAccounts.ts
5
- /** Shared engine behind every platform's `getAccounts$`. */
6
- const createPlatformAccounts$ = ({ wallets$, getInjectedAccounts$, getWalletConnectAccounts$, mapAccounts, accountChangeKey = (account) => account.id }) => {
7
- const accountsListEqual = (a, b) => a.length === b.length && a.every((account, i) => {
8
- const other = b[i];
9
- return !!other && accountChangeKey(account) === accountChangeKey(other);
10
- });
11
- return new rxjs.Observable((subscriber) => {
12
- const sub = wallets$.pipe((0, rxjs.map)((wallets) => wallets.filter((w) => w.isConnected)), (0, rxjs.switchMap)((wallets) => wallets.length ? (0, rxjs.combineLatest)([...wallets.filter((w) => !require_types.isWalletConnectWallet(w)).map(getInjectedAccounts$), ...wallets.filter(require_types.isWalletConnectWallet).map(getWalletConnectAccounts$)]) : (0, rxjs.of)([])), (0, rxjs.map)((accounts) => {
13
- const flat = accounts.flat();
14
- return mapAccounts ? mapAccounts(flat) : flat;
15
- }), (0, rxjs.distinctUntilChanged)(accountsListEqual)).subscribe(subscriber);
16
- return () => {
17
- sub.unsubscribe();
18
- };
19
- }).pipe((0, rxjs.shareReplay)({
20
- refCount: true,
21
- bufferSize: 1
22
- }));
23
- };
24
- /**
25
- * CAIP-10 account strings ("<namespace>:<chainRef>:<address>") the live
26
- * WalletConnect session carries for a namespace.
27
- */
28
- const getSessionCaip10s = (session, namespace) => Object.values(session.namespaces).flatMap((ns) => ns.accounts ?? []).filter((account) => account.startsWith(`${namespace}:`));
29
- /**
30
- * Unique addresses from CAIP-10 account strings (one entry per chain, so the
31
- * same address repeats — dedupe).
32
- */
33
- const getCaip10Addresses = (caip10s) => [...new Set(caip10s.map((account) => account.split(":")[2]).filter((address) => !!address))];
34
- /**
35
- * Shared shape of the Polkadot/Solana WalletConnect account streams: no-op
36
- * unless the session carries the platform's namespace, then a cached
37
- * observable that rebuilds the account list from the session on
38
- * `session_update` / `accountsChanged`.
39
- *
40
- * AppKit's `getAccount(namespace).allAccounts` is always empty for namespaces
41
- * without a native AppKit adapter — the WalletConnect session is the source of
42
- * truth, hence the session-driven rebuild.
43
- */
44
- const getWalletConnectSessionAccounts$ = (options) => {
45
- const { wallet, platform, namespace, cacheKey, buildAccounts } = options;
46
- const provider = wallet.appKit.getProvider(namespace);
47
- if (!wallet.platforms.includes(platform) || !provider?.session) return (0, rxjs.of)([]);
48
- return require_types.getCachedObservable$(cacheKey, () => new rxjs.Observable((subscriber) => {
49
- subscriber.next(buildAccounts(provider));
50
- const reemit = () => subscriber.next(buildAccounts(provider));
51
- provider.on("session_update", reemit);
52
- provider.on("accountsChanged", reemit);
53
- return () => {
54
- provider.off("session_update", reemit);
55
- provider.off("accountsChanged", reemit);
56
- };
57
- }).pipe((0, rxjs.shareReplay)({
58
- refCount: true,
59
- bufferSize: 1
60
- })));
61
- };
62
- //#endregion
63
- //#region src/api/injectedWallets.ts
64
- /**
65
- * Compare two wallet arrays by their relevant properties (not functions).
66
- * Shared by every platform's injected-wallets stream.
67
- */
68
- const walletsEqual = (a, b) => {
69
- if (a.length !== b.length) return false;
70
- return a.every((w, i) => w.id === b[i]?.id && w.isConnected === b[i]?.isConnected && w.name === b[i]?.name);
71
- };
72
- /**
73
- * The shared engine behind every platform's injected-wallets stream: tracks
74
- * connected wallets (and their live handles), guards double
75
- * connect/disconnect, persists connected ids to the store for auto-reconnect,
76
- * and re-emits the wallet list whenever the registry or connection state
77
- * changes.
78
- */
79
- const createInjectedWallets$ = (store, adapter) => new rxjs.Observable((subscriber) => {
80
- const handles$ = new rxjs.BehaviorSubject(/* @__PURE__ */ new Map());
81
- const connect = async (source, walletId) => {
82
- if (handles$.value.has(walletId)) throw new require_errors.KheopskitError("WALLET_ALREADY_CONNECTED", `wallet ${walletId} is already connected`, { walletId });
83
- const handle = await adapter.connect(source, walletId);
84
- const next = new Map(handles$.value);
85
- next.set(walletId, handle);
86
- handles$.next(next);
87
- store.addEnabledWalletId(walletId);
88
- };
89
- const disconnect = async (source, walletId) => {
90
- if (!handles$.value.has(walletId)) throw new require_errors.KheopskitError("WALLET_NOT_CONNECTED", `wallet ${walletId} is not connected`, { walletId });
91
- await adapter.disconnect?.(source, walletId);
92
- const next = new Map(handles$.value);
93
- next.delete(walletId);
94
- handles$.next(next);
95
- store.removeEnabledWalletId(walletId);
96
- adapter.onDisconnected?.(walletId);
97
- };
98
- const sub = (0, rxjs.combineLatest)([adapter.sources$, handles$]).pipe((0, rxjs.map)(([sources, handles]) => sources.map((source) => {
99
- const walletId = adapter.getWalletId(source);
100
- return adapter.buildWallet({
101
- source,
102
- walletId,
103
- handle: handles.get(walletId),
104
- isConnected: handles.has(walletId),
105
- connect: () => connect(source, walletId),
106
- disconnect: () => disconnect(source, walletId)
107
- });
108
- })), (0, rxjs.distinctUntilChanged)(walletsEqual)).subscribe(subscriber);
109
- return () => {
110
- sub.unsubscribe();
111
- };
112
- }).pipe((0, rxjs.shareReplay)({
113
- refCount: true,
114
- bufferSize: 1
115
- }));
116
- //#endregion
117
- Object.defineProperty(exports, "createInjectedWallets$", {
118
- enumerable: true,
119
- get: function() {
120
- return createInjectedWallets$;
121
- }
122
- });
123
- Object.defineProperty(exports, "createPlatformAccounts$", {
124
- enumerable: true,
125
- get: function() {
126
- return createPlatformAccounts$;
127
- }
128
- });
129
- Object.defineProperty(exports, "getCaip10Addresses", {
130
- enumerable: true,
131
- get: function() {
132
- return getCaip10Addresses;
133
- }
134
- });
135
- Object.defineProperty(exports, "getSessionCaip10s", {
136
- enumerable: true,
137
- get: function() {
138
- return getSessionCaip10s;
139
- }
140
- });
141
- Object.defineProperty(exports, "getWalletConnectSessionAccounts$", {
142
- enumerable: true,
143
- get: function() {
144
- return getWalletConnectSessionAccounts$;
145
- }
146
- });
147
-
148
- //# sourceMappingURL=injectedWallets-BqR-_aAy.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"injectedWallets-BqR-_aAy.js","names":["Observable","map","switchMap","combineLatest","isWalletConnectWallet","of","distinctUntilChanged","shareReplay","getCachedObservable$","Observable","BehaviorSubject","KheopskitError","combineLatest","map","distinctUntilChanged","shareReplay"],"sources":["../src/api/platformAccounts.ts","../src/api/injectedWallets.ts"],"sourcesContent":["import {\n\tcombineLatest,\n\tdistinctUntilChanged,\n\tmap,\n\tObservable,\n\tof,\n\tshareReplay,\n\tswitchMap,\n} from \"rxjs\";\nimport { getCachedObservable$ } from \"../utils/getCachedObservable\";\nimport type {\n\tBaseWallet,\n\tBaseWalletAccount,\n\tWalletConnectProvider,\n\tWalletConnectWallet,\n\tWalletPlatform,\n} from \"./types\";\nimport { isWalletConnectWallet } from \"./types\";\n\n/**\n * The platform-specific surface of an accounts stream. The shared pipeline —\n * filter connected wallets, fan out per-wallet account streams, flatten,\n * change-detect, share — is owned by {@link createPlatformAccounts$}.\n */\nexport type PlatformAccountsOptions<\n\tTWallet extends BaseWallet,\n\tTAccount extends BaseWalletAccount,\n> = {\n\t/** This platform's wallets plus the shared WalletConnect connector. */\n\twallets$: Observable<(TWallet | WalletConnectWallet)[]>;\n\t/** Account stream for one connected injected wallet. */\n\tgetInjectedAccounts$: (wallet: TWallet) => Observable<TAccount[]>;\n\t/** Account stream for the WalletConnect connector. */\n\tgetWalletConnectAccounts$: (\n\t\twallet: WalletConnectWallet,\n\t) => Observable<TAccount[]>;\n\t/** Optional post-flatten transform (e.g. Polkadot's `accountTypes` filter). */\n\tmapAccounts?: (accounts: TAccount[]) => TAccount[];\n\t/**\n\t * Signature of the account fields that should trigger a re-emission.\n\t * Defaults to the account id; platforms add mutable fields (Ethereum\n\t * `chainId`, Solana `chains`).\n\t */\n\taccountChangeKey?: (account: TAccount) => string;\n};\n\n/** Shared engine behind every platform's `getAccounts$`. */\nexport const createPlatformAccounts$ = <\n\tTWallet extends BaseWallet,\n\tTAccount extends BaseWalletAccount,\n>({\n\twallets$,\n\tgetInjectedAccounts$,\n\tgetWalletConnectAccounts$,\n\tmapAccounts,\n\taccountChangeKey = (account) => account.id,\n}: PlatformAccountsOptions<TWallet, TAccount>): Observable<TAccount[]> => {\n\tconst accountsListEqual = (a: TAccount[], b: TAccount[]) =>\n\t\ta.length === b.length &&\n\t\ta.every((account, i) => {\n\t\t\tconst other = b[i];\n\t\t\treturn !!other && accountChangeKey(account) === accountChangeKey(other);\n\t\t});\n\n\treturn new Observable<TAccount[]>((subscriber) => {\n\t\tconst sub = wallets$\n\t\t\t.pipe(\n\t\t\t\tmap((wallets) => wallets.filter((w) => w.isConnected)),\n\t\t\t\tswitchMap((wallets) =>\n\t\t\t\t\twallets.length\n\t\t\t\t\t\t? combineLatest([\n\t\t\t\t\t\t\t\t...wallets\n\t\t\t\t\t\t\t\t\t.filter((w): w is TWallet => !isWalletConnectWallet(w))\n\t\t\t\t\t\t\t\t\t.map(getInjectedAccounts$),\n\t\t\t\t\t\t\t\t...wallets\n\t\t\t\t\t\t\t\t\t.filter(isWalletConnectWallet)\n\t\t\t\t\t\t\t\t\t.map(getWalletConnectAccounts$),\n\t\t\t\t\t\t\t])\n\t\t\t\t\t\t: of([]),\n\t\t\t\t),\n\t\t\t\tmap((accounts) => {\n\t\t\t\t\tconst flat = accounts.flat();\n\t\t\t\t\treturn mapAccounts ? mapAccounts(flat) : flat;\n\t\t\t\t}),\n\t\t\t\tdistinctUntilChanged(accountsListEqual),\n\t\t\t)\n\t\t\t.subscribe(subscriber);\n\n\t\treturn () => {\n\t\t\tsub.unsubscribe();\n\t\t};\n\t}).pipe(shareReplay({ refCount: true, bufferSize: 1 }));\n};\n\n/**\n * CAIP-10 account strings (\"<namespace>:<chainRef>:<address>\") the live\n * WalletConnect session carries for a namespace.\n */\nexport const getSessionCaip10s = (\n\tsession: NonNullable<WalletConnectProvider[\"session\"]>,\n\tnamespace: string,\n): string[] =>\n\tObject.values(session.namespaces)\n\t\t.flatMap((ns) => ns.accounts ?? [])\n\t\t.filter((account) => account.startsWith(`${namespace}:`));\n\n/**\n * Unique addresses from CAIP-10 account strings (one entry per chain, so the\n * same address repeats — dedupe).\n */\nexport const getCaip10Addresses = (caip10s: string[]): string[] => [\n\t...new Set(\n\t\tcaip10s\n\t\t\t.map((account) => account.split(\":\")[2])\n\t\t\t.filter((address): address is string => !!address),\n\t),\n];\n\n/**\n * Shared shape of the Polkadot/Solana WalletConnect account streams: no-op\n * unless the session carries the platform's namespace, then a cached\n * observable that rebuilds the account list from the session on\n * `session_update` / `accountsChanged`.\n *\n * AppKit's `getAccount(namespace).allAccounts` is always empty for namespaces\n * without a native AppKit adapter — the WalletConnect session is the source of\n * truth, hence the session-driven rebuild.\n */\nexport const getWalletConnectSessionAccounts$ = <\n\tTAccount extends BaseWalletAccount,\n>(options: {\n\twallet: WalletConnectWallet;\n\tplatform: WalletPlatform;\n\t/** WalletConnect namespace, e.g. \"polkadot\" | \"solana\" | \"eip155\". */\n\tnamespace: string;\n\t/** Cache key for {@link getCachedObservable$} — must be reconnect-safe. */\n\tcacheKey: string;\n\t/** Build the account list from the live session. */\n\tbuildAccounts: (provider: WalletConnectProvider) => TAccount[];\n}): Observable<TAccount[]> => {\n\tconst { wallet, platform, namespace, cacheKey, buildAccounts } = options;\n\tconst provider = wallet.appKit.getProvider(namespace);\n\n\tif (!wallet.platforms.includes(platform) || !provider?.session) return of([]);\n\n\treturn getCachedObservable$(cacheKey, () =>\n\t\tnew Observable<TAccount[]>((subscriber) => {\n\t\t\tsubscriber.next(buildAccounts(provider));\n\n\t\t\t// Re-derive when the WalletConnect session's accounts change, mirroring\n\t\t\t// the injected paths' change subscriptions.\n\t\t\tconst reemit = () => subscriber.next(buildAccounts(provider));\n\t\t\tprovider.on(\"session_update\", reemit);\n\t\t\tprovider.on(\"accountsChanged\", reemit);\n\n\t\t\treturn () => {\n\t\t\t\tprovider.off(\"session_update\", reemit);\n\t\t\t\tprovider.off(\"accountsChanged\", reemit);\n\t\t\t};\n\t\t}).pipe(shareReplay({ refCount: true, bufferSize: 1 })),\n\t);\n};\n","import {\n\tBehaviorSubject,\n\tcombineLatest,\n\tdistinctUntilChanged,\n\tmap,\n\tObservable,\n\tshareReplay,\n} from \"rxjs\";\nimport type { WalletId } from \"../utils/WalletId\";\nimport { KheopskitError } from \"./errors\";\nimport type { KheopskitStore } from \"./store\";\nimport type { BaseWallet } from \"./types\";\n\n/**\n * Compare two wallet arrays by their relevant properties (not functions).\n * Shared by every platform's injected-wallets stream.\n */\nconst walletsEqual = <\n\tW extends Pick<BaseWallet, \"id\" | \"isConnected\" | \"name\">,\n>(\n\ta: W[],\n\tb: W[],\n): boolean => {\n\tif (a.length !== b.length) return false;\n\treturn a.every(\n\t\t(w, i) =>\n\t\t\tw.id === b[i]?.id &&\n\t\t\tw.isConnected === b[i]?.isConnected &&\n\t\t\tw.name === b[i]?.name,\n\t);\n};\n\n/**\n * The platform-specific surface of an injected-wallets stream. Everything else\n * — the connect/disconnect state machine, the connected-ids bookkeeping, the\n * store persistence, change detection and sharing — is owned by\n * {@link createInjectedWallets$}.\n *\n * @typeParam TSource - a wallet as the platform's registry reports it\n * @typeParam TWallet - the platform's wallet type\n * @typeParam THandle - live connection handle retained while connected\n * (Polkadot keeps the `InjectedExtension`; platforms with no handle use void)\n */\nexport type InjectedWalletsAdapter<\n\tTSource,\n\tTWallet extends BaseWallet,\n\tTHandle = void,\n> = {\n\t/** Live registry of the platform's injected wallets (emits `[]` during SSR). */\n\tsources$: Observable<readonly TSource[]>;\n\t/** Stable wallet id for a registry entry. */\n\tgetWalletId: (source: TSource) => WalletId;\n\t/**\n\t * Platform connect call (e.g. `connectInjectedExtension`,\n\t * `eth_requestAccounts`, `standard:connect`). The resolved value is retained\n\t * as the wallet's live handle until disconnect.\n\t */\n\tconnect: (source: TSource, walletId: WalletId) => Promise<THandle>;\n\t/**\n\t * Optional platform disconnect call, awaited before local state clears so a\n\t * failed disconnect rejects without desyncing the connected list.\n\t */\n\tdisconnect?: (source: TSource, walletId: WalletId) => Promise<void>;\n\t/**\n\t * Runs after a disconnect fully applied — the place to drop cached account\n\t * observables so a later reconnect rebuilds them against a fresh handle.\n\t */\n\tonDisconnected?: (walletId: WalletId) => void;\n\t/** Build the platform wallet object for one registry entry. */\n\tbuildWallet: (args: {\n\t\tsource: TSource;\n\t\twalletId: WalletId;\n\t\t/** Live connection handle; `undefined` while disconnected. */\n\t\thandle: THandle | undefined;\n\t\tisConnected: boolean;\n\t\tconnect: () => Promise<void>;\n\t\tdisconnect: () => Promise<void>;\n\t}) => TWallet;\n};\n\n/**\n * The shared engine behind every platform's injected-wallets stream: tracks\n * connected wallets (and their live handles), guards double\n * connect/disconnect, persists connected ids to the store for auto-reconnect,\n * and re-emits the wallet list whenever the registry or connection state\n * changes.\n */\nexport const createInjectedWallets$ = <\n\tTSource,\n\tTWallet extends BaseWallet,\n\tTHandle = void,\n>(\n\tstore: KheopskitStore,\n\tadapter: InjectedWalletsAdapter<TSource, TWallet, THandle>,\n): Observable<TWallet[]> =>\n\tnew Observable<TWallet[]>((subscriber) => {\n\t\tconst handles$ = new BehaviorSubject<Map<WalletId, THandle>>(new Map());\n\n\t\tconst connect = async (source: TSource, walletId: WalletId) => {\n\t\t\tif (handles$.value.has(walletId))\n\t\t\t\tthrow new KheopskitError(\n\t\t\t\t\t\"WALLET_ALREADY_CONNECTED\",\n\t\t\t\t\t`wallet ${walletId} is already connected`,\n\t\t\t\t\t{ walletId },\n\t\t\t\t);\n\n\t\t\tconst handle = await adapter.connect(source, walletId);\n\n\t\t\tconst next = new Map(handles$.value);\n\t\t\tnext.set(walletId, handle);\n\t\t\thandles$.next(next);\n\n\t\t\tstore.addEnabledWalletId(walletId);\n\t\t};\n\n\t\tconst disconnect = async (source: TSource, walletId: WalletId) => {\n\t\t\tif (!handles$.value.has(walletId))\n\t\t\t\tthrow new KheopskitError(\n\t\t\t\t\t\"WALLET_NOT_CONNECTED\",\n\t\t\t\t\t`wallet ${walletId} is not connected`,\n\t\t\t\t\t{ walletId },\n\t\t\t\t);\n\n\t\t\tawait adapter.disconnect?.(source, walletId);\n\n\t\t\tconst next = new Map(handles$.value);\n\t\t\tnext.delete(walletId);\n\t\t\thandles$.next(next);\n\n\t\t\tstore.removeEnabledWalletId(walletId);\n\n\t\t\tadapter.onDisconnected?.(walletId);\n\t\t};\n\n\t\tconst sub = combineLatest([adapter.sources$, handles$])\n\t\t\t.pipe(\n\t\t\t\tmap(([sources, handles]) =>\n\t\t\t\t\tsources.map((source): TWallet => {\n\t\t\t\t\t\tconst walletId = adapter.getWalletId(source);\n\t\t\t\t\t\treturn adapter.buildWallet({\n\t\t\t\t\t\t\tsource,\n\t\t\t\t\t\t\twalletId,\n\t\t\t\t\t\t\thandle: handles.get(walletId),\n\t\t\t\t\t\t\tisConnected: handles.has(walletId),\n\t\t\t\t\t\t\tconnect: () => connect(source, walletId),\n\t\t\t\t\t\t\tdisconnect: () => disconnect(source, walletId),\n\t\t\t\t\t\t});\n\t\t\t\t\t}),\n\t\t\t\t),\n\t\t\t\tdistinctUntilChanged(walletsEqual),\n\t\t\t)\n\t\t\t.subscribe(subscriber);\n\n\t\treturn () => {\n\t\t\tsub.unsubscribe();\n\t\t};\n\t}).pipe(shareReplay({ refCount: true, bufferSize: 1 }));\n"],"mappings":";;;;;AA+CA,MAAa,2BAGX,EACD,UACA,sBACA,2BACA,aACA,oBAAoB,YAAY,QAAQ,SACiC;CACzE,MAAM,qBAAqB,GAAe,MACzC,EAAE,WAAW,EAAE,UACf,EAAE,OAAO,SAAS,MAAM;EACvB,MAAM,QAAQ,EAAE;EAChB,OAAO,CAAC,CAAC,SAAS,iBAAiB,OAAO,MAAM,iBAAiB,KAAK;CACvE,CAAC;CAEF,OAAO,IAAIA,KAAAA,YAAwB,eAAe;EACjD,MAAM,MAAM,SACV,MAAA,GACAC,KAAAA,IAAAA,EAAK,YAAY,QAAQ,QAAQ,MAAM,EAAE,WAAW,CAAC,IAAA,GACrDC,KAAAA,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MAAM,QAAQ,aAAa,QAAQ,QAAQ;EAE3C,MAAM,OAAO,IAAI,IAAI,SAAS,KAAK;EACnC,KAAK,OAAO,QAAQ;EACpB,SAAS,KAAK,IAAI;EAElB,MAAM,sBAAsB,QAAQ;EAEpC,QAAQ,iBAAiB,QAAQ;CAClC;CAEA,MAAM,OAAA,GAAMC,KAAAA,cAAAA,CAAc,CAAC,QAAQ,UAAU,QAAQ,CAAC,CAAC,CACrD,MAAA,GACAC,KAAAA,IAAAA,EAAK,CAAC,SAAS,aACd,QAAQ,KAAK,WAAoB;EAChC,MAAM,WAAW,QAAQ,YAAY,MAAM;EAC3C,OAAO,QAAQ,YAAY;GAC1B;GACA;GACA,QAAQ,QAAQ,IAAI,QAAQ;GAC5B,aAAa,QAAQ,IAAI,QAAQ;GACjC,eAAe,QAAQ,QAAQ,QAAQ;GACvC,kBAAkB,WAAW,QAAQ,QAAQ;EAC9C,CAAC;CACF,CAAC,CACF,IAAA,GACAC,KAAAA,qBAAAA,CAAqB,YAAY,CAClC,CAAC,CACA,UAAU,UAAU;CAEtB,aAAa;EACZ,IAAI,YAAY;CACjB;AACD,CAAC,CAAC,CAAC,MAAA,GAAKC,KAAAA,YAAAA,CAAY;CAAE,UAAU;CAAM,YAAY;AAAE,CAAC,CAAC"}
@@ -1,119 +0,0 @@
1
- import { d as getCachedObservable$, n as isWalletConnectWallet } from "./types-jnifAAA0.mjs";
2
- import { t as KheopskitError } from "./errors-BLFP1dQI.mjs";
3
- import { BehaviorSubject, Observable, combineLatest, distinctUntilChanged, map, of, shareReplay, switchMap } from "rxjs";
4
- //#region src/api/platformAccounts.ts
5
- /** Shared engine behind every platform's `getAccounts$`. */
6
- const createPlatformAccounts$ = ({ wallets$, getInjectedAccounts$, getWalletConnectAccounts$, mapAccounts, accountChangeKey = (account) => account.id }) => {
7
- const accountsListEqual = (a, b) => a.length === b.length && a.every((account, i) => {
8
- const other = b[i];
9
- return !!other && accountChangeKey(account) === accountChangeKey(other);
10
- });
11
- return new Observable((subscriber) => {
12
- const sub = wallets$.pipe(map((wallets) => wallets.filter((w) => w.isConnected)), switchMap((wallets) => wallets.length ? combineLatest([...wallets.filter((w) => !isWalletConnectWallet(w)).map(getInjectedAccounts$), ...wallets.filter(isWalletConnectWallet).map(getWalletConnectAccounts$)]) : of([])), map((accounts) => {
13
- const flat = accounts.flat();
14
- return mapAccounts ? mapAccounts(flat) : flat;
15
- }), distinctUntilChanged(accountsListEqual)).subscribe(subscriber);
16
- return () => {
17
- sub.unsubscribe();
18
- };
19
- }).pipe(shareReplay({
20
- refCount: true,
21
- bufferSize: 1
22
- }));
23
- };
24
- /**
25
- * CAIP-10 account strings ("<namespace>:<chainRef>:<address>") the live
26
- * WalletConnect session carries for a namespace.
27
- */
28
- const getSessionCaip10s = (session, namespace) => Object.values(session.namespaces).flatMap((ns) => ns.accounts ?? []).filter((account) => account.startsWith(`${namespace}:`));
29
- /**
30
- * Unique addresses from CAIP-10 account strings (one entry per chain, so the
31
- * same address repeats — dedupe).
32
- */
33
- const getCaip10Addresses = (caip10s) => [...new Set(caip10s.map((account) => account.split(":")[2]).filter((address) => !!address))];
34
- /**
35
- * Shared shape of the Polkadot/Solana WalletConnect account streams: no-op
36
- * unless the session carries the platform's namespace, then a cached
37
- * observable that rebuilds the account list from the session on
38
- * `session_update` / `accountsChanged`.
39
- *
40
- * AppKit's `getAccount(namespace).allAccounts` is always empty for namespaces
41
- * without a native AppKit adapter — the WalletConnect session is the source of
42
- * truth, hence the session-driven rebuild.
43
- */
44
- const getWalletConnectSessionAccounts$ = (options) => {
45
- const { wallet, platform, namespace, cacheKey, buildAccounts } = options;
46
- const provider = wallet.appKit.getProvider(namespace);
47
- if (!wallet.platforms.includes(platform) || !provider?.session) return of([]);
48
- return getCachedObservable$(cacheKey, () => new Observable((subscriber) => {
49
- subscriber.next(buildAccounts(provider));
50
- const reemit = () => subscriber.next(buildAccounts(provider));
51
- provider.on("session_update", reemit);
52
- provider.on("accountsChanged", reemit);
53
- return () => {
54
- provider.off("session_update", reemit);
55
- provider.off("accountsChanged", reemit);
56
- };
57
- }).pipe(shareReplay({
58
- refCount: true,
59
- bufferSize: 1
60
- })));
61
- };
62
- //#endregion
63
- //#region src/api/injectedWallets.ts
64
- /**
65
- * Compare two wallet arrays by their relevant properties (not functions).
66
- * Shared by every platform's injected-wallets stream.
67
- */
68
- const walletsEqual = (a, b) => {
69
- if (a.length !== b.length) return false;
70
- return a.every((w, i) => w.id === b[i]?.id && w.isConnected === b[i]?.isConnected && w.name === b[i]?.name);
71
- };
72
- /**
73
- * The shared engine behind every platform's injected-wallets stream: tracks
74
- * connected wallets (and their live handles), guards double
75
- * connect/disconnect, persists connected ids to the store for auto-reconnect,
76
- * and re-emits the wallet list whenever the registry or connection state
77
- * changes.
78
- */
79
- const createInjectedWallets$ = (store, adapter) => new Observable((subscriber) => {
80
- const handles$ = new BehaviorSubject(/* @__PURE__ */ new Map());
81
- const connect = async (source, walletId) => {
82
- if (handles$.value.has(walletId)) throw new KheopskitError("WALLET_ALREADY_CONNECTED", `wallet ${walletId} is already connected`, { walletId });
83
- const handle = await adapter.connect(source, walletId);
84
- const next = new Map(handles$.value);
85
- next.set(walletId, handle);
86
- handles$.next(next);
87
- store.addEnabledWalletId(walletId);
88
- };
89
- const disconnect = async (source, walletId) => {
90
- if (!handles$.value.has(walletId)) throw new KheopskitError("WALLET_NOT_CONNECTED", `wallet ${walletId} is not connected`, { walletId });
91
- await adapter.disconnect?.(source, walletId);
92
- const next = new Map(handles$.value);
93
- next.delete(walletId);
94
- handles$.next(next);
95
- store.removeEnabledWalletId(walletId);
96
- adapter.onDisconnected?.(walletId);
97
- };
98
- const sub = combineLatest([adapter.sources$, handles$]).pipe(map(([sources, handles]) => sources.map((source) => {
99
- const walletId = adapter.getWalletId(source);
100
- return adapter.buildWallet({
101
- source,
102
- walletId,
103
- handle: handles.get(walletId),
104
- isConnected: handles.has(walletId),
105
- connect: () => connect(source, walletId),
106
- disconnect: () => disconnect(source, walletId)
107
- });
108
- })), distinctUntilChanged(walletsEqual)).subscribe(subscriber);
109
- return () => {
110
- sub.unsubscribe();
111
- };
112
- }).pipe(shareReplay({
113
- refCount: true,
114
- bufferSize: 1
115
- }));
116
- //#endregion
117
- export { getWalletConnectSessionAccounts$ as a, getSessionCaip10s as i, createPlatformAccounts$ as n, getCaip10Addresses as r, createInjectedWallets$ as t };
118
-
119
- //# sourceMappingURL=injectedWallets-Uz4hPuoW.mjs.map