@onekeyfe/hd-core 1.1.19-alpha.0 → 1.1.19-alpha.2

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 (52) hide show
  1. package/dist/api/BaseMethod.d.ts +5 -0
  2. package/dist/api/BaseMethod.d.ts.map +1 -1
  3. package/dist/api/FirmwareUpdate.d.ts.map +1 -1
  4. package/dist/api/FirmwareUpdateV2.d.ts.map +1 -1
  5. package/dist/api/FirmwareUpdateV3.d.ts.map +1 -1
  6. package/dist/api/allnetwork/AllNetworkGetAddressBase.d.ts.map +1 -1
  7. package/dist/api/evm/EVMSignTypedData.d.ts.map +1 -1
  8. package/dist/api/firmware/FirmwareUpdateBaseMethod.d.ts +4 -4
  9. package/dist/api/firmware/FirmwareUpdateBaseMethod.d.ts.map +1 -1
  10. package/dist/api/firmware/bootloaderHelper.d.ts +1 -1
  11. package/dist/api/firmware/bootloaderHelper.d.ts.map +1 -1
  12. package/dist/api/firmware/updateBootloader.d.ts +1 -1
  13. package/dist/api/firmware/updateBootloader.d.ts.map +1 -1
  14. package/dist/api/firmware/uploadFirmware.d.ts +5 -5
  15. package/dist/api/firmware/uploadFirmware.d.ts.map +1 -1
  16. package/dist/core/index.d.ts +6 -3
  17. package/dist/core/index.d.ts.map +1 -1
  18. package/dist/device/Device.d.ts +5 -2
  19. package/dist/device/Device.d.ts.map +1 -1
  20. package/dist/device/DeviceCommands.d.ts +8 -6
  21. package/dist/device/DeviceCommands.d.ts.map +1 -1
  22. package/dist/index.d.ts +51 -6
  23. package/dist/index.js +404 -76
  24. package/dist/types/device.d.ts +3 -0
  25. package/dist/types/device.d.ts.map +1 -1
  26. package/dist/utils/index.d.ts +1 -0
  27. package/dist/utils/index.d.ts.map +1 -1
  28. package/dist/utils/logger.d.ts +1 -1
  29. package/dist/utils/logger.d.ts.map +1 -1
  30. package/dist/utils/patch.d.ts +1 -1
  31. package/dist/utils/patch.d.ts.map +1 -1
  32. package/dist/utils/tracing.d.ts +34 -0
  33. package/dist/utils/tracing.d.ts.map +1 -0
  34. package/package.json +4 -4
  35. package/src/api/BaseMethod.ts +38 -1
  36. package/src/api/FirmwareUpdate.ts +2 -1
  37. package/src/api/FirmwareUpdateV2.ts +2 -1
  38. package/src/api/FirmwareUpdateV3.ts +2 -0
  39. package/src/api/allnetwork/AllNetworkGetAddressBase.ts +46 -15
  40. package/src/api/evm/EVMSignTypedData.ts +8 -2
  41. package/src/api/firmware/FirmwareUpdateBaseMethod.ts +16 -18
  42. package/src/api/firmware/bootloaderHelper.ts +3 -1
  43. package/src/api/firmware/updateBootloader.ts +6 -3
  44. package/src/api/firmware/uploadFirmware.ts +87 -21
  45. package/src/core/index.ts +135 -27
  46. package/src/data/messages/messages.json +11 -1
  47. package/src/device/Device.ts +24 -3
  48. package/src/device/DeviceCommands.ts +55 -13
  49. package/src/types/device.ts +5 -0
  50. package/src/utils/index.ts +1 -0
  51. package/src/utils/logger.ts +3 -2
  52. package/src/utils/tracing.ts +238 -0
package/dist/index.js CHANGED
@@ -787,7 +787,7 @@ const createLogMessage = (type, payload) => ({
787
787
 
788
788
  const MAX_ENTRIES = 500;
789
789
  let postMessage$1;
790
- class Log$e {
790
+ class Log$f {
791
791
  constructor(prefix, enabled) {
792
792
  this.prefix = prefix;
793
793
  this.enabled = enabled;
@@ -839,7 +839,7 @@ class Log$e {
839
839
  }
840
840
  const _logs = {};
841
841
  const initLog = (prefix, enabled) => {
842
- const instance = new Log$e(prefix, !!enabled);
842
+ const instance = new Log$f(prefix, !!enabled);
843
843
  _logs[prefix] = instance;
844
844
  return instance;
845
845
  };
@@ -1035,6 +1035,108 @@ function patchFeatures(response) {
1035
1035
  return response;
1036
1036
  }
1037
1037
 
1038
+ const Log$e = getLogger(exports.LoggerNames.Core);
1039
+ let globalInstanceCounter = 0;
1040
+ let sdkInstanceCounter = 0;
1041
+ function generateSdkInstanceId() {
1042
+ sdkInstanceCounter++;
1043
+ const timestamp = Date.now().toString().slice(-6);
1044
+ return `SDK-${sdkInstanceCounter}-${timestamp}`;
1045
+ }
1046
+ function generateInstanceId(type, sdkInstanceId) {
1047
+ globalInstanceCounter++;
1048
+ const timestamp = Date.now().toString().slice(-6);
1049
+ const baseId = `${type}-${globalInstanceCounter}-${timestamp}`;
1050
+ return sdkInstanceId ? `${sdkInstanceId}.${baseId}` : baseId;
1051
+ }
1052
+ const sdkInstances = new Map();
1053
+ const globalActiveRequests = new Map();
1054
+ function createSdkTracingContext() {
1055
+ const sdkInstanceId = generateSdkInstanceId();
1056
+ const context = {
1057
+ sdkInstanceId,
1058
+ createdAt: Date.now(),
1059
+ activeRequests: new Map(),
1060
+ };
1061
+ sdkInstances.set(sdkInstanceId, context);
1062
+ return context;
1063
+ }
1064
+ function createRequestContext(responseID, methodName, options) {
1065
+ const context = {
1066
+ responseID,
1067
+ sdkInstanceId: options === null || options === void 0 ? void 0 : options.sdkInstanceId,
1068
+ methodName,
1069
+ connectId: options === null || options === void 0 ? void 0 : options.connectId,
1070
+ deviceInstanceId: options === null || options === void 0 ? void 0 : options.deviceInstanceId,
1071
+ commandsInstanceId: options === null || options === void 0 ? void 0 : options.commandsInstanceId,
1072
+ parentResponseID: options === null || options === void 0 ? void 0 : options.parentResponseID,
1073
+ startTime: Date.now(),
1074
+ status: 'pending',
1075
+ };
1076
+ globalActiveRequests.set(context.responseID, context);
1077
+ if (options === null || options === void 0 ? void 0 : options.sdkInstanceId) {
1078
+ const sdkContext = sdkInstances.get(options.sdkInstanceId);
1079
+ if (sdkContext) {
1080
+ sdkContext.activeRequests.set(context.responseID, context);
1081
+ }
1082
+ }
1083
+ return context;
1084
+ }
1085
+ function updateRequestContext(responseID, updates) {
1086
+ const context = globalActiveRequests.get(responseID);
1087
+ if (context) {
1088
+ Object.assign(context, updates);
1089
+ }
1090
+ }
1091
+ function completeRequestContext(responseID, error) {
1092
+ const context = globalActiveRequests.get(responseID);
1093
+ if (context) {
1094
+ context.endTime = Date.now();
1095
+ context.status = error ? 'error' : 'success';
1096
+ if (error) {
1097
+ context.error = error.message;
1098
+ Log$e.error(`[RequestContext] [completeRequestContext] Error: ${formatRequestContext(context)}`);
1099
+ }
1100
+ globalActiveRequests.delete(responseID);
1101
+ if (context.sdkInstanceId) {
1102
+ const sdkContext = sdkInstances.get(context.sdkInstanceId);
1103
+ if (sdkContext) {
1104
+ sdkContext.activeRequests.delete(responseID);
1105
+ }
1106
+ }
1107
+ }
1108
+ }
1109
+ function getActiveRequestsByDeviceInstance(deviceInstanceId) {
1110
+ return Array.from(globalActiveRequests.values()).filter(ctx => ctx.deviceInstanceId === deviceInstanceId);
1111
+ }
1112
+ function formatRequestContext(context) {
1113
+ const duration = context.endTime
1114
+ ? context.endTime - context.startTime
1115
+ : Date.now() - context.startTime;
1116
+ const parts = [
1117
+ `[req:${context.responseID}]`,
1118
+ context.sdkInstanceId ? `sdk=${context.sdkInstanceId}` : null,
1119
+ `method=${context.methodName}`,
1120
+ context.connectId ? `connectId=${context.connectId}` : null,
1121
+ context.deviceInstanceId ? `deviceInst=${context.deviceInstanceId}` : null,
1122
+ context.commandsInstanceId ? `commandsInst=${context.commandsInstanceId}` : null,
1123
+ context.parentResponseID ? `parent=${context.parentResponseID}` : null,
1124
+ `duration=${duration}ms`,
1125
+ `status=${context.status}`,
1126
+ `error=${context.error}`,
1127
+ ].filter(Boolean);
1128
+ return parts.join(' ');
1129
+ }
1130
+ function cleanupSdkInstance(sdkInstanceId) {
1131
+ const sdkContext = sdkInstances.get(sdkInstanceId);
1132
+ if (sdkContext) {
1133
+ for (const responseID of sdkContext.activeRequests.keys()) {
1134
+ globalActiveRequests.delete(responseID);
1135
+ }
1136
+ sdkInstances.delete(sdkInstanceId);
1137
+ }
1138
+ }
1139
+
1038
1140
  exports.EOneKeyDeviceMode = void 0;
1039
1141
  (function (EOneKeyDeviceMode) {
1040
1142
  EOneKeyDeviceMode["bootloader"] = "bootloader";
@@ -3351,6 +3453,15 @@ var nested$1 = {
3351
3453
  }
3352
3454
  }
3353
3455
  },
3456
+ UpgradeFileHeader: {
3457
+ fields: {
3458
+ data: {
3459
+ rule: "required",
3460
+ type: "bytes",
3461
+ id: 1
3462
+ }
3463
+ }
3464
+ },
3354
3465
  CardanoDerivationType: {
3355
3466
  values: {
3356
3467
  LEDGER: 0,
@@ -13795,7 +13906,8 @@ var nested$1 = {
13795
13906
  MessageType_GetPassphraseState: 10028,
13796
13907
  MessageType_PassphraseState: 10029,
13797
13908
  MessageType_UnLockDevice: 10030,
13798
- MessageType_UnLockDeviceResponse: 10031
13909
+ MessageType_UnLockDeviceResponse: 10031,
13910
+ MessageType_UpgradeFileHeader: 10050
13799
13911
  }
13800
13912
  },
13801
13913
  google: {
@@ -26556,12 +26668,15 @@ const cancelDeviceWithInitialize = (device) => {
26556
26668
  }));
26557
26669
  };
26558
26670
  const Log$b = getLogger(exports.LoggerNames.DeviceCommands);
26671
+ const LogCore = getLogger(exports.LoggerNames.Core);
26559
26672
  class DeviceCommands {
26560
26673
  constructor(device, mainId) {
26561
26674
  this.device = device;
26562
26675
  this.mainId = mainId;
26563
26676
  this.transport = TransportManager.getTransport();
26564
26677
  this.disposed = false;
26678
+ this.instanceId = generateInstanceId('DeviceCommands', device.sdkInstanceId);
26679
+ Log$b.debug(`[DeviceCommands] Created: ${this.instanceId}, device: ${this.device.instanceId}`);
26565
26680
  }
26566
26681
  dispose(_cancelRequest) {
26567
26682
  var _a, _b;
@@ -26634,11 +26749,16 @@ class DeviceCommands {
26634
26749
  const promise = this.transport.call(this.mainId, type, msg);
26635
26750
  this.callPromise = promise;
26636
26751
  const res = yield promise;
26637
- Log$b.debug('[DeviceCommands] [call] Received', res.type);
26752
+ if (res.type === 'Failure') {
26753
+ LogCore.debug('[DeviceCommands] [call] Received', res.type, res.message);
26754
+ }
26755
+ else {
26756
+ LogCore.debug('[DeviceCommands] [call] Received', res.type);
26757
+ }
26638
26758
  return res;
26639
26759
  }
26640
26760
  catch (error) {
26641
- Log$b.debug('[DeviceCommands] [call] Received error', error);
26761
+ LogCore.debug('[DeviceCommands] [call] Received error', error);
26642
26762
  if (error.errorCode === hdShared.HardwareErrorCode.BleDeviceBondError) {
26643
26763
  return {
26644
26764
  type: 'BleDeviceBondError',
@@ -26770,12 +26890,15 @@ class DeviceCommands {
26770
26890
  (message === null || message === void 0 ? void 0 : message.includes('verify failed'))) {
26771
26891
  error = hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.FirmwareVerificationFailed, message);
26772
26892
  }
26893
+ else if (message === null || message === void 0 ? void 0 : message.includes('Firmware downgrade not allowed')) {
26894
+ error = hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.FirmwareDowngradeNotAllowed, message);
26895
+ }
26773
26896
  }
26774
26897
  if (code === 'Failure_UnexpectedMessage') {
26775
26898
  if (callType === 'PassphraseAck') {
26776
26899
  error = hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.UnexpectPassphrase);
26777
26900
  }
26778
- if (message === 'Not in Signing mode') {
26901
+ else if (message === 'Not in Signing mode') {
26779
26902
  error = hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.NotInSigningMode);
26780
26903
  }
26781
26904
  }
@@ -26837,7 +26960,7 @@ class DeviceCommands {
26837
26960
  return new Promise((resolve, reject) => {
26838
26961
  const cancelAndReject = (_error) => cancelDeviceInPrompt(this.device, false)
26839
26962
  .then(onCancel => {
26840
- const error = hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.ActionCancelled, `${DEVICE.PIN} canceled`);
26963
+ const error = hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.CallQueueActionCancelled, `${DEVICE.PIN} canceled`);
26841
26964
  if (onCancel) {
26842
26965
  const { payload } = onCancel || {};
26843
26966
  reject(error || new Error(payload === null || payload === void 0 ? void 0 : payload.message));
@@ -26849,7 +26972,13 @@ class DeviceCommands {
26849
26972
  .catch(error => {
26850
26973
  reject(error);
26851
26974
  });
26852
- if (this.device.listenerCount(DEVICE.PIN) > 0) {
26975
+ const listenerCount = this.device.listenerCount(DEVICE.PIN);
26976
+ Log$b.debug(`[${this.instanceId}] _promptPin called`, {
26977
+ responseID: this.currentResponseID,
26978
+ deviceInstanceId: this.device.instanceId,
26979
+ listenerCount,
26980
+ });
26981
+ if (listenerCount > 0) {
26853
26982
  this.device.setCancelableAction(cancelAndReject);
26854
26983
  this.device.emit(DEVICE.PIN, this.device, type, (err, pin) => {
26855
26984
  this.device.clearCancelableAction();
@@ -26862,8 +26991,16 @@ class DeviceCommands {
26862
26991
  });
26863
26992
  }
26864
26993
  else {
26865
- console.warn('[DeviceCommands] [call] PIN callback not configured, cancelling request');
26866
- reject(hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.RuntimeError, '_promptPin: PIN callback not configured'));
26994
+ const activeRequests = getActiveRequestsByDeviceInstance(this.device.instanceId);
26995
+ const errorInfo = {
26996
+ commandsInstanceId: this.instanceId,
26997
+ deviceInstanceId: this.device.instanceId,
26998
+ currentResponseID: this.currentResponseID,
26999
+ listenerCount,
27000
+ activeRequests: activeRequests.map(formatRequestContext),
27001
+ };
27002
+ LogCore.error('[DeviceCommands] [call] PIN callback not configured, cancelling request', Object.assign({}, errorInfo));
27003
+ reject(hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.RuntimeError, `_promptPin: PIN callback not configured: ${JSON.stringify(errorInfo)}`));
26867
27004
  }
26868
27005
  });
26869
27006
  }
@@ -26871,7 +27008,7 @@ class DeviceCommands {
26871
27008
  return new Promise((resolve, reject) => {
26872
27009
  const cancelAndReject = (_error) => cancelDeviceInPrompt(this.device, false)
26873
27010
  .then(onCancel => {
26874
- const error = hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.ActionCancelled, `${DEVICE.PASSPHRASE} canceled`);
27011
+ const error = hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.CallQueueActionCancelled, `${DEVICE.PASSPHRASE} canceled`);
26875
27012
  if (onCancel) {
26876
27013
  const { payload } = onCancel || {};
26877
27014
  reject(error || new Error(payload === null || payload === void 0 ? void 0 : payload.message));
@@ -26896,7 +27033,7 @@ class DeviceCommands {
26896
27033
  });
26897
27034
  }
26898
27035
  else {
26899
- Log$b.error('[DeviceCommands] [call] Passphrase callback not configured, cancelling request');
27036
+ LogCore.error('[DeviceCommands] [call] Passphrase callback not configured, cancelling request');
26900
27037
  reject(hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.RuntimeError, '_promptPassphrase: Passphrase callback not configured'));
26901
27038
  }
26902
27039
  });
@@ -26911,7 +27048,7 @@ const parseRunOptions = (options) => {
26911
27048
  const Log$a = getLogger(exports.LoggerNames.Device);
26912
27049
  const deviceSessionCache = {};
26913
27050
  class Device extends events.exports {
26914
- constructor(descriptor) {
27051
+ constructor(descriptor, sdkInstanceId) {
26915
27052
  super();
26916
27053
  this.deviceConnector = null;
26917
27054
  this.deviceAcquired = false;
@@ -26925,10 +27062,14 @@ class Device extends events.exports {
26925
27062
  this.keepSession = false;
26926
27063
  this.passphraseState = undefined;
26927
27064
  this.originalDescriptor = descriptor;
27065
+ this.sdkInstanceId = sdkInstanceId;
27066
+ this.instanceId = generateInstanceId('Device', this.sdkInstanceId);
27067
+ this.createdAt = Date.now();
27068
+ Log$a.debug(`[Device] Created: ${this.instanceId}${this.sdkInstanceId ? ` for SDK: ${this.sdkInstanceId}` : ''}`);
26928
27069
  }
26929
- static fromDescriptor(originalDescriptor) {
27070
+ static fromDescriptor(originalDescriptor, sdkInstanceId) {
26930
27071
  const descriptor = Object.assign({}, originalDescriptor);
26931
- return new Device(descriptor);
27072
+ return new Device(descriptor, sdkInstanceId);
26932
27073
  }
26933
27074
  toMessageObject() {
26934
27075
  if (this.isUnacquired() || !this.features)
@@ -26940,6 +27081,9 @@ class Device extends events.exports {
26940
27081
  return {
26941
27082
  connectId: DataManager.isBleConnect(env) ? this.mainId || null : getDeviceUUID(this.features),
26942
27083
  uuid: getDeviceUUID(this.features),
27084
+ sdkInstanceId: this.sdkInstanceId,
27085
+ instanceId: this.instanceId,
27086
+ createdAt: this.createdAt,
26943
27087
  deviceType,
26944
27088
  deviceId: this.features.device_id || null,
26945
27089
  path: this.originalDescriptor.path,
@@ -27593,8 +27737,30 @@ class BaseMethod {
27593
27737
  getVersionRange() {
27594
27738
  return {};
27595
27739
  }
27740
+ setContext(context) {
27741
+ this.sdkInstanceId = context.sdkInstanceId;
27742
+ this.instanceId = generateInstanceId('Method', this.sdkInstanceId);
27743
+ Log$9.debug(`[BaseMethod] Created: ${this.instanceId}, method: ${this.name}, SDK: ${this.sdkInstanceId}`);
27744
+ }
27596
27745
  setDevice(device) {
27746
+ var _a, _b;
27597
27747
  this.device = device;
27748
+ if (!device.sdkInstanceId && this.sdkInstanceId) {
27749
+ device.sdkInstanceId = this.sdkInstanceId;
27750
+ device.instanceId = generateInstanceId('Device', this.sdkInstanceId);
27751
+ }
27752
+ if (this.requestContext) {
27753
+ this.requestContext.deviceInstanceId = device.instanceId;
27754
+ this.requestContext.commandsInstanceId = (_a = device.commands) === null || _a === void 0 ? void 0 : _a.instanceId;
27755
+ this.requestContext.sdkInstanceId = this.sdkInstanceId;
27756
+ }
27757
+ if (device.commands && this.sdkInstanceId) {
27758
+ device.commands.instanceId = generateInstanceId('DeviceCommands', this.sdkInstanceId);
27759
+ }
27760
+ if (device.commands) {
27761
+ device.commands.currentResponseID = this.responseID;
27762
+ }
27763
+ Log$9.debug(`[${this.instanceId}] setDevice: ${device.instanceId}, commands: ${(_b = device.commands) === null || _b === void 0 ? void 0 : _b.instanceId}`);
27598
27764
  }
27599
27765
  checkFirmwareRelease() {
27600
27766
  if (!this.device || !this.device.features)
@@ -28747,27 +28913,80 @@ const waitBleInstall = (updateType) => __awaiter(void 0, void 0, void 0, functio
28747
28913
  yield wait(10 * 1000);
28748
28914
  }
28749
28915
  });
28750
- const uploadFirmware = (updateType, typedCall, postMessage, device, { payload, rebootOnSuccess, }) => __awaiter(void 0, void 0, void 0, function* () {
28916
+ const uploadFirmware = (updateType, typedCall, postMessage, device, { payload, rebootOnSuccess, }, isUpdateBootloader) => __awaiter(void 0, void 0, void 0, function* () {
28917
+ var _a, _b;
28751
28918
  const deviceType = getDeviceType(device.features);
28752
28919
  if (DeviceModelToTypes.model_mini.includes(deviceType)) {
28753
28920
  postConfirmationMessage(device);
28754
28921
  postProgressTip(device, 'ConfirmOnDevice', postMessage);
28755
- const eraseCommand = updateType === 'firmware' ? 'FirmwareErase' : 'FirmwareErase_ex';
28922
+ const isFirmware = updateType === 'firmware';
28923
+ if (isFirmware && !isUpdateBootloader) {
28924
+ const newFeatures = yield typedCall('GetFeatures', 'Features', {});
28925
+ const deviceBootloaderVersion = getDeviceBootloaderVersion(newFeatures.message).join('.');
28926
+ const supportUpgradeFileHeader = semver__default["default"].gte(deviceBootloaderVersion, '2.1.0');
28927
+ Log$8.debug('supportUpgradeFileHeader:', supportUpgradeFileHeader);
28928
+ if (supportUpgradeFileHeader) {
28929
+ const HEADER_SIZE = 1024;
28930
+ if (payload.byteLength < HEADER_SIZE) {
28931
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.RuntimeError, `firmware payload too small: ${payload.byteLength} bytes, expected at least ${HEADER_SIZE} bytes`);
28932
+ }
28933
+ Log$8.debug('Uploading firmware header:', {
28934
+ size: HEADER_SIZE,
28935
+ totalSize: payload.byteLength,
28936
+ });
28937
+ postProgressTip(device, 'UploadingFirmwareHeader', postMessage);
28938
+ const header = new Uint8Array(payload.slice(0, HEADER_SIZE));
28939
+ try {
28940
+ const headerRes = yield typedCall('UpgradeFileHeader', 'Success', {
28941
+ data: bytesToHex(header),
28942
+ });
28943
+ const isUnknownMessage = (_b = (_a = headerRes.message) === null || _a === void 0 ? void 0 : _a.message) === null || _b === void 0 ? void 0 : _b.includes('Failure_UnknownMessage');
28944
+ if (headerRes.type !== 'Success' && !isUnknownMessage) {
28945
+ Log$8.error('Firmware header upload failed:', headerRes);
28946
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.RuntimeError, 'failed to upload firmware header');
28947
+ }
28948
+ }
28949
+ catch (error) {
28950
+ Log$8.error('Firmware header upload failed:', error);
28951
+ const message = error instanceof Error ? error.message : String(error !== null && error !== void 0 ? error : '');
28952
+ if (!message.includes('Failure_UnknownMessage')) {
28953
+ throw error;
28954
+ }
28955
+ }
28956
+ Log$8.debug('Firmware header uploaded successfully');
28957
+ }
28958
+ }
28959
+ const eraseCommand = isFirmware ? 'FirmwareErase' : 'FirmwareErase_ex';
28756
28960
  const eraseRes = yield typedCall(eraseCommand, 'Success', {});
28757
28961
  if (eraseRes.type !== 'Success') {
28758
28962
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.RuntimeError, 'erase firmware error');
28759
28963
  }
28760
28964
  postProgressTip(device, 'FirmwareEraseSuccess', postMessage);
28761
28965
  postProgressMessage(device, 0, 'installingFirmware', postMessage);
28762
- const { message, type } = yield typedCall('FirmwareUpload', 'Success', {
28763
- payload,
28764
- });
28966
+ let updateResponse;
28967
+ try {
28968
+ updateResponse = yield typedCall('FirmwareUpload', 'Success', {
28969
+ payload,
28970
+ });
28971
+ }
28972
+ catch (error) {
28973
+ if (isDeviceDisconnectedError$1(error)) {
28974
+ Log$8.log('Rebooting device');
28975
+ updateResponse = {
28976
+ type: 'Success',
28977
+ message: { message: FIRMWARE_UPDATE_CONFIRM$1 },
28978
+ };
28979
+ }
28980
+ else {
28981
+ throw error;
28982
+ }
28983
+ }
28765
28984
  postProgressMessage(device, 100, 'installingFirmware', postMessage);
28766
28985
  yield waitBleInstall(updateType);
28767
- if (type !== 'Success') {
28986
+ if (updateResponse.type !== 'Success') {
28768
28987
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.RuntimeError, 'install firmware error');
28769
28988
  }
28770
- return message;
28989
+ return updateResponse.message;
28771
28990
  }
28772
28991
  if (DeviceModelToTypes.model_touch.includes(deviceType)) {
28773
28992
  if (device.features) {
@@ -28805,7 +29024,7 @@ const uploadFirmware = (updateType, typedCall, postMessage, device, { payload, r
28805
29024
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.RuntimeError, 'uploadFirmware: unknown device model');
28806
29025
  });
28807
29026
  const newTouchUpdateProcess = (updateType, postMessage, device, { payload }, rebootOnSuccess = true) => __awaiter(void 0, void 0, void 0, function* () {
28808
- var _a, _b, _c, _d, _e;
29027
+ var _c, _d, _e, _f, _g;
28809
29028
  let typedCall = device.getCommands().typedCall.bind(device.getCommands());
28810
29029
  postProgressTip(device, 'StartTransferData', postMessage);
28811
29030
  const filePath = `0:${updateType === 'ble' ? 'ble-' : ''}firmware.bin`;
@@ -28849,7 +29068,7 @@ const newTouchUpdateProcess = (updateType, postMessage, device, { payload }, reb
28849
29068
  }
28850
29069
  }
28851
29070
  if (response.type === 'Success' &&
28852
- ((_a = response === null || response === void 0 ? void 0 : response.message) === null || _a === void 0 ? void 0 : _a.message) === FIRMWARE_UPDATE_CONFIRM$1) {
29071
+ ((_c = response === null || response === void 0 ? void 0 : response.message) === null || _c === void 0 ? void 0 : _c.message) === FIRMWARE_UPDATE_CONFIRM$1) {
28853
29072
  const timeout = 2 * 60 * 1000;
28854
29073
  const startTime = Date.now();
28855
29074
  const isBleReconnect = DataManager.isBleConnect(env);
@@ -28857,7 +29076,7 @@ const newTouchUpdateProcess = (updateType, postMessage, device, { payload }, reb
28857
29076
  try {
28858
29077
  if (isBleReconnect) {
28859
29078
  try {
28860
- yield ((_b = device.deviceConnector) === null || _b === void 0 ? void 0 : _b.acquire(device.originalDescriptor.id, null, true));
29079
+ yield ((_d = device.deviceConnector) === null || _d === void 0 ? void 0 : _d.acquire(device.originalDescriptor.id, null, true));
28861
29080
  const typedCall = device.getCommands().typedCall.bind(device.getCommands());
28862
29081
  yield Promise.race([
28863
29082
  typedCall('Initialize', 'Features', {}),
@@ -28873,14 +29092,14 @@ const newTouchUpdateProcess = (updateType, postMessage, device, { payload }, reb
28873
29092
  }
28874
29093
  }
28875
29094
  else {
28876
- const deviceDiff = yield ((_c = device.deviceConnector) === null || _c === void 0 ? void 0 : _c.enumerate());
28877
- const devicesDescriptor = (_d = deviceDiff === null || deviceDiff === void 0 ? void 0 : deviceDiff.descriptors) !== null && _d !== void 0 ? _d : [];
29095
+ const deviceDiff = yield ((_e = device.deviceConnector) === null || _e === void 0 ? void 0 : _e.enumerate());
29096
+ const devicesDescriptor = (_f = deviceDiff === null || deviceDiff === void 0 ? void 0 : deviceDiff.descriptors) !== null && _f !== void 0 ? _f : [];
28878
29097
  const { deviceList } = yield DevicePool.getDevices(devicesDescriptor, device.originalDescriptor.id);
28879
29098
  if (deviceList.length === 1) {
28880
29099
  device.updateFromCache(deviceList[0]);
28881
29100
  yield device.acquire();
28882
29101
  device.commands.disposed = false;
28883
- device.getCommands().mainId = (_e = device.mainId) !== null && _e !== void 0 ? _e : '';
29102
+ device.getCommands().mainId = (_g = device.mainId) !== null && _g !== void 0 ? _g : '';
28884
29103
  }
28885
29104
  }
28886
29105
  const typedCall = device.getCommands().typedCall.bind(device.getCommands());
@@ -28898,9 +29117,9 @@ const newTouchUpdateProcess = (updateType, postMessage, device, { payload }, reb
28898
29117
  return response;
28899
29118
  });
28900
29119
  const emmcFileWriteWithRetry = (device, filePath, chunkLength, offset, chunk, overwrite, progress) => __awaiter(void 0, void 0, void 0, function* () {
28901
- var _f, _g, _h, _j, _k, _l, _m, _o, _p;
29120
+ var _h, _j, _k, _l, _m, _o, _p, _q, _r;
28902
29121
  const writeFunc = () => __awaiter(void 0, void 0, void 0, function* () {
28903
- var _q;
29122
+ var _s;
28904
29123
  const typedCall = device.getCommands().typedCall.bind(device.getCommands());
28905
29124
  const writeRes = yield typedCall('EmmcFileWrite', 'EmmcFile', {
28906
29125
  file: {
@@ -28915,7 +29134,7 @@ const emmcFileWriteWithRetry = (device, filePath, chunkLength, offset, chunk, ov
28915
29134
  });
28916
29135
  if (writeRes.type !== 'EmmcFile') {
28917
29136
  if (writeRes.type === 'CallMethodError') {
28918
- if (((_q = writeRes.message.error) !== null && _q !== void 0 ? _q : '').indexOf(SESSION_ERROR$1) > -1) {
29137
+ if (((_s = writeRes.message.error) !== null && _s !== void 0 ? _s : '').indexOf(SESSION_ERROR$1) > -1) {
28919
29138
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.RuntimeError, SESSION_ERROR$1);
28920
29139
  }
28921
29140
  }
@@ -28938,18 +29157,18 @@ const emmcFileWriteWithRetry = (device, filePath, chunkLength, offset, chunk, ov
28938
29157
  const env = DataManager.getSettings('env');
28939
29158
  if (DataManager.isBleConnect(env)) {
28940
29159
  yield wait(3000);
28941
- yield ((_f = device.deviceConnector) === null || _f === void 0 ? void 0 : _f.acquire(device.originalDescriptor.id, null, true));
29160
+ yield ((_h = device.deviceConnector) === null || _h === void 0 ? void 0 : _h.acquire(device.originalDescriptor.id, null, true));
28942
29161
  yield device.initialize();
28943
29162
  }
28944
- else if (((_g = error === null || error === void 0 ? void 0 : error.message) === null || _g === void 0 ? void 0 : _g.indexOf(SESSION_ERROR$1)) > -1 ||
28945
- ((_j = (_h = error === null || error === void 0 ? void 0 : error.response) === null || _h === void 0 ? void 0 : _h.data) === null || _j === void 0 ? void 0 : _j.indexOf(SESSION_ERROR$1)) > -1) {
28946
- const deviceDiff = yield ((_k = device.deviceConnector) === null || _k === void 0 ? void 0 : _k.enumerate());
28947
- const devicesDescriptor = (_l = deviceDiff === null || deviceDiff === void 0 ? void 0 : deviceDiff.descriptors) !== null && _l !== void 0 ? _l : [];
29163
+ else if (((_j = error === null || error === void 0 ? void 0 : error.message) === null || _j === void 0 ? void 0 : _j.indexOf(SESSION_ERROR$1)) > -1 ||
29164
+ ((_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) {
29165
+ const deviceDiff = yield ((_m = device.deviceConnector) === null || _m === void 0 ? void 0 : _m.enumerate());
29166
+ const devicesDescriptor = (_o = deviceDiff === null || deviceDiff === void 0 ? void 0 : deviceDiff.descriptors) !== null && _o !== void 0 ? _o : [];
28948
29167
  const { deviceList } = yield DevicePool.getDevices(devicesDescriptor, undefined);
28949
- if (deviceList.length === 1 && ((_o = (_m = deviceList[0]) === null || _m === void 0 ? void 0 : _m.features) === null || _o === void 0 ? void 0 : _o.bootloader_mode)) {
29168
+ if (deviceList.length === 1 && ((_q = (_p = deviceList[0]) === null || _p === void 0 ? void 0 : _p.features) === null || _q === void 0 ? void 0 : _q.bootloader_mode)) {
28950
29169
  device.updateFromCache(deviceList[0]);
28951
29170
  yield device.acquire();
28952
- device.getCommands().mainId = (_p = device.mainId) !== null && _p !== void 0 ? _p : '';
29171
+ device.getCommands().mainId = (_r = device.mainId) !== null && _r !== void 0 ? _r : '';
28953
29172
  }
28954
29173
  }
28955
29174
  yield wait(3000);
@@ -29250,9 +29469,9 @@ class FirmwareUpdateBaseMethod extends BaseMethod {
29250
29469
  startEmmcFirmwareUpdate({ path }) {
29251
29470
  return __awaiter(this, void 0, void 0, function* () {
29252
29471
  const typedCall = this.device.getCommands().typedCall.bind(this.device.getCommands());
29253
- let updaeteResponse;
29472
+ let updateResponse;
29254
29473
  try {
29255
- updaeteResponse = yield typedCall('FirmwareUpdateEmmc', 'Success', {
29474
+ updateResponse = yield typedCall('FirmwareUpdateEmmc', 'Success', {
29256
29475
  path,
29257
29476
  reboot_on_success: true,
29258
29477
  });
@@ -29260,7 +29479,7 @@ class FirmwareUpdateBaseMethod extends BaseMethod {
29260
29479
  catch (error) {
29261
29480
  if (isDeviceDisconnectedError(error)) {
29262
29481
  Log$7.log('Rebooting device');
29263
- updaeteResponse = {
29482
+ updateResponse = {
29264
29483
  type: 'Success',
29265
29484
  message: { message: FIRMWARE_UPDATE_CONFIRM },
29266
29485
  };
@@ -29269,7 +29488,7 @@ class FirmwareUpdateBaseMethod extends BaseMethod {
29269
29488
  throw error;
29270
29489
  }
29271
29490
  }
29272
- if (updaeteResponse.type !== 'Success') {
29491
+ if (updateResponse.type !== 'Success') {
29273
29492
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.FirmwareError, 'firmware update error');
29274
29493
  }
29275
29494
  this.postTipMessage(exports.FirmwareUpdateTipMessage.FirmwareUpdating);
@@ -29661,7 +29880,7 @@ class FirmwareUpdate extends BaseMethod {
29661
29880
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.FirmwareUpdateDownloadFailed, (_b = err.message) !== null && _b !== void 0 ? _b : err);
29662
29881
  }
29663
29882
  yield this.device.acquire();
29664
- const response = yield uploadFirmware(params.updateType, this.device.getCommands().typedCall.bind(this.device.getCommands()), this.postMessage, device, { payload: binary, rebootOnSuccess: this.payload.rebootOnSuccess });
29883
+ const response = yield uploadFirmware(params.updateType, this.device.getCommands().typedCall.bind(this.device.getCommands()), this.postMessage, device, { payload: binary, rebootOnSuccess: this.payload.rebootOnSuccess }, false);
29665
29884
  if (this.connectId) {
29666
29885
  DevicePool.clearDeviceCache(this.connectId);
29667
29886
  }
@@ -29933,7 +30152,7 @@ class FirmwareUpdateV2 extends BaseMethod {
29933
30152
  }
29934
30153
  (_j = (_h = this.device) === null || _h === void 0 ? void 0 : _h.commands) === null || _j === void 0 ? void 0 : _j.checkDisposed();
29935
30154
  yield this.device.acquire();
29936
- const response = yield uploadFirmware(params.updateType, this.device.getCommands().typedCall.bind(this.device.getCommands()), this.postMessage, device, { payload: binary, rebootOnSuccess: true });
30155
+ const response = yield uploadFirmware(params.updateType, this.device.getCommands().typedCall.bind(this.device.getCommands()), this.postMessage, device, { payload: binary, rebootOnSuccess: true }, params.isUpdateBootloader);
29937
30156
  if (this.connectId) {
29938
30157
  DevicePool.clearDeviceCache(this.connectId);
29939
30158
  }
@@ -30178,6 +30397,7 @@ class FirmwareUpdateV3 extends FirmwareUpdateBaseMethod {
30178
30397
  if (error === null || error === void 0 ? void 0 : error.errorCode) {
30179
30398
  const unexpectedError = [
30180
30399
  hdShared.HardwareErrorCode.ActionCancelled,
30400
+ hdShared.HardwareErrorCode.CallQueueActionCancelled,
30181
30401
  hdShared.HardwareErrorCode.FirmwareVerificationFailed,
30182
30402
  hdShared.HardwareErrorCode.BleDeviceNotBonded,
30183
30403
  hdShared.HardwareErrorCode.BleServiceNotFound,
@@ -30624,7 +30844,7 @@ class AllNetworkGetAddressBase extends BaseMethod {
30624
30844
  };
30625
30845
  }
30626
30846
  callMethod(methodName, params, rootFingerprint) {
30627
- var _a;
30847
+ var _a, _b, _c;
30628
30848
  return __awaiter(this, void 0, void 0, function* () {
30629
30849
  const method = findMethod({
30630
30850
  event: IFRAME.CALL,
@@ -30633,25 +30853,38 @@ class AllNetworkGetAddressBase extends BaseMethod {
30633
30853
  });
30634
30854
  method.connector = this.connector;
30635
30855
  method.postMessage = this.postMessage;
30856
+ if (this.context) {
30857
+ (_a = method.setContext) === null || _a === void 0 ? void 0 : _a.call(method, this.context);
30858
+ }
30859
+ method.requestContext = createRequestContext(method.responseID, methodName, {
30860
+ sdkInstanceId: this.sdkInstanceId,
30861
+ connectId: this.payload.connectId,
30862
+ parentResponseID: this.responseID,
30863
+ });
30864
+ const onSignalAbort = () => {
30865
+ var _a;
30866
+ (_a = this.abortController) === null || _a === void 0 ? void 0 : _a.abort(hdShared.HardwareErrorCodeMessage[hdShared.HardwareErrorCode.RepeatUnlocking]);
30867
+ };
30868
+ const buttonListener = (...[device, request]) => {
30869
+ if (request.code === 'ButtonRequest_PinEntry' || request.code === 'ButtonRequest_AttachPin') {
30870
+ onSignalAbort();
30871
+ }
30872
+ else {
30873
+ onDeviceButtonHandler(device, request);
30874
+ }
30875
+ };
30636
30876
  let result;
30637
30877
  try {
30638
30878
  method.init();
30639
- (_a = method.setDevice) === null || _a === void 0 ? void 0 : _a.call(method, this.device);
30879
+ (_b = method.setDevice) === null || _b === void 0 ? void 0 : _b.call(method, this.device);
30640
30880
  method.context = this.context;
30641
- const onSignalAbort = () => {
30642
- var _a;
30643
- (_a = this.abortController) === null || _a === void 0 ? void 0 : _a.abort(hdShared.HardwareErrorCodeMessage[hdShared.HardwareErrorCode.RepeatUnlocking]);
30644
- };
30645
- const _onDeviceButtonHandler = (...[device, request]) => {
30646
- if (request.code === 'ButtonRequest_PinEntry' ||
30647
- request.code === 'ButtonRequest_AttachPin') {
30648
- onSignalAbort();
30649
- }
30650
- else {
30651
- onDeviceButtonHandler(device, request);
30652
- }
30653
- };
30654
- this.device.on(DEVICE.BUTTON, _onDeviceButtonHandler);
30881
+ if (method.requestContext && this.device) {
30882
+ updateRequestContext(method.requestContext.responseID, {
30883
+ deviceInstanceId: this.device.instanceId,
30884
+ commandsInstanceId: (_c = this.device.commands) === null || _c === void 0 ? void 0 : _c.instanceId,
30885
+ });
30886
+ }
30887
+ this.device.on(DEVICE.BUTTON, buttonListener);
30655
30888
  this.device.on(DEVICE.PIN, onSignalAbort);
30656
30889
  this.device.on(DEVICE.PASSPHRASE, onSignalAbort);
30657
30890
  preCheckDeviceSupport(this.device, method);
@@ -30660,6 +30893,9 @@ class AllNetworkGetAddressBase extends BaseMethod {
30660
30893
  throw new Error('No response');
30661
30894
  }
30662
30895
  result = response.map((item, index) => (Object.assign(Object.assign({}, params.bundle[index]._originRequestParams), { success: true, payload: Object.assign(Object.assign({}, item), { rootFingerprint }) })));
30896
+ if (method.requestContext) {
30897
+ completeRequestContext(method.requestContext.responseID);
30898
+ }
30663
30899
  }
30664
30900
  catch (e) {
30665
30901
  const error = handleSkippableHardwareError(e, this.device, method);
@@ -30675,6 +30911,14 @@ class AllNetworkGetAddressBase extends BaseMethod {
30675
30911
  else {
30676
30912
  throw e;
30677
30913
  }
30914
+ if (method.requestContext) {
30915
+ completeRequestContext(method.requestContext.responseID, e instanceof Error ? e : new Error(String(e)));
30916
+ }
30917
+ }
30918
+ finally {
30919
+ this.device.off(DEVICE.BUTTON, buttonListener);
30920
+ this.device.off(DEVICE.PIN, onSignalAbort);
30921
+ this.device.off(DEVICE.PASSPHRASE, onSignalAbort);
30678
30922
  }
30679
30923
  return result;
30680
30924
  });
@@ -33159,8 +33403,12 @@ class EVMSignTypedData extends BaseMethod {
33159
33403
  return false;
33160
33404
  let biggerLimit = 1024;
33161
33405
  const currentVersion = getDeviceFirmwareVersion(this.device.features).join('.');
33406
+ const currentDeviceType = getDeviceType(this.device.features);
33162
33407
  const supportBiggerDataVersion = '4.4.0';
33163
- if (semver__default["default"].gte(currentVersion, supportBiggerDataVersion)) {
33408
+ const supportBiggerData = DeviceModelToTypes.model_classic1s.includes(currentDeviceType) ||
33409
+ (DeviceModelToTypes.model_touch.includes(currentDeviceType) &&
33410
+ semver__default["default"].gte(currentVersion, supportBiggerDataVersion));
33411
+ if (supportBiggerData) {
33164
33412
  biggerLimit = 1536;
33165
33413
  }
33166
33414
  const startIndex = data.startsWith('0x') ? 2 : 0;
@@ -39342,7 +39590,33 @@ const pollingState = {};
39342
39590
  let preConnectCache = {
39343
39591
  passphraseState: undefined,
39344
39592
  };
39593
+ const toError = (error) => {
39594
+ if (error instanceof Error)
39595
+ return error;
39596
+ if (error == null)
39597
+ return undefined;
39598
+ if (typeof error === 'string')
39599
+ return new Error(error);
39600
+ try {
39601
+ return new Error(JSON.stringify(error));
39602
+ }
39603
+ catch (_a) {
39604
+ return new Error(String(error));
39605
+ }
39606
+ };
39607
+ const updateMethodRequestContext = (method, updates) => {
39608
+ if (method.requestContext) {
39609
+ updateRequestContext(method.requestContext.responseID, updates);
39610
+ }
39611
+ };
39612
+ const completeMethodRequestContext = (method, error) => {
39613
+ if (!method.requestContext) {
39614
+ return;
39615
+ }
39616
+ completeRequestContext(method.requestContext.responseID, toError(error));
39617
+ };
39345
39618
  const callAPI = (context, message) => __awaiter(void 0, void 0, void 0, function* () {
39619
+ var _a;
39346
39620
  if (!message.id || !message.payload || message.type !== IFRAME.CALL) {
39347
39621
  return Promise.reject(hdShared.ERRORS.TypedError('on call: message.id or message.payload is missing'));
39348
39622
  }
@@ -39351,6 +39625,12 @@ const callAPI = (context, message) => __awaiter(void 0, void 0, void 0, function
39351
39625
  method = findMethod(message);
39352
39626
  method.connector = _connector;
39353
39627
  method.postMessage = postMessage;
39628
+ (_a = method.setContext) === null || _a === void 0 ? void 0 : _a.call(method, context);
39629
+ method.requestContext = createRequestContext(method.responseID, method.name, {
39630
+ sdkInstanceId: context.sdkInstanceId,
39631
+ connectId: method.connectId,
39632
+ });
39633
+ Log.debug(`[${context.sdkInstanceId}] callAPI: ${formatRequestContext(method.requestContext)}`);
39354
39634
  method.init();
39355
39635
  }
39356
39636
  catch (error) {
@@ -39358,11 +39638,14 @@ const callAPI = (context, message) => __awaiter(void 0, void 0, void 0, function
39358
39638
  }
39359
39639
  DevicePool.emitter.on(DEVICE.CONNECT, onDeviceConnectHandler);
39360
39640
  if (!method.useDevice) {
39641
+ updateMethodRequestContext(method, { status: 'running' });
39361
39642
  try {
39362
39643
  const response = yield method.run();
39644
+ completeMethodRequestContext(method);
39363
39645
  return createResponseMessage(method.responseID, true, response);
39364
39646
  }
39365
39647
  catch (error) {
39648
+ completeMethodRequestContext(method, error);
39366
39649
  return createResponseMessage(method.responseID, false, { error });
39367
39650
  }
39368
39651
  }
@@ -39402,9 +39685,10 @@ const waitForPendingPromise = (getPrePendingCallPromise, removePrePendingCallPro
39402
39685
  }
39403
39686
  });
39404
39687
  const onCallDevice = (context, message, method) => __awaiter(void 0, void 0, void 0, function* () {
39405
- var _a, _b;
39688
+ var _b, _c, _d;
39406
39689
  let messageResponse;
39407
39690
  const { requestQueue, getPrePendingCallPromise, setPrePendingCallPromise } = context;
39691
+ updateMethodRequestContext(method, { status: 'running' });
39408
39692
  const connectStateChange = preConnectCache.passphraseState !== method.payload.passphraseState;
39409
39693
  preConnectCache = {
39410
39694
  passphraseState: method.payload.passphraseState,
@@ -39424,10 +39708,11 @@ const onCallDevice = (context, message, method) => __awaiter(void 0, void 0, voi
39424
39708
  pollingState[pollingId] = false;
39425
39709
  }
39426
39710
  pollingId += 1;
39427
- device = yield ensureConnected(context, method, pollingId, (_a = task.abortController) === null || _a === void 0 ? void 0 : _a.signal);
39711
+ device = yield ensureConnected(context, method, pollingId, (_b = task.abortController) === null || _b === void 0 ? void 0 : _b.signal);
39428
39712
  }
39429
39713
  catch (e) {
39430
39714
  console.log('ensureConnected error: ', e);
39715
+ completeMethodRequestContext(method, e);
39431
39716
  if (e.name === 'AbortError' || e.message === 'Request aborted') {
39432
39717
  requestQueue.releaseTask(method.responseID);
39433
39718
  return createResponseMessage(method.responseID, false, {
@@ -39438,8 +39723,16 @@ const onCallDevice = (context, message, method) => __awaiter(void 0, void 0, voi
39438
39723
  return createResponseMessage(method.responseID, false, { error: e });
39439
39724
  }
39440
39725
  Log.debug('Call API - setDevice: ', device.mainId);
39441
- (_b = method.setDevice) === null || _b === void 0 ? void 0 : _b.call(method, device);
39726
+ (_c = method.setDevice) === null || _c === void 0 ? void 0 : _c.call(method, device);
39442
39727
  method.context = context;
39728
+ updateMethodRequestContext(method, {
39729
+ deviceInstanceId: device.instanceId,
39730
+ commandsInstanceId: (_d = device.commands) === null || _d === void 0 ? void 0 : _d.instanceId,
39731
+ });
39732
+ const activeRequests = getActiveRequestsByDeviceInstance(device.instanceId);
39733
+ if (activeRequests.length > 0) {
39734
+ Log.warn(`[${method.instanceId}] Device ${device.instanceId} has ${activeRequests.length} active requests:`, activeRequests.map(formatRequestContext));
39735
+ }
39443
39736
  device.on(DEVICE.PIN, onDevicePinHandler);
39444
39737
  device.on(DEVICE.BUTTON, onDeviceButtonHandler);
39445
39738
  device.on(DEVICE.PASSPHRASE, message.payload.useEmptyPassphrase ? onEmptyPassphraseHandler : onDevicePassphraseHandler);
@@ -39452,7 +39745,7 @@ const onCallDevice = (context, message, method) => __awaiter(void 0, void 0, voi
39452
39745
  }
39453
39746
  yield waitForPendingPromise(getPrePendingCallPromise, setPrePendingCallPromise);
39454
39747
  const inner = () => __awaiter(void 0, void 0, void 0, function* () {
39455
- var _c, _d, _e, _f, _g;
39748
+ var _e, _f, _g, _h, _j;
39456
39749
  const versionRange = getMethodVersionRange(device.features, type => method.getVersionRange()[type]);
39457
39750
  if (device.features) {
39458
39751
  yield DataManager.checkAndReloadData();
@@ -39529,7 +39822,7 @@ const onCallDevice = (context, message, method) => __awaiter(void 0, void 0, voi
39529
39822
  require: support.require,
39530
39823
  }));
39531
39824
  }
39532
- const passphraseStateSafety = yield device.checkPassphraseStateSafety((_c = method.payload) === null || _c === void 0 ? void 0 : _c.passphraseState, (_d = method.payload) === null || _d === void 0 ? void 0 : _d.useEmptyPassphrase, (_e = method.payload) === null || _e === void 0 ? void 0 : _e.skipPassphraseCheck);
39825
+ const passphraseStateSafety = yield device.checkPassphraseStateSafety((_e = method.payload) === null || _e === void 0 ? void 0 : _e.passphraseState, (_f = method.payload) === null || _f === void 0 ? void 0 : _f.useEmptyPassphrase, (_g = method.payload) === null || _g === void 0 ? void 0 : _g.skipPassphraseCheck);
39533
39826
  checkPassphraseEnableState(method, device.features);
39534
39827
  if (!passphraseStateSafety) {
39535
39828
  DevicePool.clearDeviceCache(method.payload.connectId);
@@ -39546,17 +39839,19 @@ const onCallDevice = (context, message, method) => __awaiter(void 0, void 0, voi
39546
39839
  : hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.RuntimeError, 'open safety check failed.');
39547
39840
  throw error;
39548
39841
  }
39549
- (_g = (_f = method.device) === null || _f === void 0 ? void 0 : _f.commands) === null || _g === void 0 ? void 0 : _g.checkDisposed();
39842
+ (_j = (_h = method.device) === null || _h === void 0 ? void 0 : _h.commands) === null || _j === void 0 ? void 0 : _j.checkDisposed();
39550
39843
  try {
39551
39844
  const response = yield method.run();
39552
39845
  Log.debug('Call API - Inner Method Run: ');
39553
39846
  messageResponse = createResponseMessage(method.responseID, true, response);
39554
39847
  requestQueue.resolveRequest(method.responseID, messageResponse);
39848
+ completeMethodRequestContext(method);
39555
39849
  }
39556
39850
  catch (error) {
39557
- Log.debug('Call API - Inner Method Run Error: ', error);
39851
+ Log.debug(`Call API - Inner Method Run Error`, error);
39558
39852
  messageResponse = createResponseMessage(method.responseID, false, { error });
39559
39853
  requestQueue.resolveRequest(method.responseID, messageResponse);
39854
+ completeMethodRequestContext(method, error);
39560
39855
  }
39561
39856
  });
39562
39857
  Log.debug('Call API - Device Run: ', device.mainId);
@@ -39568,6 +39863,7 @@ const onCallDevice = (context, message, method) => __awaiter(void 0, void 0, voi
39568
39863
  }
39569
39864
  catch (e) {
39570
39865
  Log.debug('Device Run Error: ', e);
39866
+ completeMethodRequestContext(method, e);
39571
39867
  return createResponseMessage(method.responseID, false, { error: e });
39572
39868
  }
39573
39869
  }
@@ -39575,6 +39871,7 @@ const onCallDevice = (context, message, method) => __awaiter(void 0, void 0, voi
39575
39871
  messageResponse = createResponseMessage(method.responseID, false, { error });
39576
39872
  requestQueue.rejectRequest(method.responseID, hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.CallMethodError, error.message));
39577
39873
  Log.debug('Call API - Run Error: ', error);
39874
+ completeMethodRequestContext(method, error);
39578
39875
  }
39579
39876
  finally {
39580
39877
  const response = messageResponse;
@@ -39586,7 +39883,19 @@ const onCallDevice = (context, message, method) => __awaiter(void 0, void 0, voi
39586
39883
  requestQueue.releaseTask(method.responseID);
39587
39884
  closePopup();
39588
39885
  cleanup();
39589
- removeDeviceListener(device);
39886
+ if (device) {
39887
+ const stillActive = getActiveRequestsByDeviceInstance(device.instanceId);
39888
+ if (stillActive.length > 1) {
39889
+ Log.warn(`[${method.instanceId}] Removing listeners while ${stillActive.length} requests are active!`, {
39890
+ deviceInstanceId: device.instanceId,
39891
+ activeRequests: stillActive.map(formatRequestContext),
39892
+ pinListeners: device.listenerCount(DEVICE.PIN),
39893
+ });
39894
+ }
39895
+ else {
39896
+ removeDeviceListener(device);
39897
+ }
39898
+ }
39590
39899
  }
39591
39900
  });
39592
39901
  function initDeviceList(method) {
@@ -39656,7 +39965,7 @@ function initDeviceForBle(method) {
39656
39965
  device = deviceCacheMap.get(method.connectId);
39657
39966
  }
39658
39967
  else {
39659
- device = Device.fromDescriptor({ id: method.connectId });
39968
+ device = Device.fromDescriptor({ id: method.connectId }, method.sdkInstanceId);
39660
39969
  deviceCacheMap.set(method.connectId, device);
39661
39970
  }
39662
39971
  device.deviceConnector = _connector;
@@ -39696,7 +40005,7 @@ const ensureConnected = (_context, method, pollingId, abortSignal) => __awaiter(
39696
40005
  if (timer) {
39697
40006
  clearTimeout(timer);
39698
40007
  }
39699
- reject(hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.ActionCancelled));
40008
+ reject(hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.CallQueueActionCancelled));
39700
40009
  return true;
39701
40010
  }
39702
40011
  return false;
@@ -39826,7 +40135,7 @@ const cancel = (context, connectId) => {
39826
40135
  setPrePendingCallPromise(device === null || device === void 0 ? void 0 : device.interruptionFromUser());
39827
40136
  canceledDevices.push(device);
39828
40137
  }
39829
- requestQueue.rejectRequest(requestId, hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.ActionCancelled));
40138
+ requestQueue.rejectRequest(requestId, hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.CallQueueActionCancelled));
39830
40139
  }
39831
40140
  }
39832
40141
  requestQueue.abortRequestsByConnectId(connectId);
@@ -39849,7 +40158,7 @@ const cancel = (context, connectId) => {
39849
40158
  device === null || device === void 0 ? void 0 : device.interruptionFromUser();
39850
40159
  canceledDevices.push(device);
39851
40160
  }
39852
- requestQueue.rejectRequest(requestId, hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.ActionCancelled));
40161
+ requestQueue.rejectRequest(requestId, hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.CallQueueActionCancelled));
39853
40162
  }
39854
40163
  }
39855
40164
  }
@@ -39861,7 +40170,7 @@ const cancel = (context, connectId) => {
39861
40170
  }
39862
40171
  });
39863
40172
  requestQueue.getRequestTasksId().forEach(requestId => {
39864
- requestQueue.rejectRequest(requestId, hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.ActionCancelled));
40173
+ requestQueue.rejectRequest(requestId, hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.CallQueueActionCancelled));
39865
40174
  });
39866
40175
  }
39867
40176
  }
@@ -39969,6 +40278,9 @@ const onSelectDeviceInBootloaderForWebDeviceHandler = (...[device, callback]) =>
39969
40278
  callback(null, uiResp.payload.deviceId);
39970
40279
  });
39971
40280
  const postMessage = (message) => {
40281
+ if (!_core) {
40282
+ return;
40283
+ }
39972
40284
  _core.emit(CORE_EVENT, message);
39973
40285
  };
39974
40286
  const createUiPromise = (promiseEvent, device) => {
@@ -39982,12 +40294,17 @@ const removeUiPromise = (promise) => {
39982
40294
  };
39983
40295
  class Core extends events.exports {
39984
40296
  constructor() {
39985
- super(...arguments);
40297
+ super();
39986
40298
  this.requestQueue = new RequestQueue();
39987
40299
  this.methodSynchronize = getSynchronize();
40300
+ this.tracingContext = createSdkTracingContext();
40301
+ this.sdkInstanceId = this.tracingContext.sdkInstanceId;
40302
+ Log.debug(`[Core] Created SDK instance: ${this.sdkInstanceId}`);
39988
40303
  }
39989
40304
  getCoreContext() {
39990
40305
  return {
40306
+ sdkInstanceId: this.sdkInstanceId,
40307
+ tracingContext: this.tracingContext,
39991
40308
  requestQueue: this.requestQueue,
39992
40309
  methodSynchronize: this.methodSynchronize,
39993
40310
  getPrePendingCallPromise: () => this.prePendingCallPromise,
@@ -40052,6 +40369,8 @@ class Core extends events.exports {
40052
40369
  dispose() {
40053
40370
  _deviceList = undefined;
40054
40371
  _connector = undefined;
40372
+ Log.debug(`[Core] Disposing SDK instance: ${this.sdkInstanceId}`);
40373
+ cleanupSdkInstance(this.sdkInstanceId);
40055
40374
  }
40056
40375
  }
40057
40376
  const initCore = () => {
@@ -40072,7 +40391,7 @@ const init = (settings, Transport, plugin) => __awaiter(void 0, void 0, void 0,
40072
40391
  yield DataManager.load(settings);
40073
40392
  initTransport(Transport, plugin);
40074
40393
  }
40075
- catch (_h) {
40394
+ catch (_k) {
40076
40395
  Log.error('DataManager.load error');
40077
40396
  }
40078
40397
  enableLog(DataManager.getSettings('debug'));
@@ -40146,18 +40465,26 @@ exports.UI_RESPONSE = UI_RESPONSE;
40146
40465
  exports.checkNeedUpdateBootForClassicAndMini = checkNeedUpdateBootForClassicAndMini;
40147
40466
  exports.checkNeedUpdateBootForTouch = checkNeedUpdateBootForTouch;
40148
40467
  exports.cleanupCallback = cleanupCallback;
40468
+ exports.cleanupSdkInstance = cleanupSdkInstance;
40469
+ exports.completeRequestContext = completeRequestContext;
40149
40470
  exports.corsValidator = corsValidator;
40150
40471
  exports.createDeviceMessage = createDeviceMessage;
40151
40472
  exports.createErrorMessage = createErrorMessage;
40152
40473
  exports.createFirmwareMessage = createFirmwareMessage;
40153
40474
  exports.createIFrameMessage = createIFrameMessage;
40154
40475
  exports.createLogMessage = createLogMessage;
40476
+ exports.createRequestContext = createRequestContext;
40155
40477
  exports.createResponseMessage = createResponseMessage;
40478
+ exports.createSdkTracingContext = createSdkTracingContext;
40156
40479
  exports.createUiMessage = createUiMessage;
40157
40480
  exports.createUiResponse = createUiResponse;
40158
40481
  exports["default"] = HardwareSdk;
40159
40482
  exports.enableLog = enableLog;
40160
40483
  exports.executeCallback = executeCallback;
40484
+ exports.formatRequestContext = formatRequestContext;
40485
+ exports.generateInstanceId = generateInstanceId;
40486
+ exports.generateSdkInstanceId = generateSdkInstanceId;
40487
+ exports.getActiveRequestsByDeviceInstance = getActiveRequestsByDeviceInstance;
40161
40488
  exports.getDeviceBLEFirmwareVersion = getDeviceBLEFirmwareVersion;
40162
40489
  exports.getDeviceBleName = getDeviceBleName;
40163
40490
  exports.getDeviceBoardloaderVersion = getDeviceBoardloaderVersion;
@@ -40195,6 +40522,7 @@ exports.safeThrowError = safeThrowError;
40195
40522
  exports.setLoggerPostMessage = setLoggerPostMessage;
40196
40523
  exports.supportInputPinOnSoftware = supportInputPinOnSoftware;
40197
40524
  exports.switchTransport = switchTransport;
40525
+ exports.updateRequestContext = updateRequestContext;
40198
40526
  exports.versionCompare = versionCompare;
40199
40527
  exports.versionSplit = versionSplit;
40200
40528
  exports.wait = wait;