@onekeyfe/hd-transport 1.2.0-alpha.18 → 1.2.0-alpha.180

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 (55) hide show
  1. package/__tests__/messages.test.js +137 -32
  2. package/__tests__/protocol-v2-ble-frame-writer.test.js +119 -0
  3. package/__tests__/protocol-v2-link-manager.test.js +246 -9
  4. package/__tests__/protocol-v2-usb-transport-base.test.js +42 -6
  5. package/__tests__/protocol-v2.test.js +632 -62
  6. package/__tests__/transport-log.test.js +79 -0
  7. package/dist/constants.d.ts +3 -1
  8. package/dist/constants.d.ts.map +1 -1
  9. package/dist/index.d.ts +539 -285
  10. package/dist/index.d.ts.map +1 -1
  11. package/dist/index.js +718 -160
  12. package/dist/protocols/index.d.ts +17 -1
  13. package/dist/protocols/index.d.ts.map +1 -1
  14. package/dist/protocols/v2/ble-frame-writer.d.ts +15 -0
  15. package/dist/protocols/v2/ble-frame-writer.d.ts.map +1 -0
  16. package/dist/protocols/v2/decode.d.ts +11 -0
  17. package/dist/protocols/v2/decode.d.ts.map +1 -1
  18. package/dist/protocols/v2/errors.d.ts +16 -0
  19. package/dist/protocols/v2/errors.d.ts.map +1 -0
  20. package/dist/protocols/v2/frame-assembler.d.ts.map +1 -1
  21. package/dist/protocols/v2/index.d.ts +2 -0
  22. package/dist/protocols/v2/index.d.ts.map +1 -1
  23. package/dist/protocols/v2/link-manager.d.ts +6 -0
  24. package/dist/protocols/v2/link-manager.d.ts.map +1 -1
  25. package/dist/protocols/v2/session.d.ts +16 -4
  26. package/dist/protocols/v2/session.d.ts.map +1 -1
  27. package/dist/protocols/v2/usb-transport-base.d.ts +2 -0
  28. package/dist/protocols/v2/usb-transport-base.d.ts.map +1 -1
  29. package/dist/serialization/protobuf/encode.d.ts.map +1 -1
  30. package/dist/types/messages.d.ts +217 -202
  31. package/dist/types/messages.d.ts.map +1 -1
  32. package/dist/types/transport.d.ts +21 -2
  33. package/dist/types/transport.d.ts.map +1 -1
  34. package/dist/utils/transportLog.d.ts +9 -0
  35. package/dist/utils/transportLog.d.ts.map +1 -0
  36. package/messages-protocol-v2.json +515 -540
  37. package/package.json +2 -2
  38. package/scripts/protobuf-types.js +7 -1
  39. package/src/constants.ts +30 -16
  40. package/src/index.ts +5 -1
  41. package/src/protocols/index.ts +114 -3
  42. package/src/protocols/v2/ble-frame-writer.ts +77 -0
  43. package/src/protocols/v2/crc8.ts +1 -1
  44. package/src/protocols/v2/decode.ts +49 -12
  45. package/src/protocols/v2/encode.ts +1 -1
  46. package/src/protocols/v2/errors.ts +54 -0
  47. package/src/protocols/v2/frame-assembler.ts +6 -4
  48. package/src/protocols/v2/index.ts +2 -0
  49. package/src/protocols/v2/link-manager.ts +110 -9
  50. package/src/protocols/v2/session.ts +260 -87
  51. package/src/protocols/v2/usb-transport-base.ts +42 -10
  52. package/src/serialization/protobuf/encode.ts +5 -1
  53. package/src/types/messages.ts +269 -258
  54. package/src/types/transport.ts +39 -7
  55. package/src/utils/transportLog.ts +102 -0
package/dist/index.js CHANGED
@@ -200,7 +200,10 @@ function patch(Message, payload) {
200
200
  }
201
201
  if (field.repeated) {
202
202
  const RefMessage = Message.lookupTypeOrEnum(field.type);
203
- patched[key] = value.map((v) => patch(RefMessage, v));
203
+ patched[key] =
204
+ RefMessage instanceof protobuf.Enum
205
+ ? value.map((v) => transform(field.type, v))
206
+ : value.map((v) => patch(RefMessage, v));
204
207
  }
205
208
  else if (typeof value === 'object' && value !== null) {
206
209
  const RefMessage = Message.lookupType(field.type);
@@ -267,9 +270,10 @@ const PROTOCOL_V1_CHUNK_PAYLOAD_SIZE = 63;
267
270
  const PROTOCOL_V1_USB_PACKET_SIZE = PROTOCOL_V1_CHUNK_PAYLOAD_SIZE + 1;
268
271
  const PROTOCOL_V1_MESSAGE_HEADER_SIZE = 2 + 4;
269
272
  const PROTOCOL_V1_ENVELOPE_HEADER_SIZE = 1 + 1 + PROTOCOL_V1_MESSAGE_HEADER_SIZE;
270
- const PROTOCOL_V2_FRAME_MAX_BYTES = 4608;
273
+ const PROTOCOL_V2_FRAME_MAX_BYTES = 4200;
271
274
  const PROTOCOL_V2_WEBUSB_FILE_CHUNK_SIZE = 4000;
272
275
  const PROTOCOL_V2_BLE_FILE_CHUNK_SIZE = 1800;
276
+ const PROTOCOL_V2_BLE_FIRMWARE_FILE_CHUNK_SIZE = 1960;
273
277
  const PROTOCOL_V2_BLE_FILE_READ_CHUNK_SIZE = 900;
274
278
  const PROTOCOL_V2_BLE_FRAME_MAX_BYTES = 2048;
275
279
  const PROTOCOL_V2_FILE_CHUNK_SIZE = PROTOCOL_V2_WEBUSB_FILE_CHUNK_SIZE;
@@ -277,6 +281,7 @@ const PROTOCOL_V2_CHANNEL_USB = 0;
277
281
  const PROTOCOL_V2_CHANNEL_BLE_UART = 1;
278
282
  const PROTOCOL_V2_CHANNEL_SOCKET = 2;
279
283
  const PROTOCOL_V2_PACKET_SRC_COMMAND = 0;
284
+ const PROTOCOL_V2_DEFAULT_RESPONSE_TIMEOUT_MS = 5 * 60 * 1000;
280
285
 
281
286
  function encodeEnvelope(data, options) {
282
287
  const { addTrezorHeaders, chunked, messageTypeId } = options;
@@ -425,7 +430,7 @@ function encodeFrame(payload, packetSrc, router, seq) {
425
430
  const payloadLen = payload ? payload.length : 0;
426
431
  const frameLen = payloadLen + PROTO_HEAD_CRC_SIZE;
427
432
  if (frameLen > PROTOCOL_V2_FRAME_MAX_BYTES) {
428
- throw new Error(`Protocol V2 frame too large: ${frameLen}`);
433
+ throw new Error(`Protocol V2 frame too large: ${frameLen} > ${PROTOCOL_V2_FRAME_MAX_BYTES}`);
429
434
  }
430
435
  const frame = new Uint8Array(frameLen);
431
436
  frame[0] = PROTO_HEAD_SOF;
@@ -450,7 +455,7 @@ function encodeProtobufFrame(messageTypeId, pbPayload, packetSrc, router, seq) {
450
455
  return encodeFrame(payload, packetSrc, router, seq);
451
456
  }
452
457
 
453
- function validateFrame(data) {
458
+ function inspectFrameHeader(data) {
454
459
  if (data.length < PROTO_HEAD_CRC_SIZE) {
455
460
  throw new Error(`Protocol V2 frame too short: ${data.length} bytes`);
456
461
  }
@@ -458,8 +463,8 @@ function validateFrame(data) {
458
463
  throw new Error(`Invalid SOF byte: expected 0x5A, got 0x${data[0].toString(16).padStart(2, '0')}`);
459
464
  }
460
465
  const frameLen = data[1] + data[2] * 256;
461
- if (data.length < frameLen) {
462
- throw new Error(`Frame truncated: expected ${frameLen} bytes, got ${data.length}`);
466
+ if (data.length !== frameLen) {
467
+ throw new Error(`Protocol V2 frame length mismatch: expected ${frameLen} bytes, got ${data.length}`);
463
468
  }
464
469
  const expectedHeaderCrc = crc8(data, 3);
465
470
  if (data[3] !== expectedHeaderCrc) {
@@ -473,30 +478,66 @@ function validateFrame(data) {
473
478
  .toString(16)
474
479
  .padStart(2, '0')}, got 0x${data[frameLen - 1].toString(16).padStart(2, '0')}`);
475
480
  }
476
- return frameLen;
481
+ const dataType = data[5] & 0x03;
482
+ const packetSrc = (data[5] >> 2) & 0x0f;
483
+ const seq = data[6];
484
+ if (seq === 0) {
485
+ throw new Error('Invalid Protocol V2 sequence: 0 is reserved');
486
+ }
487
+ return {
488
+ frameLen,
489
+ router: data[4],
490
+ packetSrc,
491
+ dataType,
492
+ seq,
493
+ };
477
494
  }
478
495
  function isAckFrame(data) {
479
496
  if (data.length < 6 || (data[5] & 0x03) !== PROTO_DATA_TYPE_ACK) {
480
497
  return false;
481
498
  }
482
- const frameLen = validateFrame(data);
483
- if (frameLen !== PROTO_HEAD_CRC_SIZE) {
484
- throw new Error(`Invalid Protocol V2 ACK frame length: ${frameLen}`);
499
+ const header = inspectFrameHeader(data);
500
+ if (header.frameLen !== PROTO_HEAD_CRC_SIZE) {
501
+ throw new Error(`Invalid Protocol V2 ACK frame length: ${header.frameLen}`);
485
502
  }
486
503
  return true;
487
504
  }
488
505
  function decodeFrame(data) {
489
- const frameLen = validateFrame(data);
490
- const seq = data[6];
506
+ const { frameLen, router, packetSrc, dataType, seq } = inspectFrameHeader(data);
507
+ if (dataType !== PROTO_DATA_TYPE_PACKET) {
508
+ throw new Error(`Invalid Protocol V2 data type: expected packet, got ${dataType}`);
509
+ }
491
510
  const payloadData = data.slice(7, frameLen - 1);
492
511
  if (payloadData.length < 2) {
493
512
  throw new Error(`Protocol V2 payload too short (need >=2 bytes for messageTypeId)`);
494
513
  }
495
514
  const messageTypeId = payloadData[0] + payloadData[1] * 256;
496
515
  const pbPayload = payloadData.slice(2);
497
- return { messageTypeId, pbPayload, seq };
516
+ return { messageTypeId, pbPayload, seq, router, packetSrc, dataType };
498
517
  }
499
518
 
519
+ class ProtocolV2LinkError extends Error {
520
+ constructor(code, message, cause) {
521
+ super(message);
522
+ this.name = 'ProtocolV2LinkError';
523
+ this.code = code;
524
+ this.cause = cause;
525
+ }
526
+ }
527
+ const isProtocolV2LinkError = (error) => error instanceof ProtocolV2LinkError;
528
+ const createProtocolV2LinkDisabledError = (failureCode, firmwareMessage) => Object.assign(new Error(firmwareMessage), {
529
+ name: 'ProtocolV2LinkDisabledError',
530
+ failureCode,
531
+ firmwareMessage,
532
+ });
533
+ const isProtocolV2LinkDisabledError = (error) => error instanceof Error &&
534
+ error.name === 'ProtocolV2LinkDisabledError' &&
535
+ 'failureCode' in error &&
536
+ 'firmwareMessage' in error;
537
+ const isProtocolV2LinkDisabledFailure = (failureCode, firmwareMessage) => (failureCode === 'Failure_ProcessError' || failureCode === 5) &&
538
+ typeof firmwareMessage === 'string' &&
539
+ firmwareMessage.trim().toLowerCase() === 'link disabled';
540
+
500
541
  function concatUint8Arrays(arrays) {
501
542
  const totalLength = arrays.reduce((sum, arr) => sum + arr.length, 0);
502
543
  const result = new Uint8Array(totalLength);
@@ -540,23 +581,23 @@ class ProtocolV2FrameAssembler {
540
581
  return undefined;
541
582
  if (this.buffer[0] !== PROTO_HEAD_SOF) {
542
583
  this.reset();
543
- throw new Error('Invalid Protocol V2 SOF');
584
+ throw new ProtocolV2LinkError('frame', 'Invalid Protocol V2 SOF');
544
585
  }
545
586
  const expectedLen = this.buffer[1] + this.buffer[2] * 256;
546
587
  if (expectedLen < PROTO_HEAD_CRC_SIZE) {
547
588
  this.reset();
548
- throw new Error(`Protocol V2 frame length too small: ${expectedLen}`);
589
+ throw new ProtocolV2LinkError('frame', `Protocol V2 frame length too small: ${expectedLen}`);
549
590
  }
550
591
  if (expectedLen > this.maxFrameBytes) {
551
592
  this.reset();
552
- throw new Error(`Protocol V2 frame too large: ${expectedLen}`);
593
+ throw new ProtocolV2LinkError('frame', `Protocol V2 frame too large: ${expectedLen}`);
553
594
  }
554
595
  if (this.buffer.length < PROTO_PRE_HEAD_SIZE)
555
596
  return undefined;
556
597
  const expectedHeaderCrc = crc8(this.buffer, 3);
557
598
  if (this.buffer[3] !== expectedHeaderCrc) {
558
599
  this.reset();
559
- throw new Error(`Protocol V2 header CRC mismatch: expected 0x${expectedHeaderCrc
600
+ throw new ProtocolV2LinkError('frame', `Protocol V2 header CRC mismatch: expected 0x${expectedHeaderCrc
560
601
  .toString(16)
561
602
  .padStart(2, '0')}`);
562
603
  }
@@ -568,6 +609,51 @@ class ProtocolV2FrameAssembler {
568
609
  }
569
610
  }
570
611
 
612
+ const defaultWait = (timeoutMs) => new Promise(resolve => {
613
+ setTimeout(resolve, timeoutMs);
614
+ });
615
+ function writeProtocolV2BleFrame({ frame, packetCapacity, writePacket, assertActive, signal, abortMessage = 'Protocol V2 BLE write aborted', initialDelayMs = 0, burstSize, burstPauseMs = 0, flushDelayMs = 0, wait = defaultWait, }) {
616
+ return __awaiter(this, void 0, void 0, function* () {
617
+ if (!Number.isInteger(packetCapacity) || packetCapacity <= 0) {
618
+ throw new Error('Protocol V2 BLE packet capacity must be a positive integer');
619
+ }
620
+ if (burstSize !== undefined && (!Number.isInteger(burstSize) || burstSize <= 0)) {
621
+ throw new Error('Protocol V2 BLE burst size must be a positive integer');
622
+ }
623
+ const assertWritable = () => {
624
+ assertActive === null || assertActive === void 0 ? void 0 : assertActive();
625
+ if (signal === null || signal === void 0 ? void 0 : signal.aborted) {
626
+ throw new Error(abortMessage);
627
+ }
628
+ };
629
+ if (frame.length > 0 && initialDelayMs > 0) {
630
+ assertWritable();
631
+ yield wait(initialDelayMs);
632
+ assertWritable();
633
+ }
634
+ let packetsWritten = 0;
635
+ for (let offset = 0; offset < frame.length; offset += packetCapacity) {
636
+ assertWritable();
637
+ const packet = frame.slice(offset, offset + packetCapacity);
638
+ yield writePacket(packet, packetsWritten);
639
+ packetsWritten += 1;
640
+ assertWritable();
641
+ const hasMorePackets = offset + packetCapacity < frame.length;
642
+ if (hasMorePackets &&
643
+ burstSize !== undefined &&
644
+ packetsWritten % burstSize === 0 &&
645
+ burstPauseMs > 0) {
646
+ yield wait(burstPauseMs);
647
+ assertWritable();
648
+ }
649
+ }
650
+ if (burstSize !== undefined && packetsWritten > burstSize && flushDelayMs > 0) {
651
+ yield wait(flushDelayMs);
652
+ assertWritable();
653
+ }
654
+ });
655
+ }
656
+
571
657
  var protocolV2Codec = /*#__PURE__*/Object.freeze({
572
658
  __proto__: null,
573
659
  PROTO_HEAD_SOF: PROTO_HEAD_SOF,
@@ -582,13 +668,95 @@ var protocolV2Codec = /*#__PURE__*/Object.freeze({
582
668
  nextProtoSeq: nextProtoSeq,
583
669
  encodeFrame: encodeFrame,
584
670
  encodeProtobufFrame: encodeProtobufFrame,
671
+ inspectFrameHeader: inspectFrameHeader,
585
672
  isAckFrame: isAckFrame,
586
673
  decodeFrame: decodeFrame,
674
+ ProtocolV2LinkError: ProtocolV2LinkError,
675
+ isProtocolV2LinkError: isProtocolV2LinkError,
676
+ createProtocolV2LinkDisabledError: createProtocolV2LinkDisabledError,
677
+ isProtocolV2LinkDisabledError: isProtocolV2LinkDisabledError,
678
+ isProtocolV2LinkDisabledFailure: isProtocolV2LinkDisabledFailure,
587
679
  concatUint8Arrays: concatUint8Arrays,
588
- ProtocolV2FrameAssembler: ProtocolV2FrameAssembler
680
+ ProtocolV2FrameAssembler: ProtocolV2FrameAssembler,
681
+ writeProtocolV2BleFrame: writeProtocolV2BleFrame
589
682
  });
590
683
 
591
684
  const PROTOCOL_V2_SYS_MESSAGE_THRESHOLD = 60000;
685
+ const LEGACY_PROTOCOL_V2_PROTOCOL_INFO = protobuf.Type.fromJSON('LegacyProtocolInfo', {
686
+ fields: {
687
+ version: {
688
+ rule: 'required',
689
+ type: 'uint32',
690
+ id: 1,
691
+ },
692
+ supported_messages: {
693
+ rule: 'repeated',
694
+ type: 'uint32',
695
+ id: 2,
696
+ options: {
697
+ packed: false,
698
+ },
699
+ },
700
+ protobuf_definition: {
701
+ type: 'string',
702
+ id: 3,
703
+ },
704
+ },
705
+ });
706
+ const decodeLegacyProtocolV2ProtocolInfo = (pbPayload) => {
707
+ var _a;
708
+ const byteBuffer = ByteBuffer__default["default"].wrap(Buffer.from(pbPayload));
709
+ const legacy = decode(LEGACY_PROTOCOL_V2_PROTOCOL_INFO, byteBuffer);
710
+ return {
711
+ version: legacy.version,
712
+ build_fingerprint: '',
713
+ supported_messages: (_a = legacy.supported_messages) !== null && _a !== void 0 ? _a : [],
714
+ protobuf_definition: null,
715
+ };
716
+ };
717
+ const isLegacyProtocolV2ProtocolInfoWireLayout = (pbPayload) => {
718
+ const reader = protobuf.Reader.create(pbPayload);
719
+ let hasVersion = false;
720
+ try {
721
+ while (reader.pos < reader.len) {
722
+ const tag = reader.uint32();
723
+ const fieldNumber = tag >>> 3;
724
+ const wireType = tag & 0x07;
725
+ if (fieldNumber === 1) {
726
+ if (wireType !== 0)
727
+ return false;
728
+ hasVersion = true;
729
+ }
730
+ else if (fieldNumber === 2) {
731
+ if (wireType !== 0)
732
+ return false;
733
+ }
734
+ else if (fieldNumber === 3) {
735
+ if (wireType !== 2)
736
+ return false;
737
+ }
738
+ else {
739
+ return false;
740
+ }
741
+ reader.skipType(wireType);
742
+ }
743
+ }
744
+ catch (_a) {
745
+ return false;
746
+ }
747
+ return hasVersion;
748
+ };
749
+ const tryDecodeLegacyProtocolV2ProtocolInfo = (messageName, pbPayload) => {
750
+ if (messageName !== 'ProtocolInfo' || !isLegacyProtocolV2ProtocolInfoWireLayout(pbPayload)) {
751
+ return undefined;
752
+ }
753
+ try {
754
+ return decodeLegacyProtocolV2ProtocolInfo(pbPayload);
755
+ }
756
+ catch (_a) {
757
+ return undefined;
758
+ }
759
+ };
592
760
  const resolveProtocolV2EncodeSchema = (name, schemas) => {
593
761
  try {
594
762
  schemas.protocolV2.lookupType(name);
@@ -634,14 +802,18 @@ const ProtocolV1 = {
634
802
  };
635
803
  const ProtocolV2 = {
636
804
  isAckFrame,
805
+ inspectFrameHeader,
637
806
  inspectFrame(schemas, frame) {
638
- const { messageTypeId, pbPayload, seq } = decodeFrame(frame);
807
+ const { messageTypeId, pbPayload, seq, router, packetSrc, dataType } = decodeFrame(frame);
639
808
  const { messageName } = createProtocolV2MessageFromType(messageTypeId, schemas);
640
809
  return {
641
810
  messageName,
642
811
  messageTypeId,
643
812
  pbPayload,
644
813
  seq,
814
+ router,
815
+ packetSrc,
816
+ dataType,
645
817
  type: messageName,
646
818
  };
647
819
  },
@@ -658,7 +830,28 @@ const ProtocolV2 = {
658
830
  const { messageTypeId, pbPayload, seq, messageName } = this.inspectFrame(schemas, frame);
659
831
  const { Message } = createProtocolV2MessageFromType(messageTypeId, schemas);
660
832
  const rxByteBuffer = ByteBuffer__default["default"].wrap(Buffer.from(pbPayload));
661
- const message = decode(Message, rxByteBuffer);
833
+ let message;
834
+ try {
835
+ message = decode(Message, rxByteBuffer);
836
+ }
837
+ catch (cause) {
838
+ const legacyProtocolInfo = tryDecodeLegacyProtocolV2ProtocolInfo(messageName, pbPayload);
839
+ if (legacyProtocolInfo) {
840
+ return {
841
+ message: legacyProtocolInfo,
842
+ messageName,
843
+ messageTypeId,
844
+ pbPayload,
845
+ seq,
846
+ type: messageName,
847
+ };
848
+ }
849
+ const error = new Error(`Protocol V2 protobuf decode failed for "${messageName}" ` +
850
+ `(${messageTypeId}, ${pbPayload.length}-byte payload); ` +
851
+ 'the payload is malformed or incompatible with the active SDK schema.');
852
+ error.cause = cause;
853
+ throw error;
854
+ }
662
855
  return {
663
856
  message,
664
857
  messageName,
@@ -807,14 +1000,27 @@ function bytesToHex(bytes) {
807
1000
  .map(b => b.toString(16).padStart(2, '0'))
808
1001
  .join('');
809
1002
  }
810
- const HIGH_VOLUME_PROTOCOL_V2_CALLS = new Set([
1003
+ const REDUCED_DEBUG_PROTOCOL_V2_CALLS = new Set([
811
1004
  ...LogBlockCommand,
812
1005
  'FilesystemFileRead',
813
1006
  'FileRead',
814
1007
  'EmmcFileRead',
815
1008
  ]);
816
1009
  function shouldReduceProtocolV2Debug(name) {
817
- return HIGH_VOLUME_PROTOCOL_V2_CALLS.has(name);
1010
+ return REDUCED_DEBUG_PROTOCOL_V2_CALLS.has(name);
1011
+ }
1012
+ const HIGH_THROUGHPUT_PROTOCOL_V2_CALLS = new Set([
1013
+ 'FilesystemFileWrite',
1014
+ 'FileWrite',
1015
+ 'EmmcFileWrite',
1016
+ 'FirmwareUpload',
1017
+ 'ResourceAck',
1018
+ 'FilesystemFileRead',
1019
+ 'FileRead',
1020
+ 'EmmcFileRead',
1021
+ ]);
1022
+ function isProtocolV2HighThroughputCall(name) {
1023
+ return HIGH_THROUGHPUT_PROTOCOL_V2_CALLS.has(name);
818
1024
  }
819
1025
  const COMMON_TERMINAL_RESPONSE_TYPES = new Set([
820
1026
  'Failure',
@@ -841,11 +1047,12 @@ function getErrorMessage(error) {
841
1047
  }
842
1048
  return String(error);
843
1049
  }
844
- function withProtocolTimeout(promise, timeoutMs, createTimeoutError, onTimeout) {
1050
+ function withProtocolTimeout(promise, timeoutMs, createTimeoutError, onTimeout, abortSignal) {
845
1051
  return __awaiter(this, void 0, void 0, function* () {
846
1052
  if (!timeoutMs)
847
1053
  return promise;
848
1054
  let timer;
1055
+ let abortHandler;
849
1056
  try {
850
1057
  return yield Promise.race([
851
1058
  promise,
@@ -855,19 +1062,37 @@ function withProtocolTimeout(promise, timeoutMs, createTimeoutError, onTimeout)
855
1062
  reject(createTimeoutError());
856
1063
  }, timeoutMs);
857
1064
  }),
1065
+ ...(abortSignal
1066
+ ? [
1067
+ new Promise((_, reject) => {
1068
+ abortHandler = () => {
1069
+ reject(new Error('Protocol V2 operation aborted'));
1070
+ };
1071
+ if (abortSignal.aborted) {
1072
+ abortHandler();
1073
+ }
1074
+ else {
1075
+ abortSignal.addEventListener('abort', abortHandler, { once: true });
1076
+ }
1077
+ }),
1078
+ ]
1079
+ : []),
858
1080
  ]);
859
1081
  }
860
1082
  finally {
861
1083
  if (timer)
862
1084
  clearTimeout(timer);
1085
+ if (abortHandler) {
1086
+ abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.removeEventListener('abort', abortHandler);
1087
+ }
863
1088
  }
864
1089
  });
865
1090
  }
866
- const PROTOCOL_V2_WRITE_WATCHDOG_TIMEOUT_MS = 0;
867
1091
  class ProtocolV2Session {
868
1092
  constructor(options) {
869
1093
  var _a;
870
1094
  this.pendingCall = Promise.resolve();
1095
+ this.pendingWrite = Promise.resolve();
871
1096
  this.options = options;
872
1097
  this.sequenceCursor = (_a = options.sequenceCursor) !== null && _a !== void 0 ? _a : new ProtocolV2SequenceCursor();
873
1098
  }
@@ -877,17 +1102,49 @@ class ProtocolV2Session {
877
1102
  this.pendingCall = result.catch(() => undefined);
878
1103
  return result;
879
1104
  }
1105
+ sendFlowControl(name, data) {
1106
+ const { schemas, router, packetSrc = PROTOCOL_V2_PACKET_SRC_COMMAND, maxFrameBytes, writeFrame, generation = 0, } = this.options;
1107
+ const abortController = new AbortController();
1108
+ const context = {
1109
+ messageName: name,
1110
+ highThroughput: false,
1111
+ generation,
1112
+ signal: abortController.signal,
1113
+ };
1114
+ const protoSeq = this.sequenceCursor.next();
1115
+ const frame = ProtocolV2.encodeFrame(schemas, name, data, {
1116
+ packetSrc,
1117
+ router,
1118
+ seq: protoSeq,
1119
+ });
1120
+ if (maxFrameBytes !== undefined && frame.length > maxFrameBytes) {
1121
+ return Promise.reject(new Error(`Protocol V2 frame too large for transport: ${frame.length} > ${maxFrameBytes}`));
1122
+ }
1123
+ return this.serializeWrite(() => writeFrame(frame, context)).then(() => ({
1124
+ type: 'WriteCompleted',
1125
+ message: {},
1126
+ }));
1127
+ }
1128
+ serializeWrite(write) {
1129
+ const result = this.pendingWrite.then(write, write);
1130
+ this.pendingWrite = result.catch(() => undefined);
1131
+ return result;
1132
+ }
880
1133
  executeCall(name, data, callOptions) {
881
- return __awaiter(this, void 0, void 0, function* () {
882
- const { schemas, router, packetSrc = PROTOCOL_V2_PACKET_SRC_COMMAND, maxFrameBytes, prepareCall, writeFrame, readFrame, logger, logPrefix = 'ProtocolV2', createTimeoutError, generation = 0, } = this.options;
883
- const shouldReduceDebug = shouldReduceProtocolV2Debug(name);
884
- const callContext = {
885
- messageName: name,
886
- timeoutMs: callOptions.timeoutMs,
887
- highVolume: shouldReduceDebug,
888
- generation,
889
- };
890
- yield (prepareCall === null || prepareCall === void 0 ? void 0 : prepareCall(callContext));
1134
+ const { schemas, router, packetSrc = PROTOCOL_V2_PACKET_SRC_COMMAND, maxFrameBytes, prepareCall, writeFrame, readFrame, logger, logPrefix = 'ProtocolV2', createTimeoutError, generation = 0, } = this.options;
1135
+ const timeoutMs = callOptions.timeoutMs && callOptions.timeoutMs > 0
1136
+ ? callOptions.timeoutMs
1137
+ : PROTOCOL_V2_DEFAULT_RESPONSE_TIMEOUT_MS;
1138
+ const abortController = new AbortController();
1139
+ const shouldReduceDebug = shouldReduceProtocolV2Debug(name);
1140
+ const baseCallContext = Object.assign(Object.assign({ messageName: name, timeoutMs, highThroughput: isProtocolV2HighThroughputCall(name) }, (callOptions.writeWithResponse === undefined
1141
+ ? {}
1142
+ : { writeWithResponse: callOptions.writeWithResponse })), { generation, signal: abortController.signal });
1143
+ const runCall = () => __awaiter(this, void 0, void 0, function* () {
1144
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j;
1145
+ if (!this.pendingResponseAfterWrite) {
1146
+ yield (prepareCall === null || prepareCall === void 0 ? void 0 : prepareCall(baseCallContext));
1147
+ }
891
1148
  const protoSeq = this.sequenceCursor.next();
892
1149
  const frame = ProtocolV2.encodeFrame(schemas, name, data, {
893
1150
  packetSrc,
@@ -897,59 +1154,134 @@ class ProtocolV2Session {
897
1154
  if (maxFrameBytes !== undefined && frame.length > maxFrameBytes) {
898
1155
  throw new Error(`Protocol V2 frame too large for transport: ${frame.length} > ${maxFrameBytes}`);
899
1156
  }
900
- yield withProtocolTimeout(writeFrame(frame, callContext), PROTOCOL_V2_WRITE_WATCHDOG_TIMEOUT_MS, () => new Error(`Protocol V2 write timeout after ${PROTOCOL_V2_WRITE_WATCHDOG_TIMEOUT_MS}ms for ${name}`));
901
- const cancellation = { cancelled: false };
902
- const readResponse = () => __awaiter(this, void 0, void 0, function* () {
903
- var _a, _b, _c, _d;
904
- while (!cancellation.cancelled) {
905
- const rxFrame = yield readFrame(callContext);
906
- if (cancellation.cancelled) {
907
- break;
1157
+ const writeStartedAt = Date.now();
1158
+ yield this.serializeWrite(() => writeFrame(frame, baseCallContext));
1159
+ try {
1160
+ (_a = callOptions.onWriteCompleted) === null || _a === void 0 ? void 0 : _a.call(callOptions, {
1161
+ elapsedMs: Math.max(Date.now() - writeStartedAt, 0),
1162
+ frameBytes: frame.byteLength,
1163
+ });
1164
+ }
1165
+ catch (error) {
1166
+ (_b = logger === null || logger === void 0 ? void 0 : logger.error) === null || _b === void 0 ? void 0 : _b.call(logger, `${logPrefix} write metrics callback failed: ${String(error)}`);
1167
+ }
1168
+ if (callOptions.returnAfterWrite) {
1169
+ if ((_c = callOptions.expectedTypes) === null || _c === void 0 ? void 0 : _c.length) {
1170
+ this.pendingResponseAfterWrite = {
1171
+ expectedTypes: new Set(callOptions.expectedTypes),
1172
+ onResponse: callOptions.onResponseAfterWrite,
1173
+ };
1174
+ }
1175
+ return { type: 'WriteCompleted', message: {} };
1176
+ }
1177
+ while (!abortController.signal.aborted) {
1178
+ const rxFrame = yield readFrame(baseCallContext);
1179
+ if (abortController.signal.aborted)
1180
+ break;
1181
+ let header;
1182
+ try {
1183
+ header = ProtocolV2.inspectFrameHeader(rxFrame);
1184
+ }
1185
+ catch (cause) {
1186
+ throw new ProtocolV2LinkError('frame', `Protocol V2 frame validation failed: ${getErrorMessage(cause)}`, cause);
1187
+ }
1188
+ if (header.router !== router) {
1189
+ throw new ProtocolV2LinkError('router', `Protocol V2 router mismatch: expected ${router}, got ${header.router}`);
1190
+ }
1191
+ if (header.packetSrc !== packetSrc) {
1192
+ throw new ProtocolV2LinkError('packet-source', `Protocol V2 packet source mismatch: expected ${packetSrc}, got ${header.packetSrc}`);
1193
+ }
1194
+ let isAck;
1195
+ try {
1196
+ isAck = ProtocolV2.isAckFrame(rxFrame);
1197
+ }
1198
+ catch (cause) {
1199
+ throw new ProtocolV2LinkError('frame', `Protocol V2 ACK validation failed: ${getErrorMessage(cause)}`, cause);
1200
+ }
1201
+ if (isAck) {
1202
+ if (header.seq !== protoSeq) {
1203
+ throw new ProtocolV2LinkError('ack-sequence', `Protocol V2 ACK sequence mismatch: expected ${protoSeq}, got ${header.seq}`);
908
1204
  }
909
- const isAck = ProtocolV2.isAckFrame(rxFrame);
910
- if (!isAck) {
911
- const decoded = ProtocolV2.decodeFrame(schemas, rxFrame);
912
- const response = call(decoded);
913
- if ((_a = callOptions.intermediateTypes) === null || _a === void 0 ? void 0 : _a.includes(response.type)) {
914
- (_b = callOptions.onIntermediateResponse) === null || _b === void 0 ? void 0 : _b.call(callOptions, response);
915
- }
916
- else if (isExpectedTerminalResponse(response, callOptions.expectedTypes)) {
917
- return response;
918
- }
919
- else if (!shouldReduceDebug) {
920
- (_c = logger === null || logger === void 0 ? void 0 : logger.debug) === null || _c === void 0 ? void 0 : _c.call(logger, `[${logPrefix}] skip unexpected response for ${name}: expected=${(_d = callOptions.expectedTypes) === null || _d === void 0 ? void 0 : _d.join('|')} got=${response.type}`);
1205
+ }
1206
+ else {
1207
+ let decoded;
1208
+ try {
1209
+ decoded = ProtocolV2.decodeFrame(schemas, rxFrame);
1210
+ }
1211
+ catch (cause) {
1212
+ throw new ProtocolV2LinkError('frame', `Protocol V2 frame decode failed: ${getErrorMessage(cause)}`, cause);
1213
+ }
1214
+ if (this.lastResponseSequence === decoded.seq) {
1215
+ throw new ProtocolV2LinkError('response-sequence', `Protocol V2 duplicate response sequence: ${decoded.seq}`);
1216
+ }
1217
+ this.lastResponseSequence = decoded.seq;
1218
+ const response = call(decoded);
1219
+ const { pendingResponseAfterWrite } = this;
1220
+ let belongsToWriteOnlyCall = false;
1221
+ if (pendingResponseAfterWrite) {
1222
+ belongsToWriteOnlyCall = pendingResponseAfterWrite.expectedTypes.has(response.type);
1223
+ if (belongsToWriteOnlyCall || COMMON_TERMINAL_RESPONSE_TYPES.has(response.type)) {
1224
+ this.pendingResponseAfterWrite = undefined;
1225
+ if (belongsToWriteOnlyCall) {
1226
+ try {
1227
+ (_d = pendingResponseAfterWrite.onResponse) === null || _d === void 0 ? void 0 : _d.call(pendingResponseAfterWrite, response);
1228
+ }
1229
+ catch (error) {
1230
+ (_e = logger === null || logger === void 0 ? void 0 : logger.error) === null || _e === void 0 ? void 0 : _e.call(logger, `${logPrefix} delayed response callback failed: ${String(error)}`);
1231
+ }
1232
+ }
921
1233
  }
922
1234
  }
1235
+ if (belongsToWriteOnlyCall) ;
1236
+ else if ((_f = callOptions.intermediateTypes) === null || _f === void 0 ? void 0 : _f.includes(response.type)) {
1237
+ (_g = callOptions.onIntermediateResponse) === null || _g === void 0 ? void 0 : _g.call(callOptions, response);
1238
+ }
1239
+ else if (isExpectedTerminalResponse(response, callOptions.expectedTypes)) {
1240
+ return response;
1241
+ }
1242
+ else if (!shouldReduceDebug) {
1243
+ (_h = logger === null || logger === void 0 ? void 0 : logger.debug) === null || _h === void 0 ? void 0 : _h.call(logger, `[${logPrefix}] skip unexpected response for ${name}: expected=${(_j = callOptions.expectedTypes) === null || _j === void 0 ? void 0 : _j.join('|')} got=${response.type}`);
1244
+ }
923
1245
  }
924
- throw new Error(`Protocol V2 read loop cancelled after timeout for ${name}`);
925
- });
926
- return withProtocolTimeout(readResponse(), callOptions.timeoutMs, () => {
927
- var _a;
928
- return createTimeoutError
929
- ? createTimeoutError(name, (_a = callOptions.timeoutMs) !== null && _a !== void 0 ? _a : 0)
930
- : new Error(`Protocol V2 response timeout after ${callOptions.timeoutMs}ms for ${name}`);
931
- }, () => {
932
- cancellation.cancelled = true;
933
- });
1246
+ }
1247
+ throw new Error(`Protocol V2 read loop cancelled after timeout for ${name}`);
1248
+ });
1249
+ return withProtocolTimeout(runCall(), timeoutMs, () => createTimeoutError
1250
+ ? createTimeoutError(name, timeoutMs)
1251
+ : new Error(`Protocol V2 response timeout after ${timeoutMs}ms for ${name}`), () => {
1252
+ abortController.abort();
934
1253
  });
935
1254
  }
936
1255
  }
937
1256
  function probeProtocolV2({ call, timeoutMs, logger, logPrefix = 'ProtocolV2', onBeforeProbe, onProbeFailed, }) {
938
- var _a;
1257
+ var _a, _b, _c;
939
1258
  return __awaiter(this, void 0, void 0, function* () {
940
1259
  let probeError;
941
1260
  try {
942
1261
  yield (onBeforeProbe === null || onBeforeProbe === void 0 ? void 0 : onBeforeProbe());
943
- const response = yield call('Ping', { message: 'protocol-v2-probe' }, { timeoutMs, expectedTypes: ['Success'] });
1262
+ const response = yield call('Ping', { message: 'protocol-v2-probe' }, {
1263
+ timeoutMs,
1264
+ expectedTypes: ['Success'],
1265
+ });
944
1266
  if (response.type === 'Success') {
945
1267
  return true;
946
1268
  }
1269
+ if (response.type === 'Failure') {
1270
+ const failureCode = (_a = response.message) === null || _a === void 0 ? void 0 : _a.code;
1271
+ const firmwareMessage = (_b = response.message) === null || _b === void 0 ? void 0 : _b.message;
1272
+ if (isProtocolV2LinkDisabledFailure(failureCode, firmwareMessage)) {
1273
+ throw createProtocolV2LinkDisabledError(failureCode, firmwareMessage);
1274
+ }
1275
+ }
947
1276
  probeError = new Error(`unexpected response type ${response.type}`);
948
1277
  }
949
1278
  catch (error) {
1279
+ if (isProtocolV2LinkDisabledError(error)) {
1280
+ throw error;
1281
+ }
950
1282
  probeError = error;
951
1283
  }
952
- (_a = logger === null || logger === void 0 ? void 0 : logger.debug) === null || _a === void 0 ? void 0 : _a.call(logger, `[${logPrefix}] Protocol V2 probe failed:`, getErrorMessage(probeError));
1284
+ (_c = logger === null || logger === void 0 ? void 0 : logger.debug) === null || _c === void 0 ? void 0 : _c.call(logger, `[${logPrefix}] Protocol V2 probe failed:`, getErrorMessage(probeError));
953
1285
  yield (onProbeFailed === null || onProbeFailed === void 0 ? void 0 : onProbeFailed(probeError));
954
1286
  return false;
955
1287
  });
@@ -960,35 +1292,98 @@ class ProtocolV2LinkManager {
960
1292
  this.links = new Map();
961
1293
  this.sequences = new Map();
962
1294
  this.callQueues = new Map();
1295
+ this.generations = new Map();
1296
+ this.invalidationReasons = new Map();
1297
+ this.invalidations = new Map();
963
1298
  this.options = options;
964
1299
  }
965
1300
  call(key, createAdapter, name, data, options) {
966
1301
  var _a;
967
- const run = () => this.executeCall(key, createAdapter, name, data, options);
968
- const previous = (_a = this.callQueues.get(key)) !== null && _a !== void 0 ? _a : Promise.resolve();
969
- const result = previous.then(run, run);
970
- const queue = result.catch(() => undefined);
1302
+ const generation = (_a = this.generations.get(key)) !== null && _a !== void 0 ? _a : 0;
1303
+ const previousQueue = this.callQueues.get(key);
1304
+ const timeoutMs = (options === null || options === void 0 ? void 0 : options.timeoutMs) && options.timeoutMs > 0
1305
+ ? options.timeoutMs
1306
+ : PROTOCOL_V2_DEFAULT_RESPONSE_TIMEOUT_MS;
1307
+ const queuedAt = Date.now();
1308
+ let queueTimeout;
1309
+ let queueTimeoutError;
1310
+ const timeoutWhileQueued = new Promise((_, reject) => {
1311
+ queueTimeout = setTimeout(() => {
1312
+ queueTimeout = undefined;
1313
+ queueTimeoutError = this.createQueuedCallTimeoutError(key, name, timeoutMs);
1314
+ reject(queueTimeoutError);
1315
+ }, timeoutMs);
1316
+ });
1317
+ const run = () => {
1318
+ if (queueTimeout) {
1319
+ clearTimeout(queueTimeout);
1320
+ queueTimeout = undefined;
1321
+ }
1322
+ if (queueTimeoutError) {
1323
+ throw queueTimeoutError;
1324
+ }
1325
+ this.assertCallGeneration(key, generation);
1326
+ const remainingTimeoutMs = previousQueue ? timeoutMs - (Date.now() - queuedAt) : timeoutMs;
1327
+ if (remainingTimeoutMs <= 0) {
1328
+ throw this.createQueuedCallTimeoutError(key, name, timeoutMs);
1329
+ }
1330
+ return this.executeCall(key, createAdapter, name, data, Object.assign(Object.assign({}, options), { timeoutMs: remainingTimeoutMs }));
1331
+ };
1332
+ const previous = previousQueue !== null && previousQueue !== void 0 ? previousQueue : Promise.resolve();
1333
+ const execution = previous.then(run, run);
1334
+ const result = Promise.race([execution, timeoutWhileQueued]);
1335
+ const queue = execution.catch(() => undefined);
971
1336
  this.callQueues.set(key, queue);
972
- result
1337
+ execution
973
1338
  .then(() => this.clearSettledCallQueue(key, queue), () => this.clearSettledCallQueue(key, queue))
974
1339
  .catch(() => undefined);
975
1340
  return result;
976
1341
  }
1342
+ sendFlowControl(key, createAdapter, name, data) {
1343
+ var _a;
1344
+ const generation = (_a = this.generations.get(key)) !== null && _a !== void 0 ? _a : 0;
1345
+ this.assertCallGeneration(key, generation);
1346
+ return this.getOrCreateLink(key, createAdapter).session.sendFlowControl(name, data);
1347
+ }
977
1348
  invalidateLink(key, reason) {
978
- var _a, _b;
1349
+ var _a;
979
1350
  return __awaiter(this, void 0, void 0, function* () {
1351
+ const generation = ((_a = this.generations.get(key)) !== null && _a !== void 0 ? _a : 0) + 1;
1352
+ this.generations.set(key, generation);
1353
+ this.invalidationReasons.set(key, { generation, reason });
1354
+ const pendingInvalidation = this.invalidations.get(key);
980
1355
  const link = this.links.get(key);
981
- if (!link)
1356
+ if (!link) {
1357
+ yield pendingInvalidation;
982
1358
  return;
1359
+ }
983
1360
  this.links.delete(key);
984
1361
  link.state.invalidatedReason = reason;
985
- yield link.adapter.reset(reason);
986
- yield ((_b = (_a = this.options).onLinkInvalidated) === null || _b === void 0 ? void 0 : _b.call(_a, key, reason));
1362
+ const invalidation = (() => __awaiter(this, void 0, void 0, function* () {
1363
+ var _b, _c;
1364
+ yield (pendingInvalidation === null || pendingInvalidation === void 0 ? void 0 : pendingInvalidation.catch(() => undefined));
1365
+ yield link.adapter.reset(reason);
1366
+ yield ((_c = (_b = this.options).onLinkInvalidated) === null || _c === void 0 ? void 0 : _c.call(_b, key, reason));
1367
+ }))();
1368
+ this.invalidations.set(key, invalidation);
1369
+ try {
1370
+ yield invalidation;
1371
+ }
1372
+ finally {
1373
+ if (this.invalidations.get(key) === invalidation) {
1374
+ this.invalidations.delete(key);
1375
+ }
1376
+ }
987
1377
  });
988
1378
  }
989
1379
  invalidateAllLinks(reason) {
990
1380
  return __awaiter(this, void 0, void 0, function* () {
991
- yield Promise.all(Array.from(this.links.keys(), key => this.invalidateLink(key, reason)));
1381
+ const keys = new Set([
1382
+ ...this.links.keys(),
1383
+ ...this.callQueues.keys(),
1384
+ ...this.invalidations.keys(),
1385
+ ]);
1386
+ yield Promise.all(Array.from(keys, key => this.invalidateLink(key, reason)));
992
1387
  });
993
1388
  }
994
1389
  dispose(reason) {
@@ -996,6 +1391,7 @@ class ProtocolV2LinkManager {
996
1391
  yield this.invalidateAllLinks(reason);
997
1392
  this.sequences.clear();
998
1393
  this.callQueues.clear();
1394
+ this.invalidations.clear();
999
1395
  });
1000
1396
  }
1001
1397
  getOrCreateLink(key, createAdapter) {
@@ -1063,6 +1459,24 @@ class ProtocolV2LinkManager {
1063
1459
  this.callQueues.delete(key);
1064
1460
  }
1065
1461
  }
1462
+ createQueuedCallTimeoutError(key, name, timeoutMs) {
1463
+ var _a;
1464
+ const adapterTimeoutError = (_a = this.links.get(key)) === null || _a === void 0 ? void 0 : _a.adapter.createTimeoutError;
1465
+ return adapterTimeoutError
1466
+ ? adapterTimeoutError(name, timeoutMs)
1467
+ : new ProtocolV2LinkError('response-timeout', `Protocol V2 call timeout after ${timeoutMs}ms while queued for ${name}`);
1468
+ }
1469
+ assertCallGeneration(key, generation) {
1470
+ var _a;
1471
+ const currentGeneration = (_a = this.generations.get(key)) !== null && _a !== void 0 ? _a : 0;
1472
+ if (currentGeneration === generation)
1473
+ return;
1474
+ const invalidation = this.invalidationReasons.get(key);
1475
+ const reason = (invalidation === null || invalidation === void 0 ? void 0 : invalidation.generation) === currentGeneration
1476
+ ? invalidation.reason
1477
+ : 'Protocol V2 link generation changed';
1478
+ throw new ProtocolV2LinkError('generation', reason);
1479
+ }
1066
1480
  }
1067
1481
 
1068
1482
  class ProtocolV2UsbTransportBase {
@@ -1073,7 +1487,7 @@ class ProtocolV2UsbTransportBase {
1073
1487
  this.protocolV2UsbOptions = options;
1074
1488
  this.protocolV2UsbLinks = new ProtocolV2LinkManager({
1075
1489
  getSchemas: () => this.getProtocolV2UsbSchemas(),
1076
- classifyError: () => 'link-fatal',
1490
+ classifyError: error => (isProtocolV2LinkError(error) ? 'link-fatal' : 'recoverable'),
1077
1491
  onLinkInvalidated: (key, reason) => __awaiter(this, void 0, void 0, function* () {
1078
1492
  var _a;
1079
1493
  (_a = this.protocolV2UsbAssemblers.get(key)) === null || _a === void 0 ? void 0 : _a.reset();
@@ -1098,6 +1512,9 @@ class ProtocolV2UsbTransportBase {
1098
1512
  callProtocolV2Usb(key, name, data, options) {
1099
1513
  return this.protocolV2UsbLinks.call(key, () => this.createProtocolV2UsbAdapter(key), name, data, options);
1100
1514
  }
1515
+ sendProtocolV2UsbFlowControl(key, name, data) {
1516
+ return this.protocolV2UsbLinks.sendFlowControl(key, () => this.createProtocolV2UsbAdapter(key), name, data);
1517
+ }
1101
1518
  invalidateProtocolV2UsbLink(key, reason) {
1102
1519
  return this.protocolV2UsbLinks.invalidateLink(key, reason);
1103
1520
  }
@@ -1123,10 +1540,10 @@ class ProtocolV2UsbTransportBase {
1123
1540
  }
1124
1541
  const assertCurrentGeneration = () => {
1125
1542
  if (cancellation.reason) {
1126
- throw new Error(cancellation.reason);
1543
+ throw new ProtocolV2LinkError('generation', cancellation.reason);
1127
1544
  }
1128
1545
  if (this.protocolV2UsbGenerations.get(key) !== generation) {
1129
- throw new Error('Protocol V2 USB connection generation changed');
1546
+ throw new ProtocolV2LinkError('generation', 'Protocol V2 USB connection generation changed');
1130
1547
  }
1131
1548
  };
1132
1549
  return {
@@ -1135,11 +1552,15 @@ class ProtocolV2UsbTransportBase {
1135
1552
  generation,
1136
1553
  prepareCall: () => {
1137
1554
  assertCurrentGeneration();
1138
- this.getProtocolV2UsbAssembler(key).reset();
1139
1555
  },
1140
1556
  writeFrame: (frame, context) => __awaiter(this, void 0, void 0, function* () {
1141
1557
  assertCurrentGeneration();
1142
- yield this.writeProtocolV2UsbPacket(key, frame, context);
1558
+ try {
1559
+ yield this.writeProtocolV2UsbPacket(key, frame, context);
1560
+ }
1561
+ catch (error) {
1562
+ throw this.createProtocolV2UsbIoError('write', error);
1563
+ }
1143
1564
  assertCurrentGeneration();
1144
1565
  }),
1145
1566
  readFrame: (context) => __awaiter(this, void 0, void 0, function* () {
@@ -1147,13 +1568,15 @@ class ProtocolV2UsbTransportBase {
1147
1568
  const assembler = this.getProtocolV2UsbAssembler(key);
1148
1569
  let frame = assembler.push(new Uint8Array(0));
1149
1570
  while (!frame) {
1150
- const packetRead = this.readProtocolV2UsbPacket(key, context).then(packet => ({
1151
- packet,
1152
- }));
1571
+ const packetRead = this.readProtocolV2UsbPacket(key, context)
1572
+ .then(packet => ({ packet }))
1573
+ .catch(error => {
1574
+ throw this.createProtocolV2UsbIoError('read', error);
1575
+ });
1153
1576
  const cancelled = cancellation.promise.then(reason => ({ reason }));
1154
1577
  const result = yield Promise.race([packetRead, cancelled]);
1155
1578
  if ('reason' in result) {
1156
- throw new Error(result.reason);
1579
+ throw new ProtocolV2LinkError('generation', result.reason);
1157
1580
  }
1158
1581
  assertCurrentGeneration();
1159
1582
  frame = assembler.push(result.packet);
@@ -1194,8 +1617,17 @@ class ProtocolV2UsbTransportBase {
1194
1617
  };
1195
1618
  return cancellation;
1196
1619
  }
1620
+ createProtocolV2UsbIoError(operation, error) {
1621
+ if (isProtocolV2LinkError(error))
1622
+ return error;
1623
+ return new ProtocolV2LinkError('io', `Protocol V2 USB ${operation} failed: ${getErrorMessage(error) || 'unknown error'}`, error);
1624
+ }
1197
1625
  }
1198
1626
 
1627
+ const TRANSPORT_EVENT = {
1628
+ DEVICE_DISCONNECT: 'transport-device-disconnect',
1629
+ };
1630
+
1199
1631
  exports.AptosTransactionType = void 0;
1200
1632
  (function (AptosTransactionType) {
1201
1633
  AptosTransactionType[AptosTransactionType["STANDARD"] = 0] = "STANDARD";
@@ -1653,11 +2085,6 @@ exports.CommandFlags = void 0;
1653
2085
  CommandFlags[CommandFlags["Default"] = 0] = "Default";
1654
2086
  CommandFlags[CommandFlags["Factory_Only"] = 1] = "Factory_Only";
1655
2087
  })(exports.CommandFlags || (exports.CommandFlags = {}));
1656
- exports.WallpaperTarget = void 0;
1657
- (function (WallpaperTarget) {
1658
- WallpaperTarget[WallpaperTarget["Home"] = 0] = "Home";
1659
- WallpaperTarget[WallpaperTarget["Lock"] = 1] = "Lock";
1660
- })(exports.WallpaperTarget || (exports.WallpaperTarget = {}));
1661
2088
  exports.MoneroNetworkType = void 0;
1662
2089
  (function (MoneroNetworkType) {
1663
2090
  MoneroNetworkType[MoneroNetworkType["MAINNET"] = 0] = "MAINNET";
@@ -1665,22 +2092,18 @@ exports.MoneroNetworkType = void 0;
1665
2092
  MoneroNetworkType[MoneroNetworkType["STAGENET"] = 2] = "STAGENET";
1666
2093
  MoneroNetworkType[MoneroNetworkType["FAKECHAIN"] = 3] = "FAKECHAIN";
1667
2094
  })(exports.MoneroNetworkType || (exports.MoneroNetworkType = {}));
1668
- exports.ViewTipType = void 0;
1669
- (function (ViewTipType) {
1670
- ViewTipType[ViewTipType["Default"] = 0] = "Default";
1671
- ViewTipType[ViewTipType["Highlight"] = 1] = "Highlight";
1672
- ViewTipType[ViewTipType["Recommend"] = 2] = "Recommend";
1673
- ViewTipType[ViewTipType["Warning"] = 3] = "Warning";
1674
- ViewTipType[ViewTipType["Danger"] = 4] = "Danger";
1675
- })(exports.ViewTipType || (exports.ViewTipType = {}));
1676
- exports.ViewSignLayout = void 0;
1677
- (function (ViewSignLayout) {
1678
- ViewSignLayout[ViewSignLayout["LayoutDefault"] = 0] = "LayoutDefault";
1679
- ViewSignLayout[ViewSignLayout["LayoutSafeTxCreate"] = 1] = "LayoutSafeTxCreate";
1680
- ViewSignLayout[ViewSignLayout["LayoutFinalConfirm"] = 2] = "LayoutFinalConfirm";
1681
- ViewSignLayout[ViewSignLayout["Layout7702"] = 3] = "Layout7702";
1682
- ViewSignLayout[ViewSignLayout["LayoutFlat"] = 4] = "LayoutFlat";
1683
- })(exports.ViewSignLayout || (exports.ViewSignLayout = {}));
2095
+ exports.UiAnimationType = void 0;
2096
+ (function (UiAnimationType) {
2097
+ UiAnimationType[UiAnimationType["Unknown"] = 0] = "Unknown";
2098
+ UiAnimationType[UiAnimationType["Signing"] = 1] = "Signing";
2099
+ })(exports.UiAnimationType || (exports.UiAnimationType = {}));
2100
+ exports.UiAnimationCommand = void 0;
2101
+ (function (UiAnimationCommand) {
2102
+ UiAnimationCommand[UiAnimationCommand["CommandUnknown"] = 0] = "CommandUnknown";
2103
+ UiAnimationCommand[UiAnimationCommand["Start"] = 1] = "Start";
2104
+ UiAnimationCommand[UiAnimationCommand["Stop"] = 2] = "Stop";
2105
+ UiAnimationCommand[UiAnimationCommand["Refresh"] = 3] = "Refresh";
2106
+ })(exports.UiAnimationCommand || (exports.UiAnimationCommand = {}));
1684
2107
  exports.DeviceErrorCode = void 0;
1685
2108
  (function (DeviceErrorCode) {
1686
2109
  DeviceErrorCode[DeviceErrorCode["DeviceError_None"] = 0] = "DeviceError_None";
@@ -1707,6 +2130,11 @@ exports.DeviceSettingsPage = void 0;
1707
2130
  DeviceSettingsPage[DeviceSettingsPage["DevicePassphrase"] = 2] = "DevicePassphrase";
1708
2131
  DeviceSettingsPage[DeviceSettingsPage["DeviceAirgap"] = 3] = "DeviceAirgap";
1709
2132
  })(exports.DeviceSettingsPage || (exports.DeviceSettingsPage = {}));
2133
+ exports.DeviceFactoryAck = void 0;
2134
+ (function (DeviceFactoryAck) {
2135
+ DeviceFactoryAck[DeviceFactoryAck["FACTORY_ACK_SUCCESS"] = 0] = "FACTORY_ACK_SUCCESS";
2136
+ DeviceFactoryAck[DeviceFactoryAck["FACTORY_ACK_FAIL"] = 1] = "FACTORY_ACK_FAIL";
2137
+ })(exports.DeviceFactoryAck || (exports.DeviceFactoryAck = {}));
1710
2138
  exports.DeviceFirmwareTargetType = void 0;
1711
2139
  (function (DeviceFirmwareTargetType) {
1712
2140
  DeviceFirmwareTargetType[DeviceFirmwareTargetType["FW_MGMT_TARGET_INVALID"] = 0] = "FW_MGMT_TARGET_INVALID";
@@ -1735,11 +2163,6 @@ exports.DeviceFirmwareUpdateTaskStatus = void 0;
1735
2163
  DeviceFirmwareUpdateTaskStatus[DeviceFirmwareUpdateTaskStatus["FW_MGMT_UPDATER_TASK_STATUS_FAILED_BUSY"] = 9] = "FW_MGMT_UPDATER_TASK_STATUS_FAILED_BUSY";
1736
2164
  DeviceFirmwareUpdateTaskStatus[DeviceFirmwareUpdateTaskStatus["FW_MGMT_UPDATER_TASK_STATUS_FAILED_ENTRY_OUT_OF_BOUNDS"] = 10] = "FW_MGMT_UPDATER_TASK_STATUS_FAILED_ENTRY_OUT_OF_BOUNDS";
1737
2165
  })(exports.DeviceFirmwareUpdateTaskStatus || (exports.DeviceFirmwareUpdateTaskStatus = {}));
1738
- exports.DeviceFactoryAck = void 0;
1739
- (function (DeviceFactoryAck) {
1740
- DeviceFactoryAck[DeviceFactoryAck["FACTORY_ACK_SUCCESS"] = 0] = "FACTORY_ACK_SUCCESS";
1741
- DeviceFactoryAck[DeviceFactoryAck["FACTORY_ACK_FAIL"] = 1] = "FACTORY_ACK_FAIL";
1742
- })(exports.DeviceFactoryAck || (exports.DeviceFactoryAck = {}));
1743
2166
  exports.DeviceType = void 0;
1744
2167
  (function (DeviceType) {
1745
2168
  DeviceType[DeviceType["CLASSIC1"] = 0] = "CLASSIC1";
@@ -1762,49 +2185,86 @@ exports.DeviceSEState = void 0;
1762
2185
  DeviceSEState[DeviceSEState["APP_FACTORY"] = 51] = "APP_FACTORY";
1763
2186
  DeviceSEState[DeviceSEState["APP"] = 85] = "APP";
1764
2187
  })(exports.DeviceSEState || (exports.DeviceSEState = {}));
2188
+ exports.DeviceSessionErrorCode = void 0;
2189
+ (function (DeviceSessionErrorCode) {
2190
+ DeviceSessionErrorCode[DeviceSessionErrorCode["DeviceSessionError_None"] = 0] = "DeviceSessionError_None";
2191
+ DeviceSessionErrorCode[DeviceSessionErrorCode["DeviceSessionError_UserCancelled"] = 1] = "DeviceSessionError_UserCancelled";
2192
+ DeviceSessionErrorCode[DeviceSessionErrorCode["DeviceSessionError_InvalidSession"] = 2] = "DeviceSessionError_InvalidSession";
2193
+ DeviceSessionErrorCode[DeviceSessionErrorCode["DeviceSessionError_AttachPinUnavailable"] = 3] = "DeviceSessionError_AttachPinUnavailable";
2194
+ DeviceSessionErrorCode[DeviceSessionErrorCode["DeviceSessionError_PassphraseDisabled"] = 4] = "DeviceSessionError_PassphraseDisabled";
2195
+ DeviceSessionErrorCode[DeviceSessionErrorCode["DeviceSessionError_Busy"] = 5] = "DeviceSessionError_Busy";
2196
+ })(exports.DeviceSessionErrorCode || (exports.DeviceSessionErrorCode = {}));
2197
+ exports.DeviceSessionSeedDomain = void 0;
2198
+ (function (DeviceSessionSeedDomain) {
2199
+ DeviceSessionSeedDomain[DeviceSessionSeedDomain["SeedDomain_Standard"] = 1] = "SeedDomain_Standard";
2200
+ DeviceSessionSeedDomain[DeviceSessionSeedDomain["SeedDomain_Cardano"] = 2] = "SeedDomain_Cardano";
2201
+ })(exports.DeviceSessionSeedDomain || (exports.DeviceSessionSeedDomain = {}));
2202
+ exports.DeviceSessionPinType = void 0;
2203
+ (function (DeviceSessionPinType) {
2204
+ DeviceSessionPinType[DeviceSessionPinType["Any"] = 1] = "Any";
2205
+ DeviceSessionPinType[DeviceSessionPinType["Main"] = 2] = "Main";
2206
+ DeviceSessionPinType[DeviceSessionPinType["AttachToPin"] = 3] = "AttachToPin";
2207
+ })(exports.DeviceSessionPinType || (exports.DeviceSessionPinType = {}));
1765
2208
  exports.DeviceSessionAskPin_FailureSubCodes = void 0;
1766
2209
  (function (DeviceSessionAskPin_FailureSubCodes) {
1767
2210
  DeviceSessionAskPin_FailureSubCodes[DeviceSessionAskPin_FailureSubCodes["UserCancel"] = 1] = "UserCancel";
1768
2211
  })(exports.DeviceSessionAskPin_FailureSubCodes || (exports.DeviceSessionAskPin_FailureSubCodes = {}));
1769
- exports.DevOnboardingStep = void 0;
1770
- (function (DevOnboardingStep) {
1771
- DevOnboardingStep[DevOnboardingStep["DEV_ONBOARDING_STEP_UNKNOWN"] = 0] = "DEV_ONBOARDING_STEP_UNKNOWN";
1772
- DevOnboardingStep[DevOnboardingStep["DEV_ONBOARDING_STEP_CHECKING"] = 1] = "DEV_ONBOARDING_STEP_CHECKING";
1773
- DevOnboardingStep[DevOnboardingStep["DEV_ONBOARDING_STEP_PERSONALIZATION"] = 2] = "DEV_ONBOARDING_STEP_PERSONALIZATION";
1774
- DevOnboardingStep[DevOnboardingStep["DEV_ONBOARDING_STEP_PIN"] = 3] = "DEV_ONBOARDING_STEP_PIN";
1775
- DevOnboardingStep[DevOnboardingStep["DEV_ONBOARDING_STEP_SETUP"] = 4] = "DEV_ONBOARDING_STEP_SETUP";
1776
- DevOnboardingStep[DevOnboardingStep["DEV_ONBOARDING_STEP_DONE"] = 5] = "DEV_ONBOARDING_STEP_DONE";
1777
- })(exports.DevOnboardingStep || (exports.DevOnboardingStep = {}));
1778
- exports.DevOnboardingPhase = void 0;
1779
- (function (DevOnboardingPhase) {
1780
- DevOnboardingPhase[DevOnboardingPhase["DEV_ONBOARDING_PHASE_UNKNOWN"] = 0] = "DEV_ONBOARDING_PHASE_UNKNOWN";
1781
- DevOnboardingPhase[DevOnboardingPhase["DEV_ONBOARDING_PHASE_SAFETY_CHECK"] = 1] = "DEV_ONBOARDING_PHASE_SAFETY_CHECK";
1782
- DevOnboardingPhase[DevOnboardingPhase["DEV_ONBOARDING_PHASE_PIN_SETUP"] = 2] = "DEV_ONBOARDING_PHASE_PIN_SETUP";
1783
- DevOnboardingPhase[DevOnboardingPhase["DEV_ONBOARDING_PHASE_FINGERPRINT_SETUP"] = 3] = "DEV_ONBOARDING_PHASE_FINGERPRINT_SETUP";
1784
- DevOnboardingPhase[DevOnboardingPhase["DEV_ONBOARDING_PHASE_SETUP_CHOICE"] = 4] = "DEV_ONBOARDING_PHASE_SETUP_CHOICE";
1785
- DevOnboardingPhase[DevOnboardingPhase["DEV_ONBOARDING_PHASE_WALLET_CREATE_START"] = 5] = "DEV_ONBOARDING_PHASE_WALLET_CREATE_START";
1786
- DevOnboardingPhase[DevOnboardingPhase["DEV_ONBOARDING_PHASE_RECOVERY_PHRASE_VIEW"] = 6] = "DEV_ONBOARDING_PHASE_RECOVERY_PHRASE_VIEW";
1787
- DevOnboardingPhase[DevOnboardingPhase["DEV_ONBOARDING_PHASE_RECOVERY_PHRASE_CONFIRM"] = 7] = "DEV_ONBOARDING_PHASE_RECOVERY_PHRASE_CONFIRM";
1788
- DevOnboardingPhase[DevOnboardingPhase["DEV_ONBOARDING_PHASE_RESTORE_METHOD_CHOICE"] = 8] = "DEV_ONBOARDING_PHASE_RESTORE_METHOD_CHOICE";
1789
- DevOnboardingPhase[DevOnboardingPhase["DEV_ONBOARDING_PHASE_RECOVERY_PHRASE_RESTORE"] = 9] = "DEV_ONBOARDING_PHASE_RECOVERY_PHRASE_RESTORE";
1790
- DevOnboardingPhase[DevOnboardingPhase["DEV_ONBOARDING_PHASE_SEEDCARD_RESTORE"] = 10] = "DEV_ONBOARDING_PHASE_SEEDCARD_RESTORE";
1791
- DevOnboardingPhase[DevOnboardingPhase["DEV_ONBOARDING_PHASE_WALLET_READY"] = 11] = "DEV_ONBOARDING_PHASE_WALLET_READY";
1792
- DevOnboardingPhase[DevOnboardingPhase["DEV_ONBOARDING_PHASE_SEEDCARD_BACKUP_PROMPT"] = 12] = "DEV_ONBOARDING_PHASE_SEEDCARD_BACKUP_PROMPT";
1793
- DevOnboardingPhase[DevOnboardingPhase["DEV_ONBOARDING_PHASE_SEEDCARD_BACKUP"] = 13] = "DEV_ONBOARDING_PHASE_SEEDCARD_BACKUP";
1794
- })(exports.DevOnboardingPhase || (exports.DevOnboardingPhase = {}));
1795
- exports.DevOnboardingSetupKind = void 0;
1796
- (function (DevOnboardingSetupKind) {
1797
- DevOnboardingSetupKind[DevOnboardingSetupKind["DEV_ONBOARDING_SETUP_KIND_UNKNOWN"] = 0] = "DEV_ONBOARDING_SETUP_KIND_UNKNOWN";
1798
- DevOnboardingSetupKind[DevOnboardingSetupKind["DEV_ONBOARDING_SETUP_KIND_CHOICE"] = 1] = "DEV_ONBOARDING_SETUP_KIND_CHOICE";
1799
- DevOnboardingSetupKind[DevOnboardingSetupKind["DEV_ONBOARDING_SETUP_KIND_CREATE"] = 2] = "DEV_ONBOARDING_SETUP_KIND_CREATE";
1800
- DevOnboardingSetupKind[DevOnboardingSetupKind["DEV_ONBOARDING_SETUP_KIND_RESTORE"] = 3] = "DEV_ONBOARDING_SETUP_KIND_RESTORE";
1801
- })(exports.DevOnboardingSetupKind || (exports.DevOnboardingSetupKind = {}));
1802
- exports.DevOnboardingSetupMethod = void 0;
1803
- (function (DevOnboardingSetupMethod) {
1804
- DevOnboardingSetupMethod[DevOnboardingSetupMethod["DEV_ONBOARDING_SETUP_METHOD_UNKNOWN"] = 0] = "DEV_ONBOARDING_SETUP_METHOD_UNKNOWN";
1805
- DevOnboardingSetupMethod[DevOnboardingSetupMethod["DEV_ONBOARDING_SETUP_METHOD_RECOVERY_PHRASE"] = 1] = "DEV_ONBOARDING_SETUP_METHOD_RECOVERY_PHRASE";
1806
- DevOnboardingSetupMethod[DevOnboardingSetupMethod["DEV_ONBOARDING_SETUP_METHOD_SEEDCARD"] = 2] = "DEV_ONBOARDING_SETUP_METHOD_SEEDCARD";
1807
- })(exports.DevOnboardingSetupMethod || (exports.DevOnboardingSetupMethod = {}));
2212
+ exports.OnboardingStep = void 0;
2213
+ (function (OnboardingStep) {
2214
+ OnboardingStep[OnboardingStep["ONBOARDING_STEP_UNKNOWN"] = 0] = "ONBOARDING_STEP_UNKNOWN";
2215
+ OnboardingStep[OnboardingStep["ONBOARDING_STEP_CHECKING"] = 1] = "ONBOARDING_STEP_CHECKING";
2216
+ OnboardingStep[OnboardingStep["ONBOARDING_STEP_PERSONALIZATION"] = 2] = "ONBOARDING_STEP_PERSONALIZATION";
2217
+ OnboardingStep[OnboardingStep["ONBOARDING_STEP_PIN"] = 3] = "ONBOARDING_STEP_PIN";
2218
+ OnboardingStep[OnboardingStep["ONBOARDING_STEP_SETUP"] = 4] = "ONBOARDING_STEP_SETUP";
2219
+ OnboardingStep[OnboardingStep["ONBOARDING_STEP_DONE"] = 5] = "ONBOARDING_STEP_DONE";
2220
+ })(exports.OnboardingStep || (exports.OnboardingStep = {}));
2221
+ exports.OnboardingPhase = void 0;
2222
+ (function (OnboardingPhase) {
2223
+ OnboardingPhase[OnboardingPhase["ONBOARDING_PHASE_UNKNOWN"] = 0] = "ONBOARDING_PHASE_UNKNOWN";
2224
+ OnboardingPhase[OnboardingPhase["ONBOARDING_PHASE_SAFETY_CHECK"] = 1] = "ONBOARDING_PHASE_SAFETY_CHECK";
2225
+ OnboardingPhase[OnboardingPhase["ONBOARDING_PHASE_PIN_SETUP"] = 2] = "ONBOARDING_PHASE_PIN_SETUP";
2226
+ OnboardingPhase[OnboardingPhase["ONBOARDING_PHASE_FINGERPRINT_SETUP"] = 3] = "ONBOARDING_PHASE_FINGERPRINT_SETUP";
2227
+ OnboardingPhase[OnboardingPhase["ONBOARDING_PHASE_SETUP_CHOICE"] = 4] = "ONBOARDING_PHASE_SETUP_CHOICE";
2228
+ OnboardingPhase[OnboardingPhase["ONBOARDING_PHASE_WALLET_CREATE_START"] = 5] = "ONBOARDING_PHASE_WALLET_CREATE_START";
2229
+ OnboardingPhase[OnboardingPhase["ONBOARDING_PHASE_RECOVERY_PHRASE_VIEW"] = 6] = "ONBOARDING_PHASE_RECOVERY_PHRASE_VIEW";
2230
+ OnboardingPhase[OnboardingPhase["ONBOARDING_PHASE_RECOVERY_PHRASE_CONFIRM"] = 7] = "ONBOARDING_PHASE_RECOVERY_PHRASE_CONFIRM";
2231
+ OnboardingPhase[OnboardingPhase["ONBOARDING_PHASE_RESTORE_METHOD_CHOICE"] = 8] = "ONBOARDING_PHASE_RESTORE_METHOD_CHOICE";
2232
+ OnboardingPhase[OnboardingPhase["ONBOARDING_PHASE_RECOVERY_PHRASE_RESTORE"] = 9] = "ONBOARDING_PHASE_RECOVERY_PHRASE_RESTORE";
2233
+ OnboardingPhase[OnboardingPhase["ONBOARDING_PHASE_SEEDCARD_RESTORE"] = 10] = "ONBOARDING_PHASE_SEEDCARD_RESTORE";
2234
+ OnboardingPhase[OnboardingPhase["ONBOARDING_PHASE_WALLET_READY"] = 11] = "ONBOARDING_PHASE_WALLET_READY";
2235
+ OnboardingPhase[OnboardingPhase["ONBOARDING_PHASE_SEEDCARD_BACKUP_PROMPT"] = 12] = "ONBOARDING_PHASE_SEEDCARD_BACKUP_PROMPT";
2236
+ OnboardingPhase[OnboardingPhase["ONBOARDING_PHASE_SEEDCARD_BACKUP"] = 13] = "ONBOARDING_PHASE_SEEDCARD_BACKUP";
2237
+ })(exports.OnboardingPhase || (exports.OnboardingPhase = {}));
2238
+ exports.OnboardingSetupKind = void 0;
2239
+ (function (OnboardingSetupKind) {
2240
+ OnboardingSetupKind[OnboardingSetupKind["ONBOARDING_SETUP_KIND_UNKNOWN"] = 0] = "ONBOARDING_SETUP_KIND_UNKNOWN";
2241
+ OnboardingSetupKind[OnboardingSetupKind["ONBOARDING_SETUP_KIND_CHOICE"] = 1] = "ONBOARDING_SETUP_KIND_CHOICE";
2242
+ OnboardingSetupKind[OnboardingSetupKind["ONBOARDING_SETUP_KIND_CREATE"] = 2] = "ONBOARDING_SETUP_KIND_CREATE";
2243
+ OnboardingSetupKind[OnboardingSetupKind["ONBOARDING_SETUP_KIND_RESTORE"] = 3] = "ONBOARDING_SETUP_KIND_RESTORE";
2244
+ })(exports.OnboardingSetupKind || (exports.OnboardingSetupKind = {}));
2245
+ exports.OnboardingSetupMethod = void 0;
2246
+ (function (OnboardingSetupMethod) {
2247
+ OnboardingSetupMethod[OnboardingSetupMethod["ONBOARDING_SETUP_METHOD_UNKNOWN"] = 0] = "ONBOARDING_SETUP_METHOD_UNKNOWN";
2248
+ OnboardingSetupMethod[OnboardingSetupMethod["ONBOARDING_SETUP_METHOD_RECOVERY_PHRASE"] = 1] = "ONBOARDING_SETUP_METHOD_RECOVERY_PHRASE";
2249
+ OnboardingSetupMethod[OnboardingSetupMethod["ONBOARDING_SETUP_METHOD_SEEDCARD"] = 2] = "ONBOARDING_SETUP_METHOD_SEEDCARD";
2250
+ })(exports.OnboardingSetupMethod || (exports.OnboardingSetupMethod = {}));
2251
+ exports.ViewTipType = void 0;
2252
+ (function (ViewTipType) {
2253
+ ViewTipType[ViewTipType["Default"] = 0] = "Default";
2254
+ ViewTipType[ViewTipType["Highlight"] = 1] = "Highlight";
2255
+ ViewTipType[ViewTipType["Recommend"] = 2] = "Recommend";
2256
+ ViewTipType[ViewTipType["Warning"] = 3] = "Warning";
2257
+ ViewTipType[ViewTipType["Danger"] = 4] = "Danger";
2258
+ })(exports.ViewTipType || (exports.ViewTipType = {}));
2259
+ exports.ViewSignLayout = void 0;
2260
+ (function (ViewSignLayout) {
2261
+ ViewSignLayout[ViewSignLayout["LayoutDefault"] = 0] = "LayoutDefault";
2262
+ ViewSignLayout[ViewSignLayout["LayoutSafeTxCreate"] = 1] = "LayoutSafeTxCreate";
2263
+ ViewSignLayout[ViewSignLayout["LayoutFinalConfirm"] = 2] = "LayoutFinalConfirm";
2264
+ ViewSignLayout[ViewSignLayout["Layout7702"] = 3] = "Layout7702";
2265
+ ViewSignLayout[ViewSignLayout["LayoutFlat"] = 4] = "LayoutFlat";
2266
+ ViewSignLayout[ViewSignLayout["LayoutEthApprove"] = 5] = "LayoutEthApprove";
2267
+ })(exports.ViewSignLayout || (exports.ViewSignLayout = {}));
1808
2268
  exports.ProtocolV2FailureType = void 0;
1809
2269
  (function (ProtocolV2FailureType) {
1810
2270
  ProtocolV2FailureType[ProtocolV2FailureType["Failure_InvalidMessage"] = 1] = "Failure_InvalidMessage";
@@ -1901,28 +2361,114 @@ var messages = /*#__PURE__*/Object.freeze({
1901
2361
  get TronResourceCode () { return exports.TronResourceCode; },
1902
2362
  get TronMessageType () { return exports.TronMessageType; },
1903
2363
  get CommandFlags () { return exports.CommandFlags; },
1904
- get WallpaperTarget () { return exports.WallpaperTarget; },
1905
2364
  get MoneroNetworkType () { return exports.MoneroNetworkType; },
1906
- get ViewTipType () { return exports.ViewTipType; },
1907
- get ViewSignLayout () { return exports.ViewSignLayout; },
2365
+ get UiAnimationType () { return exports.UiAnimationType; },
2366
+ get UiAnimationCommand () { return exports.UiAnimationCommand; },
1908
2367
  get DeviceErrorCode () { return exports.DeviceErrorCode; },
1909
2368
  get DeviceRebootType () { return exports.DeviceRebootType; },
1910
2369
  get DeviceSettingsPage () { return exports.DeviceSettingsPage; },
2370
+ get DeviceFactoryAck () { return exports.DeviceFactoryAck; },
1911
2371
  get DeviceFirmwareTargetType () { return exports.DeviceFirmwareTargetType; },
1912
2372
  get DeviceFirmwareUpdateTaskStatus () { return exports.DeviceFirmwareUpdateTaskStatus; },
1913
- get DeviceFactoryAck () { return exports.DeviceFactoryAck; },
1914
2373
  get DeviceType () { return exports.DeviceType; },
1915
2374
  get DeviceSeType () { return exports.DeviceSeType; },
1916
2375
  get DeviceSEState () { return exports.DeviceSEState; },
2376
+ get DeviceSessionErrorCode () { return exports.DeviceSessionErrorCode; },
2377
+ get DeviceSessionSeedDomain () { return exports.DeviceSessionSeedDomain; },
2378
+ get DeviceSessionPinType () { return exports.DeviceSessionPinType; },
1917
2379
  get DeviceSessionAskPin_FailureSubCodes () { return exports.DeviceSessionAskPin_FailureSubCodes; },
1918
- get DevOnboardingStep () { return exports.DevOnboardingStep; },
1919
- get DevOnboardingPhase () { return exports.DevOnboardingPhase; },
1920
- get DevOnboardingSetupKind () { return exports.DevOnboardingSetupKind; },
1921
- get DevOnboardingSetupMethod () { return exports.DevOnboardingSetupMethod; },
2380
+ get OnboardingStep () { return exports.OnboardingStep; },
2381
+ get OnboardingPhase () { return exports.OnboardingPhase; },
2382
+ get OnboardingSetupKind () { return exports.OnboardingSetupKind; },
2383
+ get OnboardingSetupMethod () { return exports.OnboardingSetupMethod; },
2384
+ get ViewTipType () { return exports.ViewTipType; },
2385
+ get ViewSignLayout () { return exports.ViewSignLayout; },
1922
2386
  get ProtocolV2FailureType () { return exports.ProtocolV2FailureType; },
1923
2387
  get Enum_ProtocolV2Capability () { return exports.Enum_ProtocolV2Capability; }
1924
2388
  });
1925
2389
 
2390
+ const REDACTED = '[REDACTED]';
2391
+ const SENSITIVE_LOG_KEYS = new Set([
2392
+ 'accesstoken',
2393
+ 'address',
2394
+ 'apikey',
2395
+ 'connectid',
2396
+ 'devicestate',
2397
+ 'deviceid',
2398
+ 'entropy',
2399
+ 'expectedpassphrasestate',
2400
+ 'mnemonic',
2401
+ 'passphrase',
2402
+ 'passphrasestate',
2403
+ 'password',
2404
+ 'pin',
2405
+ 'privatekey',
2406
+ 'publickey',
2407
+ 'seed',
2408
+ 'serialnumber',
2409
+ 'session',
2410
+ 'sessionid',
2411
+ 'signature',
2412
+ 'token',
2413
+ 'uuid',
2414
+ 'walletsessionid',
2415
+ 'xprv',
2416
+ 'xpub',
2417
+ ]);
2418
+ const normalizeLogKey = (key) => key.replace(/[_-]/g, '').toLowerCase();
2419
+ const isSensitiveLogKey = (key) => {
2420
+ const normalizedKey = normalizeLogKey(key);
2421
+ return (SENSITIVE_LOG_KEYS.has(normalizedKey) ||
2422
+ normalizedKey.endsWith('address') ||
2423
+ normalizedKey.endsWith('privatekey') ||
2424
+ normalizedKey.endsWith('publickey') ||
2425
+ normalizedKey.endsWith('signature'));
2426
+ };
2427
+ const isSigningMessage = (messageName) => Boolean(messageName && /(?:sign|txack|transaction)/i.test(messageName));
2428
+ const redactLogValue = (value, seen) => {
2429
+ if (ArrayBuffer.isView(value)) {
2430
+ return `[BINARY:${value.byteLength}]`;
2431
+ }
2432
+ if (value instanceof ArrayBuffer) {
2433
+ return `[BINARY:${value.byteLength}]`;
2434
+ }
2435
+ if (Array.isArray(value)) {
2436
+ return value.map(item => redactLogValue(item, seen));
2437
+ }
2438
+ if (!value || typeof value !== 'object') {
2439
+ return value;
2440
+ }
2441
+ if (seen.has(value)) {
2442
+ return '[CIRCULAR]';
2443
+ }
2444
+ seen.add(value);
2445
+ const redacted = Object.fromEntries(Object.entries(value).map(([key, item]) => [
2446
+ key,
2447
+ isSensitiveLogKey(key) && item !== null && item !== undefined
2448
+ ? REDACTED
2449
+ : redactLogValue(item, seen),
2450
+ ]));
2451
+ seen.delete(value);
2452
+ return redacted;
2453
+ };
2454
+ function getSafeTransportLogPayload(value, messageName) {
2455
+ if (isSigningMessage(messageName)) {
2456
+ return REDACTED;
2457
+ }
2458
+ return redactLogValue(value, new WeakSet());
2459
+ }
2460
+ function createTransportCallLog(name, protocol, data) {
2461
+ return {
2462
+ name,
2463
+ protocol,
2464
+ request: getSafeTransportLogPayload(data, name),
2465
+ };
2466
+ }
2467
+ const HIGH_VOLUME_CALLS = new Set(['FileWrite', 'FilesystemFileWrite', 'EmmcFileWrite']);
2468
+ function shouldSuppressHighVolumeCallLog(name) {
2469
+ return HIGH_VOLUME_CALLS.has(name);
2470
+ }
2471
+
1926
2472
  protobuf__namespace.util.Long = Long__default["default"];
1927
2473
  protobuf__namespace.configure();
1928
2474
  var index = {
@@ -1959,29 +2505,41 @@ exports.PROTOCOL_V1_REPORT_ID = PROTOCOL_V1_REPORT_ID;
1959
2505
  exports.PROTOCOL_V1_USB_PACKET_SIZE = PROTOCOL_V1_USB_PACKET_SIZE;
1960
2506
  exports.PROTOCOL_V2_BLE_FILE_CHUNK_SIZE = PROTOCOL_V2_BLE_FILE_CHUNK_SIZE;
1961
2507
  exports.PROTOCOL_V2_BLE_FILE_READ_CHUNK_SIZE = PROTOCOL_V2_BLE_FILE_READ_CHUNK_SIZE;
2508
+ exports.PROTOCOL_V2_BLE_FIRMWARE_FILE_CHUNK_SIZE = PROTOCOL_V2_BLE_FIRMWARE_FILE_CHUNK_SIZE;
1962
2509
  exports.PROTOCOL_V2_BLE_FRAME_MAX_BYTES = PROTOCOL_V2_BLE_FRAME_MAX_BYTES;
1963
2510
  exports.PROTOCOL_V2_CHANNEL_BLE_UART = PROTOCOL_V2_CHANNEL_BLE_UART;
1964
2511
  exports.PROTOCOL_V2_CHANNEL_SOCKET = PROTOCOL_V2_CHANNEL_SOCKET;
1965
2512
  exports.PROTOCOL_V2_CHANNEL_USB = PROTOCOL_V2_CHANNEL_USB;
2513
+ exports.PROTOCOL_V2_DEFAULT_RESPONSE_TIMEOUT_MS = PROTOCOL_V2_DEFAULT_RESPONSE_TIMEOUT_MS;
1966
2514
  exports.PROTOCOL_V2_FILE_CHUNK_SIZE = PROTOCOL_V2_FILE_CHUNK_SIZE;
1967
2515
  exports.PROTOCOL_V2_FRAME_MAX_BYTES = PROTOCOL_V2_FRAME_MAX_BYTES;
1968
2516
  exports.PROTOCOL_V2_PACKET_SRC_COMMAND = PROTOCOL_V2_PACKET_SRC_COMMAND;
1969
2517
  exports.PROTOCOL_V2_SYS_MESSAGE_THRESHOLD = PROTOCOL_V2_SYS_MESSAGE_THRESHOLD;
1970
2518
  exports.PROTOCOL_V2_WEBUSB_FILE_CHUNK_SIZE = PROTOCOL_V2_WEBUSB_FILE_CHUNK_SIZE;
1971
- exports.PROTOCOL_V2_WRITE_WATCHDOG_TIMEOUT_MS = PROTOCOL_V2_WRITE_WATCHDOG_TIMEOUT_MS;
1972
2519
  exports.ProtocolV1 = ProtocolV1;
1973
2520
  exports.ProtocolV2 = ProtocolV2;
1974
2521
  exports.ProtocolV2FrameAssembler = ProtocolV2FrameAssembler;
2522
+ exports.ProtocolV2LinkError = ProtocolV2LinkError;
1975
2523
  exports.ProtocolV2LinkManager = ProtocolV2LinkManager;
1976
2524
  exports.ProtocolV2SequenceCursor = ProtocolV2SequenceCursor;
1977
2525
  exports.ProtocolV2Session = ProtocolV2Session;
1978
2526
  exports.ProtocolV2UsbTransportBase = ProtocolV2UsbTransportBase;
2527
+ exports.TRANSPORT_EVENT = TRANSPORT_EVENT;
1979
2528
  exports.bytesToHex = bytesToHex;
1980
2529
  exports.concatUint8Arrays = concatUint8Arrays;
2530
+ exports.createProtocolV2LinkDisabledError = createProtocolV2LinkDisabledError;
2531
+ exports.createTransportCallLog = createTransportCallLog;
1981
2532
  exports["default"] = index;
1982
2533
  exports.getErrorMessage = getErrorMessage;
2534
+ exports.getSafeTransportLogPayload = getSafeTransportLogPayload;
1983
2535
  exports.hexToBytes = hexToBytes;
2536
+ exports.isProtocolV2HighThroughputCall = isProtocolV2HighThroughputCall;
2537
+ exports.isProtocolV2LinkDisabledError = isProtocolV2LinkDisabledError;
2538
+ exports.isProtocolV2LinkDisabledFailure = isProtocolV2LinkDisabledFailure;
2539
+ exports.isProtocolV2LinkError = isProtocolV2LinkError;
1984
2540
  exports.probeProtocolV2 = probeProtocolV2;
1985
2541
  exports.protocolV1 = index$1;
1986
2542
  exports.protocolV2 = protocolV2Codec;
2543
+ exports.shouldSuppressHighVolumeCallLog = shouldSuppressHighVolumeCallLog;
1987
2544
  exports.withProtocolTimeout = withProtocolTimeout;
2545
+ exports.writeProtocolV2BleFrame = writeProtocolV2BleFrame;