@onekeyfe/hd-core 1.1.26-alpha.2 → 1.1.26-alpha.30

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 (158) hide show
  1. package/__tests__/protocol-v2.test.ts +912 -0
  2. package/dist/api/DirList.d.ts +10 -0
  3. package/dist/api/DirList.d.ts.map +1 -0
  4. package/dist/api/DirMake.d.ts +9 -0
  5. package/dist/api/DirMake.d.ts.map +1 -0
  6. package/dist/api/DirRemove.d.ts +9 -0
  7. package/dist/api/DirRemove.d.ts.map +1 -0
  8. package/dist/api/FileDelete.d.ts +9 -0
  9. package/dist/api/FileDelete.d.ts.map +1 -0
  10. package/dist/api/FileRead.d.ts +19 -0
  11. package/dist/api/FileRead.d.ts.map +1 -0
  12. package/dist/api/FileWrite.d.ts +23 -0
  13. package/dist/api/FileWrite.d.ts.map +1 -0
  14. package/dist/api/FirmwareUpdateV3.d.ts +1 -0
  15. package/dist/api/FirmwareUpdateV3.d.ts.map +1 -1
  16. package/dist/api/FirmwareUpdateV4.d.ts +32 -0
  17. package/dist/api/FirmwareUpdateV4.d.ts.map +1 -0
  18. package/dist/api/GetOnekeyFeatures.d.ts.map +1 -1
  19. package/dist/api/PathInfo.d.ts +9 -0
  20. package/dist/api/PathInfo.d.ts.map +1 -0
  21. package/dist/api/SearchDevices.d.ts +2 -1
  22. package/dist/api/SearchDevices.d.ts.map +1 -1
  23. package/dist/api/alephium/AlephiumSignTransaction.d.ts +1 -1
  24. package/dist/api/alephium/AlephiumSignTransaction.d.ts.map +1 -1
  25. package/dist/api/device/DeviceRebootToBoardloader.d.ts +1 -1
  26. package/dist/api/device/DeviceRebootToBoardloader.d.ts.map +1 -1
  27. package/dist/api/device/DeviceRebootToBootloader.d.ts.map +1 -1
  28. package/dist/api/firmware/FirmwareUpdateBaseMethod.d.ts +10 -2
  29. package/dist/api/firmware/FirmwareUpdateBaseMethod.d.ts.map +1 -1
  30. package/dist/api/index.d.ts +27 -0
  31. package/dist/api/index.d.ts.map +1 -1
  32. package/dist/api/protocol-v2/DevFirmwareUpdate.d.ts +7 -0
  33. package/dist/api/protocol-v2/DevFirmwareUpdate.d.ts.map +1 -0
  34. package/dist/api/protocol-v2/DevGetDeviceInfo.d.ts +7 -0
  35. package/dist/api/protocol-v2/DevGetDeviceInfo.d.ts.map +1 -0
  36. package/dist/api/protocol-v2/DevGetFirmwareUpdateStatus.d.ts +6 -0
  37. package/dist/api/protocol-v2/DevGetFirmwareUpdateStatus.d.ts.map +1 -0
  38. package/dist/api/protocol-v2/DevGetOnboardingStatus.d.ts +6 -0
  39. package/dist/api/protocol-v2/DevGetOnboardingStatus.d.ts.map +1 -0
  40. package/dist/api/protocol-v2/DevReboot.d.ts +7 -0
  41. package/dist/api/protocol-v2/DevReboot.d.ts.map +1 -0
  42. package/dist/api/protocol-v2/FactoryDeviceInfoSettings.d.ts +7 -0
  43. package/dist/api/protocol-v2/FactoryDeviceInfoSettings.d.ts.map +1 -0
  44. package/dist/api/protocol-v2/FactoryGetDeviceInfo.d.ts +6 -0
  45. package/dist/api/protocol-v2/FactoryGetDeviceInfo.d.ts.map +1 -0
  46. package/dist/api/protocol-v2/FilesystemFixPermission.d.ts +6 -0
  47. package/dist/api/protocol-v2/FilesystemFixPermission.d.ts.map +1 -0
  48. package/dist/api/protocol-v2/FilesystemFormat.d.ts +6 -0
  49. package/dist/api/protocol-v2/FilesystemFormat.d.ts.map +1 -0
  50. package/dist/api/protocol-v2/GetProtoVersion.d.ts +6 -0
  51. package/dist/api/protocol-v2/GetProtoVersion.d.ts.map +1 -0
  52. package/dist/api/protocol-v2/Ping.d.ts +8 -0
  53. package/dist/api/protocol-v2/Ping.d.ts.map +1 -0
  54. package/dist/api/protocol-v2/helpers.d.ts +49 -0
  55. package/dist/api/protocol-v2/helpers.d.ts.map +1 -0
  56. package/dist/api/ton/TonSignData.d.ts +7 -0
  57. package/dist/api/ton/TonSignData.d.ts.map +1 -0
  58. package/dist/constants/index.d.ts +1 -1
  59. package/dist/constants/index.d.ts.map +1 -1
  60. package/dist/core/index.d.ts.map +1 -1
  61. package/dist/data-manager/DataManager.d.ts +4 -2
  62. package/dist/data-manager/DataManager.d.ts.map +1 -1
  63. package/dist/data-manager/TransportManager.d.ts +2 -1
  64. package/dist/data-manager/TransportManager.d.ts.map +1 -1
  65. package/dist/device/Device.d.ts +5 -3
  66. package/dist/device/Device.d.ts.map +1 -1
  67. package/dist/device/DeviceCommands.d.ts +12 -12
  68. package/dist/device/DeviceCommands.d.ts.map +1 -1
  69. package/dist/device/DeviceConnector.d.ts +2 -1
  70. package/dist/device/DeviceConnector.d.ts.map +1 -1
  71. package/dist/events/ui-request.d.ts +8 -0
  72. package/dist/events/ui-request.d.ts.map +1 -1
  73. package/dist/index.d.ts +207 -23
  74. package/dist/index.js +2815 -182
  75. package/dist/inject.d.ts.map +1 -1
  76. package/dist/protocols/protocol-v2/features.d.ts +56 -0
  77. package/dist/protocols/protocol-v2/features.d.ts.map +1 -0
  78. package/dist/protocols/protocol-v2/firmware.d.ts +12 -0
  79. package/dist/protocols/protocol-v2/firmware.d.ts.map +1 -0
  80. package/dist/protocols/protocol-v2/index.d.ts +3 -0
  81. package/dist/protocols/protocol-v2/index.d.ts.map +1 -0
  82. package/dist/types/api/export.d.ts +2 -1
  83. package/dist/types/api/export.d.ts.map +1 -1
  84. package/dist/types/api/firmwareUpdate.d.ts +7 -0
  85. package/dist/types/api/firmwareUpdate.d.ts.map +1 -1
  86. package/dist/types/api/index.d.ts +30 -1
  87. package/dist/types/api/index.d.ts.map +1 -1
  88. package/dist/types/api/protocolV2.d.ts +123 -0
  89. package/dist/types/api/protocolV2.d.ts.map +1 -0
  90. package/dist/types/api/searchDevices.d.ts +2 -2
  91. package/dist/types/api/searchDevices.d.ts.map +1 -1
  92. package/dist/types/api/tonSignData.d.ts +18 -0
  93. package/dist/types/api/tonSignData.d.ts.map +1 -0
  94. package/dist/types/device.d.ts +1 -1
  95. package/dist/types/device.d.ts.map +1 -1
  96. package/dist/types/params.d.ts +2 -0
  97. package/dist/types/params.d.ts.map +1 -1
  98. package/dist/types/settings.d.ts +1 -1
  99. package/dist/types/settings.d.ts.map +1 -1
  100. package/dist/utils/deviceInfoUtils.d.ts.map +1 -1
  101. package/dist/utils/patch.d.ts +1 -1
  102. package/dist/utils/patch.d.ts.map +1 -1
  103. package/dist/utils/versionUtils.d.ts +1 -1
  104. package/package.json +5 -5
  105. package/src/api/DirList.ts +25 -0
  106. package/src/api/DirMake.ts +20 -0
  107. package/src/api/DirRemove.ts +20 -0
  108. package/src/api/FileDelete.ts +20 -0
  109. package/src/api/FileRead.ts +161 -0
  110. package/src/api/FileWrite.ts +191 -0
  111. package/src/api/FirmwareUpdateV3.ts +21 -4
  112. package/src/api/FirmwareUpdateV4.ts +810 -0
  113. package/src/api/GetOnekeyFeatures.ts +75 -3
  114. package/src/api/PathInfo.ts +24 -0
  115. package/src/api/SearchDevices.ts +7 -2
  116. package/src/api/alephium/AlephiumSignTransaction.ts +6 -5
  117. package/src/api/device/DeviceRebootToBoardloader.ts +10 -1
  118. package/src/api/device/DeviceRebootToBootloader.ts +10 -1
  119. package/src/api/firmware/FirmwareUpdateBaseMethod.ts +27 -4
  120. package/src/api/index.ts +29 -0
  121. package/src/api/protocol-v2/DevFirmwareUpdate.ts +33 -0
  122. package/src/api/protocol-v2/DevGetDeviceInfo.ts +35 -0
  123. package/src/api/protocol-v2/DevGetFirmwareUpdateStatus.ts +18 -0
  124. package/src/api/protocol-v2/DevGetOnboardingStatus.ts +18 -0
  125. package/src/api/protocol-v2/DevReboot.ts +22 -0
  126. package/src/api/protocol-v2/FactoryDeviceInfoSettings.ts +27 -0
  127. package/src/api/protocol-v2/FactoryGetDeviceInfo.ts +18 -0
  128. package/src/api/protocol-v2/FilesystemFixPermission.ts +14 -0
  129. package/src/api/protocol-v2/FilesystemFormat.ts +14 -0
  130. package/src/api/protocol-v2/GetProtoVersion.ts +14 -0
  131. package/src/api/protocol-v2/Ping.ts +16 -0
  132. package/src/api/protocol-v2/helpers.ts +140 -0
  133. package/src/api/ton/TonSignData.ts +60 -0
  134. package/src/constants/index.ts +1 -1
  135. package/src/core/index.ts +19 -2
  136. package/src/data/messages/messages-pro2.json +733 -0
  137. package/src/data/messages/messages.json +98 -0
  138. package/src/data-manager/DataManager.ts +6 -2
  139. package/src/data-manager/TransportManager.ts +29 -3
  140. package/src/device/Device.ts +66 -8
  141. package/src/device/DeviceCommands.ts +160 -26
  142. package/src/device/DeviceConnector.ts +29 -4
  143. package/src/device/DevicePool.ts +1 -1
  144. package/src/events/ui-request.ts +8 -0
  145. package/src/inject.ts +45 -1
  146. package/src/protocols/protocol-v2/features.ts +259 -0
  147. package/src/protocols/protocol-v2/firmware.ts +26 -0
  148. package/src/protocols/protocol-v2/index.ts +2 -0
  149. package/src/types/api/export.ts +2 -0
  150. package/src/types/api/firmwareUpdate.ts +12 -0
  151. package/src/types/api/index.ts +65 -1
  152. package/src/types/api/protocolV2.ts +221 -0
  153. package/src/types/api/searchDevices.ts +2 -2
  154. package/src/types/api/tonSignData.ts +29 -0
  155. package/src/types/device.ts +3 -1
  156. package/src/types/params.ts +7 -0
  157. package/src/types/settings.ts +1 -1
  158. package/src/utils/deviceInfoUtils.ts +9 -5
package/dist/index.js CHANGED
@@ -119,7 +119,7 @@ const inject = ({ call, cancel, dispose, eventEmitter, init, updateSettings, swi
119
119
  };
120
120
  const createCoreApi = (call) => ({
121
121
  getLogs: () => call({ method: 'getLogs' }),
122
- searchDevices: () => call({ method: 'searchDevices' }),
122
+ searchDevices: params => call(Object.assign(Object.assign({}, params), { method: 'searchDevices' })),
123
123
  getFeatures: (connectId, params) => call(Object.assign(Object.assign({}, params), { connectId, method: 'getFeatures' })),
124
124
  getOnekeyFeatures: (connectId, params) => call(Object.assign(Object.assign({}, params), { connectId, method: 'getOnekeyFeatures' })),
125
125
  checkFirmwareRelease: connectId => call({ connectId, method: 'checkFirmwareRelease' }),
@@ -136,6 +136,31 @@ const createCoreApi = (call) => ({
136
136
  deviceFlags: (connectId, params) => call(Object.assign(Object.assign({}, params), { connectId, method: 'deviceFlags' })),
137
137
  deviceRebootToBoardloader: connectId => call({ connectId, method: 'deviceRebootToBoardloader' }),
138
138
  deviceRebootToBootloader: connectId => call({ connectId, method: 'deviceRebootToBootloader' }),
139
+ getProtoVersion: (connectId, params) => call(Object.assign(Object.assign({}, params), { connectId, method: 'getProtoVersion' })),
140
+ ping: (connectId, params) => call(Object.assign(Object.assign({}, params), { connectId, method: 'ping' })),
141
+ devReboot: (connectId, params) => call(Object.assign(Object.assign({}, params), { connectId, method: 'devReboot' })),
142
+ devGetDeviceInfo: (connectId, params) => call(Object.assign(Object.assign({}, params), { connectId, method: 'devGetDeviceInfo' })),
143
+ devGetOnboardingStatus: (connectId, params) => call(Object.assign(Object.assign({}, params), { connectId, method: 'devGetOnboardingStatus' })),
144
+ devFirmwareUpdate: (connectId, params) => call(Object.assign(Object.assign({}, params), { connectId, method: 'devFirmwareUpdate' })),
145
+ devGetFirmwareUpdateStatus: (connectId, params) => call(Object.assign(Object.assign({}, params), { connectId, method: 'devGetFirmwareUpdateStatus' })),
146
+ factoryDeviceInfoSettings: (connectId, params) => call(Object.assign(Object.assign({}, params), { connectId, method: 'factoryDeviceInfoSettings' })),
147
+ factoryGetDeviceInfo: connectId => call({ connectId, method: 'factoryGetDeviceInfo' }),
148
+ filesystemFixPermission: connectId => call({ connectId, method: 'filesystemFixPermission' }),
149
+ fileRead: (connectId, params) => call(Object.assign(Object.assign({}, params), { connectId, method: 'fileRead' })),
150
+ fileWrite: (connectId, params) => call(Object.assign(Object.assign({}, params), { connectId, method: 'fileWrite' })),
151
+ fileDelete: (connectId, params) => call(Object.assign(Object.assign({}, params), { connectId, method: 'fileDelete' })),
152
+ dirList: (connectId, params) => call(Object.assign(Object.assign({}, params), { connectId, method: 'dirList' })),
153
+ dirMake: (connectId, params) => call(Object.assign(Object.assign({}, params), { connectId, method: 'dirMake' })),
154
+ dirRemove: (connectId, params) => call(Object.assign(Object.assign({}, params), { connectId, method: 'dirRemove' })),
155
+ pathInfo: (connectId, params) => call(Object.assign(Object.assign({}, params), { connectId, method: 'pathInfo' })),
156
+ filesystemFileRead: (connectId, params) => call(Object.assign(Object.assign({}, params), { connectId, method: 'filesystemFileRead' })),
157
+ filesystemFileWrite: (connectId, params) => call(Object.assign(Object.assign({}, params), { connectId, method: 'filesystemFileWrite' })),
158
+ filesystemFileDelete: (connectId, params) => call(Object.assign(Object.assign({}, params), { connectId, method: 'filesystemFileDelete' })),
159
+ filesystemDirList: (connectId, params) => call(Object.assign(Object.assign({}, params), { connectId, method: 'filesystemDirList' })),
160
+ filesystemDirMake: (connectId, params) => call(Object.assign(Object.assign({}, params), { connectId, method: 'filesystemDirMake' })),
161
+ filesystemDirRemove: (connectId, params) => call(Object.assign(Object.assign({}, params), { connectId, method: 'filesystemDirRemove' })),
162
+ filesystemPathInfoQuery: (connectId, params) => call(Object.assign(Object.assign({}, params), { connectId, method: 'filesystemPathInfoQuery' })),
163
+ filesystemFormat: connectId => call({ connectId, method: 'filesystemFormat' }),
139
164
  deviceRecovery: (connectId, params) => call(Object.assign(Object.assign({}, params), { connectId, method: 'deviceRecovery' })),
140
165
  deviceReset: (connectId, params) => call(Object.assign(Object.assign({}, params), { connectId, method: 'deviceReset' })),
141
166
  deviceSettings: (connectId, params) => call(Object.assign(Object.assign({}, params), { connectId, method: 'deviceSettings' })),
@@ -196,6 +221,7 @@ const createCoreApi = (call) => ({
196
221
  firmwareUpdate: (connectId, params) => call(Object.assign(Object.assign({}, params), { connectId, method: 'firmwareUpdate' })),
197
222
  firmwareUpdateV2: (connectId, params) => call(Object.assign(Object.assign({}, params), { connectId, method: 'firmwareUpdateV2' })),
198
223
  firmwareUpdateV3: (connectId, params) => call(Object.assign(Object.assign({}, params), { connectId, method: 'firmwareUpdateV3' })),
224
+ firmwareUpdateV4: (connectId, params) => call(Object.assign(Object.assign({}, params), { connectId, method: 'firmwareUpdateV4' })),
199
225
  promptWebDeviceAccess: params => call(Object.assign(Object.assign({}, params), { method: 'promptWebDeviceAccess' })),
200
226
  tronGetAddress: (connectId, deviceId, params) => call(Object.assign(Object.assign({}, params), { connectId, deviceId, method: 'tronGetAddress' })),
201
227
  tronSignMessage: (connectId, deviceId, params) => call(Object.assign(Object.assign({}, params), { connectId, deviceId, method: 'tronSignMessage' })),
@@ -247,6 +273,7 @@ const createCoreApi = (call) => ({
247
273
  tonGetAddress: (connectId, deviceId, params) => call(Object.assign(Object.assign({}, params), { connectId, deviceId, method: 'tonGetAddress' })),
248
274
  tonSignMessage: (connectId, deviceId, params) => call(Object.assign(Object.assign({}, params), { connectId, deviceId, method: 'tonSignMessage' })),
249
275
  tonSignProof: (connectId, deviceId, params) => call(Object.assign(Object.assign({}, params), { connectId, deviceId, method: 'tonSignProof' })),
276
+ tonSignData: (connectId, deviceId, params) => call(Object.assign(Object.assign({}, params), { connectId, deviceId, method: 'tonSignData' })),
250
277
  scdoGetAddress: (connectId, deviceId, params) => call(Object.assign(Object.assign({}, params), { connectId, deviceId, method: 'scdoGetAddress' })),
251
278
  scdoSignMessage: (connectId, deviceId, params) => call(Object.assign(Object.assign({}, params), { connectId, deviceId, method: 'scdoSignMessage' })),
252
279
  scdoSignTransaction: (connectId, deviceId, params) => call(Object.assign(Object.assign({}, params), { connectId, deviceId, method: 'scdoSignTransaction' })),
@@ -787,7 +814,7 @@ const createLogMessage = (type, payload) => ({
787
814
 
788
815
  const MAX_ENTRIES = 500;
789
816
  let postMessage$1;
790
- class Log$g {
817
+ class Log$h {
791
818
  constructor(prefix, enabled) {
792
819
  this.prefix = prefix;
793
820
  this.enabled = enabled;
@@ -839,7 +866,7 @@ class Log$g {
839
866
  }
840
867
  const _logs = {};
841
868
  const initLog = (prefix, enabled) => {
842
- const instance = new Log$g(prefix, !!enabled);
869
+ const instance = new Log$h(prefix, !!enabled);
843
870
  _logs[prefix] = instance;
844
871
  return instance;
845
872
  };
@@ -1037,7 +1064,7 @@ function patchFeatures(response) {
1037
1064
  return response;
1038
1065
  }
1039
1066
 
1040
- const Log$f = getLogger(exports.LoggerNames.Core);
1067
+ const Log$g = getLogger(exports.LoggerNames.Core);
1041
1068
  let globalInstanceCounter = 0;
1042
1069
  let sdkInstanceCounter = 0;
1043
1070
  function generateSdkInstanceId() {
@@ -1097,7 +1124,7 @@ function completeRequestContext(responseID, error) {
1097
1124
  context.status = error ? 'error' : 'success';
1098
1125
  if (error) {
1099
1126
  context.error = error.message;
1100
- Log$f.error(`[RequestContext] [completeRequestContext] Error: ${formatRequestContext(context)}`);
1127
+ Log$g.error(`[RequestContext] [completeRequestContext] Error: ${formatRequestContext(context)}`);
1101
1128
  }
1102
1129
  globalActiveRequests.delete(responseID);
1103
1130
  if (context.sdkInstanceId) {
@@ -1164,6 +1191,7 @@ const DeviceTypeToModels = {
1164
1191
  [hdShared.EDeviceType.Mini]: ['model_mini'],
1165
1192
  [hdShared.EDeviceType.Touch]: ['model_touch'],
1166
1193
  [hdShared.EDeviceType.Pro]: ['model_touch'],
1194
+ [hdShared.EDeviceType.Pro2]: [],
1167
1195
  [hdShared.EDeviceType.Unknown]: [],
1168
1196
  };
1169
1197
 
@@ -1184,6 +1212,9 @@ const getDeviceType = (features) => {
1184
1212
  return hdShared.EDeviceType.Touch;
1185
1213
  case 'PRO':
1186
1214
  return hdShared.EDeviceType.Pro;
1215
+ case 'PRO2':
1216
+ case 'pro2':
1217
+ return hdShared.EDeviceType.Pro2;
1187
1218
  case 'PURE':
1188
1219
  return hdShared.EDeviceType.ClassicPure;
1189
1220
  default:
@@ -1215,15 +1246,17 @@ const getDeviceType = (features) => {
1215
1246
  const getDeviceTypeByBleName = (name) => {
1216
1247
  if (!name)
1217
1248
  return hdShared.EDeviceType.Unknown;
1218
- if (name.startsWith('BixinKey'))
1249
+ if (/^BixinKey/i.test(name))
1219
1250
  return hdShared.EDeviceType.Classic;
1220
- if (name.startsWith('K'))
1251
+ if (/^K/i.test(name))
1221
1252
  return hdShared.EDeviceType.Classic;
1222
- if (name.startsWith('T'))
1253
+ if (/^T/i.test(name))
1223
1254
  return hdShared.EDeviceType.Touch;
1224
- if (name.startsWith('Touch'))
1255
+ if (/^Touch/i.test(name))
1225
1256
  return hdShared.EDeviceType.Touch;
1226
- if (name.startsWith('Pro'))
1257
+ if (/\bPro\s*2\b/i.test(name) || /^Pro2/i.test(name))
1258
+ return hdShared.EDeviceType.Pro2;
1259
+ if (/\bPro\b/i.test(name) || /^Pro/i.test(name))
1227
1260
  return hdShared.EDeviceType.Pro;
1228
1261
  return hdShared.EDeviceType.Unknown;
1229
1262
  };
@@ -1456,7 +1489,7 @@ const validatePath = (path, length = 0, base = false) => {
1456
1489
  return base ? valid.splice(0, 3) : valid;
1457
1490
  };
1458
1491
 
1459
- var nested$1 = {
1492
+ var nested$2 = {
1460
1493
  AlephiumGetAddress: {
1461
1494
  fields: {
1462
1495
  address_n: {
@@ -13068,6 +13101,102 @@ var nested$1 = {
13068
13101
  }
13069
13102
  }
13070
13103
  },
13104
+ TonSignData: {
13105
+ fields: {
13106
+ address_n: {
13107
+ rule: "repeated",
13108
+ type: "uint32",
13109
+ id: 1,
13110
+ options: {
13111
+ packed: false
13112
+ }
13113
+ },
13114
+ type: {
13115
+ rule: "required",
13116
+ type: "TonSignDataType",
13117
+ id: 2
13118
+ },
13119
+ payload: {
13120
+ rule: "required",
13121
+ type: "bytes",
13122
+ id: 3
13123
+ },
13124
+ schema: {
13125
+ type: "string",
13126
+ id: 4
13127
+ },
13128
+ appdomain: {
13129
+ rule: "required",
13130
+ type: "string",
13131
+ id: 5
13132
+ },
13133
+ timestamp: {
13134
+ rule: "required",
13135
+ type: "uint64",
13136
+ id: 6
13137
+ },
13138
+ from_address: {
13139
+ type: "string",
13140
+ id: 7
13141
+ },
13142
+ wallet_version: {
13143
+ type: "TonWalletVersion",
13144
+ id: 8,
13145
+ options: {
13146
+ "default": "V4R2"
13147
+ }
13148
+ },
13149
+ wallet_id: {
13150
+ type: "uint32",
13151
+ id: 9,
13152
+ options: {
13153
+ "default": 698983191
13154
+ }
13155
+ },
13156
+ workchain: {
13157
+ type: "TonWorkChain",
13158
+ id: 10,
13159
+ options: {
13160
+ "default": "BASECHAIN"
13161
+ }
13162
+ },
13163
+ is_bounceable: {
13164
+ type: "bool",
13165
+ id: 11,
13166
+ options: {
13167
+ "default": false
13168
+ }
13169
+ },
13170
+ is_testnet_only: {
13171
+ type: "bool",
13172
+ id: 12,
13173
+ options: {
13174
+ "default": false
13175
+ }
13176
+ }
13177
+ },
13178
+ nested: {
13179
+ TonSignDataType: {
13180
+ values: {
13181
+ TEXT: 0,
13182
+ BINARY: 1,
13183
+ CELL: 2
13184
+ }
13185
+ }
13186
+ }
13187
+ },
13188
+ TonSignedData: {
13189
+ fields: {
13190
+ signature: {
13191
+ type: "bytes",
13192
+ id: 1
13193
+ },
13194
+ digest: {
13195
+ type: "bytes",
13196
+ id: 2
13197
+ }
13198
+ }
13199
+ },
13071
13200
  TronGetAddress: {
13072
13201
  fields: {
13073
13202
  address_n: {
@@ -14003,6 +14132,8 @@ var nested$1 = {
14003
14132
  MessageType_TonSignProof: 11905,
14004
14133
  MessageType_TonSignedProof: 11906,
14005
14134
  MessageType_TonTxAck: 11907,
14135
+ MessageType_TonSignData: 11908,
14136
+ MessageType_TonSignedData: 11909,
14006
14137
  MessageType_ScdoGetAddress: 12001,
14007
14138
  MessageType_ScdoAddress: 12002,
14008
14139
  MessageType_ScdoSignTx: 12003,
@@ -14802,10 +14933,10 @@ var nested$1 = {
14802
14933
  }
14803
14934
  };
14804
14935
  var MessagesJSON = {
14805
- nested: nested$1
14936
+ nested: nested$2
14806
14937
  };
14807
14938
 
14808
- var nested = {
14939
+ var nested$1 = {
14809
14940
  AlgorandGetAddress: {
14810
14941
  fields: {
14811
14942
  address_n: {
@@ -25181,6 +25312,747 @@ var nested = {
25181
25312
  }
25182
25313
  };
25183
25314
  var MessagesLegacyV1JSON = {
25315
+ nested: nested$1
25316
+ };
25317
+
25318
+ var nested = {
25319
+ GetProtoVersion: {
25320
+ fields: {
25321
+ }
25322
+ },
25323
+ ProtoVersion: {
25324
+ fields: {
25325
+ proto_version: {
25326
+ rule: "required",
25327
+ type: "uint32",
25328
+ id: 1
25329
+ }
25330
+ }
25331
+ },
25332
+ Ping: {
25333
+ fields: {
25334
+ message: {
25335
+ type: "string",
25336
+ id: 1,
25337
+ options: {
25338
+ "default": ""
25339
+ }
25340
+ }
25341
+ }
25342
+ },
25343
+ Success: {
25344
+ fields: {
25345
+ message: {
25346
+ type: "string",
25347
+ id: 1,
25348
+ options: {
25349
+ "default": ""
25350
+ }
25351
+ }
25352
+ }
25353
+ },
25354
+ Failure: {
25355
+ fields: {
25356
+ code: {
25357
+ type: "FailureType",
25358
+ id: 1
25359
+ },
25360
+ message: {
25361
+ type: "string",
25362
+ id: 2
25363
+ }
25364
+ },
25365
+ nested: {
25366
+ FailureType: {
25367
+ values: {
25368
+ Failure_UnexpectedMessage: 1,
25369
+ Failure_ButtonExpected: 2,
25370
+ Failure_DataError: 3,
25371
+ Failure_ActionCancelled: 4,
25372
+ Failure_PinExpected: 5,
25373
+ Failure_PinCancelled: 6,
25374
+ Failure_PinInvalid: 7,
25375
+ Failure_InvalidSignature: 8,
25376
+ Failure_ProcessError: 9,
25377
+ Failure_NotEnoughFunds: 10,
25378
+ Failure_NotInitialized: 11,
25379
+ Failure_PinMismatch: 12,
25380
+ Failure_WipeCodeMismatch: 13,
25381
+ Failure_InvalidSession: 14,
25382
+ Failure_FirmwareError: 99
25383
+ }
25384
+ }
25385
+ }
25386
+ },
25387
+ DevRebootType: {
25388
+ values: {
25389
+ Normal: 0,
25390
+ Boardloader: 1,
25391
+ Bootloader: 2
25392
+ }
25393
+ },
25394
+ DevReboot: {
25395
+ fields: {
25396
+ reboot_type: {
25397
+ rule: "required",
25398
+ type: "DevRebootType",
25399
+ id: 1
25400
+ }
25401
+ }
25402
+ },
25403
+ DeviceType: {
25404
+ values: {
25405
+ CLASSIC1: 0,
25406
+ CLASSIC1S: 1,
25407
+ MINI: 2,
25408
+ TOUCH: 3,
25409
+ PRO: 5,
25410
+ CLASSIC1S_PURE: 6
25411
+ }
25412
+ },
25413
+ DevSeType: {
25414
+ values: {
25415
+ THD89: 0,
25416
+ SE608A: 1
25417
+ }
25418
+ },
25419
+ DevSEState: {
25420
+ values: {
25421
+ BOOT: 0,
25422
+ APP_FACTORY: 51,
25423
+ APP: 85
25424
+ }
25425
+ },
25426
+ DevFirmwareImageInfo: {
25427
+ fields: {
25428
+ version: {
25429
+ type: "string",
25430
+ id: 10
25431
+ },
25432
+ build_id: {
25433
+ type: "string",
25434
+ id: 20
25435
+ },
25436
+ hash: {
25437
+ type: "bytes",
25438
+ id: 30
25439
+ }
25440
+ }
25441
+ },
25442
+ DevHardwareInfo: {
25443
+ fields: {
25444
+ device_type: {
25445
+ type: "DeviceType",
25446
+ id: 10
25447
+ },
25448
+ serial_no: {
25449
+ type: "string",
25450
+ id: 11
25451
+ },
25452
+ hardware_version: {
25453
+ type: "string",
25454
+ id: 100
25455
+ },
25456
+ hardware_version_raw_adc: {
25457
+ type: "uint32",
25458
+ id: 101
25459
+ }
25460
+ }
25461
+ },
25462
+ DevMainMcuInfo: {
25463
+ fields: {
25464
+ board: {
25465
+ type: "DevFirmwareImageInfo",
25466
+ id: 10
25467
+ },
25468
+ boot: {
25469
+ type: "DevFirmwareImageInfo",
25470
+ id: 20
25471
+ },
25472
+ app: {
25473
+ type: "DevFirmwareImageInfo",
25474
+ id: 30
25475
+ }
25476
+ }
25477
+ },
25478
+ DevBluetoothInfo: {
25479
+ fields: {
25480
+ boot: {
25481
+ type: "DevFirmwareImageInfo",
25482
+ id: 20
25483
+ },
25484
+ app: {
25485
+ type: "DevFirmwareImageInfo",
25486
+ id: 30
25487
+ },
25488
+ adv_name: {
25489
+ type: "string",
25490
+ id: 100
25491
+ },
25492
+ mac: {
25493
+ type: "bytes",
25494
+ id: 110
25495
+ }
25496
+ }
25497
+ },
25498
+ DevSEInfo: {
25499
+ fields: {
25500
+ boot: {
25501
+ type: "DevFirmwareImageInfo",
25502
+ id: 20
25503
+ },
25504
+ app: {
25505
+ type: "DevFirmwareImageInfo",
25506
+ id: 30
25507
+ },
25508
+ type: {
25509
+ type: "DevSeType",
25510
+ id: 100
25511
+ },
25512
+ state: {
25513
+ type: "DevSEState",
25514
+ id: 110
25515
+ }
25516
+ }
25517
+ },
25518
+ DevInfoTargets: {
25519
+ fields: {
25520
+ hw: {
25521
+ type: "bool",
25522
+ id: 100
25523
+ },
25524
+ fw: {
25525
+ type: "bool",
25526
+ id: 200
25527
+ },
25528
+ bt: {
25529
+ type: "bool",
25530
+ id: 300
25531
+ },
25532
+ se1: {
25533
+ type: "bool",
25534
+ id: 400
25535
+ },
25536
+ se2: {
25537
+ type: "bool",
25538
+ id: 410
25539
+ },
25540
+ se3: {
25541
+ type: "bool",
25542
+ id: 420
25543
+ },
25544
+ se4: {
25545
+ type: "bool",
25546
+ id: 430
25547
+ },
25548
+ status: {
25549
+ type: "bool",
25550
+ id: 10000
25551
+ }
25552
+ }
25553
+ },
25554
+ DevInfoTypes: {
25555
+ fields: {
25556
+ version: {
25557
+ type: "bool",
25558
+ id: 10
25559
+ },
25560
+ build_id: {
25561
+ type: "bool",
25562
+ id: 20
25563
+ },
25564
+ hash: {
25565
+ type: "bool",
25566
+ id: 30
25567
+ },
25568
+ specific: {
25569
+ type: "bool",
25570
+ id: 40
25571
+ }
25572
+ }
25573
+ },
25574
+ DevStatus: {
25575
+ fields: {
25576
+ language: {
25577
+ type: "string",
25578
+ id: 100
25579
+ },
25580
+ bt_enable: {
25581
+ type: "bool",
25582
+ id: 101
25583
+ },
25584
+ init_states: {
25585
+ type: "bool",
25586
+ id: 102
25587
+ },
25588
+ backup_required: {
25589
+ type: "bool",
25590
+ id: 200
25591
+ },
25592
+ passphrase_protection: {
25593
+ type: "bool",
25594
+ id: 201
25595
+ },
25596
+ label: {
25597
+ type: "string",
25598
+ id: 300
25599
+ }
25600
+ }
25601
+ },
25602
+ DevGetDeviceInfo: {
25603
+ fields: {
25604
+ targets: {
25605
+ type: "DevInfoTargets",
25606
+ id: 1
25607
+ },
25608
+ types: {
25609
+ type: "DevInfoTypes",
25610
+ id: 2
25611
+ }
25612
+ }
25613
+ },
25614
+ DeviceInfo: {
25615
+ fields: {
25616
+ protocol_version: {
25617
+ rule: "required",
25618
+ type: "uint32",
25619
+ id: 1
25620
+ },
25621
+ hw: {
25622
+ type: "DevHardwareInfo",
25623
+ id: 100
25624
+ },
25625
+ fw: {
25626
+ type: "DevMainMcuInfo",
25627
+ id: 200
25628
+ },
25629
+ bt: {
25630
+ type: "DevBluetoothInfo",
25631
+ id: 300
25632
+ },
25633
+ se1: {
25634
+ type: "DevSEInfo",
25635
+ id: 400
25636
+ },
25637
+ se2: {
25638
+ type: "DevSEInfo",
25639
+ id: 410
25640
+ },
25641
+ se3: {
25642
+ type: "DevSEInfo",
25643
+ id: 420
25644
+ },
25645
+ se4: {
25646
+ type: "DevSEInfo",
25647
+ id: 430
25648
+ },
25649
+ status: {
25650
+ type: "DevStatus",
25651
+ id: 10000
25652
+ }
25653
+ }
25654
+ },
25655
+ DevGetOnboardingStatus: {
25656
+ fields: {
25657
+ }
25658
+ },
25659
+ DevOnboardingStatus: {
25660
+ fields: {
25661
+ page_index: {
25662
+ type: "uint32",
25663
+ id: 1
25664
+ },
25665
+ page_count: {
25666
+ type: "uint32",
25667
+ id: 2
25668
+ },
25669
+ page_name: {
25670
+ type: "string",
25671
+ id: 3
25672
+ }
25673
+ }
25674
+ },
25675
+ DevFirmwareTargetType: {
25676
+ values: {
25677
+ TARGET_MAIN_APP: 0,
25678
+ TARGET_MAIN_BOOT: 1,
25679
+ TARGET_BT: 2,
25680
+ TARGET_SE1: 3,
25681
+ TARGET_SE2: 4,
25682
+ TARGET_SE3: 5,
25683
+ TARGET_SE4: 6,
25684
+ TARGET_RESOURCE: 10
25685
+ }
25686
+ },
25687
+ DevFirmwareTarget: {
25688
+ fields: {
25689
+ target_id: {
25690
+ rule: "required",
25691
+ type: "DevFirmwareTargetType",
25692
+ id: 1
25693
+ },
25694
+ path: {
25695
+ rule: "required",
25696
+ type: "string",
25697
+ id: 2
25698
+ }
25699
+ }
25700
+ },
25701
+ DevFirmwareUpdate: {
25702
+ fields: {
25703
+ targets: {
25704
+ rule: "repeated",
25705
+ type: "DevFirmwareTarget",
25706
+ id: 1
25707
+ }
25708
+ }
25709
+ },
25710
+ DevFirmwareInstallProgress: {
25711
+ fields: {
25712
+ target_id: {
25713
+ rule: "required",
25714
+ type: "DevFirmwareTargetType",
25715
+ id: 1
25716
+ },
25717
+ progress: {
25718
+ rule: "required",
25719
+ type: "uint32",
25720
+ id: 2
25721
+ },
25722
+ stage: {
25723
+ type: "string",
25724
+ id: 3
25725
+ }
25726
+ }
25727
+ },
25728
+ DevFirmwareUpdateStatusEntry: {
25729
+ fields: {
25730
+ target_id: {
25731
+ rule: "required",
25732
+ type: "DevFirmwareTargetType",
25733
+ id: 1
25734
+ },
25735
+ status: {
25736
+ rule: "required",
25737
+ type: "uint32",
25738
+ id: 2
25739
+ }
25740
+ }
25741
+ },
25742
+ DevGetFirmwareUpdateStatus: {
25743
+ fields: {
25744
+ }
25745
+ },
25746
+ DevFirmwareUpdateStatus: {
25747
+ fields: {
25748
+ targets: {
25749
+ rule: "repeated",
25750
+ type: "DevFirmwareUpdateStatusEntry",
25751
+ id: 1
25752
+ }
25753
+ }
25754
+ },
25755
+ FactoryDeviceInfoSettings: {
25756
+ fields: {
25757
+ serial_no: {
25758
+ type: "string",
25759
+ id: 1
25760
+ },
25761
+ cpu_info: {
25762
+ type: "string",
25763
+ id: 2
25764
+ },
25765
+ pre_firmware: {
25766
+ type: "string",
25767
+ id: 3
25768
+ }
25769
+ }
25770
+ },
25771
+ FactoryGetDeviceInfo: {
25772
+ fields: {
25773
+ }
25774
+ },
25775
+ FactoryDeviceInfo: {
25776
+ fields: {
25777
+ serial_no: {
25778
+ type: "string",
25779
+ id: 1
25780
+ },
25781
+ spi_flash_info: {
25782
+ type: "string",
25783
+ id: 2
25784
+ },
25785
+ se_info: {
25786
+ type: "string",
25787
+ id: 3
25788
+ },
25789
+ nft_voucher: {
25790
+ type: "bytes",
25791
+ id: 4
25792
+ },
25793
+ cpu_info: {
25794
+ type: "string",
25795
+ id: 5
25796
+ },
25797
+ pre_firmware: {
25798
+ type: "string",
25799
+ id: 6
25800
+ }
25801
+ }
25802
+ },
25803
+ FilesystemFixPermission: {
25804
+ fields: {
25805
+ }
25806
+ },
25807
+ FilesystemPathInfo: {
25808
+ fields: {
25809
+ exist: {
25810
+ rule: "required",
25811
+ type: "bool",
25812
+ id: 1
25813
+ },
25814
+ size: {
25815
+ rule: "required",
25816
+ type: "uint64",
25817
+ id: 2
25818
+ },
25819
+ year: {
25820
+ rule: "required",
25821
+ type: "uint32",
25822
+ id: 3
25823
+ },
25824
+ month: {
25825
+ rule: "required",
25826
+ type: "uint32",
25827
+ id: 4
25828
+ },
25829
+ day: {
25830
+ rule: "required",
25831
+ type: "uint32",
25832
+ id: 5
25833
+ },
25834
+ hour: {
25835
+ rule: "required",
25836
+ type: "uint32",
25837
+ id: 6
25838
+ },
25839
+ minute: {
25840
+ rule: "required",
25841
+ type: "uint32",
25842
+ id: 7
25843
+ },
25844
+ second: {
25845
+ rule: "required",
25846
+ type: "uint32",
25847
+ id: 8
25848
+ },
25849
+ readonly: {
25850
+ rule: "required",
25851
+ type: "bool",
25852
+ id: 9
25853
+ },
25854
+ hidden: {
25855
+ rule: "required",
25856
+ type: "bool",
25857
+ id: 10
25858
+ },
25859
+ system: {
25860
+ rule: "required",
25861
+ type: "bool",
25862
+ id: 11
25863
+ },
25864
+ archive: {
25865
+ rule: "required",
25866
+ type: "bool",
25867
+ id: 12
25868
+ },
25869
+ directory: {
25870
+ rule: "required",
25871
+ type: "bool",
25872
+ id: 13
25873
+ }
25874
+ }
25875
+ },
25876
+ FilesystemPathInfoQuery: {
25877
+ fields: {
25878
+ path: {
25879
+ rule: "required",
25880
+ type: "string",
25881
+ id: 1
25882
+ }
25883
+ }
25884
+ },
25885
+ FilesystemFile: {
25886
+ fields: {
25887
+ path: {
25888
+ rule: "required",
25889
+ type: "string",
25890
+ id: 1
25891
+ },
25892
+ offset: {
25893
+ rule: "required",
25894
+ type: "uint32",
25895
+ id: 2
25896
+ },
25897
+ total_size: {
25898
+ rule: "required",
25899
+ type: "uint32",
25900
+ id: 3
25901
+ },
25902
+ data: {
25903
+ type: "bytes",
25904
+ id: 4
25905
+ },
25906
+ data_hash: {
25907
+ type: "uint32",
25908
+ id: 5
25909
+ },
25910
+ processed_byte: {
25911
+ type: "uint32",
25912
+ id: 6
25913
+ }
25914
+ }
25915
+ },
25916
+ FilesystemFileRead: {
25917
+ fields: {
25918
+ file: {
25919
+ rule: "required",
25920
+ type: "FilesystemFile",
25921
+ id: 1
25922
+ },
25923
+ chunk_len: {
25924
+ type: "uint32",
25925
+ id: 2
25926
+ },
25927
+ ui_percentage: {
25928
+ type: "uint32",
25929
+ id: 3
25930
+ }
25931
+ }
25932
+ },
25933
+ FilesystemFileWrite: {
25934
+ fields: {
25935
+ file: {
25936
+ rule: "required",
25937
+ type: "FilesystemFile",
25938
+ id: 1
25939
+ },
25940
+ overwrite: {
25941
+ rule: "required",
25942
+ type: "bool",
25943
+ id: 2
25944
+ },
25945
+ append: {
25946
+ rule: "required",
25947
+ type: "bool",
25948
+ id: 3
25949
+ },
25950
+ ui_percentage: {
25951
+ type: "uint32",
25952
+ id: 4
25953
+ }
25954
+ }
25955
+ },
25956
+ FilesystemFileDelete: {
25957
+ fields: {
25958
+ path: {
25959
+ rule: "required",
25960
+ type: "string",
25961
+ id: 1
25962
+ }
25963
+ }
25964
+ },
25965
+ FilesystemDir: {
25966
+ fields: {
25967
+ path: {
25968
+ rule: "required",
25969
+ type: "string",
25970
+ id: 1
25971
+ },
25972
+ child_dirs: {
25973
+ type: "string",
25974
+ id: 2
25975
+ },
25976
+ child_files: {
25977
+ type: "string",
25978
+ id: 3
25979
+ }
25980
+ }
25981
+ },
25982
+ FilesystemDirList: {
25983
+ fields: {
25984
+ path: {
25985
+ rule: "required",
25986
+ type: "string",
25987
+ id: 1
25988
+ },
25989
+ depth: {
25990
+ type: "uint32",
25991
+ id: 2,
25992
+ options: {
25993
+ "default": 0
25994
+ }
25995
+ }
25996
+ }
25997
+ },
25998
+ FilesystemDirMake: {
25999
+ fields: {
26000
+ path: {
26001
+ rule: "required",
26002
+ type: "string",
26003
+ id: 1
26004
+ }
26005
+ }
26006
+ },
26007
+ FilesystemDirRemove: {
26008
+ fields: {
26009
+ path: {
26010
+ rule: "required",
26011
+ type: "string",
26012
+ id: 1
26013
+ }
26014
+ }
26015
+ },
26016
+ FilesystemFormat: {
26017
+ fields: {
26018
+ }
26019
+ },
26020
+ MessageType: {
26021
+ values: {
26022
+ MessageType_FactoryDeviceInfoSettings: 60000,
26023
+ MessageType_FactoryGetDeviceInfo: 60001,
26024
+ MessageType_FactoryDeviceInfo: 60002,
26025
+ MessageType_GetProtoVersion: 60200,
26026
+ MessageType_ProtoVersion: 60201,
26027
+ MessageType_StartSession: 60205,
26028
+ MessageType_Ping: 60206,
26029
+ MessageType_Success: 60207,
26030
+ MessageType_Failure: 60208,
26031
+ MessageType_DevReboot: 60400,
26032
+ MessageType_DevGetDeviceInfo: 60600,
26033
+ MessageType_DeviceInfo: 60601,
26034
+ MessageType_DevGetOnboardingStatus: 60602,
26035
+ MessageType_DevOnboardingStatus: 60603,
26036
+ MessageType_FilesystemFixPermission: 60800,
26037
+ MessageType_FilesystemPathInfo: 60801,
26038
+ MessageType_FilesystemPathInfoQuery: 60802,
26039
+ MessageType_FilesystemFile: 60803,
26040
+ MessageType_FilesystemFileRead: 60804,
26041
+ MessageType_FilesystemFileWrite: 60805,
26042
+ MessageType_FilesystemFileDelete: 60806,
26043
+ MessageType_FilesystemDir: 60807,
26044
+ MessageType_FilesystemDirList: 60808,
26045
+ MessageType_FilesystemDirMake: 60809,
26046
+ MessageType_FilesystemDirRemove: 60810,
26047
+ MessageType_FilesystemFormat: 60811,
26048
+ MessageType_DevFirmwareUpdate: 61000,
26049
+ MessageType_DevFirmwareInstallProgress: 61001,
26050
+ MessageType_DevGetFirmwareUpdateStatus: 61002,
26051
+ MessageType_DevFirmwareUpdateStatus: 61003
26052
+ }
26053
+ }
26054
+ };
26055
+ var MessagesPro2JSON = {
25184
26056
  nested: nested
25185
26057
  };
25186
26058
 
@@ -25209,7 +26081,7 @@ const findLatestRelease = (releases) => {
25209
26081
  };
25210
26082
 
25211
26083
  var _a$1;
25212
- const Log$e = getLogger(exports.LoggerNames.Core);
26084
+ const Log$f = getLogger(exports.LoggerNames.Core);
25213
26085
  const FIRMWARE_FIELDS = [
25214
26086
  'firmware',
25215
26087
  'firmware-v2',
@@ -25271,37 +26143,37 @@ class DataManager {
25271
26143
  let data = null;
25272
26144
  let fetchMethod = 'none';
25273
26145
  if (settings.configFetcher) {
25274
- Log$e.debug('[DataConfig] Trying configFetcher (client-side fetcher)...');
26146
+ Log$f.debug('[DataConfig] Trying configFetcher (client-side fetcher)...');
25275
26147
  try {
25276
26148
  data = yield settings.configFetcher(urlWithCache);
25277
26149
  if (data) {
25278
26150
  fetchMethod = 'configFetcher';
25279
- Log$e.log('[DataConfig] ConfigFetcher success');
26151
+ Log$f.log('[DataConfig] ConfigFetcher success');
25280
26152
  }
25281
26153
  else {
25282
- Log$e.debug('[DataConfig] ConfigFetcher returned null, will fallback to axios');
26154
+ Log$f.debug('[DataConfig] ConfigFetcher returned null, will fallback to axios');
25283
26155
  }
25284
26156
  }
25285
26157
  catch (e) {
25286
- Log$e.warn('[DataConfig] ConfigFetcher error, will fallback to axios:', e);
26158
+ Log$f.warn('[DataConfig] ConfigFetcher error, will fallback to axios:', e);
25287
26159
  }
25288
26160
  }
25289
26161
  if (!data) {
25290
- Log$e.debug('[DataConfig] Trying axios (SDK default fetcher)...');
26162
+ Log$f.debug('[DataConfig] Trying axios (SDK default fetcher)...');
25291
26163
  try {
25292
26164
  const response = yield axios__default["default"].get(urlWithCache, {
25293
26165
  timeout: 7000,
25294
26166
  });
25295
26167
  data = response.data;
25296
26168
  fetchMethod = 'axios';
25297
- Log$e.log('[DataConfig] Axios fetch success');
26169
+ Log$f.log('[DataConfig] Axios fetch success');
25298
26170
  }
25299
26171
  catch (e) {
25300
- Log$e.warn('[DataConfig] Axios fetch error:', e);
26172
+ Log$f.warn('[DataConfig] Axios fetch error:', e);
25301
26173
  }
25302
26174
  }
25303
26175
  if (data) {
25304
- Log$e.log(`[DataConfig] Config loaded successfully via [${fetchMethod}]`);
26176
+ Log$f.log(`[DataConfig] Config loaded successfully via [${fetchMethod}]`);
25305
26177
  this.deviceMap = {
25306
26178
  [hdShared.EDeviceType.Classic]: this.enrichFirmwareReleaseInfo(data.classic),
25307
26179
  [hdShared.EDeviceType.Classic1s]: this.enrichFirmwareReleaseInfo(data.classic1s),
@@ -25315,7 +26187,7 @@ class DataManager {
25315
26187
  };
25316
26188
  }
25317
26189
  else {
25318
- Log$e.warn('[DataConfig] All fetch methods failed, using built-in default config');
26190
+ Log$f.warn('[DataConfig] All fetch methods failed, using built-in default config');
25319
26191
  }
25320
26192
  });
25321
26193
  }
@@ -25378,6 +26250,7 @@ DataManager.assets = null;
25378
26250
  DataManager.messages = {
25379
26251
  latest: MessagesJSON,
25380
26252
  v1: MessagesLegacyV1JSON,
26253
+ protocolV2: MessagesPro2JSON,
25381
26254
  };
25382
26255
  DataManager.lastCheckTimestamp = 0;
25383
26256
  DataManager.getFirmwareStatus = (features, firmwareType) => {
@@ -26583,7 +27456,7 @@ const LogBlockEvent = new Set([
26583
27456
  UI_RESPONSE.RECEIVE_PASSPHRASE,
26584
27457
  ]);
26585
27458
 
26586
- const Log$d = getLogger(exports.LoggerNames.DevicePool);
27459
+ const Log$e = getLogger(exports.LoggerNames.DevicePool);
26587
27460
  const getDiff = (current, descriptors) => {
26588
27461
  const connected = descriptors.filter(d => current.find(x => x.path === d.path) === undefined);
26589
27462
  const disconnected = current.filter(d => descriptors.find(x => x.path === d.path) === undefined);
@@ -26641,7 +27514,7 @@ class DevicePool extends events.exports {
26641
27514
  yield this._checkDevicePool(initOptions);
26642
27515
  return { devices, deviceList };
26643
27516
  }
26644
- Log$d.debug('found device in cache, but path is different: ', connectId);
27517
+ Log$e.debug('found device in cache, but path is different: ', connectId);
26645
27518
  }
26646
27519
  }
26647
27520
  try {
@@ -26684,7 +27557,7 @@ class DevicePool extends events.exports {
26684
27557
  if (!device) {
26685
27558
  device = Device.fromDescriptor(descriptor);
26686
27559
  device.deviceConnector = this.connector;
26687
- yield device.connect();
27560
+ yield device.connect(initOptions === null || initOptions === void 0 ? void 0 : initOptions.connectProtocol);
26688
27561
  yield device.initialize(initOptions);
26689
27562
  yield device.release();
26690
27563
  }
@@ -26702,7 +27575,7 @@ class DevicePool extends events.exports {
26702
27575
  for (let i = this.connectedPool.length - 1; i >= 0; i--) {
26703
27576
  const descriptor = this.connectedPool[i];
26704
27577
  const device = yield this._createDevice(descriptor, initOptions);
26705
- Log$d.debug('emit DEVICE.CONNECT: ', device === null || device === void 0 ? void 0 : device.features);
27578
+ Log$e.debug('emit DEVICE.CONNECT: ', device === null || device === void 0 ? void 0 : device.features);
26706
27579
  this.emitter.emit(DEVICE.CONNECT, device);
26707
27580
  this.connectedPool.splice(i, 1);
26708
27581
  }
@@ -26722,9 +27595,9 @@ class DevicePool extends events.exports {
26722
27595
  const diff = getDiff(this.current || [], upcoming);
26723
27596
  this.upcoming = upcoming;
26724
27597
  this.current = this.upcoming;
26725
- Log$d.debug('device pool -> current: ', this.current);
26726
- Log$d.debug('device pool -> upcomming: ', this.upcoming);
26727
- Log$d.debug('DeviceCache.reportDeviceChange diff: ', diff);
27598
+ Log$e.debug('device pool -> current: ', this.current);
27599
+ Log$e.debug('device pool -> upcomming: ', this.upcoming);
27600
+ Log$e.debug('DeviceCache.reportDeviceChange diff: ', diff);
26728
27601
  if (!diff.didUpdate) {
26729
27602
  return;
26730
27603
  }
@@ -26734,7 +27607,7 @@ class DevicePool extends events.exports {
26734
27607
  this._addConnectedDeviceToPool(d);
26735
27608
  return;
26736
27609
  }
26737
- Log$d.debug('emit DEVICE.CONNECT: ', device.features);
27610
+ Log$e.debug('emit DEVICE.CONNECT: ', device.features);
26738
27611
  this.emitter.emit(DEVICE.CONNECT, device);
26739
27612
  });
26740
27613
  diff.disconnected.forEach(d => {
@@ -26744,7 +27617,7 @@ class DevicePool extends events.exports {
26744
27617
  this._addDisconnectedDeviceToPool(d);
26745
27618
  return;
26746
27619
  }
26747
- Log$d.debug('emit DEVICE.DISCONNECT: ', device.features);
27620
+ Log$e.debug('emit DEVICE.DISCONNECT: ', device.features);
26748
27621
  this.emitter.emit(DEVICE.DISCONNECT, device);
26749
27622
  });
26750
27623
  }
@@ -26780,7 +27653,7 @@ class DevicePool extends events.exports {
26780
27653
  this.disconnectPool = [];
26781
27654
  this.devicesCache = {};
26782
27655
  this.emitter.removeAllListeners();
26783
- Log$d.debug('DevicePool state has been reset');
27656
+ Log$e.debug('DevicePool state has been reset');
26784
27657
  }
26785
27658
  }
26786
27659
  DevicePool.current = null;
@@ -26790,16 +27663,17 @@ DevicePool.disconnectPool = [];
26790
27663
  DevicePool.devicesCache = {};
26791
27664
  DevicePool.emitter = new events.exports();
26792
27665
 
26793
- const Log$c = getLogger(exports.LoggerNames.Transport);
27666
+ const Log$d = getLogger(exports.LoggerNames.Transport);
26794
27667
  const BleLogger = getLogger(exports.LoggerNames.HdBleTransport);
26795
27668
  const HttpLogger = getLogger(exports.LoggerNames.HdTransportHttp);
26796
27669
  const LowLevelLogger = getLogger(exports.LoggerNames.HdTransportLowLevel);
26797
27670
  const NodeUsbLogger = getLogger(exports.LoggerNames.HdTransportNodeUsb);
26798
27671
  const WebBleLogger = getLogger(exports.LoggerNames.HdWebBleTransport);
26799
27672
  const WebUsbLogger = getLogger(exports.LoggerNames.HdTransportWebUsb);
27673
+ const REACT_NATIVE_BLE_SCAN_TIMEOUT_MS = 8000;
26800
27674
  class TransportManager {
26801
27675
  static load() {
26802
- Log$c.debug('transport manager load');
27676
+ Log$d.debug('transport manager load');
26803
27677
  this.defaultMessages = DataManager.getProtobufMessages();
26804
27678
  this.currentMessages = this.defaultMessages;
26805
27679
  this.messageVersion = 'latest';
@@ -26808,14 +27682,14 @@ class TransportManager {
26808
27682
  return __awaiter(this, void 0, void 0, function* () {
26809
27683
  try {
26810
27684
  const env = DataManager.getSettings('env');
26811
- Log$c.debug('Initializing transports', env);
27685
+ Log$d.debug('Initializing transports', env);
26812
27686
  if (env === 'react-native') {
26813
27687
  if (!this.reactNativeInit) {
26814
27688
  yield this.transport.init(BleLogger, DevicePool.emitter);
26815
27689
  this.reactNativeInit = true;
26816
27690
  }
26817
27691
  else {
26818
- Log$c.debug('React Native Do Not Initializing transports');
27692
+ Log$d.debug('React Native Do Not Initializing transports');
26819
27693
  }
26820
27694
  }
26821
27695
  else if (env === 'node-usb') {
@@ -26836,12 +27710,15 @@ class TransportManager {
26836
27710
  else {
26837
27711
  yield this.transport.init(HttpLogger);
26838
27712
  }
26839
- Log$c.debug('Configuring transports');
27713
+ Log$d.debug('Configuring transports');
26840
27714
  yield this.transport.configure(JSON.stringify(this.defaultMessages));
26841
- Log$c.debug('Configuring transports done');
27715
+ this.currentMessages = this.defaultMessages;
27716
+ this.messageVersion = 'latest';
27717
+ yield this.configureProtocolV2Messages();
27718
+ Log$d.debug('Configuring transports done');
26842
27719
  }
26843
27720
  catch (error) {
26844
- Log$c.debug('Initializing transports error: ', error);
27721
+ Log$d.debug('Initializing transports error: ', error);
26845
27722
  if (error.code === 'ECONNABORTED') {
26846
27723
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BridgeTimeoutError);
26847
27724
  }
@@ -26850,12 +27727,14 @@ class TransportManager {
26850
27727
  }
26851
27728
  static reconfigure(features) {
26852
27729
  return __awaiter(this, void 0, void 0, function* () {
26853
- Log$c.debug(`Begin reconfiguring transports`);
27730
+ if (!features) {
27731
+ return;
27732
+ }
26854
27733
  const { messageVersion, messages } = getSupportMessageVersion(features);
26855
27734
  if (this.currentMessages === messages || !messages) {
26856
27735
  return;
26857
27736
  }
26858
- Log$c.debug(`Reconfiguring transports version:${messageVersion}`);
27737
+ Log$d.debug(`Reconfiguring transports version:${messageVersion}`);
26859
27738
  try {
26860
27739
  yield this.transport.configure(JSON.stringify(messages));
26861
27740
  this.currentMessages = messages;
@@ -26869,20 +27748,32 @@ class TransportManager {
26869
27748
  static setTransport(TransportConstructor, plugin) {
26870
27749
  const env = DataManager.getSettings('env');
26871
27750
  if (env === 'react-native') {
26872
- this.transport = new TransportConstructor({ scanTimeout: 3000 });
27751
+ this.transport = new TransportConstructor({
27752
+ scanTimeout: REACT_NATIVE_BLE_SCAN_TIMEOUT_MS,
27753
+ });
26873
27754
  }
26874
27755
  else {
26875
27756
  this.transport = new TransportConstructor();
26876
27757
  }
26877
27758
  if (plugin) {
26878
27759
  this.plugin = plugin;
26879
- Log$c.debug('set transport plugin: ', this.plugin);
27760
+ Log$d.debug('set transport plugin: ', this.plugin);
26880
27761
  }
26881
- Log$c.debug('set transport: ', this.transport.name, this.transport.version, this.transport.configured);
27762
+ Log$d.debug('set transport: ', this.transport.name, this.transport.version, this.transport.configured);
26882
27763
  }
26883
27764
  static getTransport() {
26884
27765
  return this.transport;
26885
27766
  }
27767
+ static configureProtocolV2Messages() {
27768
+ return __awaiter(this, void 0, void 0, function* () {
27769
+ const protocolV2Messages = DataManager.getProtobufMessages('protocolV2');
27770
+ const { configureProtocolV2 } = this.transport;
27771
+ if (protocolV2Messages && typeof configureProtocolV2 === 'function') {
27772
+ yield configureProtocolV2.call(this.transport, JSON.stringify(protocolV2Messages));
27773
+ Log$d.debug('Protocol V2 messages configured');
27774
+ }
27775
+ });
27776
+ }
26886
27777
  static getDefaultMessages() {
26887
27778
  return this.defaultMessages;
26888
27779
  }
@@ -26897,6 +27788,88 @@ TransportManager.reactNativeInit = false;
26897
27788
  TransportManager.messageVersion = 'latest';
26898
27789
  TransportManager.plugin = null;
26899
27790
 
27791
+ const MAX_DEBUG_ARRAY_ITEMS = 20;
27792
+ const MAX_DEBUG_OBJECT_KEYS = 40;
27793
+ const MAX_DEBUG_STRING_LENGTH = 512;
27794
+ const MAX_DEBUG_DEPTH = 4;
27795
+ const HIGH_VOLUME_DEBUG_CALLS = new Set([
27796
+ 'FilesystemFileWrite',
27797
+ 'FileWrite',
27798
+ 'EmmcFileWrite',
27799
+ 'FirmwareUpload',
27800
+ 'ResourceAck',
27801
+ ]);
27802
+ function shouldReduceDebugForCall(type) {
27803
+ return HIGH_VOLUME_DEBUG_CALLS.has(type);
27804
+ }
27805
+ function getBinaryByteLength(value) {
27806
+ if (value instanceof ArrayBuffer) {
27807
+ return value.byteLength;
27808
+ }
27809
+ if (ArrayBuffer.isView(value)) {
27810
+ return value.byteLength;
27811
+ }
27812
+ if (typeof Blob !== 'undefined' && value instanceof Blob) {
27813
+ return value.size;
27814
+ }
27815
+ return undefined;
27816
+ }
27817
+ function summarizeRedactedData(value) {
27818
+ const byteLength = getBinaryByteLength(value);
27819
+ if (byteLength !== undefined) {
27820
+ return `[redacted data: ${byteLength} bytes]`;
27821
+ }
27822
+ if (typeof value === 'string') {
27823
+ return `[redacted data: string length=${value.length}]`;
27824
+ }
27825
+ if (Array.isArray(value)) {
27826
+ return `[redacted data: array length=${value.length}]`;
27827
+ }
27828
+ if (value && typeof value === 'object') {
27829
+ return `[redacted data: object keys=${Object.keys(value).length}]`;
27830
+ }
27831
+ return `[redacted data: ${typeof value}]`;
27832
+ }
27833
+ function sanitizeDebugPayload(value, key = '', depth = 0) {
27834
+ if (key === 'data' && value !== null && value !== undefined) {
27835
+ return summarizeRedactedData(value);
27836
+ }
27837
+ const byteLength = getBinaryByteLength(value);
27838
+ if (byteLength !== undefined) {
27839
+ return `[binary: ${byteLength} bytes]`;
27840
+ }
27841
+ if (typeof value === 'string') {
27842
+ return value.length > MAX_DEBUG_STRING_LENGTH
27843
+ ? `${value.slice(0, MAX_DEBUG_STRING_LENGTH)}... (len=${value.length})`
27844
+ : value;
27845
+ }
27846
+ if (!value || typeof value !== 'object') {
27847
+ return value;
27848
+ }
27849
+ if (depth >= MAX_DEBUG_DEPTH) {
27850
+ return Array.isArray(value)
27851
+ ? `[array length=${value.length}]`
27852
+ : `[object keys=${Object.keys(value).length}]`;
27853
+ }
27854
+ if (Array.isArray(value)) {
27855
+ const items = value
27856
+ .slice(0, MAX_DEBUG_ARRAY_ITEMS)
27857
+ .map(item => sanitizeDebugPayload(item, key, depth + 1));
27858
+ if (value.length > MAX_DEBUG_ARRAY_ITEMS) {
27859
+ items.push(`... (${value.length - MAX_DEBUG_ARRAY_ITEMS} more)`);
27860
+ }
27861
+ return items;
27862
+ }
27863
+ const entries = Object.entries(value).slice(0, MAX_DEBUG_OBJECT_KEYS);
27864
+ const sanitized = {};
27865
+ entries.forEach(([entryKey, entryValue]) => {
27866
+ sanitized[entryKey] = sanitizeDebugPayload(entryValue, entryKey, depth + 1);
27867
+ });
27868
+ if (Object.keys(value).length > MAX_DEBUG_OBJECT_KEYS) {
27869
+ sanitized.__truncated__ = `${Object.keys(value).length - MAX_DEBUG_OBJECT_KEYS} more keys`;
27870
+ }
27871
+ return sanitized;
27872
+ }
26900
27873
  const assertType = (res, resType) => {
26901
27874
  const splitResTypes = Array.isArray(resType) ? resType : resType.split('|');
26902
27875
  if (!splitResTypes.includes(res.type)) {
@@ -26966,7 +27939,7 @@ const cancelDeviceWithInitialize = (device) => {
26966
27939
  },
26967
27940
  }));
26968
27941
  };
26969
- const Log$b = getLogger(exports.LoggerNames.DeviceCommands);
27942
+ const Log$c = getLogger(exports.LoggerNames.DeviceCommands);
26970
27943
  const LogCore = getLogger(exports.LoggerNames.Core);
26971
27944
  class DeviceCommands {
26972
27945
  constructor(device, mainId) {
@@ -26975,7 +27948,7 @@ class DeviceCommands {
26975
27948
  this.transport = TransportManager.getTransport();
26976
27949
  this.disposed = false;
26977
27950
  this.instanceId = generateInstanceId('DeviceCommands', device.sdkInstanceId);
26978
- Log$b.debug(`[DeviceCommands] Created: ${this.instanceId}, device: ${this.device.instanceId}`);
27951
+ Log$c.debug(`[DeviceCommands] Created: ${this.instanceId}, device: ${this.device.instanceId}`);
26979
27952
  }
26980
27953
  dispose(_cancelRequest) {
26981
27954
  var _a, _b;
@@ -27040,18 +28013,21 @@ class DeviceCommands {
27040
28013
  }
27041
28014
  });
27042
28015
  }
27043
- call(type, msg = {}) {
28016
+ call(type, msg, options) {
27044
28017
  var _a;
27045
28018
  return __awaiter(this, void 0, void 0, function* () {
27046
- Log$b.debug('[DeviceCommands] [call] Sending', type);
28019
+ const shouldReduceDebug = shouldReduceDebugForCall(type);
28020
+ if (!shouldReduceDebug) {
28021
+ Log$c.debug('[DeviceCommands] [call] Sending', type);
28022
+ }
27047
28023
  try {
27048
- const promise = this.transport.call(this.mainId, type, msg);
28024
+ const promise = this.transport.call(this.mainId, type, msg !== null && msg !== void 0 ? msg : {}, options);
27049
28025
  this.callPromise = promise;
27050
28026
  const res = yield promise;
27051
28027
  if (res.type === 'Failure') {
27052
28028
  LogCore.debug('[DeviceCommands] [call] Received', res.type, res.message);
27053
28029
  }
27054
- else {
28030
+ else if (!shouldReduceDebug) {
27055
28031
  LogCore.debug('[DeviceCommands] [call] Received', res.type);
27056
28032
  }
27057
28033
  return res;
@@ -27077,7 +28053,7 @@ class DeviceCommands {
27077
28053
  }
27078
28054
  }
27079
28055
  if (responseData) {
27080
- Log$b.debug('error response', responseData);
28056
+ Log$c.debug('error response', responseData);
27081
28057
  }
27082
28058
  if (responseError === 'device disconnected during action') {
27083
28059
  return { type: 'BridgeDeviceDisconnected', message: { error: responseError } };
@@ -27094,7 +28070,7 @@ class DeviceCommands {
27094
28070
  }
27095
28071
  });
27096
28072
  }
27097
- typedCall(type, resType, msg) {
28073
+ typedCall(type, resType, msg, options) {
27098
28074
  return __awaiter(this, void 0, void 0, function* () {
27099
28075
  if (this.disposed) {
27100
28076
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.RuntimeError, 'typedCall: DeviceCommands already disposed');
@@ -27106,21 +28082,32 @@ class DeviceCommands {
27106
28082
  'PassphraseAck',
27107
28083
  'Cancel',
27108
28084
  'BixinPinInputOnDevice',
28085
+ 'FilesystemFileWrite',
28086
+ 'FileWrite',
28087
+ 'EmmcFileWrite',
28088
+ 'FirmwareUpload',
28089
+ 'ResourceAck',
27109
28090
  ];
27110
28091
  if (!skipTypes.includes(type) && msg) {
27111
- Log$b.debug('[DeviceCommands] [typedCall] Sending payload', type, msg);
28092
+ Log$c.debug('[DeviceCommands] [typedCall] Sending payload', type, sanitizeDebugPayload(msg));
27112
28093
  }
27113
28094
  }
27114
28095
  catch (e) {
27115
28096
  }
27116
- const response = yield this._commonCall(type, msg);
28097
+ const response = yield this._commonCall(type, msg, options);
27117
28098
  try {
27118
28099
  assertType(response, resType);
27119
28100
  }
27120
28101
  catch (error) {
27121
- Log$b.debug('DeviceCommands typedcall error: ', error);
28102
+ Log$c.debug('DeviceCommands typedcall error: ', error);
27122
28103
  if (error instanceof hdShared.HardwareError) {
27123
28104
  if (error.errorCode === hdShared.HardwareErrorCode.ResponseUnexpectTypeError) {
28105
+ Log$c.debug('[DeviceCommands] [typedCall] Unexpected response type', {
28106
+ request: type,
28107
+ expected: resType,
28108
+ received: response.type,
28109
+ response: sanitizeDebugPayload(response.message),
28110
+ });
27124
28111
  if (error.message.indexOf('BridgeNetworkError') > -1) {
27125
28112
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BridgeNetworkError);
27126
28113
  }
@@ -27130,7 +28117,7 @@ class DeviceCommands {
27130
28117
  if (error.message.indexOf('BridgeDeviceDisconnected') > -1) {
27131
28118
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BridgeDeviceDisconnected);
27132
28119
  }
27133
- throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.ResponseUnexpectTypeError);
28120
+ throw error;
27134
28121
  }
27135
28122
  }
27136
28123
  else {
@@ -27140,19 +28127,21 @@ class DeviceCommands {
27140
28127
  return response;
27141
28128
  });
27142
28129
  }
27143
- _commonCall(type, msg) {
28130
+ _commonCall(type, msg, options) {
27144
28131
  return __awaiter(this, void 0, void 0, function* () {
27145
- const resp = yield this.call(type, msg);
27146
- return this._filterCommonTypes(resp, type);
28132
+ const resp = yield this.call(type, msg, options);
28133
+ return this._filterCommonTypes(resp, type, options);
27147
28134
  });
27148
28135
  }
27149
- _filterCommonTypes(res, callType) {
28136
+ _filterCommonTypes(res, callType, options) {
27150
28137
  try {
27151
- if (DataManager.getSettings('env') === 'react-native') {
27152
- Log$b.debug('_filterCommonTypes: ', JSON.stringify(res));
28138
+ if (shouldReduceDebugForCall(callType)) {
28139
+ }
28140
+ else if (DataManager.getSettings('env') === 'react-native') {
28141
+ Log$c.debug('_filterCommonTypes: ', JSON.stringify(sanitizeDebugPayload(res)));
27153
28142
  }
27154
28143
  else {
27155
- Log$b.debug('_filterCommonTypes: ', res);
28144
+ Log$c.debug('_filterCommonTypes: ', sanitizeDebugPayload(res));
27156
28145
  }
27157
28146
  }
27158
28147
  catch (error) {
@@ -27173,6 +28162,9 @@ class DeviceCommands {
27173
28162
  if (code === 'Failure_PinCancelled') {
27174
28163
  error = hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.PinCancelled);
27175
28164
  }
28165
+ if (code === 'Failure_PinMismatch') {
28166
+ error = hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.PinMismatch, message);
28167
+ }
27176
28168
  if (code === 'Failure_DataError') {
27177
28169
  if (message === 'Please confirm the BlindSign enabled') {
27178
28170
  error = hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BlindSignDisabled);
@@ -27229,18 +28221,18 @@ class DeviceCommands {
27229
28221
  else {
27230
28222
  this.device.emit(DEVICE.BUTTON, this.device, res.message);
27231
28223
  }
27232
- return this._commonCall('ButtonAck', {});
28224
+ return this._commonCall('ButtonAck', {}, options);
27233
28225
  }
27234
28226
  if (res.type === 'EntropyRequest') ;
27235
28227
  if (res.type === 'PinMatrixRequest') {
27236
28228
  return this._promptPin(res.message.type).then(pin => {
27237
28229
  if (pin === '@@ONEKEY_INPUT_PIN_IN_DEVICE') {
27238
28230
  this.device.setCancelableAction(() => this.cancelDeviceOnOneKeyDevice());
27239
- return this._commonCall('BixinPinInputOnDevice').finally(() => {
28231
+ return this._commonCall('BixinPinInputOnDevice', {}, options).finally(() => {
27240
28232
  this.device.clearCancelableAction();
27241
28233
  });
27242
28234
  }
27243
- return this._commonCall('PinMatrixAck', { pin });
28235
+ return this._commonCall('PinMatrixAck', { pin }, options);
27244
28236
  }, error => Promise.reject(error));
27245
28237
  }
27246
28238
  if (res.type === 'PassphraseRequest') {
@@ -27250,11 +28242,11 @@ class DeviceCommands {
27250
28242
  }).then(response => {
27251
28243
  const { passphrase, passphraseOnDevice, attachPinOnDevice } = response;
27252
28244
  if (attachPinOnDevice && existsAttachPinUser) {
27253
- return this._commonCall('PassphraseAck', { on_device_attach_pin: true });
28245
+ return this._commonCall('PassphraseAck', { on_device_attach_pin: true }, options);
27254
28246
  }
27255
28247
  return !passphraseOnDevice
27256
- ? this._commonCall('PassphraseAck', { passphrase })
27257
- : this._commonCall('PassphraseAck', { on_device: true });
28248
+ ? this._commonCall('PassphraseAck', { passphrase }, options)
28249
+ : this._commonCall('PassphraseAck', { on_device: true }, options);
27258
28250
  });
27259
28251
  }
27260
28252
  if (res.type === 'Deprecated_PassphraseStateRequest') ;
@@ -27278,7 +28270,7 @@ class DeviceCommands {
27278
28270
  reject(error);
27279
28271
  });
27280
28272
  const listenerCount = this.device.listenerCount(DEVICE.PIN);
27281
- Log$b.debug(`[${this.instanceId}] _promptPin called`, {
28273
+ Log$c.debug(`[${this.instanceId}] _promptPin called`, {
27282
28274
  responseID: this.currentResponseID,
27283
28275
  deviceInstanceId: this.device.instanceId,
27284
28276
  listenerCount,
@@ -27345,12 +28337,178 @@ class DeviceCommands {
27345
28337
  }
27346
28338
  }
27347
28339
 
28340
+ const PROTOCOL_V2_DEVICE_INFO_REQUEST = {
28341
+ targets: {
28342
+ hw: true,
28343
+ fw: true,
28344
+ bt: true,
28345
+ se1: true,
28346
+ se2: true,
28347
+ se3: true,
28348
+ se4: true,
28349
+ status: true,
28350
+ },
28351
+ types: {
28352
+ version: true,
28353
+ build_id: true,
28354
+ hash: true,
28355
+ specific: true,
28356
+ },
28357
+ };
28358
+ function parseVersion(version) {
28359
+ if (!version)
28360
+ return [0, 0, 0];
28361
+ const [major = 0, minor = 0, patch = 0] = version.split('.').map(part => Number(part) || 0);
28362
+ return [major, minor, patch];
28363
+ }
28364
+ function bytesToHex$1(value) {
28365
+ if (!value)
28366
+ return undefined;
28367
+ if (typeof value === 'string')
28368
+ return value;
28369
+ if (value instanceof Uint8Array) {
28370
+ return Array.from(value)
28371
+ .map(byte => byte.toString(16).padStart(2, '0'))
28372
+ .join('');
28373
+ }
28374
+ if (Array.isArray(value)) {
28375
+ return value.map(byte => Number(byte).toString(16).padStart(2, '0')).join('');
28376
+ }
28377
+ return undefined;
28378
+ }
28379
+ function getDescriptorId(descriptor) {
28380
+ return descriptor.path || descriptor.id || '';
28381
+ }
28382
+ function getImageVersion(image) {
28383
+ return (image === null || image === void 0 ? void 0 : image.version) || undefined;
28384
+ }
28385
+ function getImageBuildId(image) {
28386
+ return (image === null || image === void 0 ? void 0 : image.build_id) || undefined;
28387
+ }
28388
+ function getImageHash(image) {
28389
+ return bytesToHex$1(image === null || image === void 0 ? void 0 : image.hash);
28390
+ }
28391
+ function getSeState(se) {
28392
+ switch (se === null || se === void 0 ? void 0 : se.state) {
28393
+ case 0:
28394
+ return 'BOOT';
28395
+ case 51:
28396
+ return 'APP_FACTORY';
28397
+ case 85:
28398
+ return 'APP';
28399
+ default:
28400
+ return null;
28401
+ }
28402
+ }
28403
+ function createBaseFeatures(descriptor) {
28404
+ const descriptorId = getDescriptorId(descriptor);
28405
+ return {
28406
+ vendor: 'onekey.so',
28407
+ major_version: 0,
28408
+ minor_version: 0,
28409
+ patch_version: 0,
28410
+ bootloader_mode: false,
28411
+ device_id: descriptorId,
28412
+ pin_protection: null,
28413
+ passphrase_protection: false,
28414
+ language: null,
28415
+ label: null,
28416
+ initialized: false,
28417
+ revision: null,
28418
+ bootloader_hash: null,
28419
+ imported: null,
28420
+ unlocked: false,
28421
+ firmware_present: false,
28422
+ needs_backup: null,
28423
+ flags: null,
28424
+ model: 'pro2',
28425
+ fw_major: 0,
28426
+ fw_minor: 0,
28427
+ fw_patch: 0,
28428
+ fw_vendor: null,
28429
+ unfinished_backup: null,
28430
+ no_backup: null,
28431
+ recovery_mode: null,
28432
+ capabilities: [],
28433
+ backup_type: null,
28434
+ sd_card_present: null,
28435
+ sd_protection: null,
28436
+ wipe_code_protection: null,
28437
+ session_id: null,
28438
+ passphrase_always_on_device: null,
28439
+ safety_checks: null,
28440
+ auto_lock_delay_ms: null,
28441
+ display_rotation: null,
28442
+ experimental_features: null,
28443
+ onekey_device_type: hdShared.EDeviceType.Pro2,
28444
+ onekey_serial_no: descriptorId,
28445
+ serial_no: descriptorId,
28446
+ };
28447
+ }
28448
+ function normalizeProtocolV2Features(descriptor, deviceInfo) {
28449
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1, _2, _3, _4, _5, _6, _7, _8;
28450
+ const features = createBaseFeatures(descriptor);
28451
+ if (!deviceInfo)
28452
+ return features;
28453
+ const serialNo = ((_a = deviceInfo.hw) === null || _a === void 0 ? void 0 : _a.serial_no) || features.onekey_serial_no || getDescriptorId(descriptor);
28454
+ const firmwareVersion = getImageVersion((_b = deviceInfo.fw) === null || _b === void 0 ? void 0 : _b.app);
28455
+ const [fwMajor, fwMinor, fwPatch] = parseVersion(firmwareVersion);
28456
+ return Object.assign(Object.assign({}, features), { major_version: fwMajor, minor_version: fwMinor, patch_version: fwPatch, fw_major: fwMajor, fw_minor: fwMinor, fw_patch: fwPatch, device_id: serialNo, serial_no: serialNo, onekey_serial_no: serialNo, label: (_d = (_c = deviceInfo.status) === null || _c === void 0 ? void 0 : _c.label) !== null && _d !== void 0 ? _d : features.label, language: (_f = (_e = deviceInfo.status) === null || _e === void 0 ? void 0 : _e.language) !== null && _f !== void 0 ? _f : features.language, initialized: (_h = (_g = deviceInfo.status) === null || _g === void 0 ? void 0 : _g.init_states) !== null && _h !== void 0 ? _h : features.initialized, passphrase_protection: (_k = (_j = deviceInfo.status) === null || _j === void 0 ? void 0 : _j.passphrase_protection) !== null && _k !== void 0 ? _k : features.passphrase_protection, needs_backup: (_m = (_l = deviceInfo.status) === null || _l === void 0 ? void 0 : _l.backup_required) !== null && _m !== void 0 ? _m : features.needs_backup, ble_enable: (_o = deviceInfo.status) === null || _o === void 0 ? void 0 : _o.bt_enable, onekey_ble_name: (_p = deviceInfo.bt) === null || _p === void 0 ? void 0 : _p.adv_name, ble_name: (_q = deviceInfo.bt) === null || _q === void 0 ? void 0 : _q.adv_name, onekey_firmware_version: firmwareVersion, onekey_firmware_build_id: getImageBuildId((_r = deviceInfo.fw) === null || _r === void 0 ? void 0 : _r.app), onekey_firmware_hash: getImageHash((_s = deviceInfo.fw) === null || _s === void 0 ? void 0 : _s.app), onekey_boot_version: getImageVersion((_t = deviceInfo.fw) === null || _t === void 0 ? void 0 : _t.boot), bootloader_version: getImageVersion((_u = deviceInfo.fw) === null || _u === void 0 ? void 0 : _u.boot), onekey_boot_build_id: getImageBuildId((_v = deviceInfo.fw) === null || _v === void 0 ? void 0 : _v.boot), onekey_boot_hash: getImageHash((_w = deviceInfo.fw) === null || _w === void 0 ? void 0 : _w.boot), onekey_board_version: getImageVersion((_x = deviceInfo.fw) === null || _x === void 0 ? void 0 : _x.board), onekey_board_hash: getImageHash((_y = deviceInfo.fw) === null || _y === void 0 ? void 0 : _y.board), onekey_ble_version: getImageVersion((_z = deviceInfo.bt) === null || _z === void 0 ? void 0 : _z.app), ble_ver: getImageVersion((_0 = deviceInfo.bt) === null || _0 === void 0 ? void 0 : _0.app), onekey_ble_build_id: getImageBuildId((_1 = deviceInfo.bt) === null || _1 === void 0 ? void 0 : _1.app), onekey_ble_hash: getImageHash((_2 = deviceInfo.bt) === null || _2 === void 0 ? void 0 : _2.app), onekey_se01_version: getImageVersion((_3 = deviceInfo.se1) === null || _3 === void 0 ? void 0 : _3.app), onekey_se01_hash: getImageHash((_4 = deviceInfo.se1) === null || _4 === void 0 ? void 0 : _4.app), onekey_se01_build_id: getImageBuildId((_5 = deviceInfo.se1) === null || _5 === void 0 ? void 0 : _5.app), onekey_se01_state: getSeState(deviceInfo.se1), onekey_se02_version: getImageVersion((_6 = deviceInfo.se2) === null || _6 === void 0 ? void 0 : _6.app), onekey_se02_state: getSeState(deviceInfo.se2), onekey_se03_version: getImageVersion((_7 = deviceInfo.se3) === null || _7 === void 0 ? void 0 : _7.app), onekey_se03_state: getSeState(deviceInfo.se3), onekey_se04_version: getImageVersion((_8 = deviceInfo.se4) === null || _8 === void 0 ? void 0 : _8.app), onekey_se04_state: getSeState(deviceInfo.se4) });
28457
+ }
28458
+ function getProtocolV2Features({ commands, descriptor, onDeviceInfoError, timeoutMs, }) {
28459
+ return __awaiter(this, void 0, void 0, function* () {
28460
+ const callOptions = timeoutMs ? { timeoutMs } : undefined;
28461
+ if (callOptions) {
28462
+ yield commands.typedCall('Ping', 'Success', { message: 'init' }, callOptions);
28463
+ }
28464
+ else {
28465
+ yield commands.typedCall('Ping', 'Success', { message: 'init' });
28466
+ }
28467
+ try {
28468
+ const { message } = callOptions
28469
+ ? yield commands.typedCall('DevGetDeviceInfo', 'DeviceInfo', PROTOCOL_V2_DEVICE_INFO_REQUEST, callOptions)
28470
+ : yield commands.typedCall('DevGetDeviceInfo', 'DeviceInfo', PROTOCOL_V2_DEVICE_INFO_REQUEST);
28471
+ return normalizeProtocolV2Features(descriptor, message);
28472
+ }
28473
+ catch (error) {
28474
+ onDeviceInfoError === null || onDeviceInfoError === void 0 ? void 0 : onDeviceInfoError(error);
28475
+ throw error;
28476
+ }
28477
+ });
28478
+ }
28479
+
28480
+ const ProtocolV2FirmwareTargetType = {
28481
+ TARGET_MAIN_APP: 0,
28482
+ TARGET_MAIN_BOOT: 1,
28483
+ TARGET_BT: 2,
28484
+ TARGET_SE1: 3,
28485
+ TARGET_SE2: 4,
28486
+ TARGET_SE3: 5,
28487
+ TARGET_SE4: 6,
28488
+ TARGET_RESOURCE: 10,
28489
+ };
28490
+ function protocolV2FileNameToTargetId(fileName) {
28491
+ if (fileName.includes('ble'))
28492
+ return ProtocolV2FirmwareTargetType.TARGET_BT;
28493
+ if (fileName.includes('bootloader'))
28494
+ return ProtocolV2FirmwareTargetType.TARGET_MAIN_BOOT;
28495
+ if (fileName.includes('se1'))
28496
+ return ProtocolV2FirmwareTargetType.TARGET_SE1;
28497
+ if (fileName.includes('se2'))
28498
+ return ProtocolV2FirmwareTargetType.TARGET_SE2;
28499
+ if (fileName.includes('se3'))
28500
+ return ProtocolV2FirmwareTargetType.TARGET_SE3;
28501
+ if (fileName.includes('se4'))
28502
+ return ProtocolV2FirmwareTargetType.TARGET_SE4;
28503
+ return ProtocolV2FirmwareTargetType.TARGET_MAIN_APP;
28504
+ }
28505
+
27348
28506
  const parseRunOptions = (options) => {
27349
28507
  if (!options)
27350
28508
  options = {};
27351
28509
  return options;
27352
28510
  };
27353
- const Log$a = getLogger(exports.LoggerNames.Device);
28511
+ const Log$b = getLogger(exports.LoggerNames.Device);
27354
28512
  const deviceSessionCache = {};
27355
28513
  function preloadSessionCache(deviceId, passphraseState, sessionId) {
27356
28514
  const key = `${deviceId}@${passphraseState}`;
@@ -27374,7 +28532,7 @@ class Device extends events.exports {
27374
28532
  this.sdkInstanceId = sdkInstanceId;
27375
28533
  this.instanceId = generateInstanceId('Device', this.sdkInstanceId);
27376
28534
  this.createdAt = Date.now();
27377
- Log$a.debug(`[Device] Created: ${this.instanceId}${this.sdkInstanceId ? ` for SDK: ${this.sdkInstanceId}` : ''}`);
28535
+ Log$b.debug(`[Device] Created: ${this.instanceId}${this.sdkInstanceId ? ` for SDK: ${this.sdkInstanceId}` : ''}`);
27378
28536
  }
27379
28537
  static fromDescriptor(originalDescriptor, sdkInstanceId) {
27380
28538
  const descriptor = Object.assign({}, originalDescriptor);
@@ -27408,12 +28566,12 @@ class Device extends events.exports {
27408
28566
  unavailableCapabilities: this.unavailableCapabilities,
27409
28567
  };
27410
28568
  }
27411
- connect() {
28569
+ connect(connectProtocol) {
27412
28570
  const env = DataManager.getSettings('env');
27413
28571
  return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
27414
28572
  if (DataManager.isBleConnect(env)) {
27415
28573
  try {
27416
- yield this.acquire();
28574
+ yield this.acquire(connectProtocol);
27417
28575
  resolve(true);
27418
28576
  }
27419
28577
  catch (error) {
@@ -27423,7 +28581,7 @@ class Device extends events.exports {
27423
28581
  }
27424
28582
  if (!this.mainId || (!this.isUsedHere() && this.originalDescriptor)) {
27425
28583
  try {
27426
- yield this.acquire();
28584
+ yield this.acquire(connectProtocol);
27427
28585
  resolve(true);
27428
28586
  }
27429
28587
  catch (error) {
@@ -27438,27 +28596,32 @@ class Device extends events.exports {
27438
28596
  resolve(false);
27439
28597
  }));
27440
28598
  }
27441
- acquire() {
27442
- var _a, _b, _c, _d;
28599
+ acquire(connectProtocol) {
28600
+ var _a, _b, _c, _d, _e, _f;
27443
28601
  return __awaiter(this, void 0, void 0, function* () {
27444
28602
  const env = DataManager.getSettings('env');
27445
28603
  const mainIdKey = DataManager.isBleConnect(env) ? 'id' : 'session';
28604
+ const expectedProtocol = connectProtocol !== null && connectProtocol !== void 0 ? connectProtocol : this.originalDescriptor.protocolType;
27446
28605
  try {
27447
28606
  if (DataManager.isBleConnect(env)) {
27448
- const res = yield ((_a = this.deviceConnector) === null || _a === void 0 ? void 0 : _a.acquire(this.originalDescriptor.id));
28607
+ const res = yield ((_a = this.deviceConnector) === null || _a === void 0 ? void 0 : _a.acquire(this.originalDescriptor.id, undefined, true, expectedProtocol));
27449
28608
  this.mainId = (_b = res.uuid) !== null && _b !== void 0 ? _b : '';
27450
- Log$a.debug('Expected uuid:', this.mainId);
28609
+ Log$b.debug('Expected uuid:', this.mainId);
27451
28610
  }
27452
28611
  else {
27453
- this.mainId = yield ((_c = this.deviceConnector) === null || _c === void 0 ? void 0 : _c.acquire(this.originalDescriptor.path, this.originalDescriptor.session));
27454
- Log$a.debug('Expected session id:', this.mainId);
28612
+ this.mainId = yield ((_c = this.deviceConnector) === null || _c === void 0 ? void 0 : _c.acquire(this.originalDescriptor.path, this.originalDescriptor.session, undefined, expectedProtocol));
28613
+ Log$b.debug('Expected session id:', this.mainId);
27455
28614
  }
27456
28615
  this.deviceAcquired = true;
27457
28616
  this.updateDescriptor({ [mainIdKey]: this.mainId });
28617
+ const detectedProtocol = (_e = (_d = TransportManager.transport) === null || _d === void 0 ? void 0 : _d.getProtocolType) === null || _e === void 0 ? void 0 : _e.call(_d, DataManager.isBleConnect(env) ? this.originalDescriptor.id : this.originalDescriptor.path);
28618
+ if (detectedProtocol) {
28619
+ this.originalDescriptor.protocolType = detectedProtocol;
28620
+ }
27458
28621
  if (this.commands) {
27459
28622
  yield this.commands.dispose(false);
27460
28623
  }
27461
- this.commands = new DeviceCommands(this, (_d = this.mainId) !== null && _d !== void 0 ? _d : '');
28624
+ this.commands = new DeviceCommands(this, (_f = this.mainId) !== null && _f !== void 0 ? _f : '');
27462
28625
  }
27463
28626
  catch (error) {
27464
28627
  if (this.runPromise) {
@@ -27479,11 +28642,11 @@ class Device extends events.exports {
27479
28642
  (this.mainId && DataManager.isBleConnect(env))) {
27480
28643
  if (this.pendingCallbackPromise) {
27481
28644
  try {
27482
- Log$a.debug('Waiting for callback tasks to complete before releasing device (in release method)');
28645
+ Log$b.debug('Waiting for callback tasks to complete before releasing device (in release method)');
27483
28646
  yield this.pendingCallbackPromise.promise;
27484
28647
  }
27485
28648
  catch (error) {
27486
- Log$a.error('Error waiting for callback tasks in release method:', error);
28649
+ Log$b.error('Error waiting for callback tasks in release method:', error);
27487
28650
  }
27488
28651
  }
27489
28652
  if (this.commands) {
@@ -27502,7 +28665,7 @@ class Device extends events.exports {
27502
28665
  this.updateDescriptor({ session: null });
27503
28666
  }
27504
28667
  catch (err) {
27505
- Log$a.error('[Device] release error: ', err);
28668
+ Log$b.error('[Device] release error: ', err);
27506
28669
  }
27507
28670
  finally {
27508
28671
  this.needReloadDevice = true;
@@ -27522,8 +28685,8 @@ class Device extends events.exports {
27522
28685
  }
27523
28686
  getInternalState(_deviceId) {
27524
28687
  var _a, _b;
27525
- Log$a.debug('getInternalState session cache: ', deviceSessionCache);
27526
- Log$a.debug('getInternalState session param: ', `device_id: ${_deviceId}`, `features.device_id: ${(_a = this.features) === null || _a === void 0 ? void 0 : _a.device_id}`, `passphraseState: ${this.passphraseState}`);
28688
+ Log$b.debug('getInternalState session cache: ', deviceSessionCache);
28689
+ Log$b.debug('getInternalState session param: ', `device_id: ${_deviceId}`, `features.device_id: ${(_a = this.features) === null || _a === void 0 ? void 0 : _a.device_id}`, `passphraseState: ${this.passphraseState}`);
27527
28690
  const deviceId = _deviceId || ((_b = this.features) === null || _b === void 0 ? void 0 : _b.device_id);
27528
28691
  if (!deviceId)
27529
28692
  return undefined;
@@ -27533,7 +28696,7 @@ class Device extends events.exports {
27533
28696
  return deviceSessionCache[usePassKey];
27534
28697
  }
27535
28698
  updateInternalState(enablePassphrase, passphraseState, deviceId, sessionId = null, featuresSessionId = null) {
27536
- Log$a.debug('updateInternalState session param: ', `device_id: ${deviceId}`, `enablePassphrase: ${enablePassphrase}`, `passphraseState: ${passphraseState}`, `sessionId: ${sessionId}`, `featuresSessionId: ${featuresSessionId}`);
28699
+ Log$b.debug('updateInternalState session param: ', `device_id: ${deviceId}`, `enablePassphrase: ${enablePassphrase}`, `passphraseState: ${passphraseState}`, `sessionId: ${sessionId}`, `featuresSessionId: ${featuresSessionId}`);
27537
28700
  if (enablePassphrase) {
27538
28701
  if (sessionId) {
27539
28702
  deviceSessionCache[this.generateStateKey(deviceId, passphraseState)] = sessionId;
@@ -27546,11 +28709,11 @@ class Device extends events.exports {
27546
28709
  if (deviceSessionCache[oldKey]) {
27547
28710
  delete deviceSessionCache[oldKey];
27548
28711
  }
27549
- Log$a.debug('updateInternalState session cache: ', deviceSessionCache);
28712
+ Log$b.debug('updateInternalState session cache: ', deviceSessionCache);
27550
28713
  }
27551
28714
  setInternalState(state, initSession) {
27552
28715
  var _a, _b;
27553
- Log$a.debug('setInternalState session param: ', `state: ${state}`, `initSession: ${initSession}`, `device_id: ${(_a = this.features) === null || _a === void 0 ? void 0 : _a.device_id}`, `passphraseState: ${this.passphraseState}`);
28716
+ Log$b.debug('setInternalState session param: ', `state: ${state}`, `initSession: ${initSession}`, `device_id: ${(_a = this.features) === null || _a === void 0 ? void 0 : _a.device_id}`, `passphraseState: ${this.passphraseState}`);
27554
28717
  if (!this.features)
27555
28718
  return;
27556
28719
  if (!this.passphraseState && !initSession)
@@ -27562,11 +28725,11 @@ class Device extends events.exports {
27562
28725
  if (state) {
27563
28726
  deviceSessionCache[key] = state;
27564
28727
  }
27565
- Log$a.debug('setInternalState done session cache: ', deviceSessionCache);
28728
+ Log$b.debug('setInternalState done session cache: ', deviceSessionCache);
27566
28729
  }
27567
28730
  clearInternalState(_deviceId) {
27568
28731
  var _a;
27569
- Log$a.debug('clearInternalState param: ', _deviceId);
28732
+ Log$b.debug('clearInternalState param: ', _deviceId);
27570
28733
  const deviceId = _deviceId || ((_a = this.features) === null || _a === void 0 ? void 0 : _a.device_id);
27571
28734
  if (!deviceId)
27572
28735
  return;
@@ -27579,6 +28742,10 @@ class Device extends events.exports {
27579
28742
  }
27580
28743
  initialize(options) {
27581
28744
  return __awaiter(this, void 0, void 0, function* () {
28745
+ if (this.originalDescriptor.protocolType === 'V2') {
28746
+ yield this._initializeProtocolV2();
28747
+ return;
28748
+ }
27582
28749
  this.passphraseState = options === null || options === void 0 ? void 0 : options.passphraseState;
27583
28750
  if (options === null || options === void 0 ? void 0 : options.initSession) {
27584
28751
  this.clearInternalState(options === null || options === void 0 ? void 0 : options.deviceId);
@@ -27593,7 +28760,7 @@ class Device extends events.exports {
27593
28760
  }
27594
28761
  payload.passphrase_state = options === null || options === void 0 ? void 0 : options.passphraseState;
27595
28762
  payload.is_contains_attach = true;
27596
- Log$a.debug('Initialize device begin:', {
28763
+ Log$b.debug('Initialize device begin:', {
27597
28764
  deviceId: options === null || options === void 0 ? void 0 : options.deviceId,
27598
28765
  passphraseState: options === null || options === void 0 ? void 0 : options.passphraseState,
27599
28766
  initSession: options === null || options === void 0 ? void 0 : options.initSession,
@@ -27608,12 +28775,40 @@ class Device extends events.exports {
27608
28775
  }, 25 * 1000);
27609
28776
  }),
27610
28777
  ]);
27611
- Log$a.debug('Initialize device end: ', message);
28778
+ Log$b.debug('Initialize device end: ', message);
27612
28779
  this._updateFeatures(message, options === null || options === void 0 ? void 0 : options.initSession);
27613
28780
  yield TransportManager.reconfigure(this.features);
27614
28781
  }
27615
28782
  catch (error) {
27616
- Log$a.error('Initialization failed:', error);
28783
+ Log$b.error('Initialization failed:', error);
28784
+ throw error;
28785
+ }
28786
+ });
28787
+ }
28788
+ _initializeProtocolV2() {
28789
+ return __awaiter(this, void 0, void 0, function* () {
28790
+ Log$b.debug('Initialize device via Protocol V2 feature adapter');
28791
+ try {
28792
+ const features = yield Promise.race([
28793
+ getProtocolV2Features({
28794
+ commands: this.commands,
28795
+ descriptor: this.originalDescriptor,
28796
+ onDeviceInfoError: error => {
28797
+ Log$b.debug('Protocol V2 DevGetDeviceInfo failed:', error);
28798
+ },
28799
+ timeoutMs: 10 * 1000,
28800
+ }),
28801
+ new Promise((_, reject) => {
28802
+ setTimeout(() => {
28803
+ reject(hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.DeviceInitializeFailed));
28804
+ }, 10 * 1000);
28805
+ }),
28806
+ ]);
28807
+ Log$b.debug('Protocol V2 normalized features:', features);
28808
+ this._updateFeatures(features);
28809
+ }
28810
+ catch (error) {
28811
+ Log$b.error('Protocol V2 initialization failed:', error);
27617
28812
  throw error;
27618
28813
  }
27619
28814
  });
@@ -27664,7 +28859,7 @@ class Device extends events.exports {
27664
28859
  return __awaiter(this, void 0, void 0, function* () {
27665
28860
  if (this.runPromise) {
27666
28861
  yield this.interruptionFromOutside();
27667
- Log$a.debug('[Device] run error:', 'Device is running, but will cancel previous operate');
28862
+ Log$b.debug('[Device] run error:', 'Device is running, but will cancel previous operate');
27668
28863
  }
27669
28864
  options = parseRunOptions(options);
27670
28865
  this.runPromise = hdShared.createDeferred(this._runInner.bind(this, fn, options));
@@ -27678,7 +28873,7 @@ class Device extends events.exports {
27678
28873
  const env = DataManager.getSettings('env');
27679
28874
  if (env !== 'react-native') {
27680
28875
  try {
27681
- yield this.acquire();
28876
+ yield this.acquire(options.connectProtocol);
27682
28877
  }
27683
28878
  catch (error) {
27684
28879
  this.runPromise = null;
@@ -27720,7 +28915,7 @@ class Device extends events.exports {
27720
28915
  yield ((_a = this.deviceConnector) === null || _a === void 0 ? void 0 : _a.disconnect(this.mainId));
27721
28916
  }
27722
28917
  yield this.release();
27723
- Log$a.debug(`error code ${e.errorCode} release device, mainId: ${this.mainId}`);
28918
+ Log$b.debug(`error code ${e.errorCode} release device, mainId: ${this.mainId}`);
27724
28919
  }
27725
28920
  this.runPromise = null;
27726
28921
  return;
@@ -27730,7 +28925,7 @@ class Device extends events.exports {
27730
28925
  options.keepSession === false) {
27731
28926
  this.keepSession = false;
27732
28927
  yield this.release();
27733
- Log$a.debug('release device, mainId: ', this.mainId);
28928
+ Log$b.debug('release device, mainId: ', this.mainId);
27734
28929
  }
27735
28930
  if (this.runPromise) {
27736
28931
  this.runPromise.resolve();
@@ -27763,7 +28958,7 @@ class Device extends events.exports {
27763
28958
  setCancelableAction(callback) {
27764
28959
  this.cancelableAction = (e) => callback(e)
27765
28960
  .catch(e2 => {
27766
- Log$a.debug('cancelableAction error', e2);
28961
+ Log$b.debug('cancelableAction error', e2);
27767
28962
  })
27768
28963
  .finally(() => {
27769
28964
  this.clearCancelableAction();
@@ -27918,7 +29113,7 @@ class Device extends events.exports {
27918
29113
  }
27919
29114
  const mainWalletUseAttachPin = unlockedAttachPin && useEmptyPassphrase;
27920
29115
  const useErrorAttachPin = unlockedAttachPin && passphraseState && passphraseState !== newPassphraseState;
27921
- Log$a.debug('Check passphrase state safety: ', {
29116
+ Log$b.debug('Check passphrase state safety: ', {
27922
29117
  passphraseState,
27923
29118
  newPassphraseState,
27924
29119
  unlockedAttachPin,
@@ -28018,7 +29213,7 @@ const getBootloaderReleaseInfo = ({ features, willUpdateFirmwareVersion, firmwar
28018
29213
  };
28019
29214
  };
28020
29215
 
28021
- const Log$9 = getLogger(exports.LoggerNames.Method);
29216
+ const Log$a = getLogger(exports.LoggerNames.Method);
28022
29217
  class BaseMethod {
28023
29218
  constructor(message) {
28024
29219
  this.shouldEnsureConnected = true;
@@ -28048,7 +29243,7 @@ class BaseMethod {
28048
29243
  setContext(context) {
28049
29244
  this.sdkInstanceId = context.sdkInstanceId;
28050
29245
  this.instanceId = generateInstanceId('Method', this.sdkInstanceId);
28051
- Log$9.debug(`[BaseMethod] Created: ${this.instanceId}, method: ${this.name}, SDK: ${this.sdkInstanceId}`);
29246
+ Log$a.debug(`[BaseMethod] Created: ${this.instanceId}, method: ${this.name}, SDK: ${this.sdkInstanceId}`);
28052
29247
  }
28053
29248
  setDevice(device) {
28054
29249
  var _a, _b;
@@ -28068,7 +29263,7 @@ class BaseMethod {
28068
29263
  if (device.commands) {
28069
29264
  device.commands.currentResponseID = this.responseID;
28070
29265
  }
28071
- Log$9.debug(`[${this.instanceId}] setDevice: ${device.instanceId}, commands: ${(_b = device.commands) === null || _b === void 0 ? void 0 : _b.instanceId}`);
29266
+ Log$a.debug(`[${this.instanceId}] setDevice: ${device.instanceId}, commands: ${(_b = device.commands) === null || _b === void 0 ? void 0 : _b.instanceId}`);
28072
29267
  }
28073
29268
  checkFirmwareRelease() {
28074
29269
  if (!this.device || !this.device.features)
@@ -28121,7 +29316,7 @@ class BaseMethod {
28121
29316
  checkFlag = true;
28122
29317
  }
28123
29318
  if (checkFlag && ((_c = this.device.features) === null || _c === void 0 ? void 0 : _c.safety_checks) === 'Strict') {
28124
- Log$9.debug('will change safety_checks level');
29319
+ Log$a.debug('will change safety_checks level');
28125
29320
  yield this.device.commands.typedCall('ApplySettings', 'Success', {
28126
29321
  safety_checks: 'PromptTemporarily',
28127
29322
  });
@@ -28159,7 +29354,7 @@ class SearchDevices extends BaseMethod {
28159
29354
  this.skipForceUpdateCheck = true;
28160
29355
  }
28161
29356
  run() {
28162
- var _a, _b, _c, _d;
29357
+ var _a, _b, _c, _d, _e;
28163
29358
  return __awaiter(this, void 0, void 0, function* () {
28164
29359
  yield TransportManager.configure();
28165
29360
  const deviceDiff = yield ((_a = this.connector) === null || _a === void 0 ? void 0 : _a.enumerate());
@@ -28172,12 +29367,15 @@ class SearchDevices extends BaseMethod {
28172
29367
  const lowerId = (_c = device.id) === null || _c === void 0 ? void 0 : _c.toLowerCase();
28173
29368
  if (!seenIds.has(lowerId)) {
28174
29369
  seenIds.add(lowerId);
28175
- devices.push(Object.assign(Object.assign({}, device), { connectId: device.id, deviceType: getDeviceTypeByBleName((_d = device.name) !== null && _d !== void 0 ? _d : '') }));
29370
+ const bleName = (_e = (_d = device.name) !== null && _d !== void 0 ? _d : device.localName) !== null && _e !== void 0 ? _e : '';
29371
+ devices.push(Object.assign(Object.assign({}, device), { connectId: device.id, name: bleName || device.name, deviceType: getDeviceTypeByBleName(bleName) }));
28176
29372
  }
28177
29373
  }
28178
29374
  return devices;
28179
29375
  }
28180
- const { deviceList } = yield DevicePool.getDevices(devicesDescriptor);
29376
+ const { deviceList } = yield DevicePool.getDevices(devicesDescriptor, undefined, {
29377
+ connectProtocol: this.payload.connectProtocol,
29378
+ });
28181
29379
  return deviceList.map(device => device.toMessageObject());
28182
29380
  });
28183
29381
  }
@@ -28202,6 +29400,70 @@ class GetFeatures extends BaseMethod {
28202
29400
  }
28203
29401
  }
28204
29402
 
29403
+ const ONEKEY_FEATURE_KEYS = [
29404
+ 'onekey_device_type',
29405
+ 'onekey_board_version',
29406
+ 'onekey_boot_version',
29407
+ 'onekey_firmware_version',
29408
+ 'onekey_board_hash',
29409
+ 'onekey_boot_hash',
29410
+ 'onekey_firmware_hash',
29411
+ 'onekey_board_build_id',
29412
+ 'onekey_boot_build_id',
29413
+ 'onekey_firmware_build_id',
29414
+ 'onekey_serial_no',
29415
+ 'onekey_ble_name',
29416
+ 'onekey_ble_version',
29417
+ 'onekey_ble_build_id',
29418
+ 'onekey_ble_hash',
29419
+ 'onekey_se_type',
29420
+ 'onekey_se01_state',
29421
+ 'onekey_se02_state',
29422
+ 'onekey_se03_state',
29423
+ 'onekey_se04_state',
29424
+ 'onekey_se01_version',
29425
+ 'onekey_se02_version',
29426
+ 'onekey_se03_version',
29427
+ 'onekey_se04_version',
29428
+ 'onekey_se01_hash',
29429
+ 'onekey_se02_hash',
29430
+ 'onekey_se03_hash',
29431
+ 'onekey_se04_hash',
29432
+ 'onekey_se01_build_id',
29433
+ 'onekey_se02_build_id',
29434
+ 'onekey_se03_build_id',
29435
+ 'onekey_se04_build_id',
29436
+ 'onekey_se01_boot_version',
29437
+ 'onekey_se02_boot_version',
29438
+ 'onekey_se03_boot_version',
29439
+ 'onekey_se04_boot_version',
29440
+ 'onekey_se01_boot_hash',
29441
+ 'onekey_se02_boot_hash',
29442
+ 'onekey_se03_boot_hash',
29443
+ 'onekey_se04_boot_hash',
29444
+ 'onekey_se01_boot_build_id',
29445
+ 'onekey_se02_boot_build_id',
29446
+ 'onekey_se03_boot_build_id',
29447
+ 'onekey_se04_boot_build_id',
29448
+ ];
29449
+ function normalizeOnekeyFirmwareVersion(message) {
29450
+ if (message.onekey_firmware_version && !semver__default["default"].valid(message.onekey_firmware_version)) {
29451
+ message.onekey_firmware_version = fixVersion(message.onekey_firmware_version);
29452
+ }
29453
+ }
29454
+ function pickOnekeyFeatures(features) {
29455
+ const message = {};
29456
+ if (!features)
29457
+ return message;
29458
+ for (const key of ONEKEY_FEATURE_KEYS) {
29459
+ const value = features[key];
29460
+ if (value !== undefined && value !== null) {
29461
+ message[key] = value;
29462
+ }
29463
+ }
29464
+ normalizeOnekeyFirmwareVersion(message);
29465
+ return message;
29466
+ }
28205
29467
  class GetOnekeyFeatures extends BaseMethod {
28206
29468
  init() {
28207
29469
  this.allowDeviceMode = [
@@ -28213,11 +29475,13 @@ class GetOnekeyFeatures extends BaseMethod {
28213
29475
  this.skipForceUpdateCheck = true;
28214
29476
  }
28215
29477
  run() {
29478
+ var _a;
28216
29479
  return __awaiter(this, void 0, void 0, function* () {
28217
- const { message } = yield this.device.commands.typedCall('OnekeyGetFeatures', 'OnekeyFeatures');
28218
- if (!!message.onekey_firmware_version && !semver__default["default"].valid(message.onekey_firmware_version)) {
28219
- message.onekey_firmware_version = fixVersion(message.onekey_firmware_version);
29480
+ if (((_a = this.device.originalDescriptor) === null || _a === void 0 ? void 0 : _a.protocolType) === 'V2') {
29481
+ return Promise.resolve(pickOnekeyFeatures(this.device.features));
28220
29482
  }
29483
+ const { message } = yield this.device.commands.typedCall('OnekeyGetFeatures', 'OnekeyFeatures');
29484
+ normalizeOnekeyFirmwareVersion(message);
28221
29485
  return Promise.resolve(message);
28222
29486
  });
28223
29487
  }
@@ -28762,7 +30026,14 @@ class DeviceRebootToBootloader extends BaseMethod {
28762
30026
  };
28763
30027
  }
28764
30028
  run() {
30029
+ var _a;
28765
30030
  return __awaiter(this, void 0, void 0, function* () {
30031
+ if (((_a = this.device.originalDescriptor) === null || _a === void 0 ? void 0 : _a.protocolType) === 'V2') {
30032
+ const res = yield this.device.commands.typedCall('DevReboot', 'Success', {
30033
+ reboot_type: hdTransport.DevRebootType.Bootloader,
30034
+ });
30035
+ return Promise.resolve(res.message);
30036
+ }
28766
30037
  const res = yield this.device.commands.typedCall('RebootToBootloader', 'Success');
28767
30038
  return Promise.resolve(res.message);
28768
30039
  });
@@ -28785,7 +30056,14 @@ class DeviceRebootToBoardloader extends BaseMethod {
28785
30056
  };
28786
30057
  }
28787
30058
  run() {
30059
+ var _a;
28788
30060
  return __awaiter(this, void 0, void 0, function* () {
30061
+ if (((_a = this.device.originalDescriptor) === null || _a === void 0 ? void 0 : _a.protocolType) === 'V2') {
30062
+ const res = yield this.device.commands.typedCall('DevReboot', 'Success', {
30063
+ reboot_type: hdTransport.DevRebootType.Boardloader,
30064
+ });
30065
+ return Promise.resolve(res.message);
30066
+ }
28789
30067
  const res = yield this.device.commands.typedCall('BixinOutMessageSE', 'Success');
28790
30068
  return Promise.resolve(res.message);
28791
30069
  });
@@ -29225,10 +30503,10 @@ const getInfo = ({ features, updateType, targetVersion, firmwareType }) => {
29225
30503
  };
29226
30504
 
29227
30505
  const NEW_BOOT_UPRATE_FIRMWARE_VERSION = '2.4.5';
29228
- const SESSION_ERROR$1 = 'session not found';
30506
+ const SESSION_ERROR$2 = 'session not found';
29229
30507
  const FIRMWARE_UPDATE_CONFIRM$1 = 'Firmware install confirmed';
29230
- const Log$8 = getLogger(exports.LoggerNames.Method);
29231
- const isDeviceDisconnectedError$1 = (error) => {
30508
+ const Log$9 = getLogger(exports.LoggerNames.Method);
30509
+ const isDeviceDisconnectedError$2 = (error) => {
29232
30510
  const message = error instanceof Error ? error.message : String(error !== null && error !== void 0 ? error : '');
29233
30511
  return (message.includes('device was disconnected') ||
29234
30512
  message.includes('transferIn') ||
@@ -29276,13 +30554,13 @@ const uploadFirmware = (updateType, typedCall, postMessage, device, { payload, r
29276
30554
  const newFeatures = yield typedCall('GetFeatures', 'Features', {});
29277
30555
  const deviceBootloaderVersion = getDeviceBootloaderVersion(newFeatures.message).join('.');
29278
30556
  const supportUpgradeFileHeader = semver__default["default"].gte(deviceBootloaderVersion, '2.1.0');
29279
- Log$8.debug('supportUpgradeFileHeader:', supportUpgradeFileHeader);
30557
+ Log$9.debug('supportUpgradeFileHeader:', supportUpgradeFileHeader);
29280
30558
  if (supportUpgradeFileHeader) {
29281
30559
  const HEADER_SIZE = 1024;
29282
30560
  if (payload.byteLength < HEADER_SIZE) {
29283
30561
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.RuntimeError, `firmware payload too small: ${payload.byteLength} bytes, expected at least ${HEADER_SIZE} bytes`);
29284
30562
  }
29285
- Log$8.debug('Uploading firmware header:', {
30563
+ Log$9.debug('Uploading firmware header:', {
29286
30564
  size: HEADER_SIZE,
29287
30565
  totalSize: payload.byteLength,
29288
30566
  });
@@ -29294,18 +30572,18 @@ const uploadFirmware = (updateType, typedCall, postMessage, device, { payload, r
29294
30572
  });
29295
30573
  const isUnknownMessage = (_b = (_a = headerRes.message) === null || _a === void 0 ? void 0 : _a.message) === null || _b === void 0 ? void 0 : _b.includes('Failure_UnknownMessage');
29296
30574
  if (headerRes.type !== 'Success' && !isUnknownMessage) {
29297
- Log$8.error('Firmware header upload failed:', headerRes);
30575
+ Log$9.error('Firmware header upload failed:', headerRes);
29298
30576
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.RuntimeError, 'failed to upload firmware header');
29299
30577
  }
29300
30578
  }
29301
30579
  catch (error) {
29302
- Log$8.error('Firmware header upload failed:', error);
30580
+ Log$9.error('Firmware header upload failed:', error);
29303
30581
  const message = error instanceof Error ? error.message : String(error !== null && error !== void 0 ? error : '');
29304
30582
  if (!message.includes('Failure_UnknownMessage')) {
29305
30583
  throw error;
29306
30584
  }
29307
30585
  }
29308
- Log$8.debug('Firmware header uploaded successfully');
30586
+ Log$9.debug('Firmware header uploaded successfully');
29309
30587
  }
29310
30588
  }
29311
30589
  const eraseCommand = isFirmware ? 'FirmwareErase' : 'FirmwareErase_ex';
@@ -29322,8 +30600,8 @@ const uploadFirmware = (updateType, typedCall, postMessage, device, { payload, r
29322
30600
  });
29323
30601
  }
29324
30602
  catch (error) {
29325
- if (isDeviceDisconnectedError$1(error)) {
29326
- Log$8.log('Rebooting device');
30603
+ if (isDeviceDisconnectedError$2(error)) {
30604
+ Log$9.log('Rebooting device');
29327
30605
  updateResponse = {
29328
30606
  type: 'Success',
29329
30607
  message: { message: FIRMWARE_UPDATE_CONFIRM$1 },
@@ -29408,8 +30686,8 @@ const newTouchUpdateProcess = (updateType, postMessage, device, { payload }, reb
29408
30686
  });
29409
30687
  }
29410
30688
  catch (error) {
29411
- if (isDeviceDisconnectedError$1(error)) {
29412
- Log$8.log('Rebooting device');
30689
+ if (isDeviceDisconnectedError$2(error)) {
30690
+ Log$9.log('Rebooting device');
29413
30691
  response = {
29414
30692
  type: 'Success',
29415
30693
  message: { message: FIRMWARE_UPDATE_CONFIRM$1 },
@@ -29440,7 +30718,7 @@ const newTouchUpdateProcess = (updateType, postMessage, device, { payload }, reb
29440
30718
  ]);
29441
30719
  }
29442
30720
  catch (e) {
29443
- Log$8.log('catch Bluetooth error when device is restarting: ', e);
30721
+ Log$9.log('catch Bluetooth error when device is restarting: ', e);
29444
30722
  }
29445
30723
  }
29446
30724
  else {
@@ -29461,7 +30739,7 @@ const newTouchUpdateProcess = (updateType, postMessage, device, { payload }, reb
29461
30739
  }
29462
30740
  catch (error) {
29463
30741
  console.error('Device reconnect failed: ', error);
29464
- Log$8.error('Device reconnect failed:', error);
30742
+ Log$9.error('Device reconnect failed:', error);
29465
30743
  yield wait(1000);
29466
30744
  }
29467
30745
  }
@@ -29486,8 +30764,8 @@ const emmcFileWriteWithRetry = (device, filePath, chunkLength, offset, chunk, ov
29486
30764
  });
29487
30765
  if (writeRes.type !== 'EmmcFile') {
29488
30766
  if (writeRes.type === 'CallMethodError') {
29489
- if (((_s = writeRes.message.error) !== null && _s !== void 0 ? _s : '').indexOf(SESSION_ERROR$1) > -1) {
29490
- throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.RuntimeError, SESSION_ERROR$1);
30767
+ if (((_s = writeRes.message.error) !== null && _s !== void 0 ? _s : '').indexOf(SESSION_ERROR$2) > -1) {
30768
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.RuntimeError, SESSION_ERROR$2);
29491
30769
  }
29492
30770
  }
29493
30771
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.EmmcFileWriteFirmwareError, 'transfer data error');
@@ -29501,7 +30779,7 @@ const emmcFileWriteWithRetry = (device, filePath, chunkLength, offset, chunk, ov
29501
30779
  return result;
29502
30780
  }
29503
30781
  catch (error) {
29504
- Log$8.error(`emmcWrite error: `, error);
30782
+ Log$9.error(`emmcWrite error: `, error);
29505
30783
  retryCount--;
29506
30784
  if (retryCount === 0) {
29507
30785
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.EmmcFileWriteFirmwareError, 'transfer data error');
@@ -29512,8 +30790,8 @@ const emmcFileWriteWithRetry = (device, filePath, chunkLength, offset, chunk, ov
29512
30790
  yield ((_h = device.deviceConnector) === null || _h === void 0 ? void 0 : _h.acquire(device.originalDescriptor.id, null, true));
29513
30791
  yield device.initialize();
29514
30792
  }
29515
- else if (((_j = error === null || error === void 0 ? void 0 : error.message) === null || _j === void 0 ? void 0 : _j.indexOf(SESSION_ERROR$1)) > -1 ||
29516
- ((_l = (_k = error === null || error === void 0 ? void 0 : error.response) === null || _k === void 0 ? void 0 : _k.data) === null || _l === void 0 ? void 0 : _l.indexOf(SESSION_ERROR$1)) > -1) {
30793
+ else if (((_j = error === null || error === void 0 ? void 0 : error.message) === null || _j === void 0 ? void 0 : _j.indexOf(SESSION_ERROR$2)) > -1 ||
30794
+ ((_l = (_k = error === null || error === void 0 ? void 0 : error.response) === null || _k === void 0 ? void 0 : _k.data) === null || _l === void 0 ? void 0 : _l.indexOf(SESSION_ERROR$2)) > -1) {
29517
30795
  const deviceDiff = yield ((_m = device.deviceConnector) === null || _m === void 0 ? void 0 : _m.enumerate());
29518
30796
  const devicesDescriptor = (_o = deviceDiff === null || deviceDiff === void 0 ? void 0 : deviceDiff.descriptors) !== null && _o !== void 0 ? _o : [];
29519
30797
  const { deviceList } = yield DevicePool.getDevices(devicesDescriptor, undefined);
@@ -29643,10 +30921,10 @@ class DeviceFullyUploadResource extends BaseMethod {
29643
30921
  }
29644
30922
  }
29645
30923
 
29646
- const Log$7 = getLogger(exports.LoggerNames.Method);
29647
- const SESSION_ERROR = 'session not found';
30924
+ const Log$8 = getLogger(exports.LoggerNames.Method);
30925
+ const SESSION_ERROR$1 = 'session not found';
29648
30926
  const FIRMWARE_UPDATE_CONFIRM = 'Firmware install confirmed';
29649
- const isDeviceDisconnectedError = (error) => {
30927
+ const isDeviceDisconnectedError$1 = (error) => {
29650
30928
  const message = error instanceof Error ? error.message : String(error !== null && error !== void 0 ? error : '');
29651
30929
  return (message.includes('device was disconnected') ||
29652
30930
  message.includes('transferIn') ||
@@ -29669,12 +30947,9 @@ class FirmwareUpdateBaseMethod extends BaseMethod {
29669
30947
  type,
29670
30948
  }));
29671
30949
  };
29672
- this.postProgressMessage = (progress, progressType) => {
29673
- this.postMessage(createUiMessage(UI_REQUEST.FIRMWARE_PROGRESS, {
29674
- device: this.device.toMessageObject(),
29675
- progress,
29676
- progressType,
29677
- }));
30950
+ this.postProgressMessage = (progress, progressType, metadata = {}) => {
30951
+ this.postMessage(createUiMessage(UI_REQUEST.FIRMWARE_PROGRESS, Object.assign({ device: this.device.toMessageObject(), progress,
30952
+ progressType }, metadata)));
29678
30953
  };
29679
30954
  }
29680
30955
  init() { }
@@ -29722,7 +30997,7 @@ class FirmwareUpdateBaseMethod extends BaseMethod {
29722
30997
  this.checkPromise = hdShared.createDeferred();
29723
30998
  const env = DataManager.getSettings('env');
29724
30999
  const isBleReconnect = connectId && DataManager.isBleConnect(env);
29725
- Log$7.log('FirmwareUpdateBaseMethod [checkDeviceToBootloader] isBleReconnect: ', isBleReconnect);
31000
+ Log$8.log('FirmwareUpdateBaseMethod [checkDeviceToBootloader] isBleReconnect: ', isBleReconnect);
29726
31001
  let isFirstCheck = true;
29727
31002
  let checkCount = 0;
29728
31003
  let timeoutTimer;
@@ -29731,10 +31006,10 @@ class FirmwareUpdateBaseMethod extends BaseMethod {
29731
31006
  const intervalTimer = setInterval(() => __awaiter(this, void 0, void 0, function* () {
29732
31007
  var _c, _d, _e, _f;
29733
31008
  checkCount += 1;
29734
- Log$7.log('FirmwareUpdateBaseMethod [checkDeviceToBootloader] isFirstCheck: ', isFirstCheck);
31009
+ Log$8.log('FirmwareUpdateBaseMethod [checkDeviceToBootloader] isFirstCheck: ', isFirstCheck);
29735
31010
  if (isTouchOrProDevice && isFirstCheck) {
29736
31011
  isFirstCheck = false;
29737
- Log$7.log('FirmwareUpdateBaseMethod [checkDeviceToBootloader] wait 3000ms');
31012
+ Log$8.log('FirmwareUpdateBaseMethod [checkDeviceToBootloader] wait 3000ms');
29738
31013
  yield wait(3000);
29739
31014
  }
29740
31015
  if (checkCount > 4 &&
@@ -29750,7 +31025,7 @@ class FirmwareUpdateBaseMethod extends BaseMethod {
29750
31025
  }
29751
31026
  }
29752
31027
  catch (e) {
29753
- Log$7.log('FirmwareUpdateBaseMethod [checkDeviceToBootloader] _promptDeviceInBootloaderForWebDevice failed: ', e);
31028
+ Log$8.log('FirmwareUpdateBaseMethod [checkDeviceToBootloader] _promptDeviceInBootloaderForWebDevice failed: ', e);
29754
31029
  (_c = this.checkPromise) === null || _c === void 0 ? void 0 : _c.reject(e);
29755
31030
  }
29756
31031
  return;
@@ -29765,7 +31040,7 @@ class FirmwareUpdateBaseMethod extends BaseMethod {
29765
31040
  }
29766
31041
  }
29767
31042
  catch (e) {
29768
- Log$7.log('catch Bluetooth error when device is restarting: ', e);
31043
+ Log$8.log('catch Bluetooth error when device is restarting: ', e);
29769
31044
  }
29770
31045
  }
29771
31046
  else {
@@ -29845,8 +31120,8 @@ class FirmwareUpdateBaseMethod extends BaseMethod {
29845
31120
  });
29846
31121
  }
29847
31122
  catch (error) {
29848
- if (isDeviceDisconnectedError(error)) {
29849
- Log$7.log('Rebooting device');
31123
+ if (isDeviceDisconnectedError$1(error)) {
31124
+ Log$8.log('Rebooting device');
29850
31125
  updateResponse = {
29851
31126
  type: 'Success',
29852
31127
  message: { message: FIRMWARE_UPDATE_CONFIRM },
@@ -29870,7 +31145,7 @@ class FirmwareUpdateBaseMethod extends BaseMethod {
29870
31145
  });
29871
31146
  });
29872
31147
  }
29873
- emmcCommonUpdateProcess({ payload, filePath, processedSize, totalSize, }) {
31148
+ emmcCommonUpdateProcess({ payload, filePath, processedSize, totalSize, transferStartTime = Date.now(), }) {
29874
31149
  return __awaiter(this, void 0, void 0, function* () {
29875
31150
  if (!filePath.startsWith('0:')) {
29876
31151
  throw new Error('filePath must start with 0:');
@@ -29880,7 +31155,6 @@ class FirmwareUpdateBaseMethod extends BaseMethod {
29880
31155
  const chunkSize = 1024 * perPackageSize;
29881
31156
  const totalChunks = Math.ceil(payload.byteLength / chunkSize);
29882
31157
  let offset = 0;
29883
- let currentFileProcessed = 0;
29884
31158
  for (let i = 0; i < totalChunks; i++) {
29885
31159
  const chunkStart = i * chunkSize;
29886
31160
  const chunkEnd = Math.min(chunkStart + chunkSize, payload.byteLength);
@@ -29889,7 +31163,7 @@ class FirmwareUpdateBaseMethod extends BaseMethod {
29889
31163
  const overwrite = i === 0;
29890
31164
  let progress;
29891
31165
  if (totalSize !== undefined && processedSize !== undefined) {
29892
- currentFileProcessed = processedSize + chunkEnd;
31166
+ const currentFileProcessed = processedSize + chunkEnd;
29893
31167
  progress = Math.min(Math.ceil((currentFileProcessed / totalSize) * 100), 99);
29894
31168
  }
29895
31169
  else {
@@ -29897,7 +31171,15 @@ class FirmwareUpdateBaseMethod extends BaseMethod {
29897
31171
  }
29898
31172
  const writeRes = yield this.emmcFileWriteWithRetry(filePath, chunkLength, offset, chunk, overwrite, progress);
29899
31173
  offset += writeRes.message.processed_byte;
29900
- this.postProgressMessage(progress, 'transferData');
31174
+ const elapsedMs = Date.now() - transferStartTime;
31175
+ const transferredBytes = totalSize !== undefined && processedSize !== undefined ? processedSize + offset : offset;
31176
+ const totalBytes = totalSize !== null && totalSize !== void 0 ? totalSize : payload.byteLength;
31177
+ this.postProgressMessage(progress, 'transferData', {
31178
+ transferredBytes,
31179
+ totalBytes,
31180
+ rateBytesPerSecond: elapsedMs > 0 ? Math.round((transferredBytes / elapsedMs) * 1000) : undefined,
31181
+ elapsedMs,
31182
+ });
29901
31183
  }
29902
31184
  return totalSize !== undefined ? (processedSize !== null && processedSize !== void 0 ? processedSize : 0) + payload.byteLength : 0;
29903
31185
  });
@@ -29921,8 +31203,8 @@ class FirmwareUpdateBaseMethod extends BaseMethod {
29921
31203
  });
29922
31204
  if (writeRes.type !== 'EmmcFile') {
29923
31205
  if (writeRes.type === 'CallMethodError') {
29924
- if (((_k = writeRes.message.error) !== null && _k !== void 0 ? _k : '').indexOf(SESSION_ERROR) > -1) {
29925
- throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.RuntimeError, SESSION_ERROR);
31206
+ if (((_k = writeRes.message.error) !== null && _k !== void 0 ? _k : '').indexOf(SESSION_ERROR$1) > -1) {
31207
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.RuntimeError, SESSION_ERROR$1);
29926
31208
  }
29927
31209
  }
29928
31210
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.EmmcFileWriteFirmwareError, 'transfer data error');
@@ -29936,7 +31218,7 @@ class FirmwareUpdateBaseMethod extends BaseMethod {
29936
31218
  return result;
29937
31219
  }
29938
31220
  catch (error) {
29939
- Log$7.error(`emmcWrite error: `, error);
31221
+ Log$8.error(`emmcWrite error: `, error);
29940
31222
  retryCount--;
29941
31223
  if (retryCount === 0) {
29942
31224
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.EmmcFileWriteFirmwareError, 'transfer data error');
@@ -29947,8 +31229,8 @@ class FirmwareUpdateBaseMethod extends BaseMethod {
29947
31229
  yield ((_a = this.device.deviceConnector) === null || _a === void 0 ? void 0 : _a.acquire(this.device.originalDescriptor.id, null, true));
29948
31230
  yield this.device.initialize();
29949
31231
  }
29950
- else if (((_b = error === null || error === void 0 ? void 0 : error.message) === null || _b === void 0 ? void 0 : _b.indexOf(SESSION_ERROR)) > -1 ||
29951
- ((_d = (_c = error === null || error === void 0 ? void 0 : error.response) === null || _c === void 0 ? void 0 : _c.data) === null || _d === void 0 ? void 0 : _d.indexOf(SESSION_ERROR)) > -1) {
31232
+ else if (((_b = error === null || error === void 0 ? void 0 : error.message) === null || _b === void 0 ? void 0 : _b.indexOf(SESSION_ERROR$1)) > -1 ||
31233
+ ((_d = (_c = error === null || error === void 0 ? void 0 : error.response) === null || _c === void 0 ? void 0 : _c.data) === null || _d === void 0 ? void 0 : _d.indexOf(SESSION_ERROR$1)) > -1) {
29952
31234
  const deviceDiff = yield ((_e = this.device.deviceConnector) === null || _e === void 0 ? void 0 : _e.enumerate());
29953
31235
  const devicesDescriptor = (_f = deviceDiff === null || deviceDiff === void 0 ? void 0 : deviceDiff.descriptors) !== null && _f !== void 0 ? _f : [];
29954
31236
  const { deviceList } = yield DevicePool.getDevices(devicesDescriptor, undefined);
@@ -30115,7 +31397,7 @@ class GetNextU2FCounter extends BaseMethod {
30115
31397
  }
30116
31398
  }
30117
31399
 
30118
- const Log$6 = getLogger(exports.LoggerNames.Method);
31400
+ const Log$7 = getLogger(exports.LoggerNames.Method);
30119
31401
  class FirmwareUpdate extends BaseMethod {
30120
31402
  constructor() {
30121
31403
  super(...arguments);
@@ -30153,7 +31435,7 @@ class FirmwareUpdate extends BaseMethod {
30153
31435
  this.checkPromise = hdShared.createDeferred();
30154
31436
  const env = DataManager.getSettings('env');
30155
31437
  const isBleReconnect = connectId && DataManager.isBleConnect(env);
30156
- Log$6.log('FirmwareUpdate [checkDeviceToBootloader] isBleReconnect: ', isBleReconnect);
31438
+ Log$7.log('FirmwareUpdate [checkDeviceToBootloader] isBleReconnect: ', isBleReconnect);
30157
31439
  const intervalTimer = setInterval(() => __awaiter(this, void 0, void 0, function* () {
30158
31440
  var _a, _b, _c, _d, _e, _f, _g, _h;
30159
31441
  if (isBleReconnect) {
@@ -30166,7 +31448,7 @@ class FirmwareUpdate extends BaseMethod {
30166
31448
  }
30167
31449
  }
30168
31450
  catch (e) {
30169
- Log$6.log('catch Bluetooth error when device is restarting: ', e);
31451
+ Log$7.log('catch Bluetooth error when device is restarting: ', e);
30170
31452
  }
30171
31453
  }
30172
31454
  else {
@@ -30220,7 +31502,7 @@ class FirmwareUpdate extends BaseMethod {
30220
31502
  if (e instanceof hdShared.HardwareError) {
30221
31503
  return Promise.reject(e);
30222
31504
  }
30223
- Log$6.log('auto go to bootloader mode failed: ', e);
31505
+ Log$7.log('auto go to bootloader mode failed: ', e);
30224
31506
  return Promise.reject(hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.FirmwareUpdateAutoEnterBootFailure));
30225
31507
  }
30226
31508
  }
@@ -30257,7 +31539,7 @@ class FirmwareUpdate extends BaseMethod {
30257
31539
  }
30258
31540
  }
30259
31541
 
30260
- const Log$5 = getLogger(exports.LoggerNames.Method);
31542
+ const Log$6 = getLogger(exports.LoggerNames.Method);
30261
31543
  class FirmwareUpdateV2 extends BaseMethod {
30262
31544
  constructor() {
30263
31545
  super(...arguments);
@@ -30320,7 +31602,7 @@ class FirmwareUpdateV2 extends BaseMethod {
30320
31602
  this.checkPromise = hdShared.createDeferred();
30321
31603
  const env = DataManager.getSettings('env');
30322
31604
  const isBleReconnect = connectId && DataManager.isBleConnect(env);
30323
- Log$5.log('FirmwareUpdateV2 [checkDeviceToBootloader] isBleReconnect: ', isBleReconnect);
31605
+ Log$6.log('FirmwareUpdateV2 [checkDeviceToBootloader] isBleReconnect: ', isBleReconnect);
30324
31606
  let isFirstCheck = true;
30325
31607
  let checkCount = 0;
30326
31608
  let timeoutTimer;
@@ -30329,10 +31611,10 @@ class FirmwareUpdateV2 extends BaseMethod {
30329
31611
  const intervalTimer = setInterval(() => __awaiter(this, void 0, void 0, function* () {
30330
31612
  var _c, _d, _e, _f;
30331
31613
  checkCount += 1;
30332
- Log$5.log('FirmwareUpdateV2 [checkDeviceToBootloader] isFirstCheck: ', isFirstCheck);
31614
+ Log$6.log('FirmwareUpdateV2 [checkDeviceToBootloader] isFirstCheck: ', isFirstCheck);
30333
31615
  if (isTouchOrProDevice && isFirstCheck) {
30334
31616
  isFirstCheck = false;
30335
- Log$5.log('FirmwareUpdateV2 [checkDeviceToBootloader] wait 3000ms');
31617
+ Log$6.log('FirmwareUpdateV2 [checkDeviceToBootloader] wait 3000ms');
30336
31618
  yield wait(3000);
30337
31619
  }
30338
31620
  if (checkCount > 4 &&
@@ -30350,7 +31632,7 @@ class FirmwareUpdateV2 extends BaseMethod {
30350
31632
  }
30351
31633
  }
30352
31634
  catch (e) {
30353
- Log$5.log('FirmwareUpdateV2 [checkDeviceToBootloader] promptDeviceInBootloaderForWebDevice failed: ', e);
31635
+ Log$6.log('FirmwareUpdateV2 [checkDeviceToBootloader] promptDeviceInBootloaderForWebDevice failed: ', e);
30354
31636
  (_c = this.checkPromise) === null || _c === void 0 ? void 0 : _c.reject(e);
30355
31637
  }
30356
31638
  return;
@@ -30365,7 +31647,7 @@ class FirmwareUpdateV2 extends BaseMethod {
30365
31647
  }
30366
31648
  }
30367
31649
  catch (e) {
30368
- Log$5.log('catch Bluetooth error when device is restarting: ', e);
31650
+ Log$6.log('catch Bluetooth error when device is restarting: ', e);
30369
31651
  }
30370
31652
  }
30371
31653
  else {
@@ -30529,7 +31811,7 @@ class FirmwareUpdateV2 extends BaseMethod {
30529
31811
  }
30530
31812
  }
30531
31813
 
30532
- const Log$4 = getLogger(exports.LoggerNames.Method);
31814
+ const Log$5 = getLogger(exports.LoggerNames.Method);
30533
31815
  const MIN_UPDATE_V3_BOOTLOADER_VERSION = '2.8.0';
30534
31816
  class FirmwareUpdateV3 extends FirmwareUpdateBaseMethod {
30535
31817
  constructor() {
@@ -30569,6 +31851,16 @@ class FirmwareUpdateV3 extends FirmwareUpdateBaseMethod {
30569
31851
  };
30570
31852
  }
30571
31853
  run() {
31854
+ var _a;
31855
+ return __awaiter(this, void 0, void 0, function* () {
31856
+ if (((_a = this.device.originalDescriptor) === null || _a === void 0 ? void 0 : _a.protocolType) === 'V2') {
31857
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.RuntimeError, 'Protocol V2 firmware update must use firmwareUpdateV4');
31858
+ }
31859
+ Log$5.debug('FirmwareUpdateV3 strategy: Protocol V1');
31860
+ return this.runProtocolV1();
31861
+ });
31862
+ }
31863
+ runProtocolV1() {
30572
31864
  var _a, _b;
30573
31865
  return __awaiter(this, void 0, void 0, function* () {
30574
31866
  const { device } = this;
@@ -30635,7 +31927,7 @@ class FirmwareUpdateV3 extends FirmwareUpdateBaseMethod {
30635
31927
  const resource = (yield getSysResourceBinary(resourceUrl)).binary;
30636
31928
  return resource;
30637
31929
  }
30638
- Log$4.warn('No resource url found');
31930
+ Log$5.warn('No resource url found');
30639
31931
  return null;
30640
31932
  });
30641
31933
  }
@@ -30720,6 +32012,7 @@ class FirmwareUpdateV3 extends FirmwareUpdateBaseMethod {
30720
32012
  totalSize += bootloaderBinary.byteLength;
30721
32013
  }
30722
32014
  this.postTipMessage(exports.FirmwareUpdateTipMessage.StartTransferData);
32015
+ const transferStartTime = Date.now();
30723
32016
  if (resourceBinary) {
30724
32017
  const file = yield JSZip__default["default"].loadAsync(resourceBinary);
30725
32018
  const files = Object.entries(file.files);
@@ -30732,6 +32025,7 @@ class FirmwareUpdateV3 extends FirmwareUpdateBaseMethod {
30732
32025
  filePath: `0:res/${name}`,
30733
32026
  processedSize,
30734
32027
  totalSize,
32028
+ transferStartTime,
30735
32029
  });
30736
32030
  }
30737
32031
  }
@@ -30742,6 +32036,7 @@ class FirmwareUpdateV3 extends FirmwareUpdateBaseMethod {
30742
32036
  filePath: `0:boot/bootloader.bin`,
30743
32037
  processedSize,
30744
32038
  totalSize,
32039
+ transferStartTime,
30745
32040
  });
30746
32041
  }
30747
32042
  yield this.createUpdatesFolderIfNotExists(`0:updates/`);
@@ -30752,17 +32047,16 @@ class FirmwareUpdateV3 extends FirmwareUpdateBaseMethod {
30752
32047
  filePath: `0:updates/${fwbinary.fileName}`,
30753
32048
  processedSize,
30754
32049
  totalSize,
32050
+ transferStartTime,
30755
32051
  });
30756
32052
  }
30757
32053
  }
30758
32054
  try {
30759
32055
  this.postTipMessage(exports.FirmwareUpdateTipMessage.ConfirmOnDevice);
30760
- yield this.startEmmcFirmwareUpdate({
30761
- path: '0:updates',
30762
- });
32056
+ yield this.startEmmcFirmwareUpdate({ path: '0:updates' });
30763
32057
  }
30764
32058
  catch (error) {
30765
- Log$4.error('triggerFirmwareUpdateEmmc error: ', error);
32059
+ Log$5.error('triggerFirmwareUpdateEmmc error: ', error);
30766
32060
  if (error === null || error === void 0 ? void 0 : error.errorCode) {
30767
32061
  const unexpectedError = [
30768
32062
  hdShared.HardwareErrorCode.ActionCancelled,
@@ -30823,7 +32117,7 @@ class FirmwareUpdateV3 extends FirmwareUpdateBaseMethod {
30823
32117
  yield hdShared.wait(1000);
30824
32118
  }
30825
32119
  catch (error) {
30826
- Log$4.log('getFeatures error', error);
32120
+ Log$5.log('getFeatures error', error);
30827
32121
  let shouldReconnect = true;
30828
32122
  const progress = this.extractUpdateModeProgress(error);
30829
32123
  if (progress !== null) {
@@ -30921,7 +32215,7 @@ class FirmwareUpdateV3 extends FirmwareUpdateBaseMethod {
30921
32215
  return;
30922
32216
  }
30923
32217
  catch (e) {
30924
- Log$4.log('catch Bluetooth error when device is restarting: ', e);
32218
+ Log$5.log('catch Bluetooth error when device is restarting: ', e);
30925
32219
  }
30926
32220
  }
30927
32221
  else {
@@ -30936,7 +32230,7 @@ class FirmwareUpdateV3 extends FirmwareUpdateBaseMethod {
30936
32230
  yield this._promptDeviceForSwitchFirmwareWebDevice();
30937
32231
  }
30938
32232
  catch (e) {
30939
- Log$4.log('WebUSB re-authorization failed: ', e);
32233
+ Log$5.log('WebUSB re-authorization failed: ', e);
30940
32234
  }
30941
32235
  webUsbCheckCount = 0;
30942
32236
  }
@@ -30957,7 +32251,7 @@ class FirmwareUpdateV3 extends FirmwareUpdateBaseMethod {
30957
32251
  }
30958
32252
  catch (error) {
30959
32253
  console.error('Device reconnect failed: ', error);
30960
- Log$4.error('Device reconnect failed:', error);
32254
+ Log$5.error('Device reconnect failed:', error);
30961
32255
  yield hdShared.wait(1000);
30962
32256
  }
30963
32257
  }
@@ -30966,6 +32260,712 @@ class FirmwareUpdateV3 extends FirmwareUpdateBaseMethod {
30966
32260
  }
30967
32261
  }
30968
32262
 
32263
+ const DEV_REBOOT_TYPES = {
32264
+ Normal: hdTransport.DevRebootType.Normal,
32265
+ normal: hdTransport.DevRebootType.Normal,
32266
+ Boardloader: hdTransport.DevRebootType.Boardloader,
32267
+ boardloader: hdTransport.DevRebootType.Boardloader,
32268
+ Bootloader: hdTransport.DevRebootType.Bootloader,
32269
+ bootloader: hdTransport.DevRebootType.Bootloader,
32270
+ };
32271
+ const PROTOCOL_V2_FIRMWARE_UPDATE_OPTIONS = {
32272
+ intermediateTypes: ['DevFirmwareInstallProgress'],
32273
+ };
32274
+ const PROTOCOL_V2_FIRMWARE_UPDATE_RESPONSE_TYPES = ['Success', 'DevFirmwareUpdateStatus'];
32275
+ function normalizeRebootType(value) {
32276
+ if (typeof value === 'number')
32277
+ return value;
32278
+ if (typeof value === 'string') {
32279
+ const numeric = Number(value);
32280
+ if (Number.isFinite(numeric))
32281
+ return numeric;
32282
+ if (value in DEV_REBOOT_TYPES)
32283
+ return DEV_REBOOT_TYPES[value];
32284
+ }
32285
+ return hdTransport.DevRebootType.Normal;
32286
+ }
32287
+ function normalizeTargetId(value) {
32288
+ if (typeof value === 'number')
32289
+ return value;
32290
+ const numeric = Number(value);
32291
+ if (Number.isFinite(numeric))
32292
+ return numeric;
32293
+ return 0;
32294
+ }
32295
+ function normalizeFirmwareTargets(params) {
32296
+ var _a, _b, _c;
32297
+ const targets = (_a = params.targets) !== null && _a !== void 0 ? _a : (params.path
32298
+ ? [
32299
+ {
32300
+ target_id: (_c = (_b = params.target_id) !== null && _b !== void 0 ? _b : params.targetId) !== null && _c !== void 0 ? _c : 0,
32301
+ path: params.path,
32302
+ },
32303
+ ]
32304
+ : []);
32305
+ return targets.map(target => ({
32306
+ target_id: normalizeTargetId('target_id' in target ? target.target_id : target.targetId),
32307
+ path: target.path,
32308
+ }));
32309
+ }
32310
+ function buildTargets(params) {
32311
+ if (params.targets)
32312
+ return params.targets;
32313
+ const targets = {
32314
+ hw: params.targetHw,
32315
+ fw: params.targetFw,
32316
+ bt: params.targetBt,
32317
+ se1: params.targetSe1,
32318
+ se2: params.targetSe2,
32319
+ se3: params.targetSe3,
32320
+ se4: params.targetSe4,
32321
+ status: params.targetStatus,
32322
+ };
32323
+ return Object.values(targets).some(value => value !== undefined) ? targets : undefined;
32324
+ }
32325
+ function buildTypes(params) {
32326
+ if (params.types)
32327
+ return params.types;
32328
+ const types = {
32329
+ version: params.includeVersion,
32330
+ build_id: params.includeBuildId,
32331
+ hash: params.includeHash,
32332
+ specific: params.includeSpecific,
32333
+ };
32334
+ return Object.values(types).some(value => value !== undefined) ? types : undefined;
32335
+ }
32336
+
32337
+ const Log$4 = getLogger(exports.LoggerNames.Method);
32338
+ const SESSION_ERROR = 'session not found';
32339
+ const PROTOCOL_V2_BOOTLOADER_RECONNECT_TIMEOUT = 60 * 1000;
32340
+ const PROTOCOL_V2_SHORT_RESPONSE_TIMEOUT = 5 * 1000;
32341
+ const PROTOCOL_V2_INSTALL_TIMEOUT = 5 * 60 * 1000;
32342
+ const PROTOCOL_V2_TARGET_STATUS_FINISHED = 0;
32343
+ const PROTOCOL_V2_TARGET_STATUS_IN_PROGRESS = 1;
32344
+ const PROTOCOL_V2_TARGET_STATUS_FAILED = 2;
32345
+ const PROTOCOL_V2_CONNECT_PROTOCOL = 'V2';
32346
+ const PROTOCOL_V2_FIRMWARE_STAGING_VOLUME = 'vol1:';
32347
+ const PROTOCOL_V2_MIN_FILE_CHUNK_SIZE = 64;
32348
+ const getUnknownErrorText = (error) => {
32349
+ if (!error) {
32350
+ return '';
32351
+ }
32352
+ if (typeof error === 'string') {
32353
+ return error;
32354
+ }
32355
+ const parts = [];
32356
+ if (error instanceof Error) {
32357
+ parts.push(error.name, error.message);
32358
+ }
32359
+ if (typeof error === 'object') {
32360
+ const record = error;
32361
+ for (const field of ['name', 'message', 'reason', 'code', 'errorCode', 'nativeErrorCode']) {
32362
+ const value = record[field];
32363
+ if (value !== undefined && value !== null) {
32364
+ parts.push(String(value));
32365
+ }
32366
+ }
32367
+ }
32368
+ const stringified = String(error);
32369
+ if (stringified && stringified !== '[object Object]') {
32370
+ parts.push(stringified);
32371
+ }
32372
+ return parts.filter(Boolean).join(' ');
32373
+ };
32374
+ const isDeviceDisconnectedError = (error) => {
32375
+ const message = getUnknownErrorText(error).toLowerCase();
32376
+ const compactMessage = message.replace(/\s+/g, '');
32377
+ return (message.includes('device was disconnected') ||
32378
+ message.includes('device disconnected') ||
32379
+ message.includes('device disconnect') ||
32380
+ message.includes('was disconnected') ||
32381
+ message.includes('bledevicedisconnected') ||
32382
+ message.includes('bleconnectederror') ||
32383
+ message.includes('connected error is always runtime error') ||
32384
+ message.includes('connection has timed out unexpectedly') ||
32385
+ message.includes('connection error has occured') ||
32386
+ message.includes('connection error has occurred') ||
32387
+ message.includes('transferIn') ||
32388
+ message.includes('transferin') ||
32389
+ message.includes('usbdevice') ||
32390
+ message.includes('multiplatformbleadapter') ||
32391
+ message.includes('multipalformebleadapter') ||
32392
+ compactMessage.includes('rxerrorerror6') ||
32393
+ message.includes('rxerror error 6'));
32394
+ };
32395
+ const isProtocolV2ReconnectProbeError = (error) => {
32396
+ const message = getUnknownErrorText(error).toLowerCase();
32397
+ return ((message.includes('device protocol mismatch') && message.includes('expected v2')) ||
32398
+ message.includes('did not respond to expected protocol'));
32399
+ };
32400
+ const isProtocolV2PollingTransientError = (error) => {
32401
+ const message = getUnknownErrorText(error).toLowerCase();
32402
+ return (isDeviceDisconnectedError(error) ||
32403
+ isProtocolV2ReconnectProbeError(error) ||
32404
+ (message.includes('response timeout') && message.includes('devgetfirmwareupdatestatus')) ||
32405
+ message.includes('device not found') ||
32406
+ message.includes('transportnotfound'));
32407
+ };
32408
+ class FirmwareUpdateV4 extends FirmwareUpdateBaseMethod {
32409
+ init() {
32410
+ this.allowDeviceMode = [UI_REQUEST.BOOTLOADER, UI_REQUEST.NOT_INITIALIZE];
32411
+ this.requireDeviceMode = [];
32412
+ this.useDevicePassphraseState = false;
32413
+ this.skipForceUpdateCheck = true;
32414
+ const { payload } = this;
32415
+ validateParams(payload, [
32416
+ { name: 'bleVersion', type: 'array' },
32417
+ { name: 'bleBinary', type: 'buffer' },
32418
+ { name: 'chunkSize', type: 'number' },
32419
+ { name: 'firmwareVersion', type: 'array' },
32420
+ { name: 'firmwareBinary', type: 'buffer' },
32421
+ { name: 'resourceBinary', type: 'buffer' },
32422
+ { name: 'forcedUpdateRes', type: 'boolean' },
32423
+ { name: 'bootloaderVersion', type: 'array' },
32424
+ { name: 'bootloaderBinary', type: 'buffer' },
32425
+ { name: 'firmwareType', type: 'string' },
32426
+ { name: 'platform', type: 'string' },
32427
+ ]);
32428
+ this.params = {
32429
+ bleBinary: payload.bleBinary,
32430
+ chunkSize: payload.chunkSize,
32431
+ firmwareBinary: payload.firmwareBinary,
32432
+ forcedUpdateRes: payload.forcedUpdateRes,
32433
+ bleVersion: payload.bleVersion,
32434
+ bootloaderVersion: payload.bootloaderVersion,
32435
+ bootloaderBinary: payload.bootloaderBinary,
32436
+ firmwareVersion: payload.firmwareVersion,
32437
+ resourceBinary: payload.resourceBinary,
32438
+ firmwareType: payload.firmwareType,
32439
+ platform: payload.platform,
32440
+ };
32441
+ }
32442
+ getProtocolV2FirmwareChunkSize() {
32443
+ var _a, _b;
32444
+ const payloadChunkSize = Number((_a = this.params) === null || _a === void 0 ? void 0 : _a.chunkSize);
32445
+ const env = DataManager.getSettings('env');
32446
+ const maxChunkSize = ((_b = this.params) === null || _b === void 0 ? void 0 : _b.platform) === 'native' || (env && DataManager.isBleConnect(env))
32447
+ ? hdTransport.PROTOCOL_V2_BLE_FILE_CHUNK_SIZE
32448
+ : hdTransport.PROTOCOL_V2_WEBUSB_FILE_CHUNK_SIZE;
32449
+ if (!Number.isFinite(payloadChunkSize) || payloadChunkSize <= 0) {
32450
+ return maxChunkSize;
32451
+ }
32452
+ return Math.min(Math.max(Math.floor(payloadChunkSize), PROTOCOL_V2_MIN_FILE_CHUNK_SIZE), maxChunkSize);
32453
+ }
32454
+ run() {
32455
+ var _a;
32456
+ return __awaiter(this, void 0, void 0, function* () {
32457
+ if (((_a = this.device.originalDescriptor) === null || _a === void 0 ? void 0 : _a.protocolType) !== 'V2') {
32458
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.RuntimeError, 'firmwareUpdateV4 requires a Protocol V2 device');
32459
+ }
32460
+ Log$4.debug('FirmwareUpdateV4 strategy: Protocol V2');
32461
+ return this.runProtocolV2();
32462
+ });
32463
+ }
32464
+ runProtocolV2() {
32465
+ var _a, _b;
32466
+ return __awaiter(this, void 0, void 0, function* () {
32467
+ const { device } = this;
32468
+ const { features } = device;
32469
+ if (!features) {
32470
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.RuntimeError, 'Device features not available');
32471
+ }
32472
+ const deviceFirmwareType = getFirmwareType(features);
32473
+ const firmwareType = (_a = this.params.firmwareType) !== null && _a !== void 0 ? _a : deviceFirmwareType;
32474
+ let resourceBinary = null;
32475
+ let fwBinaryMap = [];
32476
+ let bootloaderBinary = null;
32477
+ try {
32478
+ this.postTipMessage(exports.FirmwareUpdateTipMessage.StartDownloadFirmware);
32479
+ resourceBinary = yield this.prepareResourceBinary(firmwareType);
32480
+ fwBinaryMap = yield this.prepareFirmwareAndBleBinary(firmwareType);
32481
+ bootloaderBinary = yield this.prepareBootloaderBinary(firmwareType);
32482
+ this.postTipMessage(exports.FirmwareUpdateTipMessage.FinishDownloadFirmware);
32483
+ }
32484
+ catch (err) {
32485
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.FirmwareUpdateDownloadFailed, (_b = err.message) !== null && _b !== void 0 ? _b : err);
32486
+ }
32487
+ if (!resourceBinary && !bootloaderBinary && fwBinaryMap.length === 0) {
32488
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.FirmwareUpdateDownloadFailed, 'No firmware to update');
32489
+ }
32490
+ yield this.executeProtocolV2Update({
32491
+ resourceBinary,
32492
+ fwBinaryMap,
32493
+ bootloaderBinary,
32494
+ });
32495
+ yield this.exitProtocolV2BootloaderToNormal();
32496
+ const versions = yield this.waitForProtocolV2FinalFeatures();
32497
+ this.postTipMessage(exports.FirmwareUpdateTipMessage.FirmwareUpdateCompleted);
32498
+ DevicePool.resetState();
32499
+ return versions;
32500
+ });
32501
+ }
32502
+ prepareResourceBinary(firmwareType) {
32503
+ return __awaiter(this, void 0, void 0, function* () {
32504
+ if (this.params.resourceBinary) {
32505
+ return this.params.resourceBinary;
32506
+ }
32507
+ const { features } = this.device;
32508
+ if (!features)
32509
+ return null;
32510
+ const resourceUrl = DataManager.getSysResourcesLatestRelease({
32511
+ features,
32512
+ forcedUpdateRes: this.params.forcedUpdateRes,
32513
+ firmwareType,
32514
+ });
32515
+ if (resourceUrl) {
32516
+ const resource = (yield getSysResourceBinary(resourceUrl)).binary;
32517
+ return resource;
32518
+ }
32519
+ Log$4.warn('No resource url found');
32520
+ return null;
32521
+ });
32522
+ }
32523
+ prepareBootloaderBinary(firmwareType) {
32524
+ return __awaiter(this, void 0, void 0, function* () {
32525
+ if (this.params.bootloaderBinary) {
32526
+ return this.params.bootloaderBinary;
32527
+ }
32528
+ const { features } = this.device;
32529
+ if (!features)
32530
+ return null;
32531
+ if (this.params.bootloaderVersion) {
32532
+ const bootResourceUrl = DataManager.getBootloaderResource(features, firmwareType);
32533
+ if (bootResourceUrl) {
32534
+ const bootBinary = (yield getSysResourceBinary(bootResourceUrl)).binary;
32535
+ return bootBinary;
32536
+ }
32537
+ }
32538
+ return null;
32539
+ });
32540
+ }
32541
+ prepareFirmwareAndBleBinary(firmwareType) {
32542
+ return __awaiter(this, void 0, void 0, function* () {
32543
+ const fwBinaryMap = [];
32544
+ if (this.params.firmwareBinary) {
32545
+ fwBinaryMap.push({
32546
+ fileName: 'firmware.bin',
32547
+ binary: this.params.firmwareBinary,
32548
+ });
32549
+ }
32550
+ else if (this.params.firmwareVersion) {
32551
+ const { features } = this.device;
32552
+ if (features) {
32553
+ const firmwareBinary = (yield getBinary({
32554
+ features,
32555
+ version: this.params.firmwareVersion,
32556
+ updateType: 'firmware',
32557
+ isUpdateBootloader: false,
32558
+ firmwareType,
32559
+ })).binary;
32560
+ fwBinaryMap.push({
32561
+ fileName: 'firmware.bin',
32562
+ binary: firmwareBinary,
32563
+ });
32564
+ }
32565
+ }
32566
+ if (this.params.bleBinary) {
32567
+ fwBinaryMap.push({
32568
+ fileName: 'ble-firmware.bin',
32569
+ binary: this.params.bleBinary,
32570
+ });
32571
+ }
32572
+ else if (this.params.bleVersion) {
32573
+ const { features } = this.device;
32574
+ if (features) {
32575
+ const bleBinary = yield getBinary({
32576
+ features,
32577
+ version: this.params.bleVersion,
32578
+ updateType: 'ble',
32579
+ firmwareType,
32580
+ });
32581
+ fwBinaryMap.push({
32582
+ fileName: 'ble-firmware.bin',
32583
+ binary: bleBinary.binary,
32584
+ });
32585
+ }
32586
+ }
32587
+ return fwBinaryMap;
32588
+ });
32589
+ }
32590
+ executeProtocolV2Update({ resourceBinary, fwBinaryMap, bootloaderBinary, }) {
32591
+ return __awaiter(this, void 0, void 0, function* () {
32592
+ let totalSize = 0;
32593
+ let processedSize = 0;
32594
+ if (resourceBinary)
32595
+ totalSize += resourceBinary.byteLength;
32596
+ for (const fwbinary of fwBinaryMap)
32597
+ totalSize += fwbinary.binary.byteLength;
32598
+ if (bootloaderBinary)
32599
+ totalSize += bootloaderBinary.byteLength;
32600
+ this.postTipMessage(exports.FirmwareUpdateTipMessage.StartTransferData);
32601
+ const transferStartTime = Date.now();
32602
+ const targets = [];
32603
+ if (resourceBinary) {
32604
+ const resourcePath = `${PROTOCOL_V2_FIRMWARE_STAGING_VOLUME}res/`;
32605
+ yield this.protocolV2CreateFolder(resourcePath);
32606
+ const file = yield JSZip__default["default"].loadAsync(resourceBinary);
32607
+ const files = Object.entries(file.files);
32608
+ for (const [fileName, entry] of files) {
32609
+ const name = fileName.split('/').pop();
32610
+ if (!entry.dir && fileName.indexOf('__MACOSX') === -1 && name) {
32611
+ const data = yield entry.async('arraybuffer');
32612
+ processedSize = yield this.protocolV2CommonUpdateProcess({
32613
+ payload: data,
32614
+ filePath: `${resourcePath}${name}`,
32615
+ processedSize,
32616
+ totalSize,
32617
+ transferStartTime,
32618
+ });
32619
+ }
32620
+ }
32621
+ targets.push({
32622
+ target_id: ProtocolV2FirmwareTargetType.TARGET_RESOURCE,
32623
+ path: resourcePath,
32624
+ });
32625
+ }
32626
+ if (bootloaderBinary) {
32627
+ const bootloaderPath = `${PROTOCOL_V2_FIRMWARE_STAGING_VOLUME}bootloader.bin`;
32628
+ processedSize = yield this.protocolV2CommonUpdateProcess({
32629
+ payload: bootloaderBinary,
32630
+ filePath: bootloaderPath,
32631
+ processedSize,
32632
+ totalSize,
32633
+ transferStartTime,
32634
+ });
32635
+ targets.push({
32636
+ target_id: ProtocolV2FirmwareTargetType.TARGET_MAIN_BOOT,
32637
+ path: bootloaderPath,
32638
+ });
32639
+ }
32640
+ for (const fwbinary of fwBinaryMap) {
32641
+ const firmwarePath = `${PROTOCOL_V2_FIRMWARE_STAGING_VOLUME}${fwbinary.fileName}`;
32642
+ processedSize = yield this.protocolV2CommonUpdateProcess({
32643
+ payload: fwbinary.binary,
32644
+ filePath: firmwarePath,
32645
+ processedSize,
32646
+ totalSize,
32647
+ transferStartTime,
32648
+ });
32649
+ targets.push({
32650
+ target_id: protocolV2FileNameToTargetId(fwbinary.fileName),
32651
+ path: firmwarePath,
32652
+ });
32653
+ }
32654
+ this.postTipMessage(exports.FirmwareUpdateTipMessage.ConfirmOnDevice);
32655
+ const startResponse = yield this.protocolV2StartFirmwareUpdate({ targets });
32656
+ yield this.waitForProtocolV2FirmwareUpdateComplete(targets, startResponse);
32657
+ });
32658
+ }
32659
+ queryProtocolV2FirmwareUpdateStatus() {
32660
+ return __awaiter(this, void 0, void 0, function* () {
32661
+ const typedCall = this.device.getCommands().typedCall.bind(this.device.getCommands());
32662
+ return typedCall('DevGetFirmwareUpdateStatus', 'DevFirmwareUpdateStatus', {}, {
32663
+ timeoutMs: PROTOCOL_V2_SHORT_RESPONSE_TIMEOUT,
32664
+ });
32665
+ });
32666
+ }
32667
+ pingProtocolV2Device() {
32668
+ return __awaiter(this, void 0, void 0, function* () {
32669
+ const typedCall = this.device.getCommands().typedCall.bind(this.device.getCommands());
32670
+ yield typedCall('Ping', 'Success', { message: 'firmware-update' }, {
32671
+ timeoutMs: PROTOCOL_V2_SHORT_RESPONSE_TIMEOUT,
32672
+ });
32673
+ });
32674
+ }
32675
+ assertProtocolV2TargetStatus(statusTargets, expectedTargetIds) {
32676
+ const failedTarget = statusTargets.find(target => expectedTargetIds.has(target.target_id) &&
32677
+ target.status === PROTOCOL_V2_TARGET_STATUS_FAILED);
32678
+ if (failedTarget) {
32679
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.FirmwareError, `Protocol V2 firmware target ${failedTarget.target_id} failed`);
32680
+ }
32681
+ const completedTargets = statusTargets.filter(target => expectedTargetIds.has(target.target_id) &&
32682
+ target.status === PROTOCOL_V2_TARGET_STATUS_FINISHED);
32683
+ if (completedTargets.length === expectedTargetIds.size && expectedTargetIds.size > 0) {
32684
+ return true;
32685
+ }
32686
+ const inProgressTarget = statusTargets.find(target => expectedTargetIds.has(target.target_id) &&
32687
+ target.status === PROTOCOL_V2_TARGET_STATUS_IN_PROGRESS);
32688
+ if (inProgressTarget) {
32689
+ this.postProgressMessage(99, 'installingFirmware');
32690
+ }
32691
+ return false;
32692
+ }
32693
+ waitForProtocolV2FirmwareUpdateComplete(targets, startResponse) {
32694
+ var _a, _b;
32695
+ return __awaiter(this, void 0, void 0, function* () {
32696
+ const expectedTargetIds = new Set(targets.map(target => target.target_id));
32697
+ if ((startResponse === null || startResponse === void 0 ? void 0 : startResponse.type) === 'Success') {
32698
+ return;
32699
+ }
32700
+ if ((startResponse === null || startResponse === void 0 ? void 0 : startResponse.type) === 'DevFirmwareUpdateStatus') {
32701
+ const statusTargets = ((_a = startResponse.message.targets) !== null && _a !== void 0 ? _a : []);
32702
+ if (this.assertProtocolV2TargetStatus(statusTargets, expectedTargetIds)) {
32703
+ return;
32704
+ }
32705
+ }
32706
+ const startTime = Date.now();
32707
+ let lastError;
32708
+ while (Date.now() - startTime < PROTOCOL_V2_INSTALL_TIMEOUT) {
32709
+ try {
32710
+ const statusRes = yield this.queryProtocolV2FirmwareUpdateStatus();
32711
+ const statusTargets = ((_b = statusRes.message.targets) !== null && _b !== void 0 ? _b : []);
32712
+ if (this.assertProtocolV2TargetStatus(statusTargets, expectedTargetIds)) {
32713
+ return;
32714
+ }
32715
+ }
32716
+ catch (error) {
32717
+ lastError = error;
32718
+ if (error instanceof hdShared.HardwareError && error.errorCode === hdShared.HardwareErrorCode.FirmwareError) {
32719
+ throw error;
32720
+ }
32721
+ Log$4.log('Protocol V2 firmware install status polling failed: ', error);
32722
+ if (isProtocolV2PollingTransientError(error)) {
32723
+ try {
32724
+ yield this.reconnectProtocolV2Device();
32725
+ }
32726
+ catch (reconnectError) {
32727
+ lastError = reconnectError;
32728
+ Log$4.log('Protocol V2 firmware install reconnect/status polling failed: ', reconnectError);
32729
+ }
32730
+ try {
32731
+ yield this.pingProtocolV2Device();
32732
+ Log$4.log('Protocol V2 firmware status unavailable, Ping is ready');
32733
+ return;
32734
+ }
32735
+ catch (pingError) {
32736
+ lastError = pingError;
32737
+ Log$4.log('Protocol V2 firmware install Ping polling failed: ', pingError);
32738
+ }
32739
+ }
32740
+ }
32741
+ yield hdShared.wait(1000);
32742
+ }
32743
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.RuntimeError, `Protocol V2 firmware update status timeout: ${this.normalizeErrorMessage(lastError)}`);
32744
+ });
32745
+ }
32746
+ exitProtocolV2BootloaderToNormal() {
32747
+ return __awaiter(this, void 0, void 0, function* () {
32748
+ this.postTipMessage(exports.FirmwareUpdateTipMessage.SwitchFirmwareReconnectDevice);
32749
+ yield this.protocolV2Reboot(hdTransport.DevRebootType.Normal);
32750
+ });
32751
+ }
32752
+ waitForProtocolV2FinalFeatures() {
32753
+ return __awaiter(this, void 0, void 0, function* () {
32754
+ const features = yield this.waitForProtocolV2ReconnectAndFeatures(PROTOCOL_V2_BOOTLOADER_RECONNECT_TIMEOUT);
32755
+ this.device._updateFeatures(features);
32756
+ const bootloaderVersion = getDeviceBootloaderVersion(features).join('.');
32757
+ const bleVersion = getDeviceBLEFirmwareVersion(features).join('.');
32758
+ const firmwareVersion = getDeviceFirmwareVersion(features).join('.');
32759
+ if (firmwareVersion === '0.0.0') {
32760
+ Log$4.warn('Protocol V2 firmware update finished but app firmware version is still 0.0.0. This is allowed for Pro2 debug BLE-only update flows.');
32761
+ }
32762
+ return {
32763
+ bootloaderVersion,
32764
+ bleVersion,
32765
+ firmwareVersion,
32766
+ };
32767
+ });
32768
+ }
32769
+ waitForProtocolV2ReconnectAndFeatures(timeout) {
32770
+ return __awaiter(this, void 0, void 0, function* () {
32771
+ const startTime = Date.now();
32772
+ let lastError;
32773
+ while (Date.now() - startTime < timeout) {
32774
+ try {
32775
+ yield this.reconnectProtocolV2Device();
32776
+ const features = yield getProtocolV2Features({
32777
+ commands: this.device.getCommands(),
32778
+ descriptor: this.device.originalDescriptor,
32779
+ onDeviceInfoError: error => {
32780
+ Log$4.debug('Protocol V2 post-update DevGetDeviceInfo failed:', error);
32781
+ },
32782
+ timeoutMs: PROTOCOL_V2_SHORT_RESPONSE_TIMEOUT,
32783
+ });
32784
+ return features;
32785
+ }
32786
+ catch (error) {
32787
+ lastError = error;
32788
+ Log$4.log('Protocol V2 normal mode not ready, polling Ping/DevGetDeviceInfo: ', error);
32789
+ yield hdShared.wait(1000);
32790
+ }
32791
+ }
32792
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.DeviceNotFound, `Protocol V2 final features not ready within ${timeout / 1000}s: ${this.normalizeErrorMessage(lastError)}`);
32793
+ });
32794
+ }
32795
+ reconnectProtocolV2Device() {
32796
+ var _a, _b, _c;
32797
+ return __awaiter(this, void 0, void 0, function* () {
32798
+ if (this.isBleReconnect()) {
32799
+ yield this.acquireProtocolV2BleDevice();
32800
+ return;
32801
+ }
32802
+ const deviceDiff = yield ((_a = this.device.deviceConnector) === null || _a === void 0 ? void 0 : _a.enumerate());
32803
+ const devicesDescriptor = (_b = deviceDiff === null || deviceDiff === void 0 ? void 0 : deviceDiff.descriptors) !== null && _b !== void 0 ? _b : [];
32804
+ const { deviceList } = yield DevicePool.getDevices(devicesDescriptor, this.connectId);
32805
+ if (deviceList.length !== 1) {
32806
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.DeviceNotFound);
32807
+ }
32808
+ this.device.updateFromCache(deviceList[0]);
32809
+ yield this.device.acquire();
32810
+ this.device.commands.disposed = false;
32811
+ this.device.getCommands().mainId = (_c = this.device.mainId) !== null && _c !== void 0 ? _c : '';
32812
+ });
32813
+ }
32814
+ protocolV2CreateFolder(path) {
32815
+ return __awaiter(this, void 0, void 0, function* () {
32816
+ const typedCall = this.device.getCommands().typedCall.bind(this.device.getCommands());
32817
+ yield typedCall('FilesystemDirMake', 'Success', { path });
32818
+ });
32819
+ }
32820
+ protocolV2CommonUpdateProcess({ payload, filePath, processedSize, totalSize, transferStartTime = Date.now(), }) {
32821
+ var _a;
32822
+ return __awaiter(this, void 0, void 0, function* () {
32823
+ const chunkSize = this.getProtocolV2FirmwareChunkSize();
32824
+ let offset = 0;
32825
+ const getUploadProgress = (fileOffset) => {
32826
+ if (totalSize !== undefined && processedSize !== undefined) {
32827
+ return Math.min(Math.ceil(((processedSize + fileOffset) / totalSize) * 100), 99);
32828
+ }
32829
+ return Math.min(Math.ceil((fileOffset / payload.byteLength) * 100), 99);
32830
+ };
32831
+ while (offset < payload.byteLength) {
32832
+ const chunkEnd = Math.min(offset + chunkSize, payload.byteLength);
32833
+ const chunkLength = chunkEnd - offset;
32834
+ const chunk = payload.slice(offset, chunkEnd);
32835
+ const overwrite = offset === 0;
32836
+ const progress = getUploadProgress(chunkEnd);
32837
+ const writeRes = yield this.fileWriteWithRetry(filePath, payload.byteLength, offset, chunk, overwrite, progress);
32838
+ const nextOffset = (_a = writeRes.message.processed_byte) !== null && _a !== void 0 ? _a : offset + chunkLength;
32839
+ if (nextOffset <= offset || nextOffset > payload.byteLength) {
32840
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.EmmcFileWriteFirmwareError, `invalid processed_byte ${nextOffset} for offset ${offset}`);
32841
+ }
32842
+ offset = nextOffset;
32843
+ const elapsedMs = Date.now() - transferStartTime;
32844
+ const transferredBytes = totalSize !== undefined && processedSize !== undefined
32845
+ ? Math.min(processedSize + offset, totalSize)
32846
+ : offset;
32847
+ const totalBytes = totalSize !== null && totalSize !== void 0 ? totalSize : payload.byteLength;
32848
+ this.postProgressMessage(getUploadProgress(offset), 'transferData', {
32849
+ transferredBytes,
32850
+ totalBytes,
32851
+ rateBytesPerSecond: elapsedMs > 0 ? Math.round((transferredBytes / elapsedMs) * 1000) : undefined,
32852
+ elapsedMs,
32853
+ });
32854
+ }
32855
+ return totalSize !== undefined ? (processedSize !== null && processedSize !== void 0 ? processedSize : 0) + payload.byteLength : 0;
32856
+ });
32857
+ }
32858
+ fileWriteWithRetry(filePath, totalFileSize, offset, chunk, overwrite, progress) {
32859
+ return __awaiter(this, void 0, void 0, function* () {
32860
+ const writeFunc = () => __awaiter(this, void 0, void 0, function* () {
32861
+ var _a;
32862
+ const typedCall = this.device.getCommands().typedCall.bind(this.device.getCommands());
32863
+ const writeRes = yield typedCall('FilesystemFileWrite', 'FilesystemFile', {
32864
+ file: {
32865
+ path: filePath,
32866
+ offset,
32867
+ total_size: totalFileSize,
32868
+ data: chunk,
32869
+ },
32870
+ overwrite,
32871
+ append: false,
32872
+ ui_percentage: progress !== null && progress !== void 0 ? progress : undefined,
32873
+ });
32874
+ if (writeRes.type !== 'FilesystemFile') {
32875
+ if (writeRes.type === 'CallMethodError') {
32876
+ if (((_a = writeRes.message.error) !== null && _a !== void 0 ? _a : '').indexOf(SESSION_ERROR) > -1) {
32877
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.RuntimeError, SESSION_ERROR);
32878
+ }
32879
+ }
32880
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.EmmcFileWriteFirmwareError, 'transfer data error');
32881
+ }
32882
+ return writeRes;
32883
+ });
32884
+ let retryCount = 10;
32885
+ while (retryCount > 0) {
32886
+ try {
32887
+ const result = yield writeFunc();
32888
+ return result;
32889
+ }
32890
+ catch (error) {
32891
+ Log$4.error(`fileWrite error: `, error);
32892
+ retryCount--;
32893
+ if (retryCount === 0) {
32894
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.EmmcFileWriteFirmwareError, 'transfer data error');
32895
+ }
32896
+ const env = DataManager.getSettings('env');
32897
+ if (DataManager.isBleConnect(env)) {
32898
+ yield hdShared.wait(3000);
32899
+ yield this.acquireProtocolV2BleDevice();
32900
+ yield this.device.initialize();
32901
+ }
32902
+ yield hdShared.wait(2000);
32903
+ }
32904
+ }
32905
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.EmmcFileWriteFirmwareError, 'transfer data error');
32906
+ });
32907
+ }
32908
+ acquireProtocolV2BleDevice() {
32909
+ var _a;
32910
+ return __awaiter(this, void 0, void 0, function* () {
32911
+ yield ((_a = this.device.deviceConnector) === null || _a === void 0 ? void 0 : _a.acquire(this.device.originalDescriptor.id, null, true, PROTOCOL_V2_CONNECT_PROTOCOL));
32912
+ });
32913
+ }
32914
+ protocolV2StartFirmwareUpdate({ targets, }) {
32915
+ return __awaiter(this, void 0, void 0, function* () {
32916
+ const typedCall = this.device.getCommands().typedCall.bind(this.device.getCommands());
32917
+ let response;
32918
+ try {
32919
+ response = yield typedCall('DevFirmwareUpdate', PROTOCOL_V2_FIRMWARE_UPDATE_RESPONSE_TYPES, {
32920
+ targets,
32921
+ }, {
32922
+ intermediateTypes: ['DevFirmwareInstallProgress'],
32923
+ onIntermediateResponse: (response) => {
32924
+ var _a;
32925
+ const progress = Number((_a = response.message) === null || _a === void 0 ? void 0 : _a.progress);
32926
+ if (Number.isFinite(progress)) {
32927
+ this.postProgressMessage(Math.min(progress, 99), 'installingFirmware');
32928
+ }
32929
+ },
32930
+ });
32931
+ }
32932
+ catch (error) {
32933
+ if (isDeviceDisconnectedError(error)) {
32934
+ Log$4.log('Rebooting device');
32935
+ }
32936
+ else {
32937
+ throw error;
32938
+ }
32939
+ }
32940
+ this.postTipMessage(exports.FirmwareUpdateTipMessage.FirmwareUpdating);
32941
+ return response;
32942
+ });
32943
+ }
32944
+ protocolV2Reboot(rebootType) {
32945
+ return __awaiter(this, void 0, void 0, function* () {
32946
+ const typedCall = this.device.getCommands().typedCall.bind(this.device.getCommands());
32947
+ try {
32948
+ const res = yield typedCall('DevReboot', 'Success', {
32949
+ reboot_type: rebootType,
32950
+ });
32951
+ return res.message;
32952
+ }
32953
+ catch (error) {
32954
+ if (isDeviceDisconnectedError(error) || isProtocolV2ReconnectProbeError(error)) {
32955
+ return { message: 'Device rebooted successfully' };
32956
+ }
32957
+ throw error;
32958
+ }
32959
+ });
32960
+ }
32961
+ normalizeErrorMessage(error) {
32962
+ if (!error) {
32963
+ return '';
32964
+ }
32965
+ return getUnknownErrorText(error);
32966
+ }
32967
+ }
32968
+
30969
32969
  const Log$3 = getLogger(exports.LoggerNames.Method);
30970
32970
  class PromptWebDeviceAccess extends BaseMethod {
30971
32971
  init() {
@@ -31023,6 +33023,538 @@ class PromptWebDeviceAccess extends BaseMethod {
31023
33023
  }
31024
33024
  }
31025
33025
 
33026
+ class GetProtoVersion extends BaseMethod {
33027
+ init() {
33028
+ this.skipForceUpdateCheck = true;
33029
+ this.useDevicePassphraseState = false;
33030
+ this.params = undefined;
33031
+ }
33032
+ run() {
33033
+ return __awaiter(this, void 0, void 0, function* () {
33034
+ const res = yield this.device.commands.typedCall('GetProtoVersion', 'ProtoVersion', {});
33035
+ return Promise.resolve(res.message);
33036
+ });
33037
+ }
33038
+ }
33039
+
33040
+ class Ping extends BaseMethod {
33041
+ init() {
33042
+ this.skipForceUpdateCheck = true;
33043
+ this.useDevicePassphraseState = false;
33044
+ this.params = { message: this.payload.message };
33045
+ }
33046
+ run() {
33047
+ var _a;
33048
+ return __awaiter(this, void 0, void 0, function* () {
33049
+ const res = yield this.device.commands.typedCall('Ping', 'Success', {
33050
+ message: (_a = this.params.message) !== null && _a !== void 0 ? _a : '',
33051
+ });
33052
+ return Promise.resolve(res.message);
33053
+ });
33054
+ }
33055
+ }
33056
+
33057
+ class DevReboot extends BaseMethod {
33058
+ init() {
33059
+ this.skipForceUpdateCheck = true;
33060
+ this.useDevicePassphraseState = false;
33061
+ this.params = {
33062
+ rebootType: this.payload.rebootType,
33063
+ reboot_type: this.payload.reboot_type,
33064
+ };
33065
+ }
33066
+ run() {
33067
+ var _a;
33068
+ return __awaiter(this, void 0, void 0, function* () {
33069
+ const res = yield this.device.commands.typedCall('DevReboot', 'Success', {
33070
+ reboot_type: normalizeRebootType((_a = this.params.reboot_type) !== null && _a !== void 0 ? _a : this.params.rebootType),
33071
+ });
33072
+ return Promise.resolve(res.message);
33073
+ });
33074
+ }
33075
+ }
33076
+
33077
+ class DevGetDeviceInfo extends BaseMethod {
33078
+ init() {
33079
+ this.skipForceUpdateCheck = true;
33080
+ this.useDevicePassphraseState = false;
33081
+ this.params = {
33082
+ targets: this.payload.targets,
33083
+ types: this.payload.types,
33084
+ targetHw: this.payload.targetHw,
33085
+ targetFw: this.payload.targetFw,
33086
+ targetBt: this.payload.targetBt,
33087
+ targetSe1: this.payload.targetSe1,
33088
+ targetSe2: this.payload.targetSe2,
33089
+ targetSe3: this.payload.targetSe3,
33090
+ targetSe4: this.payload.targetSe4,
33091
+ targetStatus: this.payload.targetStatus,
33092
+ includeVersion: this.payload.includeVersion,
33093
+ includeBuildId: this.payload.includeBuildId,
33094
+ includeHash: this.payload.includeHash,
33095
+ includeSpecific: this.payload.includeSpecific,
33096
+ };
33097
+ }
33098
+ run() {
33099
+ return __awaiter(this, void 0, void 0, function* () {
33100
+ const res = yield this.device.commands.typedCall('DevGetDeviceInfo', 'DeviceInfo', {
33101
+ targets: buildTargets(this.params),
33102
+ types: buildTypes(this.params),
33103
+ });
33104
+ return Promise.resolve(res.message);
33105
+ });
33106
+ }
33107
+ }
33108
+
33109
+ class DevGetOnboardingStatus extends BaseMethod {
33110
+ init() {
33111
+ this.skipForceUpdateCheck = true;
33112
+ this.useDevicePassphraseState = false;
33113
+ this.params = undefined;
33114
+ }
33115
+ run() {
33116
+ return __awaiter(this, void 0, void 0, function* () {
33117
+ const res = yield this.device.commands.typedCall('DevGetOnboardingStatus', 'DevOnboardingStatus', {});
33118
+ return Promise.resolve(res.message);
33119
+ });
33120
+ }
33121
+ }
33122
+
33123
+ class DevFirmwareUpdate extends BaseMethod {
33124
+ init() {
33125
+ this.skipForceUpdateCheck = true;
33126
+ this.useDevicePassphraseState = false;
33127
+ this.params = {
33128
+ targets: this.payload.targets,
33129
+ targetId: this.payload.targetId,
33130
+ target_id: this.payload.target_id,
33131
+ path: this.payload.path,
33132
+ };
33133
+ }
33134
+ run() {
33135
+ return __awaiter(this, void 0, void 0, function* () {
33136
+ const res = yield this.device.commands.typedCall('DevFirmwareUpdate', PROTOCOL_V2_FIRMWARE_UPDATE_RESPONSE_TYPES, {
33137
+ targets: normalizeFirmwareTargets(this.params),
33138
+ }, PROTOCOL_V2_FIRMWARE_UPDATE_OPTIONS);
33139
+ return Promise.resolve(res.message);
33140
+ });
33141
+ }
33142
+ }
33143
+
33144
+ class DevGetFirmwareUpdateStatus extends BaseMethod {
33145
+ init() {
33146
+ this.skipForceUpdateCheck = true;
33147
+ this.useDevicePassphraseState = false;
33148
+ this.params = undefined;
33149
+ }
33150
+ run() {
33151
+ return __awaiter(this, void 0, void 0, function* () {
33152
+ const res = yield this.device.commands.typedCall('DevGetFirmwareUpdateStatus', 'DevFirmwareUpdateStatus', {});
33153
+ return Promise.resolve(res.message);
33154
+ });
33155
+ }
33156
+ }
33157
+
33158
+ class FactoryDeviceInfoSettings extends BaseMethod {
33159
+ init() {
33160
+ this.skipForceUpdateCheck = true;
33161
+ this.useDevicePassphraseState = false;
33162
+ this.params = {
33163
+ serial_no: this.payload.serial_no,
33164
+ serialNo: this.payload.serialNo,
33165
+ cpu_info: this.payload.cpu_info,
33166
+ cpuInfo: this.payload.cpuInfo,
33167
+ pre_firmware: this.payload.pre_firmware,
33168
+ preFirmware: this.payload.preFirmware,
33169
+ };
33170
+ }
33171
+ run() {
33172
+ var _a, _b, _c;
33173
+ return __awaiter(this, void 0, void 0, function* () {
33174
+ const res = yield this.device.commands.typedCall('FactoryDeviceInfoSettings', 'Success', {
33175
+ serial_no: (_a = this.params.serial_no) !== null && _a !== void 0 ? _a : this.params.serialNo,
33176
+ cpu_info: (_b = this.params.cpu_info) !== null && _b !== void 0 ? _b : this.params.cpuInfo,
33177
+ pre_firmware: (_c = this.params.pre_firmware) !== null && _c !== void 0 ? _c : this.params.preFirmware,
33178
+ });
33179
+ return Promise.resolve(res.message);
33180
+ });
33181
+ }
33182
+ }
33183
+
33184
+ class FactoryGetDeviceInfo extends BaseMethod {
33185
+ init() {
33186
+ this.skipForceUpdateCheck = true;
33187
+ this.useDevicePassphraseState = false;
33188
+ this.params = undefined;
33189
+ }
33190
+ run() {
33191
+ return __awaiter(this, void 0, void 0, function* () {
33192
+ const res = yield this.device.commands.typedCall('FactoryGetDeviceInfo', 'FactoryDeviceInfo', {});
33193
+ return Promise.resolve(res.message);
33194
+ });
33195
+ }
33196
+ }
33197
+
33198
+ class FilesystemFixPermission extends BaseMethod {
33199
+ init() {
33200
+ this.skipForceUpdateCheck = true;
33201
+ this.useDevicePassphraseState = false;
33202
+ this.params = undefined;
33203
+ }
33204
+ run() {
33205
+ return __awaiter(this, void 0, void 0, function* () {
33206
+ const res = yield this.device.commands.typedCall('FilesystemFixPermission', 'Success', {});
33207
+ return Promise.resolve(res.message);
33208
+ });
33209
+ }
33210
+ }
33211
+
33212
+ class FilesystemFormat extends BaseMethod {
33213
+ init() {
33214
+ this.skipForceUpdateCheck = true;
33215
+ this.useDevicePassphraseState = false;
33216
+ this.params = undefined;
33217
+ }
33218
+ run() {
33219
+ return __awaiter(this, void 0, void 0, function* () {
33220
+ const res = yield this.device.commands.typedCall('FilesystemFormat', 'Success', {});
33221
+ return Promise.resolve(res.message);
33222
+ });
33223
+ }
33224
+ }
33225
+
33226
+ const MIN_FILE_READ_CHUNK_SIZE = 64;
33227
+ function getProtocolV2FileReadChunkLimit() {
33228
+ const env = DataManager.getSettings('env');
33229
+ if (env && DataManager.isBleConnect(env)) {
33230
+ return hdTransport.PROTOCOL_V2_BLE_FILE_CHUNK_SIZE;
33231
+ }
33232
+ return hdTransport.PROTOCOL_V2_WEBUSB_FILE_CHUNK_SIZE;
33233
+ }
33234
+ function normalizeChunkSize$1(value, maxChunkSize) {
33235
+ const numeric = Number(value);
33236
+ if (!Number.isFinite(numeric) || numeric <= 0)
33237
+ return maxChunkSize;
33238
+ return Math.min(Math.max(Math.floor(numeric), MIN_FILE_READ_CHUNK_SIZE), maxChunkSize);
33239
+ }
33240
+ function toFiniteNumber(value) {
33241
+ if (typeof value === 'number' && Number.isFinite(value))
33242
+ return value;
33243
+ if (typeof value === 'string') {
33244
+ const numeric = Number(value);
33245
+ return Number.isFinite(numeric) ? numeric : undefined;
33246
+ }
33247
+ if (value && typeof value === 'object') {
33248
+ const longLike = value;
33249
+ if (typeof longLike.toNumber === 'function') {
33250
+ const numeric = longLike.toNumber();
33251
+ return Number.isFinite(numeric) ? numeric : undefined;
33252
+ }
33253
+ }
33254
+ return undefined;
33255
+ }
33256
+ function toUint8Array(value) {
33257
+ if (value instanceof Uint8Array)
33258
+ return value;
33259
+ if (value instanceof ArrayBuffer)
33260
+ return new Uint8Array(value);
33261
+ if (ArrayBuffer.isView(value)) {
33262
+ return new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
33263
+ }
33264
+ if (typeof value === 'string') {
33265
+ const hex = stripHexPrefix(value);
33266
+ if (!hex)
33267
+ return new Uint8Array(0);
33268
+ if (!isHexString(hex) || hex.length % 2 !== 0)
33269
+ return new Uint8Array(0);
33270
+ return hexToBytes(hex);
33271
+ }
33272
+ return new Uint8Array(0);
33273
+ }
33274
+ class FileRead extends BaseMethod {
33275
+ init() {
33276
+ var _a, _b;
33277
+ this.skipForceUpdateCheck = true;
33278
+ this.useDevicePassphraseState = false;
33279
+ this.params = {
33280
+ path: this.payload.path,
33281
+ offset: (_a = this.payload.offset) !== null && _a !== void 0 ? _a : 0,
33282
+ totalSize: (_b = this.payload.totalSize) !== null && _b !== void 0 ? _b : 0,
33283
+ chunkLen: this.payload.chunkLen,
33284
+ uiPercentage: this.payload.uiPercentage,
33285
+ };
33286
+ }
33287
+ run() {
33288
+ var _a, _b, _c, _d, _e, _f;
33289
+ return __awaiter(this, void 0, void 0, function* () {
33290
+ const startOffset = (_a = this.params.offset) !== null && _a !== void 0 ? _a : 0;
33291
+ const requestedLength = Number(this.params.totalSize);
33292
+ const chunkSize = normalizeChunkSize$1(this.params.chunkLen, getProtocolV2FileReadChunkLimit());
33293
+ let totalLength = Number.isFinite(requestedLength) && requestedLength > 0 ? requestedLength : 0;
33294
+ if (totalLength === 0) {
33295
+ const pathInfoRes = yield this.device.commands.typedCall('FilesystemPathInfoQuery', 'FilesystemPathInfo', {
33296
+ path: this.params.path,
33297
+ });
33298
+ const fileSize = toFiniteNumber((_b = pathInfoRes.message) === null || _b === void 0 ? void 0 : _b.size);
33299
+ if (!((_c = pathInfoRes.message) === null || _c === void 0 ? void 0 : _c.exist) || ((_d = pathInfoRes.message) === null || _d === void 0 ? void 0 : _d.directory)) {
33300
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.RuntimeError, `FilesystemFileRead path is not a file: ${this.params.path}`);
33301
+ }
33302
+ if (fileSize === undefined || fileSize < startOffset) {
33303
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.RuntimeError, `FilesystemFileRead invalid offset ${startOffset} for ${this.params.path}`);
33304
+ }
33305
+ totalLength = fileSize - startOffset;
33306
+ }
33307
+ const chunks = [];
33308
+ let read = 0;
33309
+ let lastMessage;
33310
+ while (read < totalLength) {
33311
+ const readLen = Math.min(chunkSize, totalLength - read);
33312
+ const offset = startOffset + read;
33313
+ const progress = (_e = this.params.uiPercentage) !== null && _e !== void 0 ? _e : Math.min(Math.ceil(((read + readLen) / Math.max(totalLength, 1)) * 100), 99);
33314
+ const res = yield this.device.commands.typedCall('FilesystemFileRead', 'FilesystemFile', {
33315
+ file: {
33316
+ path: this.params.path,
33317
+ offset,
33318
+ total_size: 0,
33319
+ },
33320
+ chunk_len: readLen,
33321
+ ui_percentage: progress,
33322
+ });
33323
+ const data = toUint8Array((_f = res.message) === null || _f === void 0 ? void 0 : _f.data);
33324
+ lastMessage = res.message;
33325
+ if (data.byteLength === 0) {
33326
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.RuntimeError, `FilesystemFileRead received empty data at offset ${offset}`);
33327
+ }
33328
+ chunks.push(data);
33329
+ read += data.byteLength;
33330
+ }
33331
+ const combined = new Uint8Array(read);
33332
+ let cursor = 0;
33333
+ chunks.forEach(chunk => {
33334
+ combined.set(chunk, cursor);
33335
+ cursor += chunk.byteLength;
33336
+ });
33337
+ return Promise.resolve(Object.assign(Object.assign({}, lastMessage), { path: this.params.path, offset: startOffset, total_size: totalLength, data: combined, chunks: chunks.length }));
33338
+ });
33339
+ }
33340
+ }
33341
+
33342
+ const MIN_FILE_CHUNK_SIZE = 64;
33343
+ function getProtocolV2FileChunkLimit() {
33344
+ const env = DataManager.getSettings('env');
33345
+ if (env && DataManager.isBleConnect(env)) {
33346
+ return hdTransport.PROTOCOL_V2_BLE_FILE_CHUNK_SIZE;
33347
+ }
33348
+ return hdTransport.PROTOCOL_V2_WEBUSB_FILE_CHUNK_SIZE;
33349
+ }
33350
+ function dataToUint8Array(data) {
33351
+ return __awaiter(this, void 0, void 0, function* () {
33352
+ if (typeof data === 'string') {
33353
+ return new TextEncoder().encode(data);
33354
+ }
33355
+ if (data instanceof ArrayBuffer) {
33356
+ return new Uint8Array(data);
33357
+ }
33358
+ if (ArrayBuffer.isView(data)) {
33359
+ return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
33360
+ }
33361
+ if (typeof Blob !== 'undefined' && data instanceof Blob) {
33362
+ return new Uint8Array(yield data.arrayBuffer());
33363
+ }
33364
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.RuntimeError, 'Unsupported FilesystemFileWrite data');
33365
+ });
33366
+ }
33367
+ function normalizeChunkSize(value, maxChunkSize) {
33368
+ const numeric = Number(value);
33369
+ if (!Number.isFinite(numeric) || numeric <= 0)
33370
+ return maxChunkSize;
33371
+ return Math.min(Math.max(Math.floor(numeric), MIN_FILE_CHUNK_SIZE), maxChunkSize);
33372
+ }
33373
+ function getConfirmedProgress(processedByte, totalSize, written, dataLength) {
33374
+ if (Number.isFinite(processedByte) && Number.isFinite(totalSize) && totalSize > 0) {
33375
+ if (processedByte >= totalSize)
33376
+ return 100;
33377
+ return Math.min(Math.max(Math.floor((processedByte / totalSize) * 100), 0), 99);
33378
+ }
33379
+ if (dataLength > 0) {
33380
+ if (written >= dataLength)
33381
+ return 100;
33382
+ return Math.min(Math.max(Math.floor((written / dataLength) * 100), 0), 99);
33383
+ }
33384
+ return 100;
33385
+ }
33386
+ class FileWrite extends BaseMethod {
33387
+ init() {
33388
+ var _a, _b, _c, _d;
33389
+ this.skipForceUpdateCheck = true;
33390
+ this.useDevicePassphraseState = false;
33391
+ const offset = (_a = this.payload.offset) !== null && _a !== void 0 ? _a : 0;
33392
+ this.params = {
33393
+ path: this.payload.path,
33394
+ offset,
33395
+ totalSize: (_b = this.payload.totalSize) !== null && _b !== void 0 ? _b : 0,
33396
+ data: this.payload.data,
33397
+ chunkSize: this.payload.chunkSize,
33398
+ chunkLen: this.payload.chunkLen,
33399
+ overwrite: (_c = this.payload.overwrite) !== null && _c !== void 0 ? _c : offset === 0,
33400
+ append: (_d = this.payload.append) !== null && _d !== void 0 ? _d : false,
33401
+ uiPercentage: this.payload.uiPercentage,
33402
+ };
33403
+ }
33404
+ run() {
33405
+ var _a, _b, _c, _d, _e, _f;
33406
+ return __awaiter(this, void 0, void 0, function* () {
33407
+ const data = yield dataToUint8Array(this.params.data);
33408
+ const dataLength = data.byteLength;
33409
+ const offsetValue = Number((_a = this.params.offset) !== null && _a !== void 0 ? _a : 0);
33410
+ const startOffset = Number.isFinite(offsetValue) && offsetValue > 0 ? offsetValue : 0;
33411
+ const payloadTotalSize = Number(this.params.totalSize);
33412
+ const totalSize = Number.isFinite(payloadTotalSize) && payloadTotalSize > 0
33413
+ ? payloadTotalSize
33414
+ : startOffset + dataLength;
33415
+ if (totalSize < startOffset + dataLength) {
33416
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.RuntimeError, `FilesystemFileWrite totalSize ${totalSize} is smaller than offset + data length ${startOffset + dataLength}`);
33417
+ }
33418
+ const chunkSize = normalizeChunkSize((_b = this.params.chunkSize) !== null && _b !== void 0 ? _b : this.params.chunkLen, getProtocolV2FileChunkLimit());
33419
+ const overwrite = (_c = this.params.overwrite) !== null && _c !== void 0 ? _c : false;
33420
+ const append = (_d = this.params.append) !== null && _d !== void 0 ? _d : false;
33421
+ let written = 0;
33422
+ let chunkIndex = 0;
33423
+ let lastMessage;
33424
+ const startTime = Date.now();
33425
+ while (written < dataLength) {
33426
+ const chunkEnd = Math.min(written + chunkSize, dataLength);
33427
+ const chunk = data.slice(written, chunkEnd);
33428
+ const offset = startOffset + written;
33429
+ const isFirstChunk = chunkIndex === 0;
33430
+ const progress = (_e = this.params.uiPercentage) !== null && _e !== void 0 ? _e : Math.min(Math.ceil(((written + chunk.byteLength) / dataLength) * 100), 99);
33431
+ const res = yield this.device.commands.typedCall('FilesystemFileWrite', 'FilesystemFile', {
33432
+ file: {
33433
+ path: this.params.path,
33434
+ offset,
33435
+ total_size: totalSize,
33436
+ data: chunk,
33437
+ },
33438
+ overwrite: isFirstChunk ? overwrite : false,
33439
+ append,
33440
+ ui_percentage: progress,
33441
+ });
33442
+ lastMessage = res.message;
33443
+ const processedByte = Number((_f = res.message) === null || _f === void 0 ? void 0 : _f.processed_byte);
33444
+ if (Number.isFinite(processedByte) && processedByte > offset) {
33445
+ written = processedByte - startOffset;
33446
+ }
33447
+ else {
33448
+ written += chunk.byteLength;
33449
+ }
33450
+ if (written > dataLength) {
33451
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.RuntimeError, `FilesystemFileWrite invalid processed_byte ${processedByte}`);
33452
+ }
33453
+ const confirmedProcessedByte = Number.isFinite(processedByte) && processedByte > offset
33454
+ ? processedByte
33455
+ : startOffset + written;
33456
+ if (typeof this.postMessage === 'function') {
33457
+ const elapsedMs = Date.now() - startTime;
33458
+ const transferredBytes = Math.min(written, dataLength);
33459
+ this.postMessage(createUiMessage(UI_REQUEST.DEVICE_PROGRESS, {
33460
+ progress: getConfirmedProgress(confirmedProcessedByte, totalSize, written, dataLength),
33461
+ transferredBytes,
33462
+ totalBytes: dataLength,
33463
+ rateBytesPerSecond: elapsedMs > 0 ? Math.round((transferredBytes / elapsedMs) * 1000) : undefined,
33464
+ elapsedMs,
33465
+ }));
33466
+ }
33467
+ chunkIndex += 1;
33468
+ }
33469
+ return Promise.resolve(Object.assign(Object.assign({}, lastMessage), { path: this.params.path, offset: startOffset, total_size: totalSize, processed_byte: startOffset + written, chunks: chunkIndex }));
33470
+ });
33471
+ }
33472
+ }
33473
+
33474
+ class FileDelete extends BaseMethod {
33475
+ init() {
33476
+ this.skipForceUpdateCheck = true;
33477
+ this.useDevicePassphraseState = false;
33478
+ this.params = { path: this.payload.path };
33479
+ }
33480
+ run() {
33481
+ return __awaiter(this, void 0, void 0, function* () {
33482
+ const res = yield this.device.commands.typedCall('FilesystemFileDelete', 'Success', {
33483
+ path: this.params.path,
33484
+ });
33485
+ return Promise.resolve(res.message);
33486
+ });
33487
+ }
33488
+ }
33489
+
33490
+ class DirList extends BaseMethod {
33491
+ init() {
33492
+ this.skipForceUpdateCheck = true;
33493
+ this.useDevicePassphraseState = false;
33494
+ this.params = {
33495
+ path: this.payload.path,
33496
+ depth: this.payload.depth,
33497
+ };
33498
+ }
33499
+ run() {
33500
+ return __awaiter(this, void 0, void 0, function* () {
33501
+ const res = yield this.device.commands.typedCall('FilesystemDirList', 'FilesystemDir', {
33502
+ path: this.params.path,
33503
+ depth: this.params.depth,
33504
+ });
33505
+ return Promise.resolve(res.message);
33506
+ });
33507
+ }
33508
+ }
33509
+
33510
+ class DirMake extends BaseMethod {
33511
+ init() {
33512
+ this.skipForceUpdateCheck = true;
33513
+ this.useDevicePassphraseState = false;
33514
+ this.params = { path: this.payload.path };
33515
+ }
33516
+ run() {
33517
+ return __awaiter(this, void 0, void 0, function* () {
33518
+ const res = yield this.device.commands.typedCall('FilesystemDirMake', 'Success', {
33519
+ path: this.params.path,
33520
+ });
33521
+ return Promise.resolve(res.message);
33522
+ });
33523
+ }
33524
+ }
33525
+
33526
+ class DirRemove extends BaseMethod {
33527
+ init() {
33528
+ this.skipForceUpdateCheck = true;
33529
+ this.useDevicePassphraseState = false;
33530
+ this.params = { path: this.payload.path };
33531
+ }
33532
+ run() {
33533
+ return __awaiter(this, void 0, void 0, function* () {
33534
+ const res = yield this.device.commands.typedCall('FilesystemDirRemove', 'Success', {
33535
+ path: this.params.path,
33536
+ });
33537
+ return Promise.resolve(res.message);
33538
+ });
33539
+ }
33540
+ }
33541
+
33542
+ class PathInfo extends BaseMethod {
33543
+ init() {
33544
+ this.skipForceUpdateCheck = true;
33545
+ this.useDevicePassphraseState = false;
33546
+ this.params = { path: this.payload.path };
33547
+ }
33548
+ run() {
33549
+ return __awaiter(this, void 0, void 0, function* () {
33550
+ const res = yield this.device.commands.typedCall('FilesystemPathInfoQuery', 'FilesystemPathInfo', {
33551
+ path: this.params.path,
33552
+ });
33553
+ return Promise.resolve(res.message);
33554
+ });
33555
+ }
33556
+ }
33557
+
31026
33558
  class CipherKeyValue extends BaseMethod {
31027
33559
  constructor() {
31028
33560
  super(...arguments);
@@ -39176,6 +41708,50 @@ class TonSignProof extends BaseMethod {
39176
41708
  }
39177
41709
  }
39178
41710
 
41711
+ class TonSignData extends BaseMethod {
41712
+ init() {
41713
+ this.strictCheckDeviceSupport = false;
41714
+ this.checkDeviceId = true;
41715
+ this.allowDeviceMode = [...this.allowDeviceMode, UI_REQUEST.NOT_INITIALIZE];
41716
+ validateParams(this.payload, [
41717
+ { name: 'path', required: true },
41718
+ { name: 'type', type: 'number', required: true },
41719
+ { name: 'payload', type: 'hexString', required: true },
41720
+ { name: 'schema', type: 'string' },
41721
+ { name: 'appdomain', type: 'string', required: true },
41722
+ { name: 'timestamp', required: true },
41723
+ { name: 'fromAddress', type: 'string' },
41724
+ { name: 'walletVersion' },
41725
+ { name: 'walletId', type: 'number' },
41726
+ { name: 'workchain' },
41727
+ { name: 'isBounceable', type: 'boolean' },
41728
+ { name: 'isTestnetOnly', type: 'boolean' },
41729
+ ]);
41730
+ const { path } = this.payload;
41731
+ const addressN = validatePath(path, 3);
41732
+ this.params = {
41733
+ address_n: addressN,
41734
+ type: this.payload.type,
41735
+ payload: formatAnyHex(this.payload.payload),
41736
+ schema: this.payload.schema,
41737
+ appdomain: this.payload.appdomain,
41738
+ timestamp: this.payload.timestamp,
41739
+ from_address: this.payload.fromAddress,
41740
+ wallet_version: this.payload.walletVersion,
41741
+ wallet_id: this.payload.walletId,
41742
+ workchain: this.payload.workchain,
41743
+ is_bounceable: this.payload.isBounceable,
41744
+ is_testnet_only: this.payload.isTestnetOnly,
41745
+ };
41746
+ }
41747
+ run() {
41748
+ return __awaiter(this, void 0, void 0, function* () {
41749
+ const res = yield this.device.commands.typedCall('TonSignData', 'TonSignedData', Object.assign({}, this.params));
41750
+ return Promise.resolve(res.message);
41751
+ });
41752
+ }
41753
+ }
41754
+
39179
41755
  class ScdoGetAddress extends BaseMethod {
39180
41756
  constructor() {
39181
41757
  super(...arguments);
@@ -39913,7 +42489,33 @@ var ApiMethods = /*#__PURE__*/Object.freeze({
39913
42489
  firmwareUpdate: FirmwareUpdate,
39914
42490
  firmwareUpdateV2: FirmwareUpdateV2,
39915
42491
  firmwareUpdateV3: FirmwareUpdateV3,
42492
+ firmwareUpdateV4: FirmwareUpdateV4,
39916
42493
  promptWebDeviceAccess: PromptWebDeviceAccess,
42494
+ getProtoVersion: GetProtoVersion,
42495
+ ping: Ping,
42496
+ devReboot: DevReboot,
42497
+ devGetDeviceInfo: DevGetDeviceInfo,
42498
+ devGetOnboardingStatus: DevGetOnboardingStatus,
42499
+ devFirmwareUpdate: DevFirmwareUpdate,
42500
+ devGetFirmwareUpdateStatus: DevGetFirmwareUpdateStatus,
42501
+ factoryDeviceInfoSettings: FactoryDeviceInfoSettings,
42502
+ factoryGetDeviceInfo: FactoryGetDeviceInfo,
42503
+ filesystemFixPermission: FilesystemFixPermission,
42504
+ filesystemFormat: FilesystemFormat,
42505
+ fileRead: FileRead,
42506
+ fileWrite: FileWrite,
42507
+ fileDelete: FileDelete,
42508
+ dirList: DirList,
42509
+ dirMake: DirMake,
42510
+ dirRemove: DirRemove,
42511
+ pathInfo: PathInfo,
42512
+ filesystemFileRead: FileRead,
42513
+ filesystemFileWrite: FileWrite,
42514
+ filesystemFileDelete: FileDelete,
42515
+ filesystemDirList: DirList,
42516
+ filesystemDirMake: DirMake,
42517
+ filesystemDirRemove: DirRemove,
42518
+ filesystemPathInfoQuery: PathInfo,
39917
42519
  cipherKeyValue: CipherKeyValue,
39918
42520
  allNetworkGetAddress: AllNetworkGetAddress,
39919
42521
  allNetworkGetAddressByLoop: AllNetworkGetAddressByLoop,
@@ -39993,6 +42595,7 @@ var ApiMethods = /*#__PURE__*/Object.freeze({
39993
42595
  tonGetAddress: TonGetAddress,
39994
42596
  tonSignMessage: TonSignMessage,
39995
42597
  tonSignProof: TonSignProof,
42598
+ tonSignData: TonSignData,
39996
42599
  scdoGetAddress: ScdoGetAddress,
39997
42600
  scdoSignTransaction: ScdoSignTransaction,
39998
42601
  scdoSignMessage: ScdoSignMessage,
@@ -40084,17 +42687,31 @@ class DeviceConnector {
40084
42687
  stop() {
40085
42688
  this.listening = false;
40086
42689
  }
40087
- acquire(path, session, forceCleanRunPromise) {
42690
+ acquire(path, session, forceCleanRunPromise, connectProtocol) {
40088
42691
  return __awaiter(this, void 0, void 0, function* () {
40089
- Log$2.debug('acquire', path, session);
42692
+ Log$2.debug('acquire', path, session, connectProtocol);
40090
42693
  const env = DataManager.getSettings('env');
40091
42694
  try {
40092
42695
  let res;
40093
42696
  if (DataManager.isBleConnect(env)) {
40094
- res = yield this.transport.acquire({ uuid: path, forceCleanRunPromise });
42697
+ res = yield this.transport.acquire({
42698
+ uuid: path,
42699
+ forceCleanRunPromise,
42700
+ expectedProtocol: connectProtocol,
42701
+ });
40095
42702
  }
40096
42703
  else {
40097
- res = yield this.transport.acquire({ path, previous: session !== null && session !== void 0 ? session : null });
42704
+ res = yield this.transport.acquire({
42705
+ path,
42706
+ previous: session !== null && session !== void 0 ? session : null,
42707
+ expectedProtocol: connectProtocol,
42708
+ });
42709
+ }
42710
+ if (connectProtocol) {
42711
+ const detectedProtocol = this.transport.getProtocolType(path);
42712
+ if (detectedProtocol !== connectProtocol) {
42713
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.RuntimeError, `Device protocol mismatch: expected ${connectProtocol}, detected ${detectedProtocol}`);
42714
+ }
40098
42715
  }
40099
42716
  return res;
40100
42717
  }
@@ -40281,6 +42898,7 @@ const parseInitOptions = (method) => ({
40281
42898
  passphraseState: method === null || method === void 0 ? void 0 : method.payload.passphraseState,
40282
42899
  deviceId: method === null || method === void 0 ? void 0 : method.payload.deviceId,
40283
42900
  deriveCardano: method && hasDeriveCardano(method),
42901
+ connectProtocol: method === null || method === void 0 ? void 0 : method.payload.connectProtocol,
40284
42902
  });
40285
42903
  let _core;
40286
42904
  let _deviceList;
@@ -40652,6 +43270,7 @@ function initDevice(method) {
40652
43270
  }
40653
43271
  else if (allDevices.length > 1) {
40654
43272
  throw hdShared.ERRORS.TypedError([
43273
+ 'firmwareUpdateV4',
40655
43274
  'firmwareUpdateV3',
40656
43275
  'firmwareUpdateV2',
40657
43276
  'checkFirmwareRelease',
@@ -40690,18 +43309,28 @@ function initDeviceForBle(method) {
40690
43309
  return device;
40691
43310
  }
40692
43311
  let bleTimeoutRetry = 0;
43312
+ function isRetryableBleProtocolV2ProbeError(method, error) {
43313
+ const message = error instanceof Error ? error.message : String(error !== null && error !== void 0 ? error : '');
43314
+ return (method.payload.connectProtocol === 'V2' &&
43315
+ message.includes('Device protocol mismatch') &&
43316
+ message.includes('expected V2') &&
43317
+ message.includes('did not respond to expected protocol'));
43318
+ }
40693
43319
  function connectDeviceForBle(method, device) {
40694
43320
  var _a;
40695
43321
  return __awaiter(this, void 0, void 0, function* () {
40696
43322
  try {
40697
- yield device.acquire();
43323
+ yield device.acquire(method.payload.connectProtocol);
40698
43324
  if ((_a = method.payload) === null || _a === void 0 ? void 0 : _a.onlyConnectBleDevice) {
40699
43325
  return;
40700
43326
  }
40701
43327
  yield device.initialize(parseInitOptions(method));
40702
43328
  }
40703
43329
  catch (err) {
40704
- if (err.errorCode === hdShared.HardwareErrorCode.BleTimeoutError && bleTimeoutRetry <= 5) {
43330
+ if ((err.errorCode === hdShared.HardwareErrorCode.BleTimeoutError ||
43331
+ err.errorCode === hdShared.HardwareErrorCode.BleConnectedError ||
43332
+ isRetryableBleProtocolV2ProbeError(method, err)) &&
43333
+ bleTimeoutRetry <= 5) {
40705
43334
  bleTimeoutRetry += 1;
40706
43335
  Log.debug(`Bletooth connect timeout and will retry, retry count: ${bleTimeoutRetry}`);
40707
43336
  yield wait(3000);
@@ -41180,6 +43809,10 @@ Object.defineProperty(exports, 'PROTO', {
41180
43809
  enumerable: true,
41181
43810
  get: function () { return hdTransport.Messages; }
41182
43811
  });
43812
+ Object.defineProperty(exports, 'TonSignDataType', {
43813
+ enumerable: true,
43814
+ get: function () { return hdTransport.TonSignDataType; }
43815
+ });
41183
43816
  exports.CORE_EVENT = CORE_EVENT;
41184
43817
  exports.Core = Core;
41185
43818
  exports.DEFAULT_PRIORITY = DEFAULT_PRIORITY;