@trezor/connect 9.7.0-beta.1 → 9.7.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 (408) hide show
  1. package/CHANGELOG.md +49 -16
  2. package/README.md +1 -1
  3. package/lib/api/applyFlags.js +31 -26
  4. package/lib/api/applySettings.js +43 -40
  5. package/lib/api/authenticateDevice.js +82 -54
  6. package/lib/api/authorizeCoinjoin.js +35 -28
  7. package/lib/api/backupDevice.js +32 -27
  8. package/lib/api/bitcoin/TransactionComposer.js +131 -123
  9. package/lib/api/bitcoin/createPendingTx.js +55 -52
  10. package/lib/api/bitcoin/enhanceSignTx.js +57 -55
  11. package/lib/api/bitcoin/index.js +4 -1
  12. package/lib/api/bitcoin/inputs.js +71 -46
  13. package/lib/api/bitcoin/outputs.js +108 -85
  14. package/lib/api/bitcoin/refTx.d.ts +1 -1
  15. package/lib/api/bitcoin/refTx.js +233 -201
  16. package/lib/api/bitcoin/signtx.js +208 -152
  17. package/lib/api/bitcoin/signtxLegacy.js +169 -119
  18. package/lib/api/bitcoin/signtxVerify.js +80 -67
  19. package/lib/api/bitcoin/transactionBytes.js +61 -59
  20. package/lib/api/bleUnpair.js +28 -25
  21. package/lib/api/blockchainDisconnect.js +31 -24
  22. package/lib/api/blockchainEstimateFee.js +94 -61
  23. package/lib/api/blockchainEvmRpcCall.js +51 -34
  24. package/lib/api/blockchainGetAccountBalanceHistory.d.ts +1 -1
  25. package/lib/api/blockchainGetAccountBalanceHistory.js +50 -32
  26. package/lib/api/blockchainGetCurrentFiatRates.d.ts +1 -1
  27. package/lib/api/blockchainGetCurrentFiatRates.js +43 -29
  28. package/lib/api/blockchainGetFiatRatesForTimestamps.d.ts +1 -1
  29. package/lib/api/blockchainGetFiatRatesForTimestamps.js +49 -32
  30. package/lib/api/blockchainGetInfo.js +31 -22
  31. package/lib/api/blockchainGetTransactions.d.ts +1 -1
  32. package/lib/api/blockchainGetTransactions.js +36 -24
  33. package/lib/api/blockchainSetCustomBackend.js +34 -25
  34. package/lib/api/blockchainSubscribe.js +57 -36
  35. package/lib/api/blockchainSubscribeFiatRates.js +36 -24
  36. package/lib/api/blockchainUnsubscribe.js +57 -37
  37. package/lib/api/blockchainUnsubscribeFiatRates.js +31 -22
  38. package/lib/api/cancelCoinjoinAuthorization.js +26 -20
  39. package/lib/api/cardano/api/cardanoComposeTransaction.js +75 -50
  40. package/lib/api/cardano/api/cardanoGetAddress.js +105 -102
  41. package/lib/api/cardano/api/cardanoGetNativeScriptHash.js +59 -56
  42. package/lib/api/cardano/api/cardanoGetPublicKey.js +58 -58
  43. package/lib/api/cardano/api/cardanoSignMessage.js +81 -78
  44. package/lib/api/cardano/api/cardanoSignTransaction.js +269 -240
  45. package/lib/api/cardano/api/index.js +40 -7
  46. package/lib/api/cardano/cardanoAddressParameters.js +71 -65
  47. package/lib/api/cardano/cardanoAuxiliaryData.js +68 -63
  48. package/lib/api/cardano/cardanoCertificate.js +124 -119
  49. package/lib/api/cardano/cardanoInputs.js +33 -33
  50. package/lib/api/cardano/cardanoOutputs.d.ts +1 -1
  51. package/lib/api/cardano/cardanoOutputs.js +63 -61
  52. package/lib/api/cardano/cardanoTokenBundle.d.ts +2 -2
  53. package/lib/api/cardano/cardanoTokenBundle.js +18 -13
  54. package/lib/api/cardano/cardanoUtils.js +94 -89
  55. package/lib/api/cardano/cardanoWitnesses.js +46 -42
  56. package/lib/api/changeLanguage.js +40 -29
  57. package/lib/api/changePin.js +21 -16
  58. package/lib/api/changeWipeCode.js +24 -16
  59. package/lib/api/cipherKeyValue.js +42 -41
  60. package/lib/api/common/Discovery.js +114 -112
  61. package/lib/api/common/paramsValidator.js +110 -116
  62. package/lib/api/composeTransaction.d.ts +1 -1
  63. package/lib/api/composeTransaction.js +307 -256
  64. package/lib/api/discoverAccounts.js +291 -191
  65. package/lib/api/eos/api/eosGetPublicKey.js +56 -52
  66. package/lib/api/eos/api/eosSignTransaction.js +35 -26
  67. package/lib/api/eos/api/index.js +16 -3
  68. package/lib/api/eos/eosSignTx.js +308 -312
  69. package/lib/api/ethereum/api/ethereumGetAddress.js +106 -107
  70. package/lib/api/ethereum/api/ethereumGetPublicKey.js +72 -62
  71. package/lib/api/ethereum/api/ethereumSignMessage.js +55 -48
  72. package/lib/api/ethereum/api/ethereumSignTransaction.d.ts +33 -0
  73. package/lib/api/ethereum/api/ethereumSignTransaction.js +137 -132
  74. package/lib/api/ethereum/api/ethereumSignTypedData.d.ts +4 -4
  75. package/lib/api/ethereum/api/ethereumSignTypedData.js +183 -181
  76. package/lib/api/ethereum/api/ethereumVerifyMessage.js +27 -24
  77. package/lib/api/ethereum/api/index.js +40 -7
  78. package/lib/api/ethereum/ethereumDefinitions.js +94 -87
  79. package/lib/api/ethereum/ethereumSignTx.js +116 -111
  80. package/lib/api/ethereum/ethereumSignTypedData.js +98 -95
  81. package/lib/api/evoluGetDelegatedIdentityKey.js +30 -26
  82. package/lib/api/evoluGetNode.js +24 -19
  83. package/lib/api/evoluSignRegistrationRequest.js +26 -21
  84. package/lib/api/firmware/calculateFirmwareHash.js +44 -32
  85. package/lib/api/firmware/getBinary.js +30 -22
  86. package/lib/api/firmware/index.js +46 -8
  87. package/lib/api/firmware/modifyFirmware.js +13 -12
  88. package/lib/api/firmware/parseFirmwareHeaders.js +29 -30
  89. package/lib/api/firmware/uploadFirmware.js +84 -67
  90. package/lib/api/firmware/verifyEntropy.js +88 -83
  91. package/lib/api/getAccountDescriptor.js +118 -120
  92. package/lib/api/getAccountInfo.d.ts +14 -14
  93. package/lib/api/getAccountInfo.js +316 -287
  94. package/lib/api/getAddress.js +128 -118
  95. package/lib/api/getCoinInfo.js +22 -17
  96. package/lib/api/getDeviceState.js +16 -10
  97. package/lib/api/getFeatures.d.ts +1 -1
  98. package/lib/api/getFeatures.js +15 -12
  99. package/lib/api/getFirmwareHash.js +23 -18
  100. package/lib/api/getNonce.js +12 -9
  101. package/lib/api/getOwnershipId.js +57 -51
  102. package/lib/api/getOwnershipProof.js +66 -60
  103. package/lib/api/getPublicKey.js +72 -66
  104. package/lib/api/getSettings.js +12 -9
  105. package/lib/api/index.js +346 -58
  106. package/lib/api/loadDevice.js +40 -35
  107. package/lib/api/monero/api/index.js +28 -5
  108. package/lib/api/monero/api/moneroGetAddress.js +108 -97
  109. package/lib/api/monero/api/moneroGetWatchKey.js +37 -32
  110. package/lib/api/monero/api/moneroKeyImageSync.js +111 -107
  111. package/lib/api/monero/api/moneroSignTransaction.js +173 -185
  112. package/lib/api/nem/api/index.js +16 -3
  113. package/lib/api/nem/api/nemGetAddress.js +107 -102
  114. package/lib/api/nem/api/nemSignTransaction.js +25 -20
  115. package/lib/api/nem/nemSignTx.js +128 -125
  116. package/lib/api/pushTransaction.js +31 -27
  117. package/lib/api/recoveryDevice.js +44 -39
  118. package/lib/api/requestLogin.d.ts +0 -1
  119. package/lib/api/requestLogin.js +47 -52
  120. package/lib/api/resetDevice.js +100 -90
  121. package/lib/api/ripple/api/index.js +16 -3
  122. package/lib/api/ripple/api/rippleGetAddress.js +92 -88
  123. package/lib/api/ripple/api/rippleSignTransaction.js +44 -34
  124. package/lib/api/setBrightness.js +21 -16
  125. package/lib/api/setBusy.js +27 -20
  126. package/lib/api/setProxy.js +22 -15
  127. package/lib/api/showDeviceTutorial.js +18 -15
  128. package/lib/api/signMessage.js +50 -46
  129. package/lib/api/signTransaction.js +325 -238
  130. package/lib/api/solana/additionalInfo.js +17 -14
  131. package/lib/api/solana/api/index.js +28 -5
  132. package/lib/api/solana/api/solanaComposeTransaction.js +46 -50
  133. package/lib/api/solana/api/solanaGetAddress.js +92 -90
  134. package/lib/api/solana/api/solanaGetPublicKey.js +56 -52
  135. package/lib/api/solana/api/solanaSignTransaction.js +175 -168
  136. package/lib/api/solana/solanaDefinitions.js +32 -25
  137. package/lib/api/solana/solanaUtils.d.ts +2 -2
  138. package/lib/api/solana/solanaUtils.js +231 -177
  139. package/lib/api/stellar/api/index.js +16 -3
  140. package/lib/api/stellar/api/stellarGetAddress.js +92 -88
  141. package/lib/api/stellar/api/stellarSignTransaction.js +51 -44
  142. package/lib/api/stellar/stellarSignTx.js +184 -179
  143. package/lib/api/tezos/api/index.js +22 -4
  144. package/lib/api/tezos/api/tezosGetAddress.js +92 -88
  145. package/lib/api/tezos/api/tezosGetPublicKey.js +55 -51
  146. package/lib/api/tezos/api/tezosSignTransaction.js +23 -18
  147. package/lib/api/tezos/tezosSignTx.js +183 -169
  148. package/lib/api/thpGetCredentials.js +23 -20
  149. package/lib/api/thpRemoveCredentials.js +28 -21
  150. package/lib/api/unlockPath.js +28 -21
  151. package/lib/api/verifyMessage.js +35 -33
  152. package/lib/api/wipeDevice.js +39 -34
  153. package/lib/backend/BackendManager.js +127 -107
  154. package/lib/backend/Blockchain.d.ts +1 -1
  155. package/lib/backend/Blockchain.js +220 -205
  156. package/lib/backend/BlockchainLink.js +17 -5
  157. package/lib/backend/fees/BitcoinFeeLevels.js +41 -34
  158. package/lib/backend/fees/EthereumFeeLevels.js +51 -51
  159. package/lib/backend/fees/MiscFeeLevels.js +25 -24
  160. package/lib/backend/fees/index.js +28 -21
  161. package/lib/constants/cardano.js +11 -8
  162. package/lib/constants/errors.js +72 -65
  163. package/lib/constants/firmware.js +5 -5
  164. package/lib/constants/index.js +16 -3
  165. package/lib/constants/nem.js +19 -16
  166. package/lib/constants/network.js +15 -22
  167. package/lib/constants/utxo.js +4 -1
  168. package/lib/core/AbstractMethod.d.ts +1 -1
  169. package/lib/core/AbstractMethod.js +248 -224
  170. package/lib/core/index.js +936 -775
  171. package/lib/core/method.js +19 -16
  172. package/lib/core/method.native.js +28 -23
  173. package/lib/core/onCallFirmwareUpdate.js +368 -299
  174. package/lib/data/DataManager.js +85 -77
  175. package/lib/data/analyticsInfo.js +35 -29
  176. package/lib/data/coinInfo.js +154 -156
  177. package/lib/data/config.d.ts +1 -1
  178. package/lib/data/config.js +362 -330
  179. package/lib/data/connectSettings.js +131 -144
  180. package/lib/data/defaultFeeLevels.js +154 -108
  181. package/lib/data/firmwareInfo.d.ts +1 -0
  182. package/lib/data/firmwareInfo.js +407 -377
  183. package/lib/data/thpSettings.js +36 -35
  184. package/lib/data/udevInfo.js +24 -24
  185. package/lib/data/version.d.ts +1 -1
  186. package/lib/data/version.js +6 -5
  187. package/lib/device/Device.d.ts +6 -7
  188. package/lib/device/Device.js +731 -749
  189. package/lib/device/DeviceCommands.js +226 -194
  190. package/lib/device/DeviceCurrentSession.d.ts +333 -333
  191. package/lib/device/DeviceCurrentSession.js +235 -236
  192. package/lib/device/DeviceList.d.ts +2 -0
  193. package/lib/device/DeviceList.js +219 -181
  194. package/lib/device/StateStorage.js +32 -29
  195. package/lib/device/TransportList.d.ts +1 -1
  196. package/lib/device/TransportList.js +37 -36
  197. package/lib/device/TransportManager.js +136 -140
  198. package/lib/device/calculateRevisionForDevice.js +20 -14
  199. package/lib/device/checkFirmwareRevision.js +66 -54
  200. package/lib/device/resolveDescriptorForTaproot.js +26 -16
  201. package/lib/device/thp/handshake.js +95 -82
  202. package/lib/device/thp/index.js +53 -38
  203. package/lib/device/thp/pairing.js +209 -199
  204. package/lib/device/thp/session.js +27 -19
  205. package/lib/device/thp/thpCall.js +53 -43
  206. package/lib/device/workflow/checkFirmwareHash.js +77 -67
  207. package/lib/device/workflow/checkFirmwareHashWithRetries.js +32 -29
  208. package/lib/device/workflow/handshake.js +50 -41
  209. package/lib/device/workflow/index.js +10 -2
  210. package/lib/device/workflow/trezorPushNotification.js +68 -64
  211. package/lib/device/workflow/validateState.js +155 -129
  212. package/lib/events/blockchain.js +13 -10
  213. package/lib/events/call.d.ts +6 -4
  214. package/lib/events/call.js +14 -13
  215. package/lib/events/core.js +24 -21
  216. package/lib/events/device.d.ts +2 -2
  217. package/lib/events/device.js +32 -19
  218. package/lib/events/iframe.js +13 -10
  219. package/lib/events/index.d.ts +0 -1
  220. package/lib/events/index.js +6 -3
  221. package/lib/events/popup.js +20 -17
  222. package/lib/events/transport.d.ts +2 -2
  223. package/lib/events/transport.js +16 -11
  224. package/lib/events/ui-promise.js +4 -1
  225. package/lib/events/ui-request.d.ts +0 -4
  226. package/lib/events/ui-request.js +48 -46
  227. package/lib/events/ui-response.d.ts +2 -2
  228. package/lib/events/ui-response.js +20 -17
  229. package/lib/events/webextension.js +9 -6
  230. package/lib/exports.js +10 -2
  231. package/lib/factory.d.ts +3 -2
  232. package/lib/factory.js +34 -143
  233. package/lib/impl/core-in-module.d.ts +1 -6
  234. package/lib/impl/core-in-module.js +187 -191
  235. package/lib/impl/dynamic.d.ts +0 -1
  236. package/lib/impl/dynamic.js +108 -97
  237. package/lib/index-browser.d.ts +1 -0
  238. package/lib/index-browser.js +18 -16
  239. package/lib/index.d.ts +2 -0
  240. package/lib/index.js +144 -148
  241. package/lib/types/account.js +4 -1
  242. package/lib/types/api/applyFlags.js +4 -1
  243. package/lib/types/api/applySettings.d.ts +2 -2
  244. package/lib/types/api/applySettings.js +7 -7
  245. package/lib/types/api/authenticateDevice.js +7 -4
  246. package/lib/types/api/authorizeCoinjoin.js +13 -10
  247. package/lib/types/api/backupDevice.js +4 -1
  248. package/lib/types/api/bitcoin/index.d.ts +5 -2
  249. package/lib/types/api/bitcoin/index.js +14 -11
  250. package/lib/types/api/bleUnpair.js +4 -1
  251. package/lib/types/api/blockchainDisconnect.js +4 -1
  252. package/lib/types/api/blockchainEstimateFee.js +4 -1
  253. package/lib/types/api/blockchainEvmRpcCall.js +4 -1
  254. package/lib/types/api/blockchainGetAccountBalanceHistory.js +4 -1
  255. package/lib/types/api/blockchainGetCurrentFiatRates.js +4 -1
  256. package/lib/types/api/blockchainGetFiatRatesForTimestamps.js +4 -1
  257. package/lib/types/api/blockchainGetInfo.js +4 -1
  258. package/lib/types/api/blockchainGetTransactions.js +4 -1
  259. package/lib/types/api/blockchainSetCustomBackend.js +4 -1
  260. package/lib/types/api/blockchainSubscribe.js +4 -1
  261. package/lib/types/api/blockchainSubscribeFiatRates.js +4 -1
  262. package/lib/types/api/blockchainUnsubscribe.js +4 -1
  263. package/lib/types/api/blockchainUnsubscribeFiatRates.js +4 -1
  264. package/lib/types/api/cancel.js +4 -1
  265. package/lib/types/api/cancelCoinjoinAuthorization.js +5 -2
  266. package/lib/types/api/cardano/index.d.ts +4 -4
  267. package/lib/types/api/cardano/index.js +173 -180
  268. package/lib/types/api/cardanoComposeTransaction.js +76 -65
  269. package/lib/types/api/cardanoGetAddress.js +4 -1
  270. package/lib/types/api/cardanoGetNativeScriptHash.js +4 -1
  271. package/lib/types/api/cardanoGetPublicKey.js +4 -1
  272. package/lib/types/api/cardanoSignMessage.js +4 -1
  273. package/lib/types/api/cardanoSignTransaction.js +4 -1
  274. package/lib/types/api/changeLanguage.d.ts +1 -1
  275. package/lib/types/api/changeLanguage.js +13 -13
  276. package/lib/types/api/changePin.js +4 -1
  277. package/lib/types/api/changeWipeCode.js +4 -1
  278. package/lib/types/api/cipherKeyValue.d.ts +2 -2
  279. package/lib/types/api/cipherKeyValue.js +11 -8
  280. package/lib/types/api/composeTransaction.js +4 -1
  281. package/lib/types/api/device.js +1 -2
  282. package/lib/types/api/disableWebUSB.js +4 -1
  283. package/lib/types/api/discoverAccounts.js +204 -55
  284. package/lib/types/api/dispose.js +4 -1
  285. package/lib/types/api/eos/index.d.ts +3 -3
  286. package/lib/types/api/eos/index.js +106 -162
  287. package/lib/types/api/eosGetPublicKey.js +4 -1
  288. package/lib/types/api/eosSignTransaction.js +4 -1
  289. package/lib/types/api/ethereum/index.d.ts +7 -7
  290. package/lib/types/api/ethereum/index.js +70 -67
  291. package/lib/types/api/ethereumGetAddress.js +4 -1
  292. package/lib/types/api/ethereumGetPublicKey.js +4 -1
  293. package/lib/types/api/ethereumSignMessage.js +4 -1
  294. package/lib/types/api/ethereumSignTransaction.js +4 -1
  295. package/lib/types/api/ethereumSignTypedData.js +4 -1
  296. package/lib/types/api/ethereumVerifyMessage.js +4 -1
  297. package/lib/types/api/evoluGetDelegatedIdentityKey.js +4 -1
  298. package/lib/types/api/evoluGetNode.js +4 -1
  299. package/lib/types/api/evoluSignRegistrationRequest.js +4 -1
  300. package/lib/types/api/firmwareUpdate.d.ts +1 -1
  301. package/lib/types/api/firmwareUpdate.js +12 -12
  302. package/lib/types/api/getAccountDescriptor.js +8 -5
  303. package/lib/types/api/getAccountInfo.js +4 -1
  304. package/lib/types/api/getAddress.js +11 -11
  305. package/lib/types/api/getCoinInfo.js +4 -1
  306. package/lib/types/api/getDeviceState.js +4 -1
  307. package/lib/types/api/getFeatures.js +4 -1
  308. package/lib/types/api/getFirmwareHash.js +4 -1
  309. package/lib/types/api/getNonce.d.ts +1 -1
  310. package/lib/types/api/getNonce.js +4 -1
  311. package/lib/types/api/getOwnershipId.js +8 -5
  312. package/lib/types/api/getOwnershipProof.js +14 -9
  313. package/lib/types/api/getPublicKey.js +25 -28
  314. package/lib/types/api/getSettings.js +4 -1
  315. package/lib/types/api/index.js +4 -1
  316. package/lib/types/api/init.js +4 -1
  317. package/lib/types/api/loadDevice.js +4 -1
  318. package/lib/types/api/manifest.js +4 -1
  319. package/lib/types/api/monero/index.js +117 -114
  320. package/lib/types/api/moneroGetAddress.js +4 -1
  321. package/lib/types/api/moneroGetWatchKey.js +4 -1
  322. package/lib/types/api/moneroKeyImageSync.js +4 -1
  323. package/lib/types/api/moneroSignTransaction.js +4 -1
  324. package/lib/types/api/nem/index.d.ts +7 -7
  325. package/lib/types/api/nem/index.js +78 -112
  326. package/lib/types/api/nemGetAddress.js +7 -7
  327. package/lib/types/api/nemSignTransaction.js +4 -1
  328. package/lib/types/api/off.js +4 -1
  329. package/lib/types/api/on.js +4 -1
  330. package/lib/types/api/pushTransaction.js +10 -10
  331. package/lib/types/api/recoveryDevice.d.ts +1 -1
  332. package/lib/types/api/recoveryDevice.js +7 -7
  333. package/lib/types/api/removeAllListeners.js +4 -1
  334. package/lib/types/api/renderWebUSBButton.js +4 -1
  335. package/lib/types/api/requestLogin.d.ts +4 -24
  336. package/lib/types/api/requestLogin.js +11 -13
  337. package/lib/types/api/requestWebUSBDevice.js +4 -1
  338. package/lib/types/api/resetDevice.js +4 -1
  339. package/lib/types/api/ripple/index.js +17 -14
  340. package/lib/types/api/rippleGetAddress.js +4 -1
  341. package/lib/types/api/rippleSignTransaction.js +4 -1
  342. package/lib/types/api/setBrightness.js +4 -1
  343. package/lib/types/api/setBusy.js +4 -1
  344. package/lib/types/api/setProxy.js +4 -1
  345. package/lib/types/api/setTransports.js +4 -1
  346. package/lib/types/api/showDeviceTutorial.js +4 -1
  347. package/lib/types/api/signMessage.js +4 -1
  348. package/lib/types/api/signTransaction.js +4 -1
  349. package/lib/types/api/solana/index.js +55 -56
  350. package/lib/types/api/solanaComposeTransaction.js +4 -1
  351. package/lib/types/api/solanaGetAddress.js +4 -1
  352. package/lib/types/api/solanaGetPublicKey.js +4 -1
  353. package/lib/types/api/solanaSignTransaction.js +4 -1
  354. package/lib/types/api/stellar/index.d.ts +146 -146
  355. package/lib/types/api/stellar/index.js +151 -221
  356. package/lib/types/api/stellarGetAddress.js +4 -1
  357. package/lib/types/api/stellarSignTransaction.js +4 -1
  358. package/lib/types/api/tezos/index.js +46 -43
  359. package/lib/types/api/tezosGetAddress.js +4 -1
  360. package/lib/types/api/tezosGetPublicKey.js +4 -1
  361. package/lib/types/api/tezosSignTransaction.js +4 -1
  362. package/lib/types/api/thpGetCredentials.js +4 -1
  363. package/lib/types/api/thpRemoveCredentials.js +4 -1
  364. package/lib/types/api/uiResponse.js +4 -1
  365. package/lib/types/api/unlockPath.js +6 -3
  366. package/lib/types/api/verifyMessage.js +4 -1
  367. package/lib/types/api/wipeDevice.js +4 -1
  368. package/lib/types/coinInfo.js +62 -77
  369. package/lib/types/device.d.ts +7 -2
  370. package/lib/types/device.js +7 -4
  371. package/lib/types/fees.js +31 -37
  372. package/lib/types/firmware.js +4 -1
  373. package/lib/types/index.d.ts +1 -0
  374. package/lib/types/index.js +18 -3
  375. package/lib/types/params.js +25 -16
  376. package/lib/types/settings.js +4 -1
  377. package/lib/types/utils.js +4 -1
  378. package/lib/types/workflow.js +4 -1
  379. package/lib/utils/accountUtils.js +76 -81
  380. package/lib/utils/addressUtils.js +21 -21
  381. package/lib/utils/assetUtils.js +29 -26
  382. package/lib/utils/assets-browser.js +19 -13
  383. package/lib/utils/assets.js +10 -9
  384. package/lib/utils/assets.native.js +24 -23
  385. package/lib/utils/assetsTypes.js +4 -1
  386. package/lib/utils/debug.js +18 -13
  387. package/lib/utils/deviceFeaturesUtils.js +105 -127
  388. package/lib/utils/ethereumUtils.js +9 -6
  389. package/lib/utils/firmwareReleaseConfigUtils.js +69 -57
  390. package/lib/utils/firmwareUtils.js +45 -57
  391. package/lib/utils/formatUtils.d.ts +0 -1
  392. package/lib/utils/formatUtils.js +63 -62
  393. package/lib/utils/hdnodeUtils.d.ts +0 -1
  394. package/lib/utils/hdnodeUtils.js +51 -57
  395. package/lib/utils/interactionTimeout.js +26 -23
  396. package/lib/utils/pathUtils.js +132 -148
  397. package/lib/utils/popupPromiseManager.js +23 -14
  398. package/lib/utils/proxy-event-emitter.js +63 -60
  399. package/lib/utils/uiPromiseManager.js +55 -43
  400. package/lib/utils/urlUtils.js +20 -26
  401. package/lib/utils/versionCheck.js +10 -10
  402. package/lib/workers/workers-browser.d.ts +5 -5
  403. package/lib/workers/workers-browser.js +5 -2
  404. package/lib/workers/workers.d.ts +1 -1
  405. package/lib/workers/workers.js +49 -38
  406. package/lib/workers/workers.native.d.ts +5 -5
  407. package/lib/workers/workers.native.js +4 -1
  408. package/package.json +23 -20
package/lib/core/index.js CHANGED
@@ -1,5 +1,8 @@
1
1
  "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
3
6
  exports.initCoreState = exports.Core = void 0;
4
7
  const tslib_1 = require("tslib");
5
8
  const events_1 = tslib_1.__importDefault(require("events"));
@@ -22,823 +25,981 @@ const interactionTimeout_1 = require("../utils/interactionTimeout");
22
25
  const popupPromiseManager_1 = require("../utils/popupPromiseManager");
23
26
  const uiPromiseManager_1 = require("../utils/uiPromiseManager");
24
27
  const _log = (0, debug_1.initLog)('Core');
25
- const waitForPopup = ({ popupPromise, sendCoreMessage }) => {
26
- sendCoreMessage((0, events_2.createUiMessage)(events_2.UI.REQUEST_UI_WINDOW));
27
- return popupPromise.wait();
28
+ const waitForPopup = ({
29
+ popupPromise,
30
+ sendCoreMessage
31
+ }) => {
32
+ sendCoreMessage((0, events_2.createUiMessage)(events_2.UI.REQUEST_UI_WINDOW));
33
+ return popupPromise.wait();
28
34
  };
29
- const startInteractionTimeout = (context) => context.interactionTimeout.start(() => {
30
- onPopupClosed(context, 'Interaction timeout');
35
+ const startInteractionTimeout = context => context.interactionTimeout.start(() => {
36
+ onPopupClosed(context, 'Interaction timeout');
31
37
  });
32
38
  const initDevice = async (context, methodCallDevice) => {
33
- const { uiPromises, deviceList, sendCoreMessage } = context;
39
+ const {
40
+ uiPromises,
41
+ deviceList,
42
+ sendCoreMessage
43
+ } = context;
44
+ (0, DeviceList_1.assertDeviceListConnected)(deviceList);
45
+ const isWebUsb = deviceList.getActiveTransports().some(t => t.type === 'WebUsbTransport');
46
+ let device;
47
+ let showDeviceSelection = isWebUsb;
48
+ const isUsingPopup = DataManager_1.DataManager.getSettings('popup');
49
+ const origin = DataManager_1.DataManager.getSettings('origin');
50
+ const useCoreInPopup = DataManager_1.DataManager.getSettings('useCoreInPopup');
51
+ const {
52
+ preferredDevice
53
+ } = connect_common_1.storage.load().origin[origin] || {};
54
+ const preferredDeviceInList = preferredDevice?.state && deviceList.getDeviceByStaticState(preferredDevice.state);
55
+ if (methodCallDevice?.state?.staticSessionId) {
56
+ device = deviceList.getDeviceByStaticState(methodCallDevice.state.staticSessionId);
57
+ }
58
+ if (!device && methodCallDevice?.path) {
59
+ device = deviceList.getDeviceByPath(methodCallDevice.path);
60
+ }
61
+ if (preferredDevice && !device) {
62
+ if (preferredDeviceInList) {
63
+ device = preferredDeviceInList;
64
+ } else {
65
+ connect_common_1.storage.save(store => {
66
+ store.origin[origin] = {
67
+ ...store.origin[origin],
68
+ preferredDevice: undefined
69
+ };
70
+ return store;
71
+ });
72
+ }
73
+ }
74
+ if (device) {
75
+ showDeviceSelection = device.isUnreadable() || device.isUnacquired() && !!isUsingPopup;
76
+ } else {
77
+ const onlyDevice = deviceList.getOnlyDevice();
78
+ if (onlyDevice && (!isWebUsb || !isUsingPopup)) {
79
+ device = onlyDevice;
80
+ showDeviceSelection = device.isUnreadable() || device.isUnacquired() || !!useCoreInPopup;
81
+ } else {
82
+ showDeviceSelection = true;
83
+ }
84
+ }
85
+ if (showDeviceSelection) {
86
+ uiPromises.create(events_2.UI.RECEIVE_DEVICE);
87
+ await waitForPopup(context);
34
88
  (0, DeviceList_1.assertDeviceListConnected)(deviceList);
35
- const isWebUsb = deviceList.getActiveTransports().some(t => t.type === 'WebUsbTransport');
36
- let device;
37
- let showDeviceSelection = isWebUsb;
38
- const isUsingPopup = DataManager_1.DataManager.getSettings('popup');
39
- const origin = DataManager_1.DataManager.getSettings('origin');
40
- const useCoreInPopup = DataManager_1.DataManager.getSettings('useCoreInPopup');
41
- const { preferredDevice } = connect_common_1.storage.load().origin[origin] || {};
42
- const preferredDeviceInList = preferredDevice?.state && deviceList.getDeviceByStaticState(preferredDevice.state);
43
- if (methodCallDevice?.state?.staticSessionId) {
44
- device = deviceList.getDeviceByStaticState(methodCallDevice.state.staticSessionId);
45
- }
46
- if (!device && methodCallDevice?.path) {
47
- device = deviceList.getDeviceByPath(methodCallDevice.path);
48
- }
49
- if (preferredDevice && !device) {
50
- if (preferredDeviceInList) {
51
- device = preferredDeviceInList;
52
- }
53
- else {
54
- connect_common_1.storage.save(store => {
55
- store.origin[origin] = { ...store.origin[origin], preferredDevice: undefined };
56
- return store;
57
- });
58
- }
59
- }
60
- if (device) {
61
- showDeviceSelection = device.isUnreadable() || (device.isUnacquired() && !!isUsingPopup);
62
- }
63
- else {
64
- const onlyDevice = deviceList.getOnlyDevice();
65
- if (onlyDevice && (!isWebUsb || !isUsingPopup)) {
66
- device = onlyDevice;
67
- showDeviceSelection =
68
- device.isUnreadable() || device.isUnacquired() || !!useCoreInPopup;
69
- }
70
- else {
71
- showDeviceSelection = true;
72
- }
73
- }
74
- if (showDeviceSelection) {
75
- uiPromises.create(events_2.UI.RECEIVE_DEVICE);
76
- await waitForPopup(context);
77
- (0, DeviceList_1.assertDeviceListConnected)(deviceList);
78
- const onlyDevice = deviceList.getOnlyDevice();
79
- if (onlyDevice &&
80
- !onlyDevice.isUnreadable() &&
81
- !onlyDevice.isUnacquired() &&
82
- !isWebUsb &&
83
- !useCoreInPopup) {
84
- device = onlyDevice;
85
- }
86
- else {
87
- sendCoreMessage((0, events_2.createUiMessage)(events_2.UI.SELECT_DEVICE, {
88
- webusb: isWebUsb,
89
- devices: deviceList.getAllDevices().map(d => d.toMessageObject()),
90
- }));
91
- if (uiPromises.exists(events_2.UI.RECEIVE_DEVICE)) {
92
- const { payload } = await uiPromises.get(events_2.UI.RECEIVE_DEVICE);
93
- if (payload.remember) {
94
- const { label, path, state } = payload.device;
95
- connect_common_1.storage.save(store => {
96
- store.origin[origin] = {
97
- ...store.origin[origin],
98
- preferredDevice: { label, path, state },
99
- };
100
- return store;
101
- });
102
- }
103
- device = deviceList.getDeviceByPath(payload.device.path);
104
- }
105
- }
106
- }
107
- else if (uiPromises.exists(events_2.UI.RECEIVE_DEVICE)) {
108
- await uiPromises.get(events_2.UI.RECEIVE_DEVICE);
109
- }
110
- if (!device) {
111
- throw constants_1.ERRORS.TypedError('Device_NotFound');
112
- }
113
- return device;
89
+ const onlyDevice = deviceList.getOnlyDevice();
90
+ if (onlyDevice && !onlyDevice.isUnreadable() && !onlyDevice.isUnacquired() && !isWebUsb && !useCoreInPopup) {
91
+ device = onlyDevice;
92
+ } else {
93
+ sendCoreMessage((0, events_2.createUiMessage)(events_2.UI.SELECT_DEVICE, {
94
+ webusb: isWebUsb,
95
+ devices: deviceList.getAllDevices().map(d => d.toMessageObject())
96
+ }));
97
+ if (uiPromises.exists(events_2.UI.RECEIVE_DEVICE)) {
98
+ const {
99
+ payload
100
+ } = await uiPromises.get(events_2.UI.RECEIVE_DEVICE);
101
+ if (payload.remember) {
102
+ const {
103
+ label,
104
+ path,
105
+ state
106
+ } = payload.device;
107
+ connect_common_1.storage.save(store => {
108
+ store.origin[origin] = {
109
+ ...store.origin[origin],
110
+ preferredDevice: {
111
+ label,
112
+ path,
113
+ state
114
+ }
115
+ };
116
+ return store;
117
+ });
118
+ }
119
+ device = deviceList.getDeviceByPath(payload.device.path);
120
+ }
121
+ }
122
+ } else if (uiPromises.exists(events_2.UI.RECEIVE_DEVICE)) {
123
+ await uiPromises.get(events_2.UI.RECEIVE_DEVICE);
124
+ }
125
+ if (!device) {
126
+ throw constants_1.ERRORS.TypedError('Device_NotFound');
127
+ }
128
+ return device;
114
129
  };
115
130
  const inner = async (context, method, device) => {
116
- const { uiPromises, sendCoreMessage } = context;
117
- const trustedHost = DataManager_1.DataManager.getSettings('trustedHost');
118
- const isUsingPopup = DataManager_1.DataManager.getSettings('popup') ?? false;
119
- const firmwareException = method.checkFirmwareRange();
120
- if (firmwareException) {
121
- if (isUsingPopup) {
122
- if (firmwareException === events_2.UI.FIRMWARE_NOT_COMPATIBLE) {
123
- await waitForPopup(context);
124
- const uiPromise = uiPromises.create(events_2.UI.RECEIVE_CONFIRMATION, device);
125
- sendCoreMessage((0, events_2.createUiMessage)(events_2.UI.FIRMWARE_NOT_COMPATIBLE, device.toMessageObject()));
126
- const uiResp = await uiPromise.promise;
127
- if (!uiResp.payload) {
128
- throw constants_1.ERRORS.TypedError('Method_PermissionsNotGranted');
129
- }
130
- }
131
- else {
132
- await waitForPopup(context);
133
- sendCoreMessage((0, events_2.createUiMessage)(firmwareException, device.toMessageObject()));
134
- await uiPromises.create(events_2.DEVICE.DISCONNECT, device).promise;
135
- return Promise.reject(constants_1.ERRORS.TypedError('Method_Cancel'));
136
- }
137
- }
138
- else {
139
- return Promise.reject(constants_1.ERRORS.TypedError('Device_FwException', firmwareException));
140
- }
141
- }
142
- const unexpectedMode = device.hasUnexpectedMode(method.allowDeviceMode, method.requireDeviceMode);
143
- if (unexpectedMode) {
144
- if (isUsingPopup) {
145
- await waitForPopup(context);
146
- sendCoreMessage((0, events_2.createUiMessage)(unexpectedMode, device.toMessageObject()));
147
- await uiPromises.create(events_2.DEVICE.DISCONNECT, device).promise;
148
- return Promise.reject(constants_1.ERRORS.TypedError('Device_ModeException', unexpectedMode));
149
- }
150
- return Promise.reject(constants_1.ERRORS.TypedError('Device_ModeException', unexpectedMode));
151
- }
152
- method.checkDeviceCapability();
153
- method.checkPermissions({ origin: DataManager_1.DataManager.getSettings('origin') });
154
- if (!trustedHost && method.requiredPermissions.length > 0) {
155
- await waitForPopup(context);
156
- const uiPromise = uiPromises.create(events_2.UI.RECEIVE_PERMISSION, device);
157
- sendCoreMessage((0, events_2.createUiMessage)(events_2.UI.REQUEST_PERMISSION, {
158
- permissions: method.requiredPermissions,
159
- device: device.toMessageObject(),
160
- }));
161
- const { granted, remember } = await uiPromise.promise.then(({ payload }) => payload);
162
- if (granted) {
163
- method.savePermissions(!remember, { origin: DataManager_1.DataManager.getSettings('origin') });
164
- }
165
- else {
166
- return Promise.reject(constants_1.ERRORS.TypedError('Method_PermissionsNotGranted'));
167
- }
168
- }
169
- const deviceNeedsBackup = device.features.backup_availability === 'Required';
170
- if (deviceNeedsBackup) {
171
- if (method.noBackupConfirmationMode === 'always' ||
172
- (method.noBackupConfirmationMode === 'popup-only' && isUsingPopup)) {
173
- await waitForPopup(context);
174
- const uiPromise = uiPromises.create(events_2.UI.RECEIVE_CONFIRMATION, device);
175
- sendCoreMessage((0, analyticsInfo_1.enhanceMessageWithAnalytics)((0, events_2.createUiMessage)(events_2.UI.REQUEST_CONFIRMATION, {
176
- view: 'no-backup',
177
- }), { device: device.toMessageObject() }));
178
- const permitted = await uiPromise.promise.then(({ payload }) => payload);
179
- if (!permitted) {
180
- return Promise.reject(constants_1.ERRORS.TypedError('Method_PermissionsNotGranted'));
181
- }
182
- }
183
- await waitForPopup(context);
184
- sendCoreMessage((0, events_2.createUiMessage)(events_2.UI.DEVICE_NEEDS_BACKUP, device.toMessageObject()));
185
- }
186
- if (device.firmwareStatus === 'outdated') {
131
+ const {
132
+ uiPromises,
133
+ sendCoreMessage
134
+ } = context;
135
+ const trustedHost = DataManager_1.DataManager.getSettings('trustedHost');
136
+ const isUsingPopup = DataManager_1.DataManager.getSettings('popup') ?? false;
137
+ const firmwareException = method.checkFirmwareRange();
138
+ if (firmwareException) {
139
+ if (isUsingPopup) {
140
+ if (firmwareException === events_2.UI.FIRMWARE_NOT_COMPATIBLE) {
187
141
  await waitForPopup(context);
188
- sendCoreMessage((0, events_2.createUiMessage)(events_2.UI.FIRMWARE_OUTDATED, device.toMessageObject()));
189
- }
190
- if (!trustedHost) {
191
- const requestConfirmation = method.confirmation;
192
- if (requestConfirmation) {
193
- await waitForPopup(context);
194
- const uiPromise = uiPromises.create(events_2.UI.RECEIVE_CONFIRMATION, device);
195
- sendCoreMessage((0, analyticsInfo_1.enhanceMessageWithAnalytics)((0, events_2.createUiMessage)(events_2.UI.REQUEST_CONFIRMATION, requestConfirmation), { device: device.toMessageObject() }));
196
- const confirmed = await uiPromise.promise.then(({ payload }) => payload);
197
- if (!confirmed) {
198
- return Promise.reject(constants_1.ERRORS.TypedError('Method_Cancel'));
199
- }
142
+ const uiPromise = uiPromises.create(events_2.UI.RECEIVE_CONFIRMATION, device);
143
+ sendCoreMessage((0, events_2.createUiMessage)(events_2.UI.FIRMWARE_NOT_COMPATIBLE, device.toMessageObject()));
144
+ const uiResp = await uiPromise.promise;
145
+ if (!uiResp.payload) {
146
+ throw constants_1.ERRORS.TypedError('Method_PermissionsNotGranted');
200
147
  }
201
- }
202
- const workflowCtx = {
203
- device,
204
- method,
205
- signal: context.signal,
206
- };
207
- await workflows.validateState(workflowCtx);
208
- if (method.useUi) {
148
+ } else {
209
149
  await waitForPopup(context);
150
+ sendCoreMessage((0, events_2.createUiMessage)(firmwareException, device.toMessageObject()));
151
+ await uiPromises.create(events_2.DEVICE.DISCONNECT, device).promise;
152
+ return Promise.reject(constants_1.ERRORS.TypedError('Method_Cancel'));
153
+ }
154
+ } else {
155
+ return Promise.reject(constants_1.ERRORS.TypedError('Device_FwException', firmwareException));
156
+ }
157
+ }
158
+ const unexpectedMode = device.hasUnexpectedMode(method.allowDeviceMode, method.requireDeviceMode);
159
+ if (unexpectedMode) {
160
+ if (isUsingPopup) {
161
+ await waitForPopup(context);
162
+ sendCoreMessage((0, events_2.createUiMessage)(unexpectedMode, device.toMessageObject()));
163
+ await uiPromises.create(events_2.DEVICE.DISCONNECT, device).promise;
164
+ return Promise.reject(constants_1.ERRORS.TypedError('Device_ModeException', unexpectedMode));
165
+ }
166
+ return Promise.reject(constants_1.ERRORS.TypedError('Device_ModeException', unexpectedMode));
167
+ }
168
+ method.checkDeviceCapability();
169
+ method.checkPermissions({
170
+ origin: DataManager_1.DataManager.getSettings('origin')
171
+ });
172
+ if (!trustedHost && method.requiredPermissions.length > 0) {
173
+ await waitForPopup(context);
174
+ const uiPromise = uiPromises.create(events_2.UI.RECEIVE_PERMISSION, device);
175
+ sendCoreMessage((0, events_2.createUiMessage)(events_2.UI.REQUEST_PERMISSION, {
176
+ permissions: method.requiredPermissions,
177
+ device: device.toMessageObject()
178
+ }));
179
+ const {
180
+ granted,
181
+ remember
182
+ } = await uiPromise.promise.then(({
183
+ payload
184
+ }) => payload);
185
+ if (granted) {
186
+ method.savePermissions(!remember, {
187
+ origin: DataManager_1.DataManager.getSettings('origin')
188
+ });
189
+ } else {
190
+ return Promise.reject(constants_1.ERRORS.TypedError('Method_PermissionsNotGranted'));
191
+ }
192
+ }
193
+ const deviceNeedsBackup = device.features.backup_availability === 'Required';
194
+ if (deviceNeedsBackup) {
195
+ if (method.noBackupConfirmationMode === 'always' || method.noBackupConfirmationMode === 'popup-only' && isUsingPopup) {
196
+ await waitForPopup(context);
197
+ const uiPromise = uiPromises.create(events_2.UI.RECEIVE_CONFIRMATION, device);
198
+ sendCoreMessage((0, analyticsInfo_1.enhanceMessageWithAnalytics)((0, events_2.createUiMessage)(events_2.UI.REQUEST_CONFIRMATION, {
199
+ view: 'no-backup'
200
+ }), {
201
+ device: device.toMessageObject()
202
+ }));
203
+ const permitted = await uiPromise.promise.then(({
204
+ payload
205
+ }) => payload);
206
+ if (!permitted) {
207
+ return Promise.reject(constants_1.ERRORS.TypedError('Method_PermissionsNotGranted'));
208
+ }
210
209
  }
211
- else {
212
- sendCoreMessage((0, events_2.createPopupMessage)(events_2.POPUP.CANCEL_POPUP_REQUEST));
213
- }
214
- try {
215
- const response = await method.run();
216
- return (0, events_2.createResponseMessage)(method.responseID, true, response, device);
217
- }
218
- catch (error) {
219
- return Promise.reject(error);
220
- }
210
+ await waitForPopup(context);
211
+ sendCoreMessage((0, events_2.createUiMessage)(events_2.UI.DEVICE_NEEDS_BACKUP, device.toMessageObject()));
212
+ }
213
+ if (device.firmwareStatus === 'outdated') {
214
+ await waitForPopup(context);
215
+ sendCoreMessage((0, events_2.createUiMessage)(events_2.UI.FIRMWARE_OUTDATED, device.toMessageObject()));
216
+ }
217
+ if (!trustedHost) {
218
+ const requestConfirmation = method.confirmation;
219
+ if (requestConfirmation) {
220
+ await waitForPopup(context);
221
+ const uiPromise = uiPromises.create(events_2.UI.RECEIVE_CONFIRMATION, device);
222
+ sendCoreMessage((0, analyticsInfo_1.enhanceMessageWithAnalytics)((0, events_2.createUiMessage)(events_2.UI.REQUEST_CONFIRMATION, requestConfirmation), {
223
+ device: device.toMessageObject()
224
+ }));
225
+ const confirmed = await uiPromise.promise.then(({
226
+ payload
227
+ }) => payload);
228
+ if (!confirmed) {
229
+ return Promise.reject(constants_1.ERRORS.TypedError('Method_Cancel'));
230
+ }
231
+ }
232
+ }
233
+ const workflowCtx = {
234
+ device,
235
+ method,
236
+ signal: context.signal
237
+ };
238
+ await workflows.validateState(workflowCtx);
239
+ if (method.useUi) {
240
+ await waitForPopup(context);
241
+ } else {
242
+ sendCoreMessage((0, events_2.createPopupMessage)(events_2.POPUP.CANCEL_POPUP_REQUEST));
243
+ }
244
+ try {
245
+ const response = await method.run();
246
+ return (0, events_2.createResponseMessage)(method.responseID, true, response, device);
247
+ } catch (error) {
248
+ return Promise.reject(error);
249
+ }
221
250
  };
222
251
  const onCall = async (context, message) => {
223
- if (!message.id || !message.payload || message.type !== events_2.IFRAME.CALL) {
224
- throw constants_1.ERRORS.TypedError('Method_InvalidParameter', 'onCall: message.id or message.payload is missing');
225
- }
226
- const { uiPromises, callMethods, methodSynchronize, resolveWaitForFirstMethod, sendCoreMessage, } = context;
227
- const responseID = message.id;
228
- let method;
252
+ if (!message.id || !message.payload || message.type !== events_2.IFRAME.CALL) {
253
+ throw constants_1.ERRORS.TypedError('Method_InvalidParameter', 'onCall: message.id or message.payload is missing');
254
+ }
255
+ const {
256
+ uiPromises,
257
+ callMethods,
258
+ methodSynchronize,
259
+ resolveWaitForFirstMethod,
260
+ sendCoreMessage
261
+ } = context;
262
+ const responseID = message.id;
263
+ let method;
264
+ try {
265
+ method = await methodSynchronize(async () => {
266
+ _log.debug('loading method...');
267
+ const method2 = await (0, method_1.getMethod)(message);
268
+ _log.debug('method selected', method2.name);
269
+ method2.postMessage = sendCoreMessage;
270
+ method2.createUiPromise = uiPromises.create;
271
+ method2.init();
272
+ await method2.initAsync?.();
273
+ return method2;
274
+ });
275
+ resolveWaitForFirstMethod();
276
+ callMethods.push(method);
277
+ } catch (error) {
278
+ sendCoreMessage((0, events_2.createPopupMessage)(events_2.POPUP.CANCEL_POPUP_REQUEST));
279
+ sendCoreMessage((0, events_2.createResponseMessage)(responseID, false, {
280
+ error
281
+ }));
282
+ return Promise.resolve();
283
+ }
284
+ if (method.payload.__info) {
285
+ const response = method.getMethodInfo();
286
+ if (method.payload.__precomposed) {
287
+ response.precomposed = await method.payloadToPrecomposed();
288
+ }
289
+ sendCoreMessage((0, events_2.createResponseMessage)(method.responseID, true, response));
290
+ return Promise.resolve();
291
+ }
292
+ if (!method.useDevice) {
229
293
  try {
230
- method = await methodSynchronize(async () => {
231
- _log.debug('loading method...');
232
- const method2 = await (0, method_1.getMethod)(message);
233
- _log.debug('method selected', method2.name);
234
- method2.postMessage = sendCoreMessage;
235
- method2.createUiPromise = uiPromises.create;
236
- method2.init();
237
- await method2.initAsync?.();
238
- return method2;
239
- });
240
- resolveWaitForFirstMethod();
241
- callMethods.push(method);
242
- }
243
- catch (error) {
244
- sendCoreMessage((0, events_2.createPopupMessage)(events_2.POPUP.CANCEL_POPUP_REQUEST));
245
- sendCoreMessage((0, events_2.createResponseMessage)(responseID, false, { error }));
246
- return Promise.resolve();
247
- }
248
- if (method.payload.__info) {
249
- const response = method.getMethodInfo();
250
- if (method.payload.__precomposed) {
251
- response.precomposed = await method.payloadToPrecomposed();
252
- }
253
- sendCoreMessage((0, events_2.createResponseMessage)(method.responseID, true, response));
254
- return Promise.resolve();
255
- }
256
- if (!method.useDevice) {
257
- try {
258
- if (method.useUi) {
259
- await waitForPopup(context);
260
- }
261
- else {
262
- sendCoreMessage((0, events_2.createPopupMessage)(events_2.POPUP.CANCEL_POPUP_REQUEST));
263
- }
264
- const response = await method.run();
265
- sendCoreMessage((0, events_2.createResponseMessage)(method.responseID, true, response));
266
- }
267
- catch (error) {
268
- sendCoreMessage((0, events_2.createResponseMessage)(method.responseID, false, { error }));
269
- }
270
- return Promise.resolve();
271
- }
272
- if (method.isManagementRestricted({ origin: DataManager_1.DataManager.getSettings('origin') })) {
294
+ if (method.useUi) {
295
+ await waitForPopup(context);
296
+ } else {
273
297
  sendCoreMessage((0, events_2.createPopupMessage)(events_2.POPUP.CANCEL_POPUP_REQUEST));
274
- sendCoreMessage((0, events_2.createResponseMessage)(responseID, false, {
275
- error: constants_1.ERRORS.TypedError('Method_NotAllowed'),
276
- }));
277
- return Promise.resolve();
278
- }
279
- return await onCallDevice(context, message, method);
298
+ }
299
+ const response = await method.run();
300
+ sendCoreMessage((0, events_2.createResponseMessage)(method.responseID, true, response));
301
+ } catch (error) {
302
+ sendCoreMessage((0, events_2.createResponseMessage)(method.responseID, false, {
303
+ error
304
+ }));
305
+ }
306
+ return Promise.resolve();
307
+ }
308
+ if (method.isManagementRestricted({
309
+ origin: DataManager_1.DataManager.getSettings('origin')
310
+ })) {
311
+ sendCoreMessage((0, events_2.createPopupMessage)(events_2.POPUP.CANCEL_POPUP_REQUEST));
312
+ sendCoreMessage((0, events_2.createResponseMessage)(responseID, false, {
313
+ error: constants_1.ERRORS.TypedError('Method_NotAllowed')
314
+ }));
315
+ return Promise.resolve();
316
+ }
317
+ return await onCallDevice(context, message, method);
280
318
  };
281
319
  const onCallDevice = async (context, message, method) => {
282
- const { deviceList, callMethods, sendCoreMessage } = context;
283
- const responseID = message.id;
284
- const { origin, env, useCoreInPopup, transports } = DataManager_1.DataManager.getSettings();
285
- if (!deviceList.isConnected() && !deviceList.pendingConnection()) {
286
- deviceList.init({ transports });
287
- }
288
- await deviceList.pendingConnection();
289
- const shouldRetry = ['web', 'webextension'].includes(env);
290
- let tempDevice;
291
- while (!tempDevice) {
292
- try {
293
- tempDevice = await initDevice(context, message.payload.device);
294
- }
295
- catch (error) {
296
- if (error.code === 'Transport_Missing') {
297
- await waitForPopup(context);
298
- sendCoreMessage((0, events_2.createUiMessage)(events_2.UI.TRANSPORT));
299
- if (deviceList.pendingConnection() && shouldRetry) {
300
- while (deviceList.pendingConnection()) {
301
- await deviceList.pendingConnection();
302
- }
303
- continue;
304
- }
305
- }
306
- else {
307
- sendCoreMessage((0, events_2.createPopupMessage)(events_2.POPUP.CANCEL_POPUP_REQUEST));
308
- }
309
- sendCoreMessage((0, events_2.createResponseMessage)(responseID, false, { error }));
310
- throw error;
311
- }
312
- }
313
- const device = tempDevice;
314
- method.setDevice(device);
315
- const previousCall = callMethods.filter(call => call &&
316
- call !== method &&
317
- call.device?.getUniquePath() === method.device.getUniquePath());
318
- if (previousCall.length > 0 && method.overridePreviousCall) {
319
- previousCall.forEach(call => {
320
- call.overridden = true;
321
- });
322
- const overrideError = constants_1.ERRORS.TypedError('Method_Override');
323
- await device.interrupt(overrideError);
324
- if (method.overridden) {
325
- sendCoreMessage((0, events_2.createResponseMessage)(method.responseID, false, { error: overrideError }));
326
- throw overrideError;
327
- }
328
- }
329
- else if (device.currentRun) {
330
- if (device.isUnacquired()) {
331
- await device.currentRun;
332
- }
333
- else {
334
- sendCoreMessage((0, events_2.createResponseMessage)(responseID, false, {
335
- error: constants_1.ERRORS.TypedError('Device_CallInProgress'),
336
- }));
337
- throw constants_1.ERRORS.TypedError('Device_CallInProgress');
338
- }
339
- }
340
- device.setInstance(message.payload.device?.instance);
341
- if (method.hasExpectedDeviceState) {
342
- device.setState(method.deviceState);
343
- }
344
- registerDeviceEvents(context, method)(device);
345
- if (useCoreInPopup && env === 'webextension' && origin) {
346
- device.initStorage(new StateStorage_1.WebextensionStateStorage(origin));
347
- }
348
- let messageResponse;
320
+ const {
321
+ deviceList,
322
+ callMethods,
323
+ sendCoreMessage
324
+ } = context;
325
+ const responseID = message.id;
326
+ const {
327
+ origin,
328
+ env,
329
+ useCoreInPopup,
330
+ transports
331
+ } = DataManager_1.DataManager.getSettings();
332
+ if (!deviceList.isConnected() && !deviceList.pendingConnection()) {
333
+ deviceList.init({
334
+ transports
335
+ });
336
+ }
337
+ await deviceList.pendingConnection();
338
+ const shouldRetry = ['web', 'webextension'].includes(env);
339
+ let tempDevice;
340
+ while (!tempDevice) {
349
341
  try {
350
- const innerAction = () => inner(context, method, device).then(response => {
351
- messageResponse = response;
352
- });
353
- await device.run(innerAction, {
354
- keepSession: method.keepSession,
355
- skipFinalReload: method.skipFinalReload,
356
- useCardanoDerivation: method.useCardanoDerivation,
357
- });
358
- }
359
- catch (error) {
360
- if (error.cause) {
361
- _log.debug('device.run error caught, caused by:', error.cause);
362
- }
363
- if (error.code === 'Device_Disconnected') {
364
- deviceList.addAuthPenalty(device);
365
- }
366
- if (method) {
367
- if (deviceList.isConnected() &&
368
- error.message === transport_1.TRANSPORT_ERROR.SESSION_WRONG_PREVIOUS) {
369
- await deviceList.enumerate();
370
- }
371
- messageResponse = (0, events_2.createResponseMessage)(method.responseID, false, { error });
372
- }
373
- }
374
- finally {
375
- if (method.keepSession &&
376
- method.deviceState &&
377
- method.deviceState.sessionId !== device.getState()?.sessionId) {
378
- sendCoreMessage((0, events_2.createDeviceMessage)(events_2.DEVICE.CHANGED, device.toMessageObject()));
379
- }
380
- const response = messageResponse;
381
- if (response) {
382
- device.eventNames().forEach(e => device.removeAllListeners(e));
383
- if (useCoreInPopup) {
384
- sendCoreMessage(response);
385
- }
386
- closePopup(context);
387
- cleanup(context);
388
- if (method) {
389
- method.dispose();
390
- }
391
- if (response.success) {
392
- deviceList.removeAuthPenalty(device);
393
- }
394
- if (!useCoreInPopup) {
395
- sendCoreMessage(response);
396
- }
397
- }
398
- }
399
- };
400
- const cleanup = ({ uiPromises, popupPromise, interactionTimeout }) => {
401
- popupPromise.clear();
402
- uiPromises.clear();
403
- interactionTimeout.stop();
404
- _log.debug('Cleanup...');
405
- };
406
- const closePopup = ({ popupPromise, sendCoreMessage }) => {
407
- if (popupPromise.isWaiting()) {
342
+ tempDevice = await initDevice(context, message.payload.device);
343
+ } catch (error) {
344
+ if (error.code === 'Transport_Missing') {
345
+ await waitForPopup(context);
346
+ sendCoreMessage((0, events_2.createUiMessage)(events_2.UI.TRANSPORT));
347
+ if (deviceList.pendingConnection() && shouldRetry) {
348
+ while (deviceList.pendingConnection()) {
349
+ await deviceList.pendingConnection();
350
+ }
351
+ continue;
352
+ }
353
+ } else {
408
354
  sendCoreMessage((0, events_2.createPopupMessage)(events_2.POPUP.CANCEL_POPUP_REQUEST));
409
- }
410
- sendCoreMessage((0, events_2.createUiMessage)(events_2.UI.CLOSE_UI_WINDOW));
355
+ }
356
+ sendCoreMessage((0, events_2.createResponseMessage)(responseID, false, {
357
+ error
358
+ }));
359
+ throw error;
360
+ }
361
+ }
362
+ const device = tempDevice;
363
+ method.setDevice(device);
364
+ const previousCall = callMethods.filter(call => call && call !== method && call.device?.getUniquePath() === method.device.getUniquePath());
365
+ if (previousCall.length > 0 && method.overridePreviousCall) {
366
+ previousCall.forEach(call => {
367
+ call.overridden = true;
368
+ });
369
+ const overrideError = constants_1.ERRORS.TypedError('Method_Override');
370
+ await device.interrupt(overrideError);
371
+ if (method.overridden) {
372
+ sendCoreMessage((0, events_2.createResponseMessage)(method.responseID, false, {
373
+ error: overrideError
374
+ }));
375
+ throw overrideError;
376
+ }
377
+ } else if (device.currentRun) {
378
+ if (device.isUnacquired()) {
379
+ await device.currentRun;
380
+ } else {
381
+ sendCoreMessage((0, events_2.createResponseMessage)(responseID, false, {
382
+ error: constants_1.ERRORS.TypedError('Device_CallInProgress')
383
+ }));
384
+ throw constants_1.ERRORS.TypedError('Device_CallInProgress');
385
+ }
386
+ }
387
+ device.setInstance(message.payload.device?.instance);
388
+ if (method.hasExpectedDeviceState) {
389
+ device.setState(method.deviceState);
390
+ }
391
+ registerDeviceEvents(context, method)(device);
392
+ if (useCoreInPopup && env === 'webextension' && origin) {
393
+ device.initStorage(new StateStorage_1.WebextensionStateStorage(origin));
394
+ }
395
+ let messageResponse;
396
+ try {
397
+ const innerAction = () => inner(context, method, device).then(response => {
398
+ messageResponse = response;
399
+ });
400
+ await device.run(innerAction, {
401
+ keepSession: method.keepSession,
402
+ skipFinalReload: method.skipFinalReload,
403
+ useCardanoDerivation: method.useCardanoDerivation
404
+ });
405
+ } catch (error) {
406
+ if (error.cause) {
407
+ _log.debug('device.run error caught, caused by:', error.cause);
408
+ }
409
+ if (error.code === 'Device_Disconnected') {
410
+ deviceList.addAuthPenalty(device);
411
+ }
412
+ if (method) {
413
+ if (deviceList.isConnected() && error.message === transport_1.TRANSPORT_ERROR.SESSION_WRONG_PREVIOUS) {
414
+ await deviceList.enumerate();
415
+ }
416
+ messageResponse = (0, events_2.createResponseMessage)(method.responseID, false, {
417
+ error
418
+ });
419
+ }
420
+ } finally {
421
+ if (method.keepSession && method.deviceState && method.deviceState.sessionId !== device.getState()?.sessionId) {
422
+ sendCoreMessage((0, events_2.createDeviceMessage)(events_2.DEVICE.CHANGED, device.toMessageObject()));
423
+ }
424
+ const response = messageResponse;
425
+ if (response) {
426
+ device.eventNames().forEach(e => device.removeAllListeners(e));
427
+ if (useCoreInPopup) {
428
+ sendCoreMessage(response);
429
+ }
430
+ closePopup(context);
431
+ cleanup(context);
432
+ if (method) {
433
+ method.dispose();
434
+ }
435
+ if (response.success) {
436
+ deviceList.removeAuthPenalty(device);
437
+ }
438
+ if (!useCoreInPopup) {
439
+ sendCoreMessage(response);
440
+ }
441
+ }
442
+ }
411
443
  };
412
- const onDeviceButtonHandler = (device, context, method) => async ({ payload: request }) => {
413
- const { sendCoreMessage } = context;
414
- const addressRequest = request.code === 'ButtonRequest_Address';
415
- if (!addressRequest || (addressRequest && method?.useUi)) {
416
- await waitForPopup(context);
417
- }
418
- const data = typeof method?.getButtonRequestData === 'function' && request.code
419
- ? method?.getButtonRequestData(request.code, request.name)
420
- : undefined;
421
- startInteractionTimeout(context);
422
- sendCoreMessage((0, events_2.createDeviceMessage)(events_2.DEVICE.BUTTON, { ...request, device: device.toMessageObject() }));
423
- sendCoreMessage((0, events_2.createUiMessage)(events_2.UI.REQUEST_BUTTON, {
424
- ...request,
425
- device: device.toMessageObject(),
426
- data,
427
- }));
428
- if (addressRequest && !method?.useUi) {
429
- sendCoreMessage((0, events_2.createUiMessage)(events_2.UI.ADDRESS_VALIDATION, data));
430
- }
444
+ const cleanup = ({
445
+ uiPromises,
446
+ popupPromise,
447
+ interactionTimeout
448
+ }) => {
449
+ popupPromise.clear();
450
+ uiPromises.clear();
451
+ interactionTimeout.stop();
452
+ _log.debug('Cleanup...');
431
453
  };
432
- const onDevicePinHandler = (device, context) => async ({ type, callback }) => {
433
- const { uiPromises, sendCoreMessage } = context;
434
- await waitForPopup(context);
435
- const uiPromise = uiPromises.create(events_2.UI.RECEIVE_PIN, device);
436
- sendCoreMessage((0, events_2.createUiMessage)(events_2.UI.REQUEST_PIN, { device: device.toMessageObject(), type }));
437
- try {
438
- const uiResp = await uiPromise.promise;
439
- if (uiResp.payload == null) {
440
- callback({ success: false, error: new Error(`${events_2.UI.RECEIVE_PIN} missing payload`) });
441
- }
442
- else {
443
- callback({ success: true, payload: uiResp.payload });
444
- }
445
- }
446
- catch (error) {
447
- callback({ success: false, error });
448
- }
454
+ const closePopup = ({
455
+ popupPromise,
456
+ sendCoreMessage
457
+ }) => {
458
+ if (popupPromise.isWaiting()) {
459
+ sendCoreMessage((0, events_2.createPopupMessage)(events_2.POPUP.CANCEL_POPUP_REQUEST));
460
+ }
461
+ sendCoreMessage((0, events_2.createUiMessage)(events_2.UI.CLOSE_UI_WINDOW));
449
462
  };
450
- const onDeviceWordHandler = (device, context) => async ({ type, callback }) => {
451
- const { uiPromises, sendCoreMessage } = context;
463
+ const onDeviceButtonHandler = (device, context, method) => async ({
464
+ payload: request
465
+ }) => {
466
+ const {
467
+ sendCoreMessage
468
+ } = context;
469
+ const addressRequest = request.code === 'ButtonRequest_Address';
470
+ if (!addressRequest || addressRequest && method?.useUi) {
452
471
  await waitForPopup(context);
453
- const uiPromise = uiPromises.create(events_2.UI.RECEIVE_WORD, device);
454
- sendCoreMessage((0, events_2.createUiMessage)(events_2.UI.REQUEST_WORD, { device: device.toMessageObject(), type }));
455
- try {
456
- const uiResp = await uiPromise.promise;
457
- if (uiResp.payload == null) {
458
- callback({
459
- success: false,
460
- error: new Error(`${events_2.UI.RECEIVE_WORD} missing payload`),
461
- });
462
- }
463
- else {
464
- callback({ success: true, payload: uiResp.payload });
465
- }
466
- }
467
- catch (error) {
468
- callback({ success: false, error });
469
- }
472
+ }
473
+ const data = typeof method?.getButtonRequestData === 'function' && request.code ? method?.getButtonRequestData(request.code, request.name) : undefined;
474
+ startInteractionTimeout(context);
475
+ sendCoreMessage((0, events_2.createDeviceMessage)(events_2.DEVICE.BUTTON, {
476
+ ...request,
477
+ device: device.toMessageObject()
478
+ }));
479
+ sendCoreMessage((0, events_2.createUiMessage)(events_2.UI.REQUEST_BUTTON, {
480
+ ...request,
481
+ device: device.toMessageObject(),
482
+ data
483
+ }));
484
+ if (addressRequest && !method?.useUi) {
485
+ sendCoreMessage((0, events_2.createUiMessage)(events_2.UI.ADDRESS_VALIDATION, data));
486
+ }
470
487
  };
471
- const onDevicePassphraseHandler = (device, context) => async ({ callback }) => {
472
- const { uiPromises, sendCoreMessage } = context;
473
- await waitForPopup(context);
474
- const uiPromise = uiPromises.create(events_2.UI.RECEIVE_PASSPHRASE, device);
475
- sendCoreMessage((0, events_2.createUiMessage)(events_2.UI.REQUEST_PASSPHRASE, { device: device.toMessageObject() }));
476
- try {
477
- const uiResp = await uiPromise.promise;
478
- if (uiResp.payload == null) {
479
- callback({
480
- success: false,
481
- error: new Error(`${events_2.UI.RECEIVE_PASSPHRASE} missing payload`),
482
- });
483
- }
484
- else {
485
- callback({ success: true, payload: uiResp.payload });
486
- }
487
- }
488
- catch (error) {
489
- callback({ success: false, error });
490
- }
488
+ const onDevicePinHandler = (device, context) => async ({
489
+ type,
490
+ callback
491
+ }) => {
492
+ const {
493
+ uiPromises,
494
+ sendCoreMessage
495
+ } = context;
496
+ await waitForPopup(context);
497
+ const uiPromise = uiPromises.create(events_2.UI.RECEIVE_PIN, device);
498
+ sendCoreMessage((0, events_2.createUiMessage)(events_2.UI.REQUEST_PIN, {
499
+ device: device.toMessageObject(),
500
+ type
501
+ }));
502
+ try {
503
+ const uiResp = await uiPromise.promise;
504
+ if (uiResp.payload == null) {
505
+ callback({
506
+ success: false,
507
+ error: new Error(`${events_2.UI.RECEIVE_PIN} missing payload`)
508
+ });
509
+ } else {
510
+ callback({
511
+ success: true,
512
+ payload: uiResp.payload
513
+ });
514
+ }
515
+ } catch (error) {
516
+ callback({
517
+ success: false,
518
+ error
519
+ });
520
+ }
491
521
  };
492
- const onEmptyPassphraseHandler = () => ({ callback }) => {
493
- callback({ success: true, payload: { value: '' } });
522
+ const onDeviceWordHandler = (device, context) => async ({
523
+ type,
524
+ callback
525
+ }) => {
526
+ const {
527
+ uiPromises,
528
+ sendCoreMessage
529
+ } = context;
530
+ await waitForPopup(context);
531
+ const uiPromise = uiPromises.create(events_2.UI.RECEIVE_WORD, device);
532
+ sendCoreMessage((0, events_2.createUiMessage)(events_2.UI.REQUEST_WORD, {
533
+ device: device.toMessageObject(),
534
+ type
535
+ }));
536
+ try {
537
+ const uiResp = await uiPromise.promise;
538
+ if (uiResp.payload == null) {
539
+ callback({
540
+ success: false,
541
+ error: new Error(`${events_2.UI.RECEIVE_WORD} missing payload`)
542
+ });
543
+ } else {
544
+ callback({
545
+ success: true,
546
+ payload: uiResp.payload
547
+ });
548
+ }
549
+ } catch (error) {
550
+ callback({
551
+ success: false,
552
+ error
553
+ });
554
+ }
494
555
  };
495
- const onThpPairingHandler = (device, context) => async ({ callback, payload }) => {
496
- const { uiPromises, sendCoreMessage } = context;
497
- await waitForPopup(context);
498
- const uiPromise = uiPromises.create(events_2.UI.RECEIVE_THP_PAIRING_TAG, device);
499
- sendCoreMessage((0, events_2.createUiMessage)(events_2.UI.REQUEST_THP_PAIRING, {
500
- device: device.toMessageObject(),
501
- ...payload,
502
- }));
503
- try {
504
- const uiResp = await uiPromise.promise;
505
- if (uiResp.payload == null) {
506
- callback({
507
- success: false,
508
- error: new Error(`${events_2.UI.RECEIVE_THP_PAIRING_TAG} missing payload`),
509
- });
510
- }
511
- else {
512
- callback({ success: true, payload: uiResp.payload });
513
- }
514
- }
515
- catch (error) {
516
- callback({ success: false, error });
517
- }
556
+ const onDevicePassphraseHandler = (device, context) => async ({
557
+ callback
558
+ }) => {
559
+ const {
560
+ uiPromises,
561
+ sendCoreMessage
562
+ } = context;
563
+ await waitForPopup(context);
564
+ const uiPromise = uiPromises.create(events_2.UI.RECEIVE_PASSPHRASE, device);
565
+ sendCoreMessage((0, events_2.createUiMessage)(events_2.UI.REQUEST_PASSPHRASE, {
566
+ device: device.toMessageObject()
567
+ }));
568
+ try {
569
+ const uiResp = await uiPromise.promise;
570
+ if (uiResp.payload == null) {
571
+ callback({
572
+ success: false,
573
+ error: new Error(`${events_2.UI.RECEIVE_PASSPHRASE} missing payload`)
574
+ });
575
+ } else {
576
+ callback({
577
+ success: true,
578
+ payload: uiResp.payload
579
+ });
580
+ }
581
+ } catch (error) {
582
+ callback({
583
+ success: false,
584
+ error
585
+ });
586
+ }
518
587
  };
519
- const onThpCredentialsChangedHandler = (device, context) => (payload) => {
520
- const { sendCoreMessage } = context;
521
- sendCoreMessage((0, events_2.createDeviceMessage)(events_2.DEVICE.THP_CREDENTIALS_CHANGED, {
522
- device: device.toMessageObject(),
523
- ...payload,
524
- }));
588
+ const onEmptyPassphraseHandler = () => ({
589
+ callback
590
+ }) => {
591
+ callback({
592
+ success: true,
593
+ payload: {
594
+ value: ''
595
+ }
596
+ });
525
597
  };
526
- const registerDeviceEvents = (context, method) => (device) => {
527
- device.removeAllListeners();
528
- device.on(events_2.DEVICE.BUTTON, onDeviceButtonHandler(device, context, method));
529
- device.on(events_2.DEVICE.PIN, onDevicePinHandler(device, context));
530
- device.on(events_2.DEVICE.WORD, onDeviceWordHandler(device, context));
531
- device.on(events_2.DEVICE.PASSPHRASE, (method?.useEmptyPassphrase ? onEmptyPassphraseHandler : onDevicePassphraseHandler)(device, context));
532
- device.on(events_2.DEVICE.PASSPHRASE_ON_DEVICE, () => {
533
- context.sendCoreMessage((0, events_2.createUiMessage)(events_2.UI.REQUEST_PASSPHRASE_ON_DEVICE, {
534
- device: device.toMessageObject(),
535
- }));
536
- });
537
- device.on(events_2.DEVICE.FIRMWARE_VERSION_CHANGED, payload => {
538
- context.sendCoreMessage((0, events_2.createDeviceMessage)(events_2.DEVICE.FIRMWARE_VERSION_CHANGED, payload));
598
+ const onThpPairingHandler = (device, context) => async ({
599
+ callback,
600
+ payload
601
+ }) => {
602
+ const {
603
+ uiPromises,
604
+ sendCoreMessage
605
+ } = context;
606
+ await waitForPopup(context);
607
+ const uiPromise = uiPromises.create(events_2.UI.RECEIVE_THP_PAIRING_TAG, device);
608
+ sendCoreMessage((0, events_2.createUiMessage)(events_2.UI.REQUEST_THP_PAIRING, {
609
+ device: device.toMessageObject(),
610
+ ...payload
611
+ }));
612
+ try {
613
+ const uiResp = await uiPromise.promise;
614
+ if (uiResp.payload == null) {
615
+ callback({
616
+ success: false,
617
+ error: new Error(`${events_2.UI.RECEIVE_THP_PAIRING_TAG} missing payload`)
618
+ });
619
+ } else {
620
+ callback({
621
+ success: true,
622
+ payload: uiResp.payload
623
+ });
624
+ }
625
+ } catch (error) {
626
+ callback({
627
+ success: false,
628
+ error
539
629
  });
540
- device.on(events_2.DEVICE.THP_PAIRING, onThpPairingHandler(device, context));
541
- device.on(events_2.DEVICE.THP_CREDENTIALS_CHANGED, onThpCredentialsChangedHandler(device, context));
630
+ }
631
+ };
632
+ const onThpCredentialsChangedHandler = (device, context) => payload => {
633
+ const {
634
+ sendCoreMessage
635
+ } = context;
636
+ sendCoreMessage((0, events_2.createDeviceMessage)(events_2.DEVICE.THP_CREDENTIALS_CHANGED, {
637
+ device: device.toMessageObject(),
638
+ ...payload
639
+ }));
640
+ };
641
+ const registerDeviceEvents = (context, method) => device => {
642
+ device.removeAllListeners();
643
+ device.on(events_2.DEVICE.BUTTON, onDeviceButtonHandler(device, context, method));
644
+ device.on(events_2.DEVICE.PIN, onDevicePinHandler(device, context));
645
+ device.on(events_2.DEVICE.WORD, onDeviceWordHandler(device, context));
646
+ device.on(events_2.DEVICE.PASSPHRASE, (method?.useEmptyPassphrase ? onEmptyPassphraseHandler : onDevicePassphraseHandler)(device, context));
647
+ device.on(events_2.DEVICE.PASSPHRASE_ON_DEVICE, () => {
648
+ context.sendCoreMessage((0, events_2.createUiMessage)(events_2.UI.REQUEST_PASSPHRASE_ON_DEVICE, {
649
+ device: device.toMessageObject()
650
+ }));
651
+ });
652
+ device.on(events_2.DEVICE.FIRMWARE_VERSION_CHANGED, payload => {
653
+ context.sendCoreMessage((0, events_2.createDeviceMessage)(events_2.DEVICE.FIRMWARE_VERSION_CHANGED, payload));
654
+ });
655
+ device.on(events_2.DEVICE.THP_PAIRING, onThpPairingHandler(device, context));
656
+ device.on(events_2.DEVICE.THP_CREDENTIALS_CHANGED, onThpCredentialsChangedHandler(device, context));
542
657
  };
543
658
  const onPopupClosed = (context, customErrorMessage) => {
544
- const { uiPromises, popupPromise, deviceList, callMethods, resetWaitForFirstMethod, sendCoreMessage, } = context;
545
- const error = customErrorMessage
546
- ? constants_1.ERRORS.TypedError('Method_Cancel', customErrorMessage)
547
- : constants_1.ERRORS.TypedError('Method_Interrupted');
548
- if (deviceList.isConnected() && deviceList.getDeviceCount() > 0) {
549
- deviceList.getAllDevices().forEach(d => {
550
- if (d.isUsedHere()) {
551
- d.interrupt(error);
552
- }
553
- else {
554
- const success = uiPromises.resolve({ type: events_2.DEVICE.DISCONNECT, payload: undefined });
555
- if (!success) {
556
- callMethods.forEach(m => {
557
- sendCoreMessage((0, events_2.createResponseMessage)(m.responseID, false, { error }));
558
- });
559
- callMethods.splice(0, callMethods.length);
560
- resetWaitForFirstMethod();
561
- }
562
- }
659
+ const {
660
+ uiPromises,
661
+ popupPromise,
662
+ deviceList,
663
+ callMethods,
664
+ resetWaitForFirstMethod,
665
+ sendCoreMessage
666
+ } = context;
667
+ const error = customErrorMessage ? constants_1.ERRORS.TypedError('Method_Cancel', customErrorMessage) : constants_1.ERRORS.TypedError('Method_Interrupted');
668
+ if (deviceList.isConnected() && deviceList.getDeviceCount() > 0) {
669
+ deviceList.getAllDevices().forEach(d => {
670
+ if (d.isUsedHere()) {
671
+ d.interrupt(error);
672
+ } else {
673
+ const success = uiPromises.resolve({
674
+ type: events_2.DEVICE.DISCONNECT,
675
+ payload: undefined
563
676
  });
564
- }
565
- else {
566
- uiPromises.rejectAll(error);
567
- popupPromise.reject(error);
568
- }
569
- cleanup(context);
570
- };
571
- const handleDeviceSelectionChanges = (context, interruptDevice) => {
572
- const { uiPromises, deviceList, sendCoreMessage } = context;
573
- const promiseExists = uiPromises.exists(events_2.UI.RECEIVE_DEVICE);
574
- if (promiseExists && deviceList.isConnected()) {
575
- const onlyDevice = deviceList.getOnlyDevice();
576
- const isWebUsb = deviceList.getActiveTransports().some(t => t.type === 'WebUsbTransport');
577
- if (onlyDevice && !isWebUsb) {
578
- uiPromises.resolve({
579
- type: events_2.UI.RECEIVE_DEVICE,
580
- payload: { device: onlyDevice.toMessageObject() },
581
- });
582
- }
583
- else {
584
- sendCoreMessage((0, events_2.createUiMessage)(events_2.UI.SELECT_DEVICE, {
585
- webusb: isWebUsb,
586
- devices: deviceList.getAllDevices().map(d => d.toMessageObject()),
677
+ if (!success) {
678
+ callMethods.forEach(m => {
679
+ sendCoreMessage((0, events_2.createResponseMessage)(m.responseID, false, {
680
+ error
587
681
  }));
682
+ });
683
+ callMethods.splice(0, callMethods.length);
684
+ resetWaitForFirstMethod();
588
685
  }
589
- }
590
- if (interruptDevice) {
591
- const { path } = interruptDevice;
592
- const shouldClosePopup = uiPromises.disconnected(path);
593
- if (shouldClosePopup) {
594
- closePopup(context);
595
- cleanup(context);
596
- }
597
- }
598
- };
599
- const initDeviceList = (context) => {
600
- const { deviceList, sendCoreMessage } = context;
601
- deviceList.on(events_2.DEVICE.CONNECT, device => {
602
- handleDeviceSelectionChanges(context);
603
- sendCoreMessage((0, events_2.createDeviceMessage)(events_2.DEVICE.CONNECT, device.toMessageObject()));
604
- });
605
- deviceList.on(events_2.DEVICE.CONNECT_UNACQUIRED, device => {
606
- handleDeviceSelectionChanges(context);
607
- sendCoreMessage((0, events_2.createDeviceMessage)(events_2.DEVICE.CONNECT_UNACQUIRED, device.toMessageObject()));
608
- });
609
- deviceList.on(events_2.DEVICE.DISCONNECT, device => {
610
- handleDeviceSelectionChanges(context);
611
- sendCoreMessage((0, events_2.createDeviceMessage)(events_2.DEVICE.DISCONNECT, device.toMessageObject()));
612
- });
613
- deviceList.on(events_2.DEVICE.CHANGED, device => {
614
- sendCoreMessage((0, events_2.createDeviceMessage)(events_2.DEVICE.CHANGED, device.toMessageObject()));
615
- });
616
- deviceList.on(events_2.DEVICE.TREZOR_PUSH_NOTIFICATION, payload => {
617
- sendCoreMessage((0, events_2.createDeviceMessage)(events_2.DEVICE.TREZOR_PUSH_NOTIFICATION, {
618
- device: payload.device.toMessageObject(),
619
- mode: payload.mode,
620
- type: payload.type,
621
- }));
622
- });
623
- deviceList.on(transport_1.TRANSPORT.START, transport => sendCoreMessage((0, events_2.createTransportMessage)(transport_1.TRANSPORT.START, transport)));
624
- deviceList.on(transport_1.TRANSPORT.ERROR, error => {
625
- _log.warn('TRANSPORT.ERROR', error.error);
626
- sendCoreMessage((0, events_2.createTransportMessage)(transport_1.TRANSPORT.ERROR, error));
686
+ }
627
687
  });
688
+ } else {
689
+ uiPromises.rejectAll(error);
690
+ popupPromise.reject(error);
691
+ }
692
+ cleanup(context);
693
+ };
694
+ const handleDeviceSelectionChanges = (context, interruptDevice) => {
695
+ const {
696
+ uiPromises,
697
+ deviceList,
698
+ sendCoreMessage
699
+ } = context;
700
+ const promiseExists = uiPromises.exists(events_2.UI.RECEIVE_DEVICE);
701
+ if (promiseExists && deviceList.isConnected()) {
702
+ const onlyDevice = deviceList.getOnlyDevice();
703
+ const isWebUsb = deviceList.getActiveTransports().some(t => t.type === 'WebUsbTransport');
704
+ if (onlyDevice && !isWebUsb) {
705
+ uiPromises.resolve({
706
+ type: events_2.UI.RECEIVE_DEVICE,
707
+ payload: {
708
+ device: onlyDevice.toMessageObject()
709
+ }
710
+ });
711
+ } else {
712
+ sendCoreMessage((0, events_2.createUiMessage)(events_2.UI.SELECT_DEVICE, {
713
+ webusb: isWebUsb,
714
+ devices: deviceList.getAllDevices().map(d => d.toMessageObject())
715
+ }));
716
+ }
717
+ }
718
+ if (interruptDevice) {
719
+ const {
720
+ path
721
+ } = interruptDevice;
722
+ const shouldClosePopup = uiPromises.disconnected(path);
723
+ if (shouldClosePopup) {
724
+ closePopup(context);
725
+ cleanup(context);
726
+ }
727
+ }
728
+ };
729
+ const initDeviceList = context => {
730
+ const {
731
+ deviceList,
732
+ sendCoreMessage
733
+ } = context;
734
+ deviceList.on(events_2.DEVICE.CONNECT, device => {
735
+ handleDeviceSelectionChanges(context);
736
+ sendCoreMessage((0, events_2.createDeviceMessage)(events_2.DEVICE.CONNECT, device.toMessageObject()));
737
+ });
738
+ deviceList.on(events_2.DEVICE.CONNECT_UNACQUIRED, device => {
739
+ handleDeviceSelectionChanges(context);
740
+ sendCoreMessage((0, events_2.createDeviceMessage)(events_2.DEVICE.CONNECT_UNACQUIRED, device.toMessageObject()));
741
+ });
742
+ deviceList.on(events_2.DEVICE.DISCONNECT, device => {
743
+ handleDeviceSelectionChanges(context);
744
+ sendCoreMessage((0, events_2.createDeviceMessage)(events_2.DEVICE.DISCONNECT, device.toMessageObject()));
745
+ });
746
+ deviceList.on(events_2.DEVICE.CHANGED, device => {
747
+ sendCoreMessage((0, events_2.createDeviceMessage)(events_2.DEVICE.CHANGED, device.toMessageObject()));
748
+ });
749
+ deviceList.on(events_2.DEVICE.TREZOR_PUSH_NOTIFICATION, payload => {
750
+ sendCoreMessage((0, events_2.createDeviceMessage)(events_2.DEVICE.TREZOR_PUSH_NOTIFICATION, {
751
+ device: payload.device.toMessageObject(),
752
+ mode: payload.mode,
753
+ type: payload.type
754
+ }));
755
+ });
756
+ deviceList.on(transport_1.TRANSPORT.START, transport => sendCoreMessage((0, events_2.createTransportMessage)(transport_1.TRANSPORT.START, transport)));
757
+ deviceList.on(transport_1.TRANSPORT.ERROR, error => {
758
+ _log.warn('TRANSPORT.ERROR', error.error);
759
+ sendCoreMessage((0, events_2.createTransportMessage)(transport_1.TRANSPORT.ERROR, error));
760
+ });
628
761
  };
629
762
  class Core extends events_1.default {
630
- abortController = new AbortController();
631
- callMethods = [];
632
- popupPromise = (0, popupPromiseManager_1.createPopupPromiseManager)();
633
- methodSynchronize = (0, utils_1.getSynchronize)();
634
- uiPromises = (0, uiPromiseManager_1.createUiPromiseManager)(() => startInteractionTimeout(this.getCoreContext()));
635
- waitForFirstMethod = (0, utils_1.createDeferred)();
636
- _interactionTimeout;
637
- get interactionTimeout() {
638
- return this._interactionTimeout ?? (0, utils_1.throwError)('Core not initialized: interactionTimeout');
639
- }
640
- _deviceList;
641
- get deviceList() {
642
- return this._deviceList ?? (0, utils_1.throwError)('Core not initialized: deviceList');
643
- }
644
- sendCoreMessage(message) {
645
- if (message.event === events_2.RESPONSE_EVENT) {
646
- const index = this.callMethods.findIndex(call => call && call.responseID === message.id);
647
- if (index >= 0) {
648
- this.callMethods.splice(index, 1);
649
- if (this.callMethods.length === 0) {
650
- this.waitForFirstMethod = (0, utils_1.createDeferred)();
651
- }
652
- }
653
- }
654
- this.emit(events_2.CORE_EVENT, message);
655
- }
656
- getCoreContext() {
657
- return {
658
- signal: this.abortController.signal,
659
- uiPromises: this.uiPromises,
660
- popupPromise: this.popupPromise,
661
- interactionTimeout: this.interactionTimeout,
662
- deviceList: this.deviceList,
663
- callMethods: this.callMethods,
664
- methodSynchronize: this.methodSynchronize,
665
- sendCoreMessage: this.sendCoreMessage.bind(this),
666
- resetWaitForFirstMethod: () => {
667
- this.waitForFirstMethod = (0, utils_1.createDeferred)();
668
- },
669
- resolveWaitForFirstMethod: () => {
670
- this.waitForFirstMethod.resolve();
671
- },
672
- };
673
- }
674
- handleMessage(message) {
675
- _log.debug('handleMessage', message.type);
676
- switch (message.type) {
677
- case events_2.POPUP.HANDSHAKE:
678
- this.popupPromise.resolve();
679
- break;
680
- case events_2.POPUP.CLOSED:
681
- this.popupPromise.clear();
682
- onPopupClosed(this.getCoreContext(), message.payload ? message.payload.error : null);
683
- break;
684
- case transport_1.TRANSPORT.DISABLE_WEBUSB: {
685
- const settings = DataManager_1.DataManager.getSettings();
686
- const transports = settings.transports?.filter(t => t !== 'WebUsbTransport');
687
- if (transports && !transports.includes('BridgeTransport')) {
688
- transports.unshift('BridgeTransport');
689
- }
690
- settings.transports = transports;
691
- resetTransports(this.getCoreContext());
692
- break;
693
- }
694
- case transport_1.TRANSPORT.SET_TRANSPORTS:
695
- DataManager_1.DataManager.getSettings().transports = message.payload.transports;
696
- resetTransports(this.getCoreContext());
697
- break;
698
- case transport_1.TRANSPORT.REQUEST_DEVICE:
699
- if (this.deviceList.isConnected()) {
700
- this.deviceList.enumerate();
701
- }
702
- break;
703
- case transport_1.TRANSPORT.GET_INFO:
704
- this.sendCoreMessage((0, events_2.createResponseMessage)(message.id, true, this.getActiveTransports()));
705
- break;
706
- case events_2.UI.RECEIVE_DEVICE:
707
- case events_2.UI.RECEIVE_CONFIRMATION:
708
- case events_2.UI.RECEIVE_PERMISSION:
709
- case events_2.UI.RECEIVE_PIN:
710
- case events_2.UI.RECEIVE_PASSPHRASE:
711
- case events_2.UI.INVALID_PASSPHRASE_ACTION:
712
- case events_2.UI.RECEIVE_THP_PAIRING_TAG:
713
- case events_2.UI.RECEIVE_ACCOUNT:
714
- case events_2.UI.RECEIVE_FEE:
715
- case events_2.UI.RECEIVE_WORD:
716
- case events_2.UI.LOGIN_CHALLENGE_RESPONSE:
717
- this.uiPromises.resolve(message);
718
- break;
719
- case events_2.UI.RECEIVE_FIRMWARE: {
720
- const localFirmwares = message.payload && (0, connectSettings_1.parseLocalFirmwares)(message.payload);
721
- if (localFirmwares) {
722
- DataManager_1.DataManager.setLocalFirmwares(localFirmwares);
723
- }
724
- break;
725
- }
726
- case events_2.IFRAME.CALL:
727
- if (message.payload.method === 'firmwareUpdate') {
728
- (0, DeviceList_1.assertDeviceListConnected)(this.deviceList);
729
- const coreContext = this.getCoreContext();
730
- (0, onCallFirmwareUpdate_1.onCallFirmwareUpdate)({
731
- params: message.payload,
732
- context: {
733
- deviceList: this.deviceList,
734
- postMessage: this.sendCoreMessage.bind(this),
735
- initDevice: path => initDevice(coreContext, { path }),
736
- log: _log,
737
- abortSignal: this.abortController.signal,
738
- registerEvents: registerDeviceEvents(coreContext),
739
- uiPromises: coreContext.uiPromises,
740
- },
741
- })
742
- .then(payload => {
743
- this.sendCoreMessage((0, events_2.createResponseMessage)(message.id, true, payload));
744
- })
745
- .catch(error => {
746
- this.sendCoreMessage((0, events_2.createResponseMessage)(message.id, false, { error }));
747
- _log.error('onCallFirmwareUpdate', error);
748
- });
749
- }
750
- else {
751
- onCall(this.getCoreContext(), message).catch(error => {
752
- _log.error('onCall', error);
753
- });
754
- }
755
- }
756
- }
757
- dispose() {
758
- (0, BlockchainLink_1.dispose)();
759
- this.removeAllListeners();
760
- this.abortController.abort();
761
- this.deviceList.dispose();
762
- }
763
- async getCurrentMethod() {
764
- await this.waitForFirstMethod.promise;
765
- return await this.methodSynchronize(() => this.callMethods[0]);
766
- }
767
- getActiveTransports() {
768
- if (this.deviceList.isConnected()) {
769
- return this.deviceList.getActiveTransports();
770
- }
771
- }
772
- enumerate() {
763
+ abortController = new AbortController();
764
+ callMethods = [];
765
+ popupPromise = (0, popupPromiseManager_1.createPopupPromiseManager)();
766
+ methodSynchronize = (0, utils_1.getSynchronize)();
767
+ uiPromises = (0, uiPromiseManager_1.createUiPromiseManager)(() => startInteractionTimeout(this.getCoreContext()));
768
+ waitForFirstMethod = (0, utils_1.createDeferred)();
769
+ _interactionTimeout;
770
+ get interactionTimeout() {
771
+ return this._interactionTimeout ?? (0, utils_1.throwError)('Core not initialized: interactionTimeout');
772
+ }
773
+ _deviceList;
774
+ get deviceList() {
775
+ return this._deviceList ?? (0, utils_1.throwError)('Core not initialized: deviceList');
776
+ }
777
+ sendCoreMessage(message) {
778
+ if (message.event === events_2.RESPONSE_EVENT) {
779
+ const index = this.callMethods.findIndex(call => call && call.responseID === message.id);
780
+ if (index >= 0) {
781
+ this.callMethods.splice(index, 1);
782
+ if (this.callMethods.length === 0) {
783
+ this.waitForFirstMethod = (0, utils_1.createDeferred)();
784
+ }
785
+ }
786
+ }
787
+ this.emit(events_2.CORE_EVENT, message);
788
+ }
789
+ getCoreContext() {
790
+ return {
791
+ signal: this.abortController.signal,
792
+ uiPromises: this.uiPromises,
793
+ popupPromise: this.popupPromise,
794
+ interactionTimeout: this.interactionTimeout,
795
+ deviceList: this.deviceList,
796
+ callMethods: this.callMethods,
797
+ methodSynchronize: this.methodSynchronize,
798
+ sendCoreMessage: this.sendCoreMessage.bind(this),
799
+ resetWaitForFirstMethod: () => {
800
+ this.waitForFirstMethod = (0, utils_1.createDeferred)();
801
+ },
802
+ resolveWaitForFirstMethod: () => {
803
+ this.waitForFirstMethod.resolve();
804
+ }
805
+ };
806
+ }
807
+ handleMessage(message) {
808
+ _log.debug('handleMessage', message.type);
809
+ switch (message.type) {
810
+ case events_2.POPUP.HANDSHAKE:
811
+ this.popupPromise.resolve();
812
+ break;
813
+ case events_2.POPUP.CLOSED:
814
+ this.popupPromise.clear();
815
+ onPopupClosed(this.getCoreContext(), message.payload ? message.payload.error : null);
816
+ break;
817
+ case transport_1.TRANSPORT.DISABLE_WEBUSB:
818
+ {
819
+ const settings = DataManager_1.DataManager.getSettings();
820
+ const transports = settings.transports?.filter(t => t !== 'WebUsbTransport');
821
+ if (transports && !transports.includes('BridgeTransport')) {
822
+ transports.unshift('BridgeTransport');
823
+ }
824
+ settings.transports = transports;
825
+ resetTransports(this.getCoreContext());
826
+ break;
827
+ }
828
+ case transport_1.TRANSPORT.SET_TRANSPORTS:
829
+ DataManager_1.DataManager.getSettings().transports = message.payload.transports;
830
+ resetTransports(this.getCoreContext());
831
+ break;
832
+ case transport_1.TRANSPORT.REQUEST_DEVICE:
773
833
  if (this.deviceList.isConnected()) {
774
- this.deviceList.enumerate();
775
- }
776
- }
777
- async init(settings, onCoreEvent, logWriterFactory) {
778
- if (logWriterFactory) {
779
- (0, debug_1.setLogWriter)(logWriterFactory);
780
- }
781
- const throttlePromise = (0, utils_1.createDeferred)();
782
- throttlePromise.promise.catch(() => { });
783
- const onCoreEventThrottled = (message) => throttlePromise.promise.then(() => onCoreEvent(message));
784
- try {
785
- await DataManager_1.DataManager.load(settings);
786
- const localFirmwares = settings.localFirmwares && (0, connectSettings_1.parseLocalFirmwares)(settings.localFirmwares);
787
- if (localFirmwares) {
788
- DataManager_1.DataManager.setLocalFirmwares(localFirmwares);
834
+ this.deviceList.enumerate();
835
+ }
836
+ break;
837
+ case transport_1.TRANSPORT.GET_INFO:
838
+ this.sendCoreMessage((0, events_2.createResponseMessage)(message.id, true, this.getActiveTransports()));
839
+ break;
840
+ case events_2.UI.RECEIVE_DEVICE:
841
+ case events_2.UI.RECEIVE_CONFIRMATION:
842
+ case events_2.UI.RECEIVE_PERMISSION:
843
+ case events_2.UI.RECEIVE_PIN:
844
+ case events_2.UI.RECEIVE_PASSPHRASE:
845
+ case events_2.UI.INVALID_PASSPHRASE_ACTION:
846
+ case events_2.UI.RECEIVE_THP_PAIRING_TAG:
847
+ case events_2.UI.RECEIVE_ACCOUNT:
848
+ case events_2.UI.RECEIVE_FEE:
849
+ case events_2.UI.RECEIVE_WORD:
850
+ case events_2.UI.LOGIN_CHALLENGE_RESPONSE:
851
+ this.uiPromises.resolve(message);
852
+ break;
853
+ case events_2.UI.RECEIVE_FIRMWARE:
854
+ {
855
+ const localFirmwares = message.payload && (0, connectSettings_1.parseLocalFirmwares)(message.payload);
856
+ if (localFirmwares) {
857
+ DataManager_1.DataManager.setLocalFirmwares(localFirmwares);
858
+ }
859
+ break;
860
+ }
861
+ case events_2.IFRAME.CALL:
862
+ if (message.payload.method === 'firmwareUpdate') {
863
+ (0, DeviceList_1.assertDeviceListConnected)(this.deviceList);
864
+ const coreContext = this.getCoreContext();
865
+ (0, onCallFirmwareUpdate_1.onCallFirmwareUpdate)({
866
+ params: message.payload,
867
+ context: {
868
+ deviceList: this.deviceList,
869
+ postMessage: this.sendCoreMessage.bind(this),
870
+ initDevice: path => initDevice(coreContext, {
871
+ path
872
+ }),
873
+ log: _log,
874
+ abortSignal: this.abortController.signal,
875
+ registerEvents: registerDeviceEvents(coreContext),
876
+ uiPromises: coreContext.uiPromises
789
877
  }
790
- const { debug, priority, manifest } = DataManager_1.DataManager.getSettings();
791
- const messages = DataManager_1.DataManager.getProtobufMessages();
792
- (0, debug_1.enableLog)(debug);
793
- this._interactionTimeout = new interactionTimeout_1.InteractionTimeout(settings.popup ? settings.interactionTimeout : 0);
794
- this._deviceList = new DeviceList_1.DeviceList({
795
- debug,
796
- messages,
797
- priority,
798
- manifest,
799
- });
800
- initDeviceList(this.getCoreContext());
801
- this.on(events_2.CORE_EVENT, onCoreEventThrottled);
802
- }
803
- catch (error) {
804
- _log.error('init', error);
805
- throttlePromise.reject(error);
806
- throw error;
807
- }
808
- const { transports, pendingTransportEvent, transportReconnect, coreMode } = DataManager_1.DataManager.getSettings();
809
- try {
810
- this.deviceList.init({ transports, pendingTransportEvent, transportReconnect });
811
- }
812
- catch (error) {
813
- this.sendCoreMessage((0, events_2.createTransportMessage)(transport_1.TRANSPORT.ERROR, { error }));
814
- throttlePromise.reject(error);
815
- throw error;
816
- }
817
- if (!transportReconnect || coreMode === 'auto') {
818
- await this.deviceList.pendingConnection();
819
- }
820
- this.on(events_2.CORE_EVENT, onCoreEvent);
821
- this.off(events_2.CORE_EVENT, onCoreEventThrottled);
822
- setTimeout(throttlePromise.resolve, 0);
823
- }
878
+ }).then(payload => {
879
+ this.sendCoreMessage((0, events_2.createResponseMessage)(message.id, true, payload));
880
+ }).catch(error => {
881
+ this.sendCoreMessage((0, events_2.createResponseMessage)(message.id, false, {
882
+ error
883
+ }));
884
+ _log.error('onCallFirmwareUpdate', error);
885
+ });
886
+ } else {
887
+ onCall(this.getCoreContext(), message).catch(error => {
888
+ _log.error('onCall', error);
889
+ });
890
+ }
891
+ }
892
+ }
893
+ dispose() {
894
+ (0, BlockchainLink_1.dispose)();
895
+ this.removeAllListeners();
896
+ this.abortController.abort();
897
+ this.deviceList.dispose();
898
+ }
899
+ async getCurrentMethod() {
900
+ await this.waitForFirstMethod.promise;
901
+ return await this.methodSynchronize(() => this.callMethods[0]);
902
+ }
903
+ getActiveTransports() {
904
+ if (this.deviceList.isConnected()) {
905
+ return this.deviceList.getActiveTransports();
906
+ }
907
+ }
908
+ enumerate() {
909
+ if (this.deviceList.isConnected()) {
910
+ this.deviceList.enumerate();
911
+ }
912
+ }
913
+ async init(settings, onCoreEvent, logWriterFactory) {
914
+ if (logWriterFactory) {
915
+ (0, debug_1.setLogWriter)(logWriterFactory);
916
+ }
917
+ const throttlePromise = (0, utils_1.createDeferred)();
918
+ throttlePromise.promise.catch(() => {});
919
+ const onCoreEventThrottled = message => throttlePromise.promise.then(() => onCoreEvent(message));
920
+ try {
921
+ await DataManager_1.DataManager.load(settings);
922
+ const localFirmwares = settings.localFirmwares && (0, connectSettings_1.parseLocalFirmwares)(settings.localFirmwares);
923
+ if (localFirmwares) {
924
+ DataManager_1.DataManager.setLocalFirmwares(localFirmwares);
925
+ }
926
+ const {
927
+ debug,
928
+ priority,
929
+ manifest
930
+ } = DataManager_1.DataManager.getSettings();
931
+ const messages = DataManager_1.DataManager.getProtobufMessages();
932
+ (0, debug_1.enableLog)(debug);
933
+ this._interactionTimeout = new interactionTimeout_1.InteractionTimeout(settings.popup ? settings.interactionTimeout : 0);
934
+ this._deviceList = new DeviceList_1.DeviceList({
935
+ debug,
936
+ messages,
937
+ priority,
938
+ manifest
939
+ });
940
+ initDeviceList(this.getCoreContext());
941
+ this.on(events_2.CORE_EVENT, onCoreEventThrottled);
942
+ } catch (error) {
943
+ _log.error('init', error);
944
+ throttlePromise.reject(error);
945
+ throw error;
946
+ }
947
+ const {
948
+ transports,
949
+ pendingTransportEvent,
950
+ transportReconnect,
951
+ coreMode
952
+ } = DataManager_1.DataManager.getSettings();
953
+ try {
954
+ this.deviceList.init({
955
+ transports,
956
+ pendingTransportEvent,
957
+ transportReconnect
958
+ });
959
+ } catch (error) {
960
+ this.sendCoreMessage((0, events_2.createTransportMessage)(transport_1.TRANSPORT.ERROR, {
961
+ error
962
+ }));
963
+ throttlePromise.reject(error);
964
+ throw error;
965
+ }
966
+ if (!transportReconnect || coreMode === 'auto') {
967
+ await this.deviceList.pendingConnection();
968
+ }
969
+ this.on(events_2.CORE_EVENT, onCoreEvent);
970
+ this.off(events_2.CORE_EVENT, onCoreEventThrottled);
971
+ setTimeout(throttlePromise.resolve, 0);
972
+ }
824
973
  }
825
974
  exports.Core = Core;
826
- const resetTransports = async ({ deviceList, sendCoreMessage }) => {
827
- const { transports, pendingTransportEvent, transportReconnect } = DataManager_1.DataManager.getSettings();
828
- try {
829
- await deviceList.init({ transports, pendingTransportEvent, transportReconnect });
830
- }
831
- catch (error) {
832
- sendCoreMessage((0, events_2.createTransportMessage)(transport_1.TRANSPORT.ERROR, { error }));
833
- }
975
+ const resetTransports = async ({
976
+ deviceList,
977
+ sendCoreMessage
978
+ }) => {
979
+ const {
980
+ transports,
981
+ pendingTransportEvent,
982
+ transportReconnect
983
+ } = DataManager_1.DataManager.getSettings();
984
+ try {
985
+ await deviceList.init({
986
+ transports,
987
+ pendingTransportEvent,
988
+ transportReconnect
989
+ });
990
+ } catch (error) {
991
+ sendCoreMessage((0, events_2.createTransportMessage)(transport_1.TRANSPORT.ERROR, {
992
+ error
993
+ }));
994
+ }
834
995
  };
835
996
  const initCore = async (...params) => {
836
- const core = new Core();
837
- await core.init(...params);
838
- return core;
997
+ const core = new Core();
998
+ await core.init(...params);
999
+ return core;
839
1000
  };
840
- const disposeCore = (core) => {
841
- core.dispose();
1001
+ const disposeCore = core => {
1002
+ core.dispose();
842
1003
  };
843
1004
  const initCoreState = () => (0, utils_1.createLazy)(initCore, disposeCore);
844
1005
  exports.initCoreState = initCoreState;