@shadow-corp/nearconnect 1.0.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 (179) hide show
  1. package/README.md +546 -0
  2. package/build/InjectedWallet.d.ts +22 -0
  3. package/build/InjectedWallet.js +58 -0
  4. package/build/InjectedWallet.js.map +1 -0
  5. package/build/NearConnector.d.ts +151 -0
  6. package/build/NearConnector.js +536 -0
  7. package/build/NearConnector.js.map +1 -0
  8. package/build/ParentFrameWallet.d.ts +22 -0
  9. package/build/ParentFrameWallet.js +66 -0
  10. package/build/ParentFrameWallet.js.map +1 -0
  11. package/build/SandboxedWallet/code.d.ts +7 -0
  12. package/build/SandboxedWallet/code.js +324 -0
  13. package/build/SandboxedWallet/code.js.map +1 -0
  14. package/build/SandboxedWallet/executor.d.ts +23 -0
  15. package/build/SandboxedWallet/executor.js +338 -0
  16. package/build/SandboxedWallet/executor.js.map +1 -0
  17. package/build/SandboxedWallet/iframe.d.ts +18 -0
  18. package/build/SandboxedWallet/iframe.js +78 -0
  19. package/build/SandboxedWallet/iframe.js.map +1 -0
  20. package/build/SandboxedWallet/index.d.ts +24 -0
  21. package/build/SandboxedWallet/index.js +54 -0
  22. package/build/SandboxedWallet/index.js.map +1 -0
  23. package/build/actions/index.d.ts +3 -0
  24. package/build/actions/index.js +105 -0
  25. package/build/actions/index.js.map +1 -0
  26. package/build/actions/types.d.ts +76 -0
  27. package/build/actions/types.js +3 -0
  28. package/build/actions/types.js.map +1 -0
  29. package/build/connection/health.d.ts +213 -0
  30. package/build/connection/health.js +391 -0
  31. package/build/connection/health.js.map +1 -0
  32. package/build/connection/index.d.ts +4 -0
  33. package/build/connection/index.js +48 -0
  34. package/build/connection/index.js.map +1 -0
  35. package/build/connection/reconnect.d.ts +261 -0
  36. package/build/connection/reconnect.js +454 -0
  37. package/build/connection/reconnect.js.map +1 -0
  38. package/build/connection/retry.d.ts +187 -0
  39. package/build/connection/retry.js +427 -0
  40. package/build/connection/retry.js.map +1 -0
  41. package/build/connection/state.d.ts +222 -0
  42. package/build/connection/state.js +431 -0
  43. package/build/connection/state.js.map +1 -0
  44. package/build/errors.d.ts +177 -0
  45. package/build/errors.js +546 -0
  46. package/build/errors.js.map +1 -0
  47. package/build/hardware/errors.d.ts +36 -0
  48. package/build/hardware/errors.js +127 -0
  49. package/build/hardware/errors.js.map +1 -0
  50. package/build/hardware/index.d.ts +7 -0
  51. package/build/hardware/index.js +39 -0
  52. package/build/hardware/index.js.map +1 -0
  53. package/build/hardware/near-app.d.ts +95 -0
  54. package/build/hardware/near-app.js +291 -0
  55. package/build/hardware/near-app.js.map +1 -0
  56. package/build/hardware/transport.d.ts +94 -0
  57. package/build/hardware/transport.js +267 -0
  58. package/build/hardware/transport.js.map +1 -0
  59. package/build/hardware/types.d.ts +98 -0
  60. package/build/hardware/types.js +72 -0
  61. package/build/hardware/types.js.map +1 -0
  62. package/build/helpers/analytics.d.ts +191 -0
  63. package/build/helpers/analytics.js +304 -0
  64. package/build/helpers/analytics.js.map +1 -0
  65. package/build/helpers/base58.d.ts +6 -0
  66. package/build/helpers/base58.js +47 -0
  67. package/build/helpers/base58.js.map +1 -0
  68. package/build/helpers/events.d.ts +42 -0
  69. package/build/helpers/events.js +68 -0
  70. package/build/helpers/events.js.map +1 -0
  71. package/build/helpers/html.d.ts +8 -0
  72. package/build/helpers/html.js +30 -0
  73. package/build/helpers/html.js.map +1 -0
  74. package/build/helpers/indexdb.d.ts +14 -0
  75. package/build/helpers/indexdb.js +166 -0
  76. package/build/helpers/indexdb.js.map +1 -0
  77. package/build/helpers/manifest.d.ts +147 -0
  78. package/build/helpers/manifest.js +329 -0
  79. package/build/helpers/manifest.js.map +1 -0
  80. package/build/helpers/queue.d.ts +11 -0
  81. package/build/helpers/queue.js +48 -0
  82. package/build/helpers/queue.js.map +1 -0
  83. package/build/helpers/session.d.ts +119 -0
  84. package/build/helpers/session.js +289 -0
  85. package/build/helpers/session.js.map +1 -0
  86. package/build/helpers/simulation.d.ts +128 -0
  87. package/build/helpers/simulation.js +441 -0
  88. package/build/helpers/simulation.js.map +1 -0
  89. package/build/helpers/storage.d.ts +58 -0
  90. package/build/helpers/storage.js +190 -0
  91. package/build/helpers/storage.js.map +1 -0
  92. package/build/helpers/trust.d.ts +157 -0
  93. package/build/helpers/trust.js +340 -0
  94. package/build/helpers/trust.js.map +1 -0
  95. package/build/helpers/url.d.ts +1 -0
  96. package/build/helpers/url.js +13 -0
  97. package/build/helpers/url.js.map +1 -0
  98. package/build/helpers/uuid.d.ts +1 -0
  99. package/build/helpers/uuid.js +14 -0
  100. package/build/helpers/uuid.js.map +1 -0
  101. package/build/index.d.ts +21 -0
  102. package/build/index.js +167 -0
  103. package/build/index.js.map +1 -0
  104. package/build/popups/IframeWalletPopup.d.ts +16 -0
  105. package/build/popups/IframeWalletPopup.js +38 -0
  106. package/build/popups/IframeWalletPopup.js.map +1 -0
  107. package/build/popups/NearWalletsPopup.d.ts +25 -0
  108. package/build/popups/NearWalletsPopup.js +153 -0
  109. package/build/popups/NearWalletsPopup.js.map +1 -0
  110. package/build/popups/Popup.d.ts +22 -0
  111. package/build/popups/Popup.js +94 -0
  112. package/build/popups/Popup.js.map +1 -0
  113. package/build/popups/styles.d.ts +1 -0
  114. package/build/popups/styles.js +257 -0
  115. package/build/popups/styles.js.map +1 -0
  116. package/build/security/audit-log.d.ts +123 -0
  117. package/build/security/audit-log.js +268 -0
  118. package/build/security/audit-log.js.map +1 -0
  119. package/build/security/csp.d.ts +68 -0
  120. package/build/security/csp.js +328 -0
  121. package/build/security/csp.js.map +1 -0
  122. package/build/security/index.d.ts +10 -0
  123. package/build/security/index.js +42 -0
  124. package/build/security/index.js.map +1 -0
  125. package/build/security/origin-guard.d.ts +90 -0
  126. package/build/security/origin-guard.js +244 -0
  127. package/build/security/origin-guard.js.map +1 -0
  128. package/build/security/rate-limiter.d.ts +84 -0
  129. package/build/security/rate-limiter.js +212 -0
  130. package/build/security/rate-limiter.js.map +1 -0
  131. package/build/security/secure-storage.d.ts +77 -0
  132. package/build/security/secure-storage.js +242 -0
  133. package/build/security/secure-storage.js.map +1 -0
  134. package/build/security/transaction-guard.d.ts +71 -0
  135. package/build/security/transaction-guard.js +239 -0
  136. package/build/security/transaction-guard.js.map +1 -0
  137. package/build/types.d.ts +508 -0
  138. package/build/types.js +3 -0
  139. package/build/types.js.map +1 -0
  140. package/build/ui/AccountSwitcherModal.d.ts +53 -0
  141. package/build/ui/AccountSwitcherModal.js +239 -0
  142. package/build/ui/AccountSwitcherModal.js.map +1 -0
  143. package/build/ui/Modal.d.ts +84 -0
  144. package/build/ui/Modal.js +278 -0
  145. package/build/ui/Modal.js.map +1 -0
  146. package/build/ui/TransactionModal.d.ts +84 -0
  147. package/build/ui/TransactionModal.js +406 -0
  148. package/build/ui/TransactionModal.js.map +1 -0
  149. package/build/ui/WalletSelectorModal.d.ts +97 -0
  150. package/build/ui/WalletSelectorModal.js +481 -0
  151. package/build/ui/WalletSelectorModal.js.map +1 -0
  152. package/build/ui/icons.d.ts +19 -0
  153. package/build/ui/icons.js +65 -0
  154. package/build/ui/icons.js.map +1 -0
  155. package/build/ui/index.d.ts +10 -0
  156. package/build/ui/index.js +31 -0
  157. package/build/ui/index.js.map +1 -0
  158. package/build/ui/styles.d.ts +5 -0
  159. package/build/ui/styles.js +973 -0
  160. package/build/ui/styles.js.map +1 -0
  161. package/build/ui/theme.d.ts +133 -0
  162. package/build/ui/theme.js +204 -0
  163. package/build/ui/theme.js.map +1 -0
  164. package/build/wallets/external/index.d.ts +4 -0
  165. package/build/wallets/external/index.js +9 -0
  166. package/build/wallets/external/index.js.map +1 -0
  167. package/build/wallets/external/manager.d.ts +152 -0
  168. package/build/wallets/external/manager.js +586 -0
  169. package/build/wallets/external/manager.js.map +1 -0
  170. package/build/wallets/privileged/index.d.ts +5 -0
  171. package/build/wallets/privileged/index.js +12 -0
  172. package/build/wallets/privileged/index.js.map +1 -0
  173. package/build/wallets/privileged/ledger.d.ts +132 -0
  174. package/build/wallets/privileged/ledger.js +563 -0
  175. package/build/wallets/privileged/ledger.js.map +1 -0
  176. package/build/wallets/privileged/manager.d.ts +54 -0
  177. package/build/wallets/privileged/manager.js +174 -0
  178. package/build/wallets/privileged/manager.js.map +1 -0
  179. package/package.json +33 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/actions/index.ts"],"names":[],"mappings":";;;AAEA,8CAAiD;AAEjD,MAAM,eAAe,GAAG,CAAC,IAAgB,EAAE,EAAE;IAC3C,IAAI,CAAC;QACH,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC;IACpD,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC,CAAC;AAEK,MAAM,6BAA6B,GAAG,CAAC,OAAqC,EAAqB,EAAE;IACxG,OAAO,OAAO,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,EAAE;QAC5B,IAAI,MAAM,IAAI,MAAM;YAAE,OAAO,MAAyB,CAAC;QAEvD,IAAI,MAAM,CAAC,YAAY,EAAE,CAAC;YACxB,OAAO;gBACL,IAAI,EAAE,cAAc;gBACpB,MAAM,EAAE;oBACN,UAAU,EAAE,MAAM,CAAC,YAAY,CAAC,UAAU;oBAC1C,IAAI,EAAE,eAAe,CAAC,MAAM,CAAC,YAAY,CAAC,IAAI,CAAC;oBAC/C,GAAG,EAAE,MAAM,CAAC,YAAY,CAAC,GAAG,CAAC,QAAQ,EAAE;oBACvC,OAAO,EAAE,MAAM,CAAC,YAAY,CAAC,OAAO,CAAC,QAAQ,EAAE;iBAChD;aACF,CAAC;QACJ,CAAC;QAED,IAAI,MAAM,CAAC,oBAAoB,EAAE,CAAC;YAChC,OAAO;gBACL,IAAI,EAAE,sBAAsB;gBAC5B,MAAM,EAAE;oBACN,IAAI,EAAE,MAAM,CAAC,oBAAoB,CAAC,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,6BAA6B,iCAoGxC"}
@@ -0,0 +1,76 @@
1
+ export interface CreateAccountAction {
2
+ type: "CreateAccount";
3
+ }
4
+ export interface DeployContractAction {
5
+ type: "DeployContract";
6
+ params: {
7
+ code: Uint8Array;
8
+ };
9
+ }
10
+ export interface FunctionCallAction {
11
+ type: "FunctionCall";
12
+ params: {
13
+ methodName: string;
14
+ args: object;
15
+ gas: string;
16
+ deposit: string;
17
+ };
18
+ }
19
+ export interface TransferAction {
20
+ type: "Transfer";
21
+ params: {
22
+ deposit: string;
23
+ };
24
+ }
25
+ export interface StakeAction {
26
+ type: "Stake";
27
+ params: {
28
+ stake: string;
29
+ publicKey: string;
30
+ };
31
+ }
32
+ export interface AddKeyAction {
33
+ type: "AddKey";
34
+ params: {
35
+ publicKey: string;
36
+ accessKey: {
37
+ nonce?: number;
38
+ permission: "FullAccess" | {
39
+ receiverId: string;
40
+ allowance?: string;
41
+ methodNames?: Array<string>;
42
+ };
43
+ };
44
+ };
45
+ }
46
+ export interface DeleteKeyAction {
47
+ type: "DeleteKey";
48
+ params: {
49
+ publicKey: string;
50
+ };
51
+ }
52
+ export interface DeleteAccountAction {
53
+ type: "DeleteAccount";
54
+ params: {
55
+ beneficiaryId: string;
56
+ };
57
+ }
58
+ export interface UseGlobalContractAction {
59
+ type: "UseGlobalContract";
60
+ params: {
61
+ contractIdentifier: {
62
+ accountId: string;
63
+ } | {
64
+ /** Base58 encoded code hash */
65
+ codeHash: string;
66
+ };
67
+ };
68
+ }
69
+ export interface DeployGlobalContractAction {
70
+ type: "DeployGlobalContract";
71
+ params: {
72
+ code: Uint8Array;
73
+ deployMode: "CodeHash" | "AccountId";
74
+ };
75
+ }
76
+ export type ConnectorAction = CreateAccountAction | DeployContractAction | FunctionCallAction | TransferAction | StakeAction | AddKeyAction | DeleteKeyAction | DeleteAccountAction | UseGlobalContractAction | DeployGlobalContractAction;
@@ -0,0 +1,3 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/actions/types.ts"],"names":[],"mappings":""}
@@ -0,0 +1,213 @@
1
+ import { Account } from "../types";
2
+ /**
3
+ * Connection health status
4
+ */
5
+ export type HealthStatus = "healthy" | "degraded" | "stale" | "lost";
6
+ /**
7
+ * Connection health information
8
+ */
9
+ export interface ConnectionHealth {
10
+ /** Current health status */
11
+ status: HealthStatus;
12
+ /** Timestamp of last successful heartbeat */
13
+ lastHeartbeat: number;
14
+ /** Timestamp of last user interaction */
15
+ lastInteraction: number;
16
+ /** Average response latency in ms */
17
+ latency: number;
18
+ /** Number of consecutive heartbeat failures */
19
+ consecutiveFailures: number;
20
+ /** Whether currently checking health */
21
+ checking: boolean;
22
+ }
23
+ /**
24
+ * Health check result
25
+ */
26
+ export interface HealthCheckResult {
27
+ success: boolean;
28
+ latency: number;
29
+ accounts?: Account[];
30
+ error?: Error;
31
+ timestamp: number;
32
+ }
33
+ /**
34
+ * Health monitor configuration
35
+ */
36
+ export interface HealthConfig {
37
+ /** Interval between heartbeats in ms (default: 30000 = 30s) */
38
+ heartbeatInterval: number;
39
+ /** Timeout for heartbeat response in ms (default: 10000 = 10s) */
40
+ heartbeatTimeout: number;
41
+ /** Time since last interaction to consider connection stale (default: 300000 = 5min) */
42
+ staleThreshold: number;
43
+ /** Number of consecutive failures before marking as lost (default: 3) */
44
+ maxConsecutiveFailures: number;
45
+ /** Whether to auto-reconnect on failure (default: true) */
46
+ autoReconnect: boolean;
47
+ /** Whether to sync account list on heartbeat (default: false) */
48
+ syncAccounts: boolean;
49
+ /** Interval for account sync in ms (default: 60000 = 1min) */
50
+ syncInterval: number;
51
+ /** Latency threshold for degraded status in ms (default: 5000) */
52
+ degradedLatencyThreshold: number;
53
+ /** Whether to disable heartbeat entirely (default: false) */
54
+ disabled: boolean;
55
+ }
56
+ /**
57
+ * Default health configuration
58
+ */
59
+ export declare const DEFAULT_HEALTH_CONFIG: HealthConfig;
60
+ /**
61
+ * Health event types
62
+ */
63
+ export interface HealthEventMap {
64
+ "health:check": {
65
+ result: HealthCheckResult;
66
+ };
67
+ "health:status-changed": {
68
+ from: HealthStatus;
69
+ to: HealthStatus;
70
+ health: ConnectionHealth;
71
+ };
72
+ "health:degraded": {
73
+ latency: number;
74
+ threshold: number;
75
+ };
76
+ "health:stale": {
77
+ lastInteraction: number;
78
+ threshold: number;
79
+ };
80
+ "health:lost": {
81
+ failures: number;
82
+ lastError?: Error;
83
+ };
84
+ "health:restored": {
85
+ previousStatus: HealthStatus;
86
+ };
87
+ "accounts:synced": {
88
+ accounts: Account[];
89
+ };
90
+ "accounts:changed": {
91
+ previous: Account[];
92
+ current: Account[];
93
+ };
94
+ }
95
+ /**
96
+ * Health check function type
97
+ */
98
+ export type HealthCheckFn = () => Promise<HealthCheckResult>;
99
+ /**
100
+ * Connection Health Monitor
101
+ *
102
+ * Monitors the health of wallet connections through periodic heartbeats
103
+ * and tracks connection quality metrics
104
+ */
105
+ export declare class HealthMonitor {
106
+ private config;
107
+ private health;
108
+ private heartbeatTimer;
109
+ private syncTimer;
110
+ private running;
111
+ private healthCheck;
112
+ private listeners;
113
+ private latencyHistory;
114
+ private maxLatencyHistory;
115
+ private lastAccounts;
116
+ constructor(healthCheck: HealthCheckFn, config?: Partial<HealthConfig>);
117
+ /**
118
+ * Create initial health state
119
+ */
120
+ private createInitialHealth;
121
+ /**
122
+ * Start health monitoring
123
+ */
124
+ start(): void;
125
+ /**
126
+ * Stop health monitoring
127
+ */
128
+ stop(): void;
129
+ /**
130
+ * Perform a health check
131
+ */
132
+ performCheck(): Promise<HealthCheckResult>;
133
+ /**
134
+ * Record user interaction
135
+ */
136
+ recordInteraction(): void;
137
+ /**
138
+ * Get current health state
139
+ */
140
+ getHealth(): ConnectionHealth;
141
+ /**
142
+ * Get current status
143
+ */
144
+ getStatus(): HealthStatus;
145
+ /**
146
+ * Check if connection is healthy
147
+ */
148
+ isHealthy(): boolean;
149
+ /**
150
+ * Update latency tracking
151
+ */
152
+ private updateLatency;
153
+ /**
154
+ * Update health status based on current metrics
155
+ */
156
+ private updateStatus;
157
+ /**
158
+ * Check for account changes
159
+ */
160
+ private checkAccountChanges;
161
+ /**
162
+ * Sync account list
163
+ */
164
+ private syncAccountList;
165
+ /**
166
+ * Event listener
167
+ */
168
+ on<K extends keyof HealthEventMap>(event: K, callback: (payload: HealthEventMap[K]) => void): () => void;
169
+ /**
170
+ * Emit event
171
+ */
172
+ private emit;
173
+ /**
174
+ * Promise with timeout wrapper
175
+ */
176
+ private withTimeout;
177
+ /**
178
+ * Force a status update
179
+ */
180
+ forceStatusUpdate(): void;
181
+ /**
182
+ * Reset health state
183
+ */
184
+ reset(): void;
185
+ /**
186
+ * Update configuration
187
+ */
188
+ updateConfig(config: Partial<HealthConfig>): void;
189
+ /**
190
+ * Get average latency
191
+ */
192
+ getAverageLatency(): number;
193
+ /**
194
+ * Get latency percentile
195
+ */
196
+ getLatencyPercentile(percentile: number): number;
197
+ /**
198
+ * Get uptime percentage since last reset
199
+ */
200
+ getUptimePercentage(): number;
201
+ /**
202
+ * Cleanup
203
+ */
204
+ destroy(): void;
205
+ }
206
+ /**
207
+ * Create a basic health check function for NEAR wallets
208
+ */
209
+ export declare function createWalletHealthCheck(getAccounts: () => Promise<Account[]>): HealthCheckFn;
210
+ /**
211
+ * Create a health monitor with standard configuration
212
+ */
213
+ export declare function createHealthMonitor(healthCheck: HealthCheckFn, config?: Partial<HealthConfig>): HealthMonitor;
@@ -0,0 +1,391 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.HealthMonitor = exports.DEFAULT_HEALTH_CONFIG = void 0;
4
+ exports.createWalletHealthCheck = createWalletHealthCheck;
5
+ exports.createHealthMonitor = createHealthMonitor;
6
+ /**
7
+ * Default health configuration
8
+ */
9
+ exports.DEFAULT_HEALTH_CONFIG = {
10
+ heartbeatInterval: 30000,
11
+ heartbeatTimeout: 10000,
12
+ staleThreshold: 300000, // 5 minutes
13
+ maxConsecutiveFailures: 3,
14
+ autoReconnect: true,
15
+ syncAccounts: false,
16
+ syncInterval: 60000,
17
+ degradedLatencyThreshold: 5000,
18
+ disabled: false,
19
+ };
20
+ /**
21
+ * Connection Health Monitor
22
+ *
23
+ * Monitors the health of wallet connections through periodic heartbeats
24
+ * and tracks connection quality metrics
25
+ */
26
+ class HealthMonitor {
27
+ config;
28
+ health;
29
+ heartbeatTimer = null;
30
+ syncTimer = null;
31
+ running = false;
32
+ healthCheck;
33
+ listeners = new Map();
34
+ latencyHistory = [];
35
+ maxLatencyHistory = 10;
36
+ lastAccounts = [];
37
+ constructor(healthCheck, config = {}) {
38
+ this.healthCheck = healthCheck;
39
+ this.config = { ...exports.DEFAULT_HEALTH_CONFIG, ...config };
40
+ this.health = this.createInitialHealth();
41
+ }
42
+ /**
43
+ * Create initial health state
44
+ */
45
+ createInitialHealth() {
46
+ const now = Date.now();
47
+ return {
48
+ status: "healthy",
49
+ lastHeartbeat: now,
50
+ lastInteraction: now,
51
+ latency: 0,
52
+ consecutiveFailures: 0,
53
+ checking: false,
54
+ };
55
+ }
56
+ /**
57
+ * Start health monitoring
58
+ */
59
+ start() {
60
+ if (this.running || this.config.disabled)
61
+ return;
62
+ this.running = true;
63
+ this.health = this.createInitialHealth();
64
+ // Start heartbeat
65
+ this.heartbeatTimer = setInterval(() => this.performCheck(), this.config.heartbeatInterval);
66
+ // Start account sync if enabled
67
+ if (this.config.syncAccounts) {
68
+ this.syncTimer = setInterval(() => this.syncAccountList(), this.config.syncInterval);
69
+ }
70
+ // Perform initial check
71
+ this.performCheck();
72
+ }
73
+ /**
74
+ * Stop health monitoring
75
+ */
76
+ stop() {
77
+ this.running = false;
78
+ if (this.heartbeatTimer) {
79
+ clearInterval(this.heartbeatTimer);
80
+ this.heartbeatTimer = null;
81
+ }
82
+ if (this.syncTimer) {
83
+ clearInterval(this.syncTimer);
84
+ this.syncTimer = null;
85
+ }
86
+ }
87
+ /**
88
+ * Perform a health check
89
+ */
90
+ async performCheck() {
91
+ if (!this.running) {
92
+ return {
93
+ success: false,
94
+ latency: 0,
95
+ error: new Error("Monitor not running"),
96
+ timestamp: Date.now(),
97
+ };
98
+ }
99
+ this.health.checking = true;
100
+ const startTime = Date.now();
101
+ try {
102
+ // Execute health check with timeout
103
+ const result = await this.withTimeout(this.healthCheck(), this.config.heartbeatTimeout);
104
+ // Update health state
105
+ this.health.lastHeartbeat = Date.now();
106
+ this.health.consecutiveFailures = 0;
107
+ this.updateLatency(result.latency);
108
+ // Check for account changes
109
+ if (result.accounts && this.config.syncAccounts) {
110
+ this.checkAccountChanges(result.accounts);
111
+ }
112
+ // Emit check event
113
+ this.emit("health:check", { result });
114
+ // Update status
115
+ this.updateStatus();
116
+ this.health.checking = false;
117
+ return result;
118
+ }
119
+ catch (error) {
120
+ const result = {
121
+ success: false,
122
+ latency: Date.now() - startTime,
123
+ error: error instanceof Error ? error : new Error(String(error)),
124
+ timestamp: Date.now(),
125
+ };
126
+ // Update failure count
127
+ this.health.consecutiveFailures++;
128
+ // Emit check event
129
+ this.emit("health:check", { result });
130
+ // Update status
131
+ this.updateStatus();
132
+ this.health.checking = false;
133
+ return result;
134
+ }
135
+ }
136
+ /**
137
+ * Record user interaction
138
+ */
139
+ recordInteraction() {
140
+ this.health.lastInteraction = Date.now();
141
+ this.updateStatus();
142
+ }
143
+ /**
144
+ * Get current health state
145
+ */
146
+ getHealth() {
147
+ return { ...this.health };
148
+ }
149
+ /**
150
+ * Get current status
151
+ */
152
+ getStatus() {
153
+ return this.health.status;
154
+ }
155
+ /**
156
+ * Check if connection is healthy
157
+ */
158
+ isHealthy() {
159
+ return this.health.status === "healthy";
160
+ }
161
+ /**
162
+ * Update latency tracking
163
+ */
164
+ updateLatency(latency) {
165
+ this.latencyHistory.push(latency);
166
+ if (this.latencyHistory.length > this.maxLatencyHistory) {
167
+ this.latencyHistory.shift();
168
+ }
169
+ // Calculate average latency
170
+ const sum = this.latencyHistory.reduce((a, b) => a + b, 0);
171
+ this.health.latency = Math.round(sum / this.latencyHistory.length);
172
+ }
173
+ /**
174
+ * Update health status based on current metrics
175
+ */
176
+ updateStatus() {
177
+ const previousStatus = this.health.status;
178
+ let newStatus;
179
+ if (this.health.consecutiveFailures >= this.config.maxConsecutiveFailures) {
180
+ newStatus = "lost";
181
+ this.emit("health:lost", {
182
+ failures: this.health.consecutiveFailures,
183
+ });
184
+ }
185
+ else if (Date.now() - this.health.lastInteraction > this.config.staleThreshold) {
186
+ newStatus = "stale";
187
+ this.emit("health:stale", {
188
+ lastInteraction: this.health.lastInteraction,
189
+ threshold: this.config.staleThreshold,
190
+ });
191
+ }
192
+ else if (this.health.latency > this.config.degradedLatencyThreshold) {
193
+ newStatus = "degraded";
194
+ this.emit("health:degraded", {
195
+ latency: this.health.latency,
196
+ threshold: this.config.degradedLatencyThreshold,
197
+ });
198
+ }
199
+ else {
200
+ newStatus = "healthy";
201
+ }
202
+ if (newStatus !== previousStatus) {
203
+ this.health.status = newStatus;
204
+ // Emit status change
205
+ this.emit("health:status-changed", {
206
+ from: previousStatus,
207
+ to: newStatus,
208
+ health: this.getHealth(),
209
+ });
210
+ // Emit restored event if recovering
211
+ if (newStatus === "healthy" &&
212
+ ["degraded", "stale", "lost"].includes(previousStatus)) {
213
+ this.emit("health:restored", { previousStatus });
214
+ }
215
+ }
216
+ }
217
+ /**
218
+ * Check for account changes
219
+ */
220
+ checkAccountChanges(accounts) {
221
+ // Compare account IDs
222
+ const prevIds = new Set(this.lastAccounts.map((a) => a.accountId));
223
+ const currIds = new Set(accounts.map((a) => a.accountId));
224
+ const hasChanges = prevIds.size !== currIds.size ||
225
+ [...prevIds].some((id) => !currIds.has(id));
226
+ if (hasChanges) {
227
+ this.emit("accounts:changed", {
228
+ previous: this.lastAccounts,
229
+ current: accounts,
230
+ });
231
+ }
232
+ this.lastAccounts = accounts;
233
+ this.emit("accounts:synced", { accounts });
234
+ }
235
+ /**
236
+ * Sync account list
237
+ */
238
+ async syncAccountList() {
239
+ try {
240
+ const result = await this.performCheck();
241
+ if (result.accounts) {
242
+ this.checkAccountChanges(result.accounts);
243
+ }
244
+ }
245
+ catch (e) {
246
+ // Silently fail sync
247
+ }
248
+ }
249
+ /**
250
+ * Event listener
251
+ */
252
+ on(event, callback) {
253
+ if (!this.listeners.has(event)) {
254
+ this.listeners.set(event, new Set());
255
+ }
256
+ this.listeners.get(event).add(callback);
257
+ return () => {
258
+ this.listeners.get(event)?.delete(callback);
259
+ };
260
+ }
261
+ /**
262
+ * Emit event
263
+ */
264
+ emit(event, payload) {
265
+ const listeners = this.listeners.get(event);
266
+ if (listeners) {
267
+ for (const listener of listeners) {
268
+ try {
269
+ listener(payload);
270
+ }
271
+ catch (e) {
272
+ console.error(`Error in health event listener for ${event}:`, e);
273
+ }
274
+ }
275
+ }
276
+ }
277
+ /**
278
+ * Promise with timeout wrapper
279
+ */
280
+ async withTimeout(promise, timeoutMs) {
281
+ return new Promise((resolve, reject) => {
282
+ const timeoutId = setTimeout(() => {
283
+ reject(new Error(`Health check timed out after ${timeoutMs}ms`));
284
+ }, timeoutMs);
285
+ promise
286
+ .then((result) => {
287
+ clearTimeout(timeoutId);
288
+ resolve(result);
289
+ })
290
+ .catch((error) => {
291
+ clearTimeout(timeoutId);
292
+ reject(error);
293
+ });
294
+ });
295
+ }
296
+ /**
297
+ * Force a status update
298
+ */
299
+ forceStatusUpdate() {
300
+ this.updateStatus();
301
+ }
302
+ /**
303
+ * Reset health state
304
+ */
305
+ reset() {
306
+ this.health = this.createInitialHealth();
307
+ this.latencyHistory = [];
308
+ this.lastAccounts = [];
309
+ }
310
+ /**
311
+ * Update configuration
312
+ */
313
+ updateConfig(config) {
314
+ this.config = { ...this.config, ...config };
315
+ // Restart if running and interval changed
316
+ if (this.running) {
317
+ this.stop();
318
+ this.start();
319
+ }
320
+ }
321
+ /**
322
+ * Get average latency
323
+ */
324
+ getAverageLatency() {
325
+ if (this.latencyHistory.length === 0)
326
+ return 0;
327
+ const sum = this.latencyHistory.reduce((a, b) => a + b, 0);
328
+ return Math.round(sum / this.latencyHistory.length);
329
+ }
330
+ /**
331
+ * Get latency percentile
332
+ */
333
+ getLatencyPercentile(percentile) {
334
+ if (this.latencyHistory.length === 0)
335
+ return 0;
336
+ const sorted = [...this.latencyHistory].sort((a, b) => a - b);
337
+ const index = Math.ceil((percentile / 100) * sorted.length) - 1;
338
+ return sorted[Math.max(0, index)];
339
+ }
340
+ /**
341
+ * Get uptime percentage since last reset
342
+ */
343
+ getUptimePercentage() {
344
+ // This is a simplified calculation
345
+ // In production, you'd track actual check results
346
+ const maxFailures = this.config.maxConsecutiveFailures;
347
+ const failureRate = this.health.consecutiveFailures / maxFailures;
348
+ return Math.max(0, (1 - failureRate) * 100);
349
+ }
350
+ /**
351
+ * Cleanup
352
+ */
353
+ destroy() {
354
+ this.stop();
355
+ this.listeners.clear();
356
+ }
357
+ }
358
+ exports.HealthMonitor = HealthMonitor;
359
+ /**
360
+ * Create a basic health check function for NEAR wallets
361
+ */
362
+ function createWalletHealthCheck(getAccounts) {
363
+ return async () => {
364
+ const startTime = Date.now();
365
+ try {
366
+ const accounts = await getAccounts();
367
+ const latency = Date.now() - startTime;
368
+ return {
369
+ success: true,
370
+ latency,
371
+ accounts,
372
+ timestamp: Date.now(),
373
+ };
374
+ }
375
+ catch (error) {
376
+ return {
377
+ success: false,
378
+ latency: Date.now() - startTime,
379
+ error: error instanceof Error ? error : new Error(String(error)),
380
+ timestamp: Date.now(),
381
+ };
382
+ }
383
+ };
384
+ }
385
+ /**
386
+ * Create a health monitor with standard configuration
387
+ */
388
+ function createHealthMonitor(healthCheck, config) {
389
+ return new HealthMonitor(healthCheck, config);
390
+ }
391
+ //# sourceMappingURL=health.js.map