@ledgerhq/device-management-kit 0.0.0-legacy-speculos-datasource-20250820121907 → 0.0.0-multisig-20250821134850

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 (61) hide show
  1. package/lib/cjs/package.json +1 -1
  2. package/lib/cjs/src/api/apdu/utils/ByteArrayBuilder.js +1 -1
  3. package/lib/cjs/src/api/apdu/utils/ByteArrayBuilder.js.map +2 -2
  4. package/lib/cjs/src/api/apdu/utils/ByteArrayBuilder.test.js +1 -1
  5. package/lib/cjs/src/api/apdu/utils/ByteArrayBuilder.test.js.map +2 -2
  6. package/lib/cjs/src/api/device-action/xstate-utils/XStateDeviceAction.js +1 -1
  7. package/lib/cjs/src/api/device-action/xstate-utils/XStateDeviceAction.js.map +2 -2
  8. package/lib/cjs/src/api/device-model/data/StaticDeviceModelDataSource.js +1 -1
  9. package/lib/cjs/src/api/device-model/data/StaticDeviceModelDataSource.js.map +2 -2
  10. package/lib/cjs/src/api/device-model/data/StaticDeviceModelDataSource.test.js +1 -1
  11. package/lib/cjs/src/api/device-model/data/StaticDeviceModelDataSource.test.js.map +2 -2
  12. package/lib/cjs/src/api/secure-channel/task/ConnectToSecureChannelTask.js +1 -1
  13. package/lib/cjs/src/api/secure-channel/task/ConnectToSecureChannelTask.js.map +2 -2
  14. package/lib/cjs/src/api/transport/model/DeviceConnectionStateMachine.js +1 -1
  15. package/lib/cjs/src/api/transport/model/DeviceConnectionStateMachine.js.map +2 -2
  16. package/lib/cjs/src/api/transport/model/Errors.js +1 -1
  17. package/lib/cjs/src/api/transport/model/Errors.js.map +3 -3
  18. package/lib/cjs/src/api/utils/HexaString.js +1 -1
  19. package/lib/cjs/src/api/utils/HexaString.js.map +3 -3
  20. package/lib/cjs/src/api/utils/HexaString.test.js +1 -1
  21. package/lib/cjs/src/api/utils/HexaString.test.js.map +2 -2
  22. package/lib/cjs/src/internal/device-session/service/DefaultApduReceiverService.js +1 -1
  23. package/lib/cjs/src/internal/device-session/service/DefaultApduReceiverService.js.map +2 -2
  24. package/lib/cjs/src/internal/device-session/service/DefaultApduSenderService.js +1 -1
  25. package/lib/cjs/src/internal/device-session/service/DefaultApduSenderService.js.map +2 -2
  26. package/lib/esm/package.json +1 -1
  27. package/lib/esm/src/api/apdu/utils/ByteArrayBuilder.js +1 -1
  28. package/lib/esm/src/api/apdu/utils/ByteArrayBuilder.js.map +3 -3
  29. package/lib/esm/src/api/apdu/utils/ByteArrayBuilder.test.js +1 -1
  30. package/lib/esm/src/api/apdu/utils/ByteArrayBuilder.test.js.map +2 -2
  31. package/lib/esm/src/api/device-action/xstate-utils/XStateDeviceAction.js +1 -1
  32. package/lib/esm/src/api/device-action/xstate-utils/XStateDeviceAction.js.map +2 -2
  33. package/lib/esm/src/api/device-model/data/StaticDeviceModelDataSource.js +1 -1
  34. package/lib/esm/src/api/device-model/data/StaticDeviceModelDataSource.js.map +2 -2
  35. package/lib/esm/src/api/device-model/data/StaticDeviceModelDataSource.test.js +1 -1
  36. package/lib/esm/src/api/device-model/data/StaticDeviceModelDataSource.test.js.map +2 -2
  37. package/lib/esm/src/api/secure-channel/task/ConnectToSecureChannelTask.js +1 -1
  38. package/lib/esm/src/api/secure-channel/task/ConnectToSecureChannelTask.js.map +2 -2
  39. package/lib/esm/src/api/transport/model/DeviceConnectionStateMachine.js +1 -1
  40. package/lib/esm/src/api/transport/model/DeviceConnectionStateMachine.js.map +2 -2
  41. package/lib/esm/src/api/transport/model/Errors.js +1 -1
  42. package/lib/esm/src/api/transport/model/Errors.js.map +3 -3
  43. package/lib/esm/src/api/utils/HexaString.js +1 -1
  44. package/lib/esm/src/api/utils/HexaString.js.map +3 -3
  45. package/lib/esm/src/api/utils/HexaString.test.js +1 -1
  46. package/lib/esm/src/api/utils/HexaString.test.js.map +2 -2
  47. package/lib/esm/src/internal/device-session/service/DefaultApduReceiverService.js +1 -1
  48. package/lib/esm/src/internal/device-session/service/DefaultApduReceiverService.js.map +2 -2
  49. package/lib/esm/src/internal/device-session/service/DefaultApduSenderService.js +1 -1
  50. package/lib/esm/src/internal/device-session/service/DefaultApduSenderService.js.map +2 -2
  51. package/lib/types/src/api/apdu/utils/ByteArrayBuilder.d.ts +38 -0
  52. package/lib/types/src/api/apdu/utils/ByteArrayBuilder.d.ts.map +1 -1
  53. package/lib/types/src/api/device-action/xstate-utils/XStateDeviceAction.d.ts +1 -0
  54. package/lib/types/src/api/device-action/xstate-utils/XStateDeviceAction.d.ts.map +1 -1
  55. package/lib/types/src/api/transport/model/Errors.d.ts +5 -0
  56. package/lib/types/src/api/transport/model/Errors.d.ts.map +1 -1
  57. package/lib/types/src/api/utils/HexaString.d.ts +4 -3
  58. package/lib/types/src/api/utils/HexaString.d.ts.map +1 -1
  59. package/lib/types/src/internal/device-session/service/DefaultApduReceiverService.d.ts.map +1 -1
  60. package/lib/types/tsconfig.prod.tsbuildinfo +1 -1
  61. package/package.json +6 -6
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../../src/api/device-model/data/StaticDeviceModelDataSource.test.ts"],
4
- "sourcesContent": ["import { DeviceModelId } from \"@api/device/DeviceModel\";\nimport { BleDeviceInfos } from \"@api/device-model/model/BleDeviceInfos\";\n\nimport { StaticDeviceModelDataSource } from \"./StaticDeviceModelDataSource\";\n\ndescribe(\"StaticDeviceModelDataSource\", () => {\n describe(\"getAllDeviceModels\", () => {\n it(\"should return all device models\", () => {\n const dataSource = new StaticDeviceModelDataSource();\n const deviceModels = dataSource.getAllDeviceModels();\n\n expect(deviceModels.length).toEqual(6);\n expect(deviceModels).toContainEqual(\n expect.objectContaining({ id: DeviceModelId.APEX }),\n );\n expect(deviceModels).toContainEqual(\n expect.objectContaining({ id: DeviceModelId.NANO_S }),\n );\n expect(deviceModels).toContainEqual(\n expect.objectContaining({ id: DeviceModelId.NANO_SP }),\n );\n expect(deviceModels).toContainEqual(\n expect.objectContaining({ id: DeviceModelId.NANO_X }),\n );\n expect(deviceModels).toContainEqual(\n expect.objectContaining({ id: DeviceModelId.STAX }),\n );\n expect(deviceModels).toContainEqual(\n expect.objectContaining({ id: DeviceModelId.FLEX }),\n );\n });\n });\n\n describe(\"getDeviceModel\", () => {\n it(\"should return the associated device model\", () => {\n const dataSource = new StaticDeviceModelDataSource();\n\n const deviceModel1 = dataSource.getDeviceModel({\n id: DeviceModelId.NANO_S,\n });\n expect(deviceModel1).toEqual(\n expect.objectContaining({ id: DeviceModelId.NANO_S }),\n );\n\n const deviceModel2 = dataSource.getDeviceModel({\n id: DeviceModelId.NANO_SP,\n });\n expect(deviceModel2).toEqual(\n expect.objectContaining({ id: DeviceModelId.NANO_SP }),\n );\n\n const deviceModel3 = dataSource.getDeviceModel({\n id: DeviceModelId.NANO_X,\n });\n expect(deviceModel3).toEqual(\n expect.objectContaining({ id: DeviceModelId.NANO_X }),\n );\n\n const deviceModel4 = dataSource.getDeviceModel({\n id: DeviceModelId.STAX,\n });\n expect(deviceModel4).toEqual(\n expect.objectContaining({ id: DeviceModelId.STAX }),\n );\n\n const deviceModel5 = dataSource.getDeviceModel({\n id: DeviceModelId.FLEX,\n });\n expect(deviceModel5).toEqual(\n expect.objectContaining({ id: DeviceModelId.FLEX }),\n );\n });\n });\n\n describe(\"filterDeviceModels\", () => {\n it(\"should return the device models that match the given single parameter\", () => {\n const dataSource = new StaticDeviceModelDataSource();\n\n const deviceModels1 = dataSource.filterDeviceModels({ usbOnly: true });\n expect(deviceModels1.length).toEqual(2);\n expect(deviceModels1).toContainEqual(\n expect.objectContaining({ id: DeviceModelId.NANO_SP }),\n );\n expect(deviceModels1).toContainEqual(\n expect.objectContaining({ id: DeviceModelId.NANO_S }),\n );\n\n const deviceModels2 = dataSource.filterDeviceModels({\n usbProductId: 0x10,\n });\n expect(deviceModels2.length).toEqual(1);\n expect(deviceModels2[0]).toEqual(\n expect.objectContaining({ id: DeviceModelId.NANO_S }),\n );\n\n const deviceModels3 = dataSource.filterDeviceModels({\n usbProductId: 0x40,\n });\n expect(deviceModels3.length).toEqual(1);\n expect(deviceModels3[0]).toEqual(\n expect.objectContaining({ id: DeviceModelId.NANO_X }),\n );\n\n const deviceModels4 = dataSource.filterDeviceModels({\n usbProductId: 0x50,\n });\n expect(deviceModels4.length).toEqual(1);\n expect(deviceModels4[0]).toEqual(\n expect.objectContaining({ id: DeviceModelId.NANO_SP }),\n );\n\n const deviceModels5 = dataSource.filterDeviceModels({\n usbProductId: 0x60,\n });\n expect(deviceModels5.length).toEqual(1);\n expect(deviceModels5[0]).toEqual(\n expect.objectContaining({ id: DeviceModelId.STAX }),\n );\n\n const deviceModels6 = dataSource.filterDeviceModels({\n usbProductId: 0x00,\n });\n expect(deviceModels6.length).toEqual(0);\n });\n\n it(\"should return the device models that match the given multiple parameters\", () => {\n const dataSource = new StaticDeviceModelDataSource();\n\n const deviceModels1 = dataSource.filterDeviceModels({\n usbOnly: false,\n usbProductId: 0x40,\n });\n expect(deviceModels1.length).toEqual(1);\n expect(deviceModels1[0]).toEqual(\n expect.objectContaining({ id: DeviceModelId.NANO_X }),\n );\n\n const deviceModels2 = dataSource.filterDeviceModels({\n usbOnly: true,\n usbProductId: 0x50,\n });\n expect(deviceModels2.length).toEqual(1);\n expect(deviceModels2[0]).toEqual(\n expect.objectContaining({ id: DeviceModelId.NANO_SP }),\n );\n\n // Nano S is usbOnly\n const deviceModels3 = dataSource.filterDeviceModels({\n usbOnly: false,\n usbProductId: 0x10,\n });\n expect(deviceModels3.length).toEqual(0);\n });\n });\n describe(\"getBluetoothServicesInfos\", () => {\n it(\"should return the ble service infos record\", () => {\n // given\n const dataSource = new StaticDeviceModelDataSource();\n // when\n const bleServiceInfos = dataSource.getBluetoothServicesInfos();\n // then\n expect(bleServiceInfos).toStrictEqual({\n \"13d63400-2c97-0004-0000-4c6564676572\": new BleDeviceInfos(\n dataSource.getDeviceModel({ id: DeviceModelId.NANO_X }),\n \"13d63400-2c97-0004-0000-4c6564676572\",\n \"13d63400-2c97-0004-0002-4c6564676572\",\n \"13d63400-2c97-0004-0003-4c6564676572\",\n \"13d63400-2c97-0004-0001-4c6564676572\",\n ),\n \"13d63400-2c97-6004-0000-4c6564676572\": new BleDeviceInfos(\n dataSource.getDeviceModel({ id: DeviceModelId.STAX }),\n \"13d63400-2c97-6004-0000-4c6564676572\",\n \"13d63400-2c97-6004-0002-4c6564676572\",\n \"13d63400-2c97-6004-0003-4c6564676572\",\n \"13d63400-2c97-6004-0001-4c6564676572\",\n ),\n \"13d63400-2c97-3004-0000-4c6564676572\": new BleDeviceInfos(\n dataSource.getDeviceModel({ id: DeviceModelId.FLEX }),\n \"13d63400-2c97-3004-0000-4c6564676572\",\n \"13d63400-2c97-3004-0002-4c6564676572\",\n \"13d63400-2c97-3004-0003-4c6564676572\",\n \"13d63400-2c97-3004-0001-4c6564676572\",\n ),\n });\n });\n });\n describe(\"getBluetoothServices\", () => {\n it(\"should return the bluetooth services\", () => {\n // given\n const dataSource = new StaticDeviceModelDataSource();\n // when\n const bleServices = dataSource.getBluetoothServices();\n // then\n expect(bleServices).toStrictEqual([\n \"13d63400-2c97-6004-0000-4c6564676572\",\n \"13d63400-2c97-0004-0000-4c6564676572\",\n \"13d63400-2c97-6004-0000-4c6564676572\",\n \"13d63400-2c97-3004-0000-4c6564676572\",\n ]);\n });\n });\n});\n"],
5
- "mappings": "aAAA,IAAAA,EAA8B,mCAC9BC,EAA+B,kDAE/BC,EAA4C,yCAE5C,SAAS,8BAA+B,IAAM,CAC5C,SAAS,qBAAsB,IAAM,CACnC,GAAG,kCAAmC,IAAM,CAE1C,MAAMC,EADa,IAAI,8BAA4B,EACnB,mBAAmB,EAEnD,OAAOA,EAAa,MAAM,EAAE,QAAQ,CAAC,EACrC,OAAOA,CAAY,EAAE,eACnB,OAAO,iBAAiB,CAAE,GAAI,gBAAc,IAAK,CAAC,CACpD,EACA,OAAOA,CAAY,EAAE,eACnB,OAAO,iBAAiB,CAAE,GAAI,gBAAc,MAAO,CAAC,CACtD,EACA,OAA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CAAC,CACH,CAAC,CACH,CAAC",
4
+ "sourcesContent": ["import { DeviceModelId } from \"@api/device/DeviceModel\";\nimport { BleDeviceInfos } from \"@api/device-model/model/BleDeviceInfos\";\n\nimport { StaticDeviceModelDataSource } from \"./StaticDeviceModelDataSource\";\n\ndescribe(\"StaticDeviceModelDataSource\", () => {\n describe(\"getAllDeviceModels\", () => {\n it(\"should return all device models\", () => {\n const dataSource = new StaticDeviceModelDataSource();\n const deviceModels = dataSource.getAllDeviceModels();\n\n expect(deviceModels.length).toEqual(6);\n expect(deviceModels).toContainEqual(\n expect.objectContaining({ id: DeviceModelId.APEX }),\n );\n expect(deviceModels).toContainEqual(\n expect.objectContaining({ id: DeviceModelId.NANO_S }),\n );\n expect(deviceModels).toContainEqual(\n expect.objectContaining({ id: DeviceModelId.NANO_SP }),\n );\n expect(deviceModels).toContainEqual(\n expect.objectContaining({ id: DeviceModelId.NANO_X }),\n );\n expect(deviceModels).toContainEqual(\n expect.objectContaining({ id: DeviceModelId.STAX }),\n );\n expect(deviceModels).toContainEqual(\n expect.objectContaining({ id: DeviceModelId.FLEX }),\n );\n });\n });\n\n describe(\"getDeviceModel\", () => {\n it(\"should return the associated device model\", () => {\n const dataSource = new StaticDeviceModelDataSource();\n\n const deviceModel1 = dataSource.getDeviceModel({\n id: DeviceModelId.NANO_S,\n });\n expect(deviceModel1).toEqual(\n expect.objectContaining({ id: DeviceModelId.NANO_S }),\n );\n\n const deviceModel2 = dataSource.getDeviceModel({\n id: DeviceModelId.NANO_SP,\n });\n expect(deviceModel2).toEqual(\n expect.objectContaining({ id: DeviceModelId.NANO_SP }),\n );\n\n const deviceModel3 = dataSource.getDeviceModel({\n id: DeviceModelId.NANO_X,\n });\n expect(deviceModel3).toEqual(\n expect.objectContaining({ id: DeviceModelId.NANO_X }),\n );\n\n const deviceModel4 = dataSource.getDeviceModel({\n id: DeviceModelId.STAX,\n });\n expect(deviceModel4).toEqual(\n expect.objectContaining({ id: DeviceModelId.STAX }),\n );\n\n const deviceModel5 = dataSource.getDeviceModel({\n id: DeviceModelId.FLEX,\n });\n expect(deviceModel5).toEqual(\n expect.objectContaining({ id: DeviceModelId.FLEX }),\n );\n });\n });\n\n describe(\"filterDeviceModels\", () => {\n it(\"should return the device models that match the given single parameter\", () => {\n const dataSource = new StaticDeviceModelDataSource();\n\n const deviceModels1 = dataSource.filterDeviceModels({ usbOnly: true });\n expect(deviceModels1.length).toEqual(2);\n expect(deviceModels1).toContainEqual(\n expect.objectContaining({ id: DeviceModelId.NANO_SP }),\n );\n expect(deviceModels1).toContainEqual(\n expect.objectContaining({ id: DeviceModelId.NANO_S }),\n );\n\n const deviceModels2 = dataSource.filterDeviceModels({\n usbProductId: 0x10,\n });\n expect(deviceModels2.length).toEqual(1);\n expect(deviceModels2[0]).toEqual(\n expect.objectContaining({ id: DeviceModelId.NANO_S }),\n );\n\n const deviceModels3 = dataSource.filterDeviceModels({\n usbProductId: 0x40,\n });\n expect(deviceModels3.length).toEqual(1);\n expect(deviceModels3[0]).toEqual(\n expect.objectContaining({ id: DeviceModelId.NANO_X }),\n );\n\n const deviceModels4 = dataSource.filterDeviceModels({\n usbProductId: 0x50,\n });\n expect(deviceModels4.length).toEqual(1);\n expect(deviceModels4[0]).toEqual(\n expect.objectContaining({ id: DeviceModelId.NANO_SP }),\n );\n\n const deviceModels5 = dataSource.filterDeviceModels({\n usbProductId: 0x60,\n });\n expect(deviceModels5.length).toEqual(1);\n expect(deviceModels5[0]).toEqual(\n expect.objectContaining({ id: DeviceModelId.STAX }),\n );\n\n const deviceModels6 = dataSource.filterDeviceModels({\n usbProductId: 0x00,\n });\n expect(deviceModels6.length).toEqual(0);\n });\n\n it(\"should return the device models that match the given multiple parameters\", () => {\n const dataSource = new StaticDeviceModelDataSource();\n\n const deviceModels1 = dataSource.filterDeviceModels({\n usbOnly: false,\n usbProductId: 0x40,\n });\n expect(deviceModels1.length).toEqual(1);\n expect(deviceModels1[0]).toEqual(\n expect.objectContaining({ id: DeviceModelId.NANO_X }),\n );\n\n const deviceModels2 = dataSource.filterDeviceModels({\n usbOnly: true,\n usbProductId: 0x50,\n });\n expect(deviceModels2.length).toEqual(1);\n expect(deviceModels2[0]).toEqual(\n expect.objectContaining({ id: DeviceModelId.NANO_SP }),\n );\n\n // Nano S is usbOnly\n const deviceModels3 = dataSource.filterDeviceModels({\n usbOnly: false,\n usbProductId: 0x10,\n });\n expect(deviceModels3.length).toEqual(0);\n });\n });\n describe(\"getBluetoothServicesInfos\", () => {\n it(\"should return the ble service infos record\", () => {\n // given\n const dataSource = new StaticDeviceModelDataSource();\n // when\n const bleServiceInfos = dataSource.getBluetoothServicesInfos();\n // then\n expect(bleServiceInfos).toStrictEqual({\n \"13d63400-2c97-0004-0000-4c6564676572\": new BleDeviceInfos(\n dataSource.getDeviceModel({ id: DeviceModelId.NANO_X }),\n \"13d63400-2c97-0004-0000-4c6564676572\",\n \"13d63400-2c97-0004-0002-4c6564676572\",\n \"13d63400-2c97-0004-0003-4c6564676572\",\n \"13d63400-2c97-0004-0001-4c6564676572\",\n ),\n \"13d63400-2c97-6004-0000-4c6564676572\": new BleDeviceInfos(\n dataSource.getDeviceModel({ id: DeviceModelId.STAX }),\n \"13d63400-2c97-6004-0000-4c6564676572\",\n \"13d63400-2c97-6004-0002-4c6564676572\",\n \"13d63400-2c97-6004-0003-4c6564676572\",\n \"13d63400-2c97-6004-0001-4c6564676572\",\n ),\n \"13d63400-2c97-3004-0000-4c6564676572\": new BleDeviceInfos(\n dataSource.getDeviceModel({ id: DeviceModelId.FLEX }),\n \"13d63400-2c97-3004-0000-4c6564676572\",\n \"13d63400-2c97-3004-0002-4c6564676572\",\n \"13d63400-2c97-3004-0003-4c6564676572\",\n \"13d63400-2c97-3004-0001-4c6564676572\",\n ),\n \"13d63400-2c97-8004-0000-4c6564676572\": new BleDeviceInfos(\n dataSource.getDeviceModel({ id: DeviceModelId.APEX }),\n \"13d63400-2c97-8004-0000-4c6564676572\",\n \"13d63400-2c97-8004-0002-4c6564676572\",\n \"13d63400-2c97-8004-0003-4c6564676572\",\n \"13d63400-2c97-8004-0001-4c6564676572\",\n ),\n });\n });\n });\n describe(\"getBluetoothServices\", () => {\n it(\"should return the bluetooth services\", () => {\n // given\n const dataSource = new StaticDeviceModelDataSource();\n // when\n const bleServices = dataSource.getBluetoothServices();\n // then\n expect(bleServices).toStrictEqual([\n \"13d63400-2c97-0004-0000-4c6564676572\",\n \"13d63400-2c97-6004-0000-4c6564676572\",\n \"13d63400-2c97-3004-0000-4c6564676572\",\n \"13d63400-2c97-8004-0000-4c6564676572\",\n ]);\n });\n });\n});\n"],
5
+ "mappings": "aAAA,IAAAA,EAA8B,mCAC9BC,EAA+B,kDAE/BC,EAA4C,yCAE5C,SAAS,8BAA+B,IAAM,CAC5C,SAAS,qBAAsB,IAAM,CACnC,GAAG,kCAAmC,IAAM,CAE1C,MAAMC,EADa,IAAI,8BAA4B,EACnB,mBAAmB,EAEnD,OAAOA,EAAa,MAAM,EAAE,QAAQ,CAAC,EACrC,OAAOA,CAAY,EAAE,eACnB,OAAO,iBAAiB,CAAE,GAAI,gBAAc,IAAK,CAAC,CACpD,EACA,OAAOA,CAAY,EAAE,eACnB,OAAO,iBAAiB,CAAE,GAAI,gBAAc,MAAO,CAAC,CACtD,EACA,OAAOA,CAAY,EAAE,eACnB,OAAO,iBAAiB,CAAE,GAAI,gBAAc,OAAQ,CAAC,CACvD,EACA,OAAOA,CAAY,EAAE,eACnB,OAAO,iBAAiB,CAAE,GAAI,gBAAc,MAAO,CAAC,CACtD,EACA,OAAOA,CAAY,EAAE,eACnB,OAAO,iBAAiB,CAAE,GAAI,gBAAc,IAAK,CAAC,CACpD,EACA,OAAOA,CAAY,EAAE,eACnB,OAAO,iBAAiB,CAAE,GAAI,gBAAc,IAAK,CAAC,CACpD,CACF,CAAC,CACH,CAAC,EAED,SAAS,iBAAkB,IAAM,CAC/B,GAAG,4CAA6C,IAAM,CACpD,MAAMC,EAAa,IAAI,8BAEjBC,EAAeD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A,MAAMC,EAAgBR,EAAW,mBAAmB,CAClD,QAAS,GACT,aAAc,EAChB,CAAC,EACD,OAAOQ,EAAc,MAAM,EAAE,QAAQ,CAAC,CACxC,CAAC,CACH,CAAC,EACD,SAAS,4BAA6B,IAAM,CAC1C,GAAG,6CAA8C,IAAM,CAErD,MAAMR,EAAa,IAAI,8BAEjBY,EAAkBZ,EAAW,0BAA0B,EAE7D,OAAOY,CAAe,EAAE,cAAc,CACpC,uCAAwC,IAAI,iBAC1CZ,EAAW,eAAe,CAAE,GAAI,gBAAc,MAAO,CAAC,EACtD,uCACA,uCACA,uCACA,sCACF,EACA,uCAAwC,IAAI,iBAC1CA,EAAW,eAAe,CAAE,GAAI,gBAAc,IAAK,CAAC,EACpD,uCACA,uCACA,uCACA,sCACF,EACA,uCAAwC,IAAI,iBAC1CA,EAAW,eAAe,CAAE,GAAI,gBAAc,IAAK,CAAC,EACpD,uCACA,uCACA,uCACA,sCACF,EACA,uCAAwC,IAAI,iBAC1CA,EAAW,eAAe,CAAE,GAAI,gBAAc,IAAK,CAAC,EACpD,uCACA,uCACA,uCACA,sCACF,CACF,CAAC,CACH,CAAC,CACH,CAAC,EACD,SAAS,uBAAwB,IAAM,CACrC,GAAG,uCAAwC,IAAM,CAI/C,MAAMa,EAFa,IAAI,8BAA4B,EAEpB,qBAAqB,EAEpD,OAAOA,CAAW,EAAE,cAAc,CAChC,uCACA,uCACA,uCACA,sCACF,CAAC,CACH,CAAC,CACH,CAAC,CACH,CAAC",
6
6
  "names": ["import_DeviceModel", "import_BleDeviceInfos", "import_StaticDeviceModelDataSource", "deviceModels", "dataSource", "deviceModel1", "deviceModel2", "deviceModel3", "deviceModel4", "deviceModel5", "deviceModels1", "deviceModels2", "deviceModels3", "deviceModels4", "deviceModels5", "deviceModels6", "bleServiceInfos", "bleServices"]
7
7
  }
@@ -1,2 +1,2 @@
1
- "use strict";var R=Object.create;var E=Object.defineProperty;var T=Object.getOwnPropertyDescriptor;var O=Object.getOwnPropertyNames;var I=Object.getPrototypeOf,D=Object.prototype.hasOwnProperty;var U=(i,e)=>{for(var s in e)E(i,s,{get:e[s],enumerable:!0})},_=(i,e,s,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let c of O(e))!D.call(i,c)&&c!==s&&E(i,c,{get:()=>e[c],enumerable:!(r=T(e,c))||r.enumerable});return i};var N=(i,e,s)=>(s=i!=null?R(I(i)):{},_(e||!i||!i.__esModule?E(s,"default",{value:i,enumerable:!0}):s,i)),P=i=>_(E({},"__esModule",{value:!0}),i);var q={};U(q,{ConnectToSecureChannelTask:()=>W});module.exports=P(q);var A=N(require("isomorphic-ws")),x=require("rxjs"),g=require("../../command/utils/CommandUtils"),n=require("../../secure-channel/task/types"),M=require("../../secure-channel/utils"),m=require("../../utils/HexaString"),t=require("../../../internal/secure-channel/model/Errors");class W{constructor(e,s){this._api=e;this._args=s;if(this._args.connection.isRight())this._connection=this._args.connection.extract();else throw new t.SecureChannelError(`Invalid WebSocket connection: ${String(this._args.connection.extract())}`)}_connection;run(){const e=this._api.disableRefresher("connectToSecureChannel");return new x.Observable(r=>{let c=!1,p=!1,v=!1;const l=y=>{r.next({type:n.SecureChannelEventType.Error,error:y}),r.complete(),p=!0};return this._connection.onopen=()=>{r.next({type:n.SecureChannelEventType.Opened})},this._connection.onerror=y=>{p||(r.next({type:n.SecureChannelEventType.Error,error:new t.SecureChannelError({url:this._connection.url,errorMessage:y.message})}),r.complete())},this._connection.onclose=()=>{p||(v?r.next({type:n.SecureChannelEventType.Closed}):r.next({type:n.SecureChannelEventType.Error,error:new t.SecureChannelError({url:this._connection.url,errorMessage:"Connection closed unexpectedly"})}),r.complete())},this._connection.onmessage=async y=>{if(c)return;let a;try{const o=JSON.parse(String(y.data));if(this.isInMessageType(o))a=o;else throw new Error("Data does not match InMessageType")}catch{l(new t.SecureChannelError({url:this._connection.url,errorMessage:`Invalid message received: ${String(y.data)}`}));return}switch(a.query){case n.InMessageQueryEnum.EXCHANGE:{const{nonce:o,data:d}=a;if(typeof d!="string"){l(new t.SecureChannelError(`${n.InMessageQueryEnum.EXCHANGE} data type should be an APDU`));return}const u=(0,m.hexaStringToBuffer)(d);if(u===null||u.length<5){l(new t.SecureChannelError(`Received invalid APDU data: ${d}`));return}r.next({type:n.SecureChannelEventType.PreExchange,payload:{nonce:o,apdu:u}});let f=!1;(0,M.willRequestPermission)(u)&&!this.isSecureConnectionAllowed()&&(f=!0,r.next({type:n.SecureChannelEventType.PermissionRequested}));const S=await this._api.sendApdu(u);if(c)return;S.caseOf({Left:h=>{l(new t.SecureChannelError(h))},Right:h=>{let C;const w=this.mapDeviceError(h);w===null?(C=n.OutMessageResponseEnum.SUCCESS,r.next({type:n.SecureChannelEventType.Exchange,payload:{nonce:o,apdu:u,data:h.data,status:h.statusCode}}),f&&r.next({type:n.SecureChannelEventType.PermissionGranted})):(C=n.OutMessageResponseEnum.ERROR,l(w));const k={nonce:o,response:C,data:(0,m.bufferToHexaString)(h.data).slice(2)};this._connection.send(JSON.stringify(k))}});break}case n.InMessageQueryEnum.BULK:{if(p=!0,this._connection.close(),!Array.isArray(a.data)||a.data.length===0||!a.data.every(o=>typeof o=="string")){l(new t.SecureChannelError("Invalid bulk data received"));return}for(let o=0,d=a.data.length;o<d;o++){const u=(0,m.hexaStringToBuffer)(a.data[o]);if(u===null||u.length<5){l(new t.SecureChannelError(`Received invalid APDU bulk data: ${a.data[o]}`));return}const f=await this._api.sendApdu(u);if(c)return;if(f.isLeft()){l(new t.SecureChannelError(f.extract()));return}else if(f.isRight()){const S=this.mapDeviceError(f.extract());if(S===null)r.next({type:n.SecureChannelEventType.Progress,payload:{progress:+Number((o+1)/d).toFixed(2),index:o,total:d}});else{l(S);return}}}v=!0,r.complete();break}case n.InMessageQueryEnum.SUCCESS:{if(p)break;const o=a.result??a.data;o&&r.next({type:n.SecureChannelEventType.Result,payload:o??""}),v=!0,r.complete();break}case n.InMessageQueryEnum.WARNING:{if(p)break;r.next({type:n.SecureChannelEventType.Warning,payload:{message:String(a.data)}});break}case n.InMessageQueryEnum.ERROR:{if(p)break;l(new t.SecureChannelError({url:this._connection.url,errorMessage:String(a.data)}))}}},()=>{e(),c=!0,this._connection.readyState===A.default.OPEN&&this._connection.close()}})}isSecureConnectionAllowed(){const e=this._api.getDeviceSessionState();return"isSecureConnectionAllowed"in e&&e.isSecureConnectionAllowed}isInMessageType(e){if(typeof e!="object"||!e)return!1;const s=e;return typeof s.uuid=="string"&&typeof s.session=="string"&&typeof s.query=="string"&&Object.values(n.InMessageQueryEnum).includes(s.query)&&typeof s.nonce=="number"}mapDeviceError(e){return g.CommandUtils.isSuccessResponse(e)?null:g.CommandUtils.isLockedDeviceResponse(e)?new t.SecureChannelError({url:this._connection.url,errorMessage:"Device is locked"},t.SecureChannelErrorType.DeviceLocked):g.CommandUtils.isRefusedByUser(e)?new t.SecureChannelError({url:this._connection.url,errorMessage:"User refused on the device"},t.SecureChannelErrorType.RefusedByUser):g.CommandUtils.isAppAlreadyInstalled(e)?new t.SecureChannelError({url:this._connection.url,errorMessage:"App already installed"},t.SecureChannelErrorType.AppAlreadyInstalled):g.CommandUtils.isOutOfMemory(e)?new t.SecureChannelError({url:this._connection.url,errorMessage:"Out of memory"},t.SecureChannelErrorType.OutOfMemory):new t.SecureChannelError({url:this._connection.url,errorMessage:`Invalid status code: ${(0,m.bufferToHexaString)(e.statusCode)}`})}}0&&(module.exports={ConnectToSecureChannelTask});
1
+ "use strict";var R=Object.create;var E=Object.defineProperty;var T=Object.getOwnPropertyDescriptor;var O=Object.getOwnPropertyNames;var I=Object.getPrototypeOf,D=Object.prototype.hasOwnProperty;var U=(i,e)=>{for(var s in e)E(i,s,{get:e[s],enumerable:!0})},_=(i,e,s,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let c of O(e))!D.call(i,c)&&c!==s&&E(i,c,{get:()=>e[c],enumerable:!(r=T(e,c))||r.enumerable});return i};var N=(i,e,s)=>(s=i!=null?R(I(i)):{},_(e||!i||!i.__esModule?E(s,"default",{value:i,enumerable:!0}):s,i)),P=i=>_(E({},"__esModule",{value:!0}),i);var q={};U(q,{ConnectToSecureChannelTask:()=>W});module.exports=P(q);var A=N(require("isomorphic-ws")),x=require("rxjs"),g=require("../../command/utils/CommandUtils"),n=require("../../secure-channel/task/types"),M=require("../../secure-channel/utils"),m=require("../../utils/HexaString"),t=require("../../../internal/secure-channel/model/Errors");class W{constructor(e,s){this._api=e;this._args=s;if(this._args.connection.isRight())this._connection=this._args.connection.extract();else throw new t.SecureChannelError(`Invalid WebSocket connection: ${String(this._args.connection.extract())}`)}_connection;run(){const e=this._api.disableRefresher("connectToSecureChannel");return new x.Observable(r=>{let c=!1,p=!1,v=!1;const l=y=>{r.next({type:n.SecureChannelEventType.Error,error:y}),r.complete(),p=!0};return this._connection.onopen=()=>{r.next({type:n.SecureChannelEventType.Opened})},this._connection.onerror=y=>{p||(r.next({type:n.SecureChannelEventType.Error,error:new t.SecureChannelError({url:this._connection.url,errorMessage:y.message})}),r.complete())},this._connection.onclose=()=>{p||(v?r.next({type:n.SecureChannelEventType.Closed}):r.next({type:n.SecureChannelEventType.Error,error:new t.SecureChannelError({url:this._connection.url,errorMessage:"Connection closed unexpectedly"})}),r.complete())},this._connection.onmessage=async y=>{if(c)return;let a;try{const o=JSON.parse(String(y.data));if(this.isInMessageType(o))a=o;else throw new Error("Data does not match InMessageType")}catch{l(new t.SecureChannelError({url:this._connection.url,errorMessage:`Invalid message received: ${String(y.data)}`}));return}switch(a.query){case n.InMessageQueryEnum.EXCHANGE:{const{nonce:o,data:d}=a;if(typeof d!="string"){l(new t.SecureChannelError(`${n.InMessageQueryEnum.EXCHANGE} data type should be an APDU`));return}const u=(0,m.hexaStringToBuffer)(d);if(u===null||u.length<5){l(new t.SecureChannelError(`Received invalid APDU data: ${d}`));return}r.next({type:n.SecureChannelEventType.PreExchange,payload:{nonce:o,apdu:u}});let f=!1;(0,M.willRequestPermission)(u)&&!this.isSecureConnectionAllowed()&&(f=!0,r.next({type:n.SecureChannelEventType.PermissionRequested}));const S=await this._api.sendApdu(u);if(c)return;S.caseOf({Left:h=>{l(new t.SecureChannelError(h))},Right:h=>{let C;const w=this.mapDeviceError(h);w===null?(C=n.OutMessageResponseEnum.SUCCESS,r.next({type:n.SecureChannelEventType.Exchange,payload:{nonce:o,apdu:u,data:h.data,status:h.statusCode}}),f&&r.next({type:n.SecureChannelEventType.PermissionGranted})):(C=n.OutMessageResponseEnum.ERROR,l(w));const k={nonce:o,response:C,data:(0,m.bufferToHexaString)(h.data,!1)};this._connection.send(JSON.stringify(k))}});break}case n.InMessageQueryEnum.BULK:{if(p=!0,this._connection.close(),!Array.isArray(a.data)||a.data.length===0||!a.data.every(o=>typeof o=="string")){l(new t.SecureChannelError("Invalid bulk data received"));return}for(let o=0,d=a.data.length;o<d;o++){const u=(0,m.hexaStringToBuffer)(a.data[o]);if(u===null||u.length<5){l(new t.SecureChannelError(`Received invalid APDU bulk data: ${a.data[o]}`));return}const f=await this._api.sendApdu(u);if(c)return;if(f.isLeft()){l(new t.SecureChannelError(f.extract()));return}else if(f.isRight()){const S=this.mapDeviceError(f.extract());if(S===null)r.next({type:n.SecureChannelEventType.Progress,payload:{progress:+Number((o+1)/d).toFixed(2),index:o,total:d}});else{l(S);return}}}v=!0,r.complete();break}case n.InMessageQueryEnum.SUCCESS:{if(p)break;const o=a.result??a.data;o&&r.next({type:n.SecureChannelEventType.Result,payload:o??""}),v=!0,r.complete();break}case n.InMessageQueryEnum.WARNING:{if(p)break;r.next({type:n.SecureChannelEventType.Warning,payload:{message:String(a.data)}});break}case n.InMessageQueryEnum.ERROR:{if(p)break;l(new t.SecureChannelError({url:this._connection.url,errorMessage:String(a.data)}))}}},()=>{e(),c=!0,this._connection.readyState===A.default.OPEN&&this._connection.close()}})}isSecureConnectionAllowed(){const e=this._api.getDeviceSessionState();return"isSecureConnectionAllowed"in e&&e.isSecureConnectionAllowed}isInMessageType(e){if(typeof e!="object"||!e)return!1;const s=e;return typeof s.uuid=="string"&&typeof s.session=="string"&&typeof s.query=="string"&&Object.values(n.InMessageQueryEnum).includes(s.query)&&typeof s.nonce=="number"}mapDeviceError(e){return g.CommandUtils.isSuccessResponse(e)?null:g.CommandUtils.isLockedDeviceResponse(e)?new t.SecureChannelError({url:this._connection.url,errorMessage:"Device is locked"},t.SecureChannelErrorType.DeviceLocked):g.CommandUtils.isRefusedByUser(e)?new t.SecureChannelError({url:this._connection.url,errorMessage:"User refused on the device"},t.SecureChannelErrorType.RefusedByUser):g.CommandUtils.isAppAlreadyInstalled(e)?new t.SecureChannelError({url:this._connection.url,errorMessage:"App already installed"},t.SecureChannelErrorType.AppAlreadyInstalled):g.CommandUtils.isOutOfMemory(e)?new t.SecureChannelError({url:this._connection.url,errorMessage:"Out of memory"},t.SecureChannelErrorType.OutOfMemory):new t.SecureChannelError({url:this._connection.url,errorMessage:`Invalid status code: ${(0,m.bufferToHexaString)(e.statusCode)}`})}}0&&(module.exports={ConnectToSecureChannelTask});
2
2
  //# sourceMappingURL=ConnectToSecureChannelTask.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../../src/api/secure-channel/task/ConnectToSecureChannelTask.ts"],
4
- "sourcesContent": ["import WebSocket from \"isomorphic-ws\";\nimport { type Either } from \"purify-ts\";\nimport { Observable } from \"rxjs\";\n\nimport { CommandUtils } from \"@api/command/utils/CommandUtils\";\nimport { type InternalApi } from \"@api/device-action/DeviceAction\";\nimport { type ApduResponse } from \"@api/device-session/ApduResponse\";\nimport {\n InMessageQueryEnum,\n type InMessageType,\n OutMessageResponseEnum,\n type OutMessageType,\n type SecureChannelEvent,\n SecureChannelEventType,\n} from \"@api/secure-channel/task/types\";\nimport { willRequestPermission } from \"@api/secure-channel/utils\";\nimport { bufferToHexaString, hexaStringToBuffer } from \"@api/utils/HexaString\";\nimport {\n SecureChannelError,\n SecureChannelErrorType,\n type WebSocketConnectionError,\n} from \"@internal/secure-channel/model/Errors\";\n\nexport type ConnectToSecureChannelTaskArgs = {\n connection: Either<WebSocketConnectionError, WebSocket>;\n};\n\nexport class ConnectToSecureChannelTask {\n private readonly _connection: WebSocket;\n constructor(\n private readonly _api: InternalApi,\n private readonly _args: ConnectToSecureChannelTaskArgs,\n ) {\n if (this._args.connection.isRight()) {\n this._connection = this._args.connection.extract();\n } else {\n throw new SecureChannelError(\n `Invalid WebSocket connection: ${String(this._args.connection.extract())}`,\n );\n }\n }\n\n run(): Observable<SecureChannelEvent> {\n const reenableRefresher = this._api.disableRefresher(\n \"connectToSecureChannel\",\n );\n\n const obs = new Observable<SecureChannelEvent>((subscriber) => {\n let unsubscribed: boolean = false;\n let ignoreNetworkEvents = false;\n let communicationFinished = false;\n\n const notifyError = (error: SecureChannelError) => {\n subscriber.next({\n type: SecureChannelEventType.Error,\n error,\n });\n subscriber.complete();\n\n // Netowrks events can be ignored once the obervable has been completed\n ignoreNetworkEvents = true;\n };\n\n this._connection.onopen = () => {\n subscriber.next({\n type: SecureChannelEventType.Opened,\n });\n };\n\n this._connection.onerror = (error) => {\n if (ignoreNetworkEvents) {\n return;\n }\n\n subscriber.next({\n type: SecureChannelEventType.Error,\n error: new SecureChannelError({\n url: this._connection.url,\n errorMessage: error.message,\n }),\n });\n subscriber.complete();\n };\n\n this._connection.onclose = () => {\n if (ignoreNetworkEvents) {\n return;\n }\n\n if (communicationFinished) {\n subscriber.next({\n type: SecureChannelEventType.Closed,\n });\n } else {\n subscriber.next({\n type: SecureChannelEventType.Error,\n error: new SecureChannelError({\n url: this._connection.url,\n errorMessage: \"Connection closed unexpectedly\",\n }),\n });\n }\n subscriber.complete();\n };\n\n this._connection.onmessage = async (event) => {\n // When unsubscribed, ignore the message\n if (unsubscribed) {\n return;\n }\n\n // Parse input message\n let input: InMessageType;\n try {\n const jsonData = JSON.parse(String(event.data));\n if (this.isInMessageType(jsonData)) {\n input = jsonData;\n } else {\n throw new Error(\"Data does not match InMessageType\");\n }\n } catch (_) {\n notifyError(\n new SecureChannelError({\n url: this._connection.url,\n errorMessage: `Invalid message received: ${String(event.data)}`,\n }),\n );\n return;\n }\n\n // Execute message query\n switch (input.query) {\n case InMessageQueryEnum.EXCHANGE: {\n const { nonce, data } = input;\n\n // Exchange query should contain a single APDU\n if (typeof data !== \"string\") {\n notifyError(\n new SecureChannelError(\n `${InMessageQueryEnum.EXCHANGE} data type should be an APDU`,\n ),\n );\n return;\n }\n\n // APDU should be a valid hex string\n const apdu = hexaStringToBuffer(data);\n if (apdu === null || apdu.length < 5) {\n notifyError(\n new SecureChannelError(`Received invalid APDU data: ${data}`),\n );\n return;\n }\n subscriber.next({\n type: SecureChannelEventType.PreExchange,\n payload: { nonce, apdu },\n });\n\n // Notify permission requested\n let permissionRequested = false;\n if (\n willRequestPermission(apdu) &&\n !this.isSecureConnectionAllowed()\n ) {\n permissionRequested = true;\n subscriber.next({\n type: SecureChannelEventType.PermissionRequested,\n });\n }\n\n // Send APDU to the device\n const response = await this._api.sendApdu(apdu);\n if (unsubscribed) {\n return;\n }\n\n // Map device response\n response.caseOf({\n Left: (error) => {\n notifyError(new SecureChannelError(error));\n },\n Right: (apduResponse: ApduResponse) => {\n let outMessageResponse: OutMessageResponseEnum;\n const deviceError = this.mapDeviceError(apduResponse);\n if (deviceError === null) {\n outMessageResponse = OutMessageResponseEnum.SUCCESS;\n\n // Emit event for the exchange\n subscriber.next({\n type: SecureChannelEventType.Exchange,\n payload: {\n nonce,\n apdu,\n data: apduResponse.data,\n status: apduResponse.statusCode,\n },\n });\n\n // If manager consent was requested, notify the \"granted\" event\n if (permissionRequested) {\n subscriber.next({\n type: SecureChannelEventType.PermissionGranted,\n });\n }\n } else {\n outMessageResponse = OutMessageResponseEnum.ERROR;\n notifyError(deviceError);\n }\n\n // Send the message back to the server\n const message: OutMessageType = {\n nonce,\n response: outMessageResponse,\n data: bufferToHexaString(apduResponse.data).slice(2),\n };\n this._connection.send(JSON.stringify(message));\n },\n });\n break;\n }\n case InMessageQueryEnum.BULK: {\n // Network not needed anymore during bulk APDUs sending\n ignoreNetworkEvents = true;\n this._connection.close();\n\n // A valid array of APDUs is required in a bulk query\n if (\n !Array.isArray(input.data) ||\n input.data.length === 0 ||\n !input.data.every((data) => typeof data === \"string\")\n ) {\n notifyError(new SecureChannelError(\"Invalid bulk data received\"));\n return;\n }\n\n for (let i = 0, len = input.data.length; i < len; i++) {\n // APDU should be a valid hex string\n const apdu = hexaStringToBuffer(input.data[i]!);\n if (apdu === null || apdu.length < 5) {\n notifyError(\n new SecureChannelError(\n `Received invalid APDU bulk data: ${input.data[i]}`,\n ),\n );\n return;\n }\n\n // Send APDU to the device\n const response = await this._api.sendApdu(apdu);\n if (unsubscribed) {\n return;\n }\n\n // Map device response\n if (response.isLeft()) {\n notifyError(new SecureChannelError(response.extract()));\n return;\n } else if (response.isRight()) {\n const deviceError = this.mapDeviceError(response.extract());\n if (deviceError === null) {\n // Notify the progress\n subscriber.next({\n type: SecureChannelEventType.Progress,\n payload: {\n progress: +Number((i + 1) / len).toFixed(2),\n index: i,\n total: len,\n },\n });\n } else {\n notifyError(deviceError);\n return;\n }\n }\n }\n communicationFinished = true;\n subscriber.complete();\n break;\n }\n case InMessageQueryEnum.SUCCESS: {\n if (ignoreNetworkEvents) {\n break;\n }\n // Emit the result if there is any\n const payload = input.result ?? input.data;\n if (payload) {\n subscriber.next({\n type: SecureChannelEventType.Result,\n payload: payload ?? \"\",\n });\n }\n communicationFinished = true;\n subscriber.complete();\n break;\n }\n case InMessageQueryEnum.WARNING: {\n if (ignoreNetworkEvents) {\n break;\n }\n subscriber.next({\n type: SecureChannelEventType.Warning,\n payload: { message: String(input.data) },\n });\n break;\n }\n case InMessageQueryEnum.ERROR: {\n if (ignoreNetworkEvents) {\n break;\n }\n notifyError(\n new SecureChannelError({\n url: this._connection.url,\n errorMessage: String(input.data),\n }),\n );\n }\n }\n };\n\n return () => {\n reenableRefresher();\n unsubscribed = true;\n // Close the connection if it is open when unsubscribing\n if (this._connection.readyState === WebSocket.OPEN) {\n this._connection.close();\n }\n };\n });\n\n return obs;\n }\n\n /**\n * Determines if a secure connection is already allowed based on the current device session state.\n *\n * @returns {boolean} `true` if a secure connection is allowed, otherwise `false`.\n */\n isSecureConnectionAllowed(): boolean {\n const deviceSessionState = this._api.getDeviceSessionState();\n return (\n \"isSecureConnectionAllowed\" in deviceSessionState &&\n deviceSessionState.isSecureConnectionAllowed\n );\n }\n\n isInMessageType(data: unknown): data is InMessageType {\n if (typeof data !== \"object\" || !data) {\n return false;\n }\n\n const message = data as InMessageType;\n return (\n typeof message.uuid === \"string\" &&\n typeof message.session === \"string\" &&\n typeof message.query === \"string\" &&\n Object.values(InMessageQueryEnum).includes(message.query) &&\n typeof message.nonce === \"number\"\n );\n }\n\n mapDeviceError(apduResponse: ApduResponse): SecureChannelError | null {\n if (CommandUtils.isSuccessResponse(apduResponse)) {\n return null;\n }\n\n // Device is locked\n if (CommandUtils.isLockedDeviceResponse(apduResponse)) {\n return new SecureChannelError(\n {\n url: this._connection.url,\n errorMessage: `Device is locked`,\n },\n SecureChannelErrorType.DeviceLocked,\n );\n }\n\n // User refused the permission\n if (CommandUtils.isRefusedByUser(apduResponse)) {\n return new SecureChannelError(\n {\n url: this._connection.url,\n errorMessage: \"User refused on the device\",\n },\n SecureChannelErrorType.RefusedByUser,\n );\n }\n\n // App already installed\n if (CommandUtils.isAppAlreadyInstalled(apduResponse)) {\n return new SecureChannelError(\n {\n url: this._connection.url,\n errorMessage: \"App already installed\",\n },\n SecureChannelErrorType.AppAlreadyInstalled,\n );\n }\n\n // Out of memory\n if (CommandUtils.isOutOfMemory(apduResponse)) {\n return new SecureChannelError(\n {\n url: this._connection.url,\n errorMessage: \"Out of memory\",\n },\n SecureChannelErrorType.OutOfMemory,\n );\n }\n\n return new SecureChannelError({\n url: this._connection.url,\n errorMessage: `Invalid status code: ${bufferToHexaString(\n apduResponse.statusCode,\n )}`,\n });\n }\n}\n"],
5
- "mappings": "0jBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,gC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,uBAAuBA,CAAY,EAC3C,IAAI,qBACT,CACE,IAAK,KAAK,YAAY,IACtB,aAAc,kBAChB,EACA,yBAAuB,YACzB,EAIE,eAAa,gBAAgBA,CAAY,EACpC,IAAI,qBACT,CACE,IAAK,KAAK,YAAY,IACtB,aAAc,4BAChB,EACA,yBAAuB,aACzB,EAIE,eAAa,sBAAsBA,CAAY,EAC1C,IAAI,qBACT,CACE,IAAK,KAAK,YAAY,IACtB,aAAc,uBAChB,EACA,yBAAuB,mBACzB,EAIE,eAAa,cAAcA,CAAY,EAClC,IAAI,qBACT,CACE,IAAK,KAAK,YAAY,IACtB,aAAc,eAChB,EACA,yBAAuB,WACzB,EAGK,IAAI,qBAAmB,CAC5B,IAAK,KAAK,YAAY,IACtB,aAAc,2BAAwB,sBACpCA,EAAa,UACf,CAAC,EACH,CAAC,CACH,CACF",
4
+ "sourcesContent": ["import WebSocket from \"isomorphic-ws\";\nimport { type Either } from \"purify-ts\";\nimport { Observable } from \"rxjs\";\n\nimport { CommandUtils } from \"@api/command/utils/CommandUtils\";\nimport { type InternalApi } from \"@api/device-action/DeviceAction\";\nimport { type ApduResponse } from \"@api/device-session/ApduResponse\";\nimport {\n InMessageQueryEnum,\n type InMessageType,\n OutMessageResponseEnum,\n type OutMessageType,\n type SecureChannelEvent,\n SecureChannelEventType,\n} from \"@api/secure-channel/task/types\";\nimport { willRequestPermission } from \"@api/secure-channel/utils\";\nimport { bufferToHexaString, hexaStringToBuffer } from \"@api/utils/HexaString\";\nimport {\n SecureChannelError,\n SecureChannelErrorType,\n type WebSocketConnectionError,\n} from \"@internal/secure-channel/model/Errors\";\n\nexport type ConnectToSecureChannelTaskArgs = {\n connection: Either<WebSocketConnectionError, WebSocket>;\n};\n\nexport class ConnectToSecureChannelTask {\n private readonly _connection: WebSocket;\n constructor(\n private readonly _api: InternalApi,\n private readonly _args: ConnectToSecureChannelTaskArgs,\n ) {\n if (this._args.connection.isRight()) {\n this._connection = this._args.connection.extract();\n } else {\n throw new SecureChannelError(\n `Invalid WebSocket connection: ${String(this._args.connection.extract())}`,\n );\n }\n }\n\n run(): Observable<SecureChannelEvent> {\n const reenableRefresher = this._api.disableRefresher(\n \"connectToSecureChannel\",\n );\n\n const obs = new Observable<SecureChannelEvent>((subscriber) => {\n let unsubscribed: boolean = false;\n let ignoreNetworkEvents = false;\n let communicationFinished = false;\n\n const notifyError = (error: SecureChannelError) => {\n subscriber.next({\n type: SecureChannelEventType.Error,\n error,\n });\n subscriber.complete();\n\n // Netowrks events can be ignored once the obervable has been completed\n ignoreNetworkEvents = true;\n };\n\n this._connection.onopen = () => {\n subscriber.next({\n type: SecureChannelEventType.Opened,\n });\n };\n\n this._connection.onerror = (error) => {\n if (ignoreNetworkEvents) {\n return;\n }\n\n subscriber.next({\n type: SecureChannelEventType.Error,\n error: new SecureChannelError({\n url: this._connection.url,\n errorMessage: error.message,\n }),\n });\n subscriber.complete();\n };\n\n this._connection.onclose = () => {\n if (ignoreNetworkEvents) {\n return;\n }\n\n if (communicationFinished) {\n subscriber.next({\n type: SecureChannelEventType.Closed,\n });\n } else {\n subscriber.next({\n type: SecureChannelEventType.Error,\n error: new SecureChannelError({\n url: this._connection.url,\n errorMessage: \"Connection closed unexpectedly\",\n }),\n });\n }\n subscriber.complete();\n };\n\n this._connection.onmessage = async (event) => {\n // When unsubscribed, ignore the message\n if (unsubscribed) {\n return;\n }\n\n // Parse input message\n let input: InMessageType;\n try {\n const jsonData = JSON.parse(String(event.data));\n if (this.isInMessageType(jsonData)) {\n input = jsonData;\n } else {\n throw new Error(\"Data does not match InMessageType\");\n }\n } catch (_) {\n notifyError(\n new SecureChannelError({\n url: this._connection.url,\n errorMessage: `Invalid message received: ${String(event.data)}`,\n }),\n );\n return;\n }\n\n // Execute message query\n switch (input.query) {\n case InMessageQueryEnum.EXCHANGE: {\n const { nonce, data } = input;\n\n // Exchange query should contain a single APDU\n if (typeof data !== \"string\") {\n notifyError(\n new SecureChannelError(\n `${InMessageQueryEnum.EXCHANGE} data type should be an APDU`,\n ),\n );\n return;\n }\n\n // APDU should be a valid hex string\n const apdu = hexaStringToBuffer(data);\n if (apdu === null || apdu.length < 5) {\n notifyError(\n new SecureChannelError(`Received invalid APDU data: ${data}`),\n );\n return;\n }\n subscriber.next({\n type: SecureChannelEventType.PreExchange,\n payload: { nonce, apdu },\n });\n\n // Notify permission requested\n let permissionRequested = false;\n if (\n willRequestPermission(apdu) &&\n !this.isSecureConnectionAllowed()\n ) {\n permissionRequested = true;\n subscriber.next({\n type: SecureChannelEventType.PermissionRequested,\n });\n }\n\n // Send APDU to the device\n const response = await this._api.sendApdu(apdu);\n if (unsubscribed) {\n return;\n }\n\n // Map device response\n response.caseOf({\n Left: (error) => {\n notifyError(new SecureChannelError(error));\n },\n Right: (apduResponse: ApduResponse) => {\n let outMessageResponse: OutMessageResponseEnum;\n const deviceError = this.mapDeviceError(apduResponse);\n if (deviceError === null) {\n outMessageResponse = OutMessageResponseEnum.SUCCESS;\n\n // Emit event for the exchange\n subscriber.next({\n type: SecureChannelEventType.Exchange,\n payload: {\n nonce,\n apdu,\n data: apduResponse.data,\n status: apduResponse.statusCode,\n },\n });\n\n // If manager consent was requested, notify the \"granted\" event\n if (permissionRequested) {\n subscriber.next({\n type: SecureChannelEventType.PermissionGranted,\n });\n }\n } else {\n outMessageResponse = OutMessageResponseEnum.ERROR;\n notifyError(deviceError);\n }\n\n // Send the message back to the server\n const message: OutMessageType = {\n nonce,\n response: outMessageResponse,\n data: bufferToHexaString(apduResponse.data, false),\n };\n this._connection.send(JSON.stringify(message));\n },\n });\n break;\n }\n case InMessageQueryEnum.BULK: {\n // Network not needed anymore during bulk APDUs sending\n ignoreNetworkEvents = true;\n this._connection.close();\n\n // A valid array of APDUs is required in a bulk query\n if (\n !Array.isArray(input.data) ||\n input.data.length === 0 ||\n !input.data.every((data) => typeof data === \"string\")\n ) {\n notifyError(new SecureChannelError(\"Invalid bulk data received\"));\n return;\n }\n\n for (let i = 0, len = input.data.length; i < len; i++) {\n // APDU should be a valid hex string\n const apdu = hexaStringToBuffer(input.data[i]!);\n if (apdu === null || apdu.length < 5) {\n notifyError(\n new SecureChannelError(\n `Received invalid APDU bulk data: ${input.data[i]}`,\n ),\n );\n return;\n }\n\n // Send APDU to the device\n const response = await this._api.sendApdu(apdu);\n if (unsubscribed) {\n return;\n }\n\n // Map device response\n if (response.isLeft()) {\n notifyError(new SecureChannelError(response.extract()));\n return;\n } else if (response.isRight()) {\n const deviceError = this.mapDeviceError(response.extract());\n if (deviceError === null) {\n // Notify the progress\n subscriber.next({\n type: SecureChannelEventType.Progress,\n payload: {\n progress: +Number((i + 1) / len).toFixed(2),\n index: i,\n total: len,\n },\n });\n } else {\n notifyError(deviceError);\n return;\n }\n }\n }\n communicationFinished = true;\n subscriber.complete();\n break;\n }\n case InMessageQueryEnum.SUCCESS: {\n if (ignoreNetworkEvents) {\n break;\n }\n // Emit the result if there is any\n const payload = input.result ?? input.data;\n if (payload) {\n subscriber.next({\n type: SecureChannelEventType.Result,\n payload: payload ?? \"\",\n });\n }\n communicationFinished = true;\n subscriber.complete();\n break;\n }\n case InMessageQueryEnum.WARNING: {\n if (ignoreNetworkEvents) {\n break;\n }\n subscriber.next({\n type: SecureChannelEventType.Warning,\n payload: { message: String(input.data) },\n });\n break;\n }\n case InMessageQueryEnum.ERROR: {\n if (ignoreNetworkEvents) {\n break;\n }\n notifyError(\n new SecureChannelError({\n url: this._connection.url,\n errorMessage: String(input.data),\n }),\n );\n }\n }\n };\n\n return () => {\n reenableRefresher();\n unsubscribed = true;\n // Close the connection if it is open when unsubscribing\n if (this._connection.readyState === WebSocket.OPEN) {\n this._connection.close();\n }\n };\n });\n\n return obs;\n }\n\n /**\n * Determines if a secure connection is already allowed based on the current device session state.\n *\n * @returns {boolean} `true` if a secure connection is allowed, otherwise `false`.\n */\n isSecureConnectionAllowed(): boolean {\n const deviceSessionState = this._api.getDeviceSessionState();\n return (\n \"isSecureConnectionAllowed\" in deviceSessionState &&\n deviceSessionState.isSecureConnectionAllowed\n );\n }\n\n isInMessageType(data: unknown): data is InMessageType {\n if (typeof data !== \"object\" || !data) {\n return false;\n }\n\n const message = data as InMessageType;\n return (\n typeof message.uuid === \"string\" &&\n typeof message.session === \"string\" &&\n typeof message.query === \"string\" &&\n Object.values(InMessageQueryEnum).includes(message.query) &&\n typeof message.nonce === \"number\"\n );\n }\n\n mapDeviceError(apduResponse: ApduResponse): SecureChannelError | null {\n if (CommandUtils.isSuccessResponse(apduResponse)) {\n return null;\n }\n\n // Device is locked\n if (CommandUtils.isLockedDeviceResponse(apduResponse)) {\n return new SecureChannelError(\n {\n url: this._connection.url,\n errorMessage: `Device is locked`,\n },\n SecureChannelErrorType.DeviceLocked,\n );\n }\n\n // User refused the permission\n if (CommandUtils.isRefusedByUser(apduResponse)) {\n return new SecureChannelError(\n {\n url: this._connection.url,\n errorMessage: \"User refused on the device\",\n },\n SecureChannelErrorType.RefusedByUser,\n );\n }\n\n // App already installed\n if (CommandUtils.isAppAlreadyInstalled(apduResponse)) {\n return new SecureChannelError(\n {\n url: this._connection.url,\n errorMessage: \"App already installed\",\n },\n SecureChannelErrorType.AppAlreadyInstalled,\n );\n }\n\n // Out of memory\n if (CommandUtils.isOutOfMemory(apduResponse)) {\n return new SecureChannelError(\n {\n url: this._connection.url,\n errorMessage: \"Out of memory\",\n },\n SecureChannelErrorType.OutOfMemory,\n );\n }\n\n return new SecureChannelError({\n url: this._connection.url,\n errorMessage: `Invalid status code: ${bufferToHexaString(\n apduResponse.statusCode,\n )}`,\n });\n }\n}\n"],
5
+ "mappings": "0jBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,gCAAAE,IAAA,eAAAC,EAAAH,GAAA,IAAAI,EAAsB,4BAEtBC,EAA2B,gBAE3BC,EAA6B,2CAG7BC,EAOO,0CACPC,EAAsC,qCACtCC,EAAuD,iCACvDC,EAIO,iDAMA,MAAMR,CAA2B,CAEtC,YACmBS,EACAC,EACjB,CAFiB,UAAAD,EACA,WAA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A,CAAY,EAC1C,IAAI,qBACT,CACE,IAAK,KAAK,YAAY,IACtB,aAAc,uBAChB,EACA,yBAAuB,mBACzB,EAIE,eAAa,cAAcA,CAAY,EAClC,IAAI,qBACT,CACE,IAAK,KAAK,YAAY,IACtB,aAAc,eAChB,EACA,yBAAuB,WACzB,EAGK,IAAI,qBAAmB,CAC5B,IAAK,KAAK,YAAY,IACtB,aAAc,2BAAwB,sBACpCA,EAAa,UACf,CAAC,EACH,CAAC,CACH,CACF",
6
6
  "names": ["ConnectToSecureChannelTask_exports", "__export", "ConnectToSecureChannelTask", "__toCommonJS", "import_isomorphic_ws", "import_rxjs", "import_CommandUtils", "import_types", "import_utils", "import_HexaString", "import_Errors", "_api", "_args", "reenableRefresher", "subscriber", "unsubscribed", "ignoreNetworkEvents", "communicationFinished", "notifyError", "error", "event", "input", "jsonData", "nonce", "data", "apdu", "permissionRequested", "response", "apduResponse", "outMessageResponse", "deviceError", "message", "i", "len", "payload", "WebSocket", "deviceSessionState"]
7
7
  }
@@ -1,2 +1,2 @@
1
- "use strict";var m=Object.defineProperty;var C=Object.getOwnPropertyDescriptor;var R=Object.getOwnPropertyNames;var y=Object.prototype.hasOwnProperty;var v=(s,n)=>{for(var i in n)m(s,i,{get:n[i],enumerable:!0})},h=(s,n,i,c)=>{if(n&&typeof n=="object"||typeof n=="function")for(let o of R(n))!y.call(s,o)&&o!==i&&m(s,o,{get:()=>n[o],enumerable:!(c=C(n,o))||c.enumerable});return s};var T=s=>h(m({},"__esModule",{value:!0}),s);var E={};v(E,{DeviceConnectionStateMachine:()=>S});module.exports=T(E);var t=require("purify-ts"),r=require("xstate"),D=require("../../command/os/GetAppAndVersionCommand"),A=require("../../command/utils/CommandUtils"),g=require("../../Error"),d=require("./Errors");class S{deviceId;deviceAdpuSender;machineActor;timeoutDuration;timeout=null;startReconnectionTimeout(){this.timeout=setTimeout(()=>{this.machineActor.send({type:"ReconnectionTimedOut"})},this.timeoutDuration)}constructor(n){this.deviceId=n.deviceId,this.deviceAdpuSender=n.deviceApduSender,this.timeoutDuration=n.timeoutDuration,this.machineActor=(0,r.createActor)(b({sendApduFn:(i,c,o)=>this.sendApduToDeviceConnection(i,c,o),startReconnectionTimeout:()=>this.startReconnectionTimeout(),cancelReconnectionTimeout:()=>{this.timeout&&(clearTimeout(this.timeout),this.timeout=null)},tryToReconnect:()=>{n.tryToReconnect(this.timeoutDuration)},onTerminated:n.onTerminated,closeConnection:()=>{this.deviceAdpuSender.closeConnection()}})),this.machineActor.start()}sendApduToDeviceConnection(n,i,c){this.deviceAdpuSender.sendApdu(n,i,c).then(o=>{o.caseOf({Left:a=>{this.machineActor.send({type:"ApduSendingError",error:a})},Right:a=>{this.machineActor.send({type:"ApduResponseReceived",apduResponse:a})}})}).catch(o=>{this.machineActor.send({type:"ApduSendingError",error:new g.UnknownDeviceExchangeError(o)})})}getDependencies(){return this.deviceAdpuSender.getDependencies()}setDependencies(n){this.deviceAdpuSender.setDependencies(n)}getDeviceId(){return this.deviceId}sendApdu(n,i,c){return new Promise(o=>{this.machineActor.send({type:"SendApduCalled",apdu:n,triggersDisconnection:!!i,abortTimeout:c,responseCallback:o})})}async setupConnection(){await this.deviceAdpuSender.setupConnection()}eventDeviceConnected(){this.machineActor.send({type:"DeviceConnected"})}eventDeviceDisconnected(){this.machineActor.send({type:"DeviceDisconnected"})}closeConnection(){this.machineActor.send({type:"CloseConnectionCalled"})}}function b({sendApduFn:s,startReconnectionTimeout:n,cancelReconnectionTimeout:i,tryToReconnect:c,onTerminated:o,closeConnection:a}){return(0,r.setup)({types:{},actions:{startTimer:()=>{n()},cancelTimer:()=>{i()},reconnectionTimeoutEvent:(0,r.emit)({type:"ReconnectionTimedOut"}),sendApdu:({context:e})=>{e.apduInProgress.ifJust(({apdu:p,triggersDisconnection:u,abortTimeout:l})=>{s(p,u,l)})},sendApduResponse:({context:e},p)=>{e.apduInProgress.map(({responseCallback:u})=>u(p.response))},sendGetAppAndVersion:()=>{s(new D.GetAppAndVersionCommand().getApdu().getRawApdu(),!1)},tryToReconnect:()=>{c()},clearApduInProgress:(0,r.assign)({apduInProgress:t.Nothing}),clearApduResponse:(0,r.assign)({apduResponse:t.Nothing}),signalTermination:()=>{o()},closeConnection:()=>{a()}},guards:{isApduThatTriggersDisconnection:({context:e,event:p})=>p.type!=="ApduResponseReceived"?!1:e.apduInProgress.caseOf({Just:({triggersDisconnection:u,apdu:l})=>(u||A.CommandUtils.isApduThatTriggersDisconnection(l))&&A.CommandUtils.isSuccessResponse(p.apduResponse),Nothing:()=>!1}),isSendApduBusyError:({event:e})=>e.type!=="ApduResponseReceived"?!1:e.apduResponse.statusCode[0]===102&&e.apduResponse.statusCode[1]===1}}).createMachine({id:"deviceConnection",initial:"Connected",context:{apduInProgress:t.Nothing,apduResponse:t.Nothing},states:{Connected:{on:{DeviceDisconnected:{target:"WaitingForReconnection"},SendApduCalled:{target:"SendingApdu",actions:(0,r.assign)({apduInProgress:({event:e})=>t.Maybe.of({apdu:e.apdu,triggersDisconnection:e.triggersDisconnection,abortTimeout:e.abortTimeout,responseCallback:e.responseCallback})})},CloseConnectionCalled:{target:"Terminated"}}},SendingApdu:{entry:"sendApdu",on:{ApduResponseReceived:[{guard:"isApduThatTriggersDisconnection",target:"WaitingForDisconnection",actions:[(0,r.assign)({apduResponse:({event:e})=>t.Maybe.of(e.apduResponse)})]},{target:"Connected",actions:[{type:"sendApduResponse",params:({event:e})=>({response:(0,t.Right)(e.apduResponse)})},{type:"clearApduInProgress"}]}],ApduSendingError:{target:"Connected",actions:[{type:"sendApduResponse",params:({event:e})=>({response:(0,t.Left)(e.error)})},"clearApduInProgress"]},DeviceDisconnected:{target:"WaitingForReconnection",actions:[{type:"sendApduResponse",params:{response:(0,t.Left)(new d.DeviceDisconnectedWhileSendingError)}},"clearApduInProgress"]},CloseConnectionCalled:{target:"Terminated",actions:[{type:"sendApduResponse",params:{response:(0,t.Left)(new d.DeviceDisconnectedWhileSendingError)}},"clearApduInProgress"]},SendApduCalled:{actions:({event:e})=>{e.responseCallback((0,t.Left)(new d.AlreadySendingApduError))}}}},WaitingForDisconnection:{entry:["sendGetAppAndVersion"],exit:[{type:"sendApduResponse",params:({context:e})=>({response:e.apduResponse.caseOf({Just:p=>(0,t.Right)(p),Nothing:()=>(0,t.Left)(new g.UnknownDeviceExchangeError)})})},{type:"clearApduInProgress"},{type:"clearApduResponse"}],on:{ApduResponseReceived:[{guard:"isSendApduBusyError",actions:["sendGetAppAndVersion"],target:"WaitingForDisconnection"},{target:"Connected"}],ApduSendingError:[{target:"WaitingForReconnection"}],SendApduCalled:{actions:({event:e})=>{e.responseCallback((0,t.Left)(new d.AlreadySendingApduError))}},DeviceDisconnected:{target:"WaitingForReconnection"},CloseConnectionCalled:{target:"Terminated"}}},WaitingForReconnection:{entry:["startTimer","tryToReconnect"],on:{DeviceConnected:{target:"Connected",actions:"cancelTimer"},SendApduCalled:{target:"WaitingForReconnectionWithQueuedSendApdu",actions:(0,r.assign)({apduInProgress:({event:e})=>t.Maybe.of({apdu:e.apdu,triggersDisconnection:e.triggersDisconnection,abortTimeout:e.abortTimeout,responseCallback:e.responseCallback})})},ReconnectionTimedOut:{target:"Terminated"},CloseConnectionCalled:{target:"Terminated"}}},WaitingForReconnectionWithQueuedSendApdu:{on:{DeviceConnected:{target:"SendingApdu",actions:"cancelTimer"},ReconnectionTimedOut:{target:"Terminated",actions:[{type:"sendApduResponse",params:{response:(0,t.Left)(new d.DeviceDisconnectedBeforeSendingApdu)}},{type:"clearApduInProgress"}]},CloseConnectionCalled:{target:"Terminated",actions:[{type:"sendApduResponse",params:{response:(0,t.Left)(new d.DeviceDisconnectedWhileSendingError)}},"clearApduInProgress"]},SendApduCalled:{actions:({event:e})=>{e.responseCallback((0,t.Left)(new d.AlreadySendingApduError))}}}},Terminated:{entry:["signalTermination","closeConnection"],type:"final"}}})}0&&(module.exports={DeviceConnectionStateMachine});
1
+ "use strict";var l=Object.defineProperty;var C=Object.getOwnPropertyDescriptor;var R=Object.getOwnPropertyNames;var y=Object.prototype.hasOwnProperty;var v=(s,n)=>{for(var i in n)l(s,i,{get:n[i],enumerable:!0})},h=(s,n,i,c)=>{if(n&&typeof n=="object"||typeof n=="function")for(let o of R(n))!y.call(s,o)&&o!==i&&l(s,o,{get:()=>n[o],enumerable:!(c=C(n,o))||c.enumerable});return s};var T=s=>h(l({},"__esModule",{value:!0}),s);var E={};v(E,{DeviceConnectionStateMachine:()=>S});module.exports=T(E);var t=require("purify-ts"),r=require("xstate"),g=require("../../command/os/GetAppAndVersionCommand"),m=require("../../command/utils/CommandUtils"),A=require("../../Error"),d=require("./Errors");class S{deviceId;deviceAdpuSender;machineActor;timeoutDuration;timeout=null;startReconnectionTimeout(){this.timeout=setTimeout(()=>{this.machineActor.send({type:"ReconnectionTimedOut"})},this.timeoutDuration)}constructor(n){this.deviceId=n.deviceId,this.deviceAdpuSender=n.deviceApduSender,this.timeoutDuration=n.timeoutDuration,this.machineActor=(0,r.createActor)(b({sendApduFn:(i,c,o)=>this.sendApduToDeviceConnection(i,c,o),startReconnectionTimeout:()=>this.startReconnectionTimeout(),cancelReconnectionTimeout:()=>{this.timeout&&(clearTimeout(this.timeout),this.timeout=null)},tryToReconnect:()=>{n.tryToReconnect(this.timeoutDuration)},onTerminated:n.onTerminated,closeConnection:()=>{this.deviceAdpuSender.closeConnection()}})),this.machineActor.start()}sendApduToDeviceConnection(n,i,c){this.deviceAdpuSender.sendApdu(n,i,c).then(o=>{o.caseOf({Left:a=>{this.machineActor.send({type:"ApduSendingError",error:a})},Right:a=>{this.machineActor.send({type:"ApduResponseReceived",apduResponse:a})}})}).catch(o=>{this.machineActor.send({type:"ApduSendingError",error:new A.UnknownDeviceExchangeError(o)})})}getDependencies(){return this.deviceAdpuSender.getDependencies()}setDependencies(n){this.deviceAdpuSender.setDependencies(n)}getDeviceId(){return this.deviceId}sendApdu(n,i,c){return new Promise(o=>{this.machineActor.send({type:"SendApduCalled",apdu:n,triggersDisconnection:!!i,abortTimeout:c,responseCallback:o})})}async setupConnection(){await this.deviceAdpuSender.setupConnection()}eventDeviceConnected(){this.machineActor.send({type:"DeviceConnected"})}eventDeviceDisconnected(){this.machineActor.send({type:"DeviceDisconnected"})}closeConnection(){this.machineActor.send({type:"CloseConnectionCalled"})}}function b({sendApduFn:s,startReconnectionTimeout:n,cancelReconnectionTimeout:i,tryToReconnect:c,onTerminated:o,closeConnection:a}){return(0,r.setup)({types:{},actions:{startTimer:()=>{n()},cancelTimer:()=>{i()},reconnectionTimeoutEvent:(0,r.emit)({type:"ReconnectionTimedOut"}),sendApdu:({context:e})=>{e.apduInProgress.map(({apdu:p,abortTimeout:u})=>{s(p,!1,u)})},sendApduResponse:({context:e},p)=>{e.apduInProgress.map(({responseCallback:u})=>u(p.response))},sendGetAppAndVersion:()=>{s(new g.GetAppAndVersionCommand().getApdu().getRawApdu(),!1)},tryToReconnect:()=>{c()},clearApduInProgress:(0,r.assign)({apduInProgress:t.Nothing}),clearApduResponse:(0,r.assign)({apduResponse:t.Nothing}),signalTermination:()=>{o()},closeConnection:()=>{a()}},guards:{isApduThatTriggersDisconnection:({context:e,event:p})=>p.type!=="ApduResponseReceived"?!1:e.apduInProgress.caseOf({Just:({triggersDisconnection:u,apdu:D})=>(u||m.CommandUtils.isApduThatTriggersDisconnection(D))&&m.CommandUtils.isSuccessResponse(p.apduResponse),Nothing:()=>!1}),isSendApduBusyError:({event:e})=>e.type!=="ApduResponseReceived"?!1:e.apduResponse.statusCode[0]===102&&e.apduResponse.statusCode[1]===1}}).createMachine({id:"deviceConnection",initial:"Connected",context:{apduInProgress:t.Nothing,apduResponse:t.Nothing},states:{Connected:{on:{DeviceDisconnected:{target:"WaitingForReconnection"},SendApduCalled:{target:"SendingApdu",actions:(0,r.assign)({apduInProgress:({event:e})=>t.Maybe.of({apdu:e.apdu,triggersDisconnection:e.triggersDisconnection,abortTimeout:e.abortTimeout,responseCallback:e.responseCallback})})},CloseConnectionCalled:{target:"Terminated"}}},SendingApdu:{entry:"sendApdu",on:{ApduResponseReceived:[{guard:"isApduThatTriggersDisconnection",target:"WaitingForDisconnection",actions:[(0,r.assign)({apduResponse:({event:e})=>t.Maybe.of(e.apduResponse)})]},{target:"Connected",actions:[{type:"sendApduResponse",params:({event:e})=>({response:(0,t.Right)(e.apduResponse)})},{type:"clearApduInProgress"}]}],ApduSendingError:{target:"Connected",actions:[{type:"sendApduResponse",params:({event:e})=>({response:(0,t.Left)(e.error)})},"clearApduInProgress"]},DeviceDisconnected:{target:"WaitingForReconnection",actions:[{type:"sendApduResponse",params:{response:(0,t.Left)(new d.DeviceDisconnectedWhileSendingError)}},"clearApduInProgress"]},CloseConnectionCalled:{target:"Terminated",actions:[{type:"sendApduResponse",params:{response:(0,t.Left)(new d.DeviceDisconnectedWhileSendingError)}},"clearApduInProgress"]},SendApduCalled:{actions:({event:e})=>{e.responseCallback((0,t.Left)(new d.AlreadySendingApduError))}}}},WaitingForDisconnection:{entry:["sendGetAppAndVersion"],exit:[{type:"sendApduResponse",params:({context:e})=>({response:e.apduResponse.caseOf({Just:p=>(0,t.Right)(p),Nothing:()=>(0,t.Left)(new A.UnknownDeviceExchangeError)})})},{type:"clearApduInProgress"},{type:"clearApduResponse"}],on:{ApduResponseReceived:[{guard:"isSendApduBusyError",actions:["sendGetAppAndVersion"],target:"WaitingForDisconnection"},{target:"Connected"}],ApduSendingError:[{target:"WaitingForReconnection"}],SendApduCalled:{actions:({event:e})=>{e.responseCallback((0,t.Left)(new d.AlreadySendingApduError))}},DeviceDisconnected:{target:"WaitingForReconnection"},CloseConnectionCalled:{target:"Terminated"}}},WaitingForReconnection:{entry:["startTimer","tryToReconnect"],on:{DeviceConnected:{target:"Connected",actions:"cancelTimer"},SendApduCalled:{target:"WaitingForReconnectionWithQueuedSendApdu",actions:(0,r.assign)({apduInProgress:({event:e})=>t.Maybe.of({apdu:e.apdu,triggersDisconnection:e.triggersDisconnection,abortTimeout:e.abortTimeout,responseCallback:e.responseCallback})})},ReconnectionTimedOut:{target:"Terminated"},CloseConnectionCalled:{target:"Terminated"}}},WaitingForReconnectionWithQueuedSendApdu:{on:{DeviceConnected:{target:"SendingApdu",actions:"cancelTimer"},ReconnectionTimedOut:{target:"Terminated",actions:[{type:"sendApduResponse",params:{response:(0,t.Left)(new d.DeviceDisconnectedBeforeSendingApdu)}},{type:"clearApduInProgress"}]},CloseConnectionCalled:{target:"Terminated",actions:[{type:"sendApduResponse",params:{response:(0,t.Left)(new d.DeviceDisconnectedWhileSendingError)}},"clearApduInProgress"]},SendApduCalled:{actions:({event:e})=>{e.responseCallback((0,t.Left)(new d.AlreadySendingApduError))}}}},Terminated:{entry:["signalTermination","closeConnection"],type:"final"}}})}0&&(module.exports={DeviceConnectionStateMachine});
2
2
  //# sourceMappingURL=DeviceConnectionStateMachine.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../../src/api/transport/model/DeviceConnectionStateMachine.ts"],
4
- "sourcesContent": ["// import { createBrowserInspector } from \"@statelyai/inspect\";\nimport { type Either, Left, Maybe, Nothing, Right } from \"purify-ts\";\nimport { type Actor, assign, createActor, emit, setup } from \"xstate\";\n\nimport { GetAppAndVersionCommand } from \"@api/command/os/GetAppAndVersionCommand\";\nimport { CommandUtils } from \"@api/command/utils/CommandUtils\";\nimport { type ApduResponse } from \"@api/device-session/ApduResponse\";\nimport { type DmkError, UnknownDeviceExchangeError } from \"@api/Error\";\nimport { type DeviceId } from \"@api/types\";\n\nimport { type DeviceApduSender } from \"./DeviceApduSender\";\nimport {\n AlreadySendingApduError,\n DeviceDisconnectedBeforeSendingApdu,\n DeviceDisconnectedWhileSendingError,\n} from \"./Errors\";\n\n// const { inspect } = createBrowserInspector();\n\ntype DeviceDisconnectedEvent = {\n type: \"DeviceDisconnected\";\n};\n\ntype DeviceConnectedEvent = {\n type: \"DeviceConnected\";\n};\n\ntype ApduResponseReceived = {\n type: \"ApduResponseReceived\";\n apduResponse: ApduResponse;\n};\n\ntype ApduSendingError = {\n type: \"ApduSendingError\";\n error: DmkError;\n};\n\ntype SendApduCalled = {\n type: \"SendApduCalled\";\n apdu: Uint8Array;\n triggersDisconnection: boolean;\n abortTimeout?: number;\n responseCallback: (response: Either<DmkError, ApduResponse>) => void;\n};\n\ntype ReconnectionTimedOut = {\n type: \"ReconnectionTimedOut\";\n};\n\ntype CloseConnectionCalled = {\n type: \"CloseConnectionCalled\";\n};\n\nexport type Events =\n | DeviceDisconnectedEvent\n | DeviceConnectedEvent\n | ApduResponseReceived\n | ApduSendingError\n | SendApduCalled\n | CloseConnectionCalled\n | ReconnectionTimedOut;\n\nexport type DeviceConnectionStateMachineParams<Dependencies> = {\n deviceId: DeviceId;\n deviceApduSender: DeviceApduSender<Dependencies>;\n timeoutDuration: number;\n tryToReconnect: (timeoutDuration: number) => void;\n onTerminated: () => void;\n};\n\nexport class DeviceConnectionStateMachine<Dependencies> {\n private deviceId: DeviceId;\n private deviceAdpuSender: DeviceApduSender<Dependencies>;\n\n private machineActor: Actor<ReturnType<typeof makeStateMachine>>;\n\n private timeoutDuration: number;\n private timeout: ReturnType<typeof setTimeout> | null = null;\n\n startReconnectionTimeout() {\n this.timeout = setTimeout(() => {\n this.machineActor.send({ type: \"ReconnectionTimedOut\" });\n }, this.timeoutDuration);\n }\n\n constructor(params: DeviceConnectionStateMachineParams<Dependencies>) {\n this.deviceId = params.deviceId;\n this.deviceAdpuSender = params.deviceApduSender;\n this.timeoutDuration = params.timeoutDuration;\n this.machineActor = createActor(\n makeStateMachine({\n sendApduFn: (apdu, triggersDisconnection, abortTimeout) =>\n this.sendApduToDeviceConnection(\n apdu,\n triggersDisconnection,\n abortTimeout,\n ),\n startReconnectionTimeout: () => this.startReconnectionTimeout(),\n cancelReconnectionTimeout: () => {\n if (this.timeout) {\n clearTimeout(this.timeout);\n this.timeout = null;\n }\n },\n tryToReconnect: () => {\n params.tryToReconnect(this.timeoutDuration);\n },\n onTerminated: params.onTerminated,\n closeConnection: () => {\n this.deviceAdpuSender.closeConnection();\n },\n }),\n // {\n // // inspect,\n // },\n );\n this.machineActor.start();\n }\n\n private sendApduToDeviceConnection(\n apdu: Uint8Array,\n triggersDisconnection?: boolean,\n abortTimeout?: number,\n ) {\n this.deviceAdpuSender\n .sendApdu(apdu, triggersDisconnection, abortTimeout)\n .then((response) => {\n response.caseOf({\n Left: (error) => {\n this.machineActor.send({ type: \"ApduSendingError\", error });\n },\n Right: (apduResponse) => {\n this.machineActor.send({\n type: \"ApduResponseReceived\",\n apduResponse,\n });\n },\n });\n })\n .catch((error) => {\n this.machineActor.send({\n type: \"ApduSendingError\",\n error: new UnknownDeviceExchangeError(error),\n });\n });\n }\n\n /**\n * Called by the transport\n */\n\n public getDependencies(): Dependencies {\n return this.deviceAdpuSender.getDependencies();\n }\n\n public setDependencies(dependencies: Dependencies) {\n this.deviceAdpuSender.setDependencies(dependencies);\n }\n\n public getDeviceId() {\n return this.deviceId;\n }\n\n public sendApdu(\n apdu: Uint8Array,\n triggersDisconnection?: boolean,\n abortTimeout?: number,\n ): Promise<Either<DmkError, ApduResponse>> {\n return new Promise((responseCallback) => {\n this.machineActor.send({\n type: \"SendApduCalled\",\n apdu,\n triggersDisconnection: !!triggersDisconnection,\n abortTimeout,\n responseCallback,\n });\n });\n }\n\n public async setupConnection() {\n await this.deviceAdpuSender.setupConnection();\n }\n\n // State Machine Events\n\n public eventDeviceConnected() {\n this.machineActor.send({ type: \"DeviceConnected\" });\n }\n\n public eventDeviceDisconnected() {\n this.machineActor.send({ type: \"DeviceDisconnected\" });\n }\n\n public closeConnection() {\n this.machineActor.send({ type: \"CloseConnectionCalled\" });\n }\n}\n\nfunction makeStateMachine({\n sendApduFn,\n startReconnectionTimeout,\n cancelReconnectionTimeout,\n tryToReconnect,\n onTerminated,\n closeConnection,\n}: {\n sendApduFn: (\n apdu: Uint8Array,\n triggersDisconnection: boolean,\n abortTimeout?: number,\n ) => void;\n startReconnectionTimeout: () => void;\n cancelReconnectionTimeout: () => void;\n tryToReconnect: () => void;\n onTerminated: () => void;\n closeConnection: () => void;\n}) {\n return setup({\n types: {} as {\n context: {\n apduInProgress: Maybe<{\n apdu: Uint8Array;\n triggersDisconnection: boolean;\n abortTimeout?: number;\n responseCallback: (response: Either<DmkError, ApduResponse>) => void;\n }>;\n apduResponse: Maybe<ApduResponse>;\n };\n events: Events;\n },\n actions: {\n // event transitions\n startTimer: () => {\n startReconnectionTimeout();\n },\n cancelTimer: () => {\n cancelReconnectionTimeout();\n },\n reconnectionTimeoutEvent: emit({ type: \"ReconnectionTimedOut\" }),\n sendApdu: ({ context }) => {\n context.apduInProgress.ifJust(\n ({ apdu, triggersDisconnection, abortTimeout }) => {\n sendApduFn(apdu, triggersDisconnection, abortTimeout);\n },\n );\n },\n sendApduResponse: (\n { context },\n params: { response: Either<DmkError, ApduResponse> },\n ) => {\n context.apduInProgress.map(({ responseCallback }) =>\n responseCallback(params.response),\n );\n },\n sendGetAppAndVersion: () => {\n sendApduFn(new GetAppAndVersionCommand().getApdu().getRawApdu(), false);\n },\n tryToReconnect: () => {\n tryToReconnect();\n },\n clearApduInProgress: assign({\n apduInProgress: Nothing,\n }),\n clearApduResponse: assign({\n apduResponse: Nothing,\n }),\n signalTermination: () => {\n onTerminated();\n },\n closeConnection: () => {\n closeConnection(); // ASK: how do we handle errors ?\n },\n },\n guards: {\n isApduThatTriggersDisconnection: ({ context, event }) => {\n if (event.type !== \"ApduResponseReceived\") {\n return false;\n }\n return context.apduInProgress.caseOf({\n /**\n * If the apdu is known as one that triggers a disconnection,\n * and if it's a success response,\n * then will trigger a disconnection (on Ledger OS prior to the IO revamp).\n */\n Just: ({ triggersDisconnection, apdu }) =>\n (triggersDisconnection ||\n CommandUtils.isApduThatTriggersDisconnection(apdu)) &&\n CommandUtils.isSuccessResponse(event.apduResponse),\n Nothing: () => false,\n });\n },\n isSendApduBusyError: ({ event }) => {\n if (event.type !== \"ApduResponseReceived\") {\n return false;\n }\n return (\n event.apduResponse.statusCode[0] === 0x66 &&\n event.apdu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ofifVQOm8YyWjKtSKs8sVlICiECAImQeAARRyMAdogX8JRoqs6IYgDQ30zUjJ8CkWQmYZbOsFLGWzUyzE5bssx8ObAsoSqlpq8r1tILadr2g6ERWksQvCiAopi5i4qbRKjH7Bo4N1dsvFjOxEIeIwUPQ9o9AGSYvG+1bfsW7yVN8+agZB3bIHByUGtk1aWti874s1FGJOHYy6gTLo3lMVN7wPBNVAtbRRg0IEC35NmS0pxTltpwL6e2xn9s0w7mY5hGuaRzrAWZIYBJpc0pd1E18tNMZLOMAwnOCAsCDwFB4CORWms3bnm1AozWSgrHYMsYyEL6FGKXcDleMMO5rXJ5XZ0gP3jZqB4evaLwXEeqwnJNKYDypWlzHePwcIVotyuFT83QldOOpqWNU30A8rEmrMjPcAJk6FP7qch432rY3dxnN1onlaZ9idy5NILuCxl+UEwrH7wiqeqmnarpjatbB3Xcibser3eckfmd3xOkrnpce0DMjHMeoAgLjeqCCsBfVCmFOESE+EqdSfnmNwLJjBPBSs0QwuV3CQWPN3AwT4LTtldoEIAA */\n id: \"deviceConnection\",\n initial: \"Connected\",\n context: {\n apduInProgress: Nothing,\n apduResponse: Nothing,\n },\n states: {\n Connected: {\n on: {\n DeviceDisconnected: {\n target: \"WaitingForReconnection\",\n },\n SendApduCalled: {\n target: \"SendingApdu\",\n actions: assign({\n apduInProgress: ({ event }) => {\n return Maybe.of({\n apdu: event.apdu,\n triggersDisconnection: event.triggersDisconnection,\n abortTimeout: event.abortTimeout,\n responseCallback: event.responseCallback,\n });\n },\n }),\n },\n CloseConnectionCalled: {\n target: \"Terminated\",\n },\n },\n },\n SendingApdu: {\n entry: \"sendApdu\",\n on: {\n ApduResponseReceived: [\n {\n guard: \"isApduThatTriggersDisconnection\",\n target: \"WaitingForDisconnection\",\n actions: [\n assign({\n apduResponse: ({ event }) => Maybe.of(event.apduResponse),\n }),\n ],\n },\n {\n target: \"Connected\",\n actions: [\n {\n type: \"sendApduResponse\",\n // https://stately.ai/docs/actions#dynamic-action-parameters\n params: ({ event }) => {\n return {\n response: Right(event.apduResponse),\n };\n },\n },\n { type: \"clearApduInProgress\" },\n ],\n },\n ],\n ApduSendingError: {\n target: \"Connected\",\n actions: [\n {\n type: \"sendApduResponse\",\n // https://stately.ai/docs/actions#dynamic-action-parameters\n params: ({ event }) => {\n return {\n response: Left(event.error),\n };\n },\n },\n \"clearApduInProgress\",\n ],\n },\n DeviceDisconnected: {\n target: \"WaitingForReconnection\",\n actions: [\n {\n type: \"sendApduResponse\",\n params: {\n response: Left(new DeviceDisconnectedWhileSendingError()),\n },\n },\n \"clearApduInProgress\",\n ],\n },\n CloseConnectionCalled: {\n target: \"Terminated\",\n actions: [\n {\n type: \"sendApduResponse\",\n params: {\n response: Left(new DeviceDisconnectedWhileSendingError()),\n },\n },\n \"clearApduInProgress\",\n ],\n },\n SendApduCalled: {\n actions: ({ event }) => {\n event.responseCallback(Left(new AlreadySendingApduError()));\n },\n },\n },\n },\n WaitingForDisconnection: {\n entry: [\"sendGetAppAndVersion\"],\n exit: [\n {\n type: \"sendApduResponse\",\n params: ({ context }) => {\n return {\n response: context.apduResponse.caseOf({\n Just: (apduResponse) => Right(apduResponse),\n Nothing: () => Left(new UnknownDeviceExchangeError()),\n }),\n };\n },\n },\n { type: \"clearApduInProgress\" },\n { type: \"clearApduResponse\" },\n ],\n on: {\n ApduResponseReceived: [\n {\n guard: \"isSendApduBusyError\",\n actions: [\"sendGetAppAndVersion\"],\n target: \"WaitingForDisconnection\",\n },\n {\n target: \"Connected\",\n },\n ],\n ApduSendingError: [\n {\n target: \"WaitingForReconnection\",\n },\n ],\n SendApduCalled: {\n actions: ({ event }) => {\n event.responseCallback(Left(new AlreadySendingApduError()));\n },\n },\n DeviceDisconnected: {\n target: \"WaitingForReconnection\",\n },\n CloseConnectionCalled: {\n target: \"Terminated\",\n },\n },\n },\n WaitingForReconnection: {\n entry: [\"startTimer\", \"tryToReconnect\"],\n on: {\n DeviceConnected: {\n target: \"Connected\",\n actions: \"cancelTimer\",\n },\n SendApduCalled: {\n target: \"WaitingForReconnectionWithQueuedSendApdu\",\n actions: assign({\n apduInProgress: ({ event }) => {\n return Maybe.of({\n apdu: event.apdu,\n triggersDisconnection: event.triggersDisconnection,\n abortTimeout: event.abortTimeout,\n responseCallback: event.responseCallback,\n });\n },\n }),\n },\n ReconnectionTimedOut: {\n target: \"Terminated\",\n },\n CloseConnectionCalled: {\n target: \"Terminated\",\n },\n },\n },\n WaitingForReconnectionWithQueuedSendApdu: {\n on: {\n DeviceConnected: {\n target: \"SendingApdu\",\n actions: \"cancelTimer\",\n },\n ReconnectionTimedOut: {\n target: \"Terminated\",\n actions: [\n {\n type: \"sendApduResponse\",\n params: {\n response: Left(new DeviceDisconnectedBeforeSendingApdu()),\n },\n },\n {\n type: \"clearApduInProgress\",\n },\n ],\n },\n CloseConnectionCalled: {\n target: \"Terminated\",\n actions: [\n {\n type: \"sendApduResponse\",\n params: {\n response: Left(new DeviceDisconnectedWhileSendingError()),\n },\n },\n \"clearApduInProgress\",\n ],\n },\n SendApduCalled: {\n actions: ({ event }) => {\n event.responseCallback(Left(new AlreadySendingApduError()));\n },\n },\n },\n },\n // TODO: ADD INACTIVE STATE\n Terminated: {\n entry: [\"signalTermination\", \"closeConnection\"],\n type: \"final\",\n },\n },\n });\n}\n"],
5
- "mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,kCAAAE,IAAA,eAAAC,EAAAH,GACA,IAAAI,EAAyD,qBACzDC,EAA6D,kBAE7DC,EAAwC,mDACxCC,EAA6B,2CAE7BC,EAA0D,sBAI1DC,EAIO,oBAuDA,MAAMP,CAA2C,CAC9C,SACA,iBAEA,aAEA,gBACA,QAAgD,KAExD,0BAA2B,CACzB,KAAK,QAAU,WAAW,IAAM,CAC9B,KAAK,aAAa,KAAK,CAAE,KAAM,sBAAuB,CAAC,CACzD,EAAG,KAAK,eAAe,CACzB,CAEA,YAAYQ,EAA0D,CACpE,KAAK,SAAWA,EAAO,SACvB,KAAK,iBAAmBA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AAAA,CAAM,IAChB,QAAM,GAAG,CACd,KAAMA,EAAM,KACZ,sBAAuBA,EAAM,sBAC7B,aAAcA,EAAM,aACpB,iBAAkBA,EAAM,gBAC1B,CAAC,CAEL,CAAC,CACH,EACA,qBAAsB,CACpB,OAAQ,YACV,EACA,sBAAuB,CACrB,OAAQ,YACV,CACF,CACF,EACA,yCAA0C,CACxC,GAAI,CACF,gBAAiB,CACf,OAAQ,cACR,QAAS,aACX,EACA,qBAAsB,CACpB,OAAQ,aACR,QAAS,CACP,CACE,KAAM,mBACN,OAAQ,CACN,YAAU,QAAK,IAAI,qCAAqC,CAC1D,CACF,EACA,CACE,KAAM,qBACR,CACF,CACF,EACA,sBAAuB,CACrB,OAAQ,aACR,QAAS,CACP,CACE,KAAM,mBACN,OAAQ,CACN,YAAU,QAAK,IAAI,qCAAqC,CAC1D,CACF,EACA,qBACF,CACF,EACA,eAAgB,CACd,QAAS,CAAC,CAAE,MAAAA,CAAM,IAAM,CACtBA,EAAM,oBAAiB,QAAK,IAAI,yBAAyB,CAAC,CAC5D,CACF,CACF,CACF,EAEA,WAAY,CACV,MAAO,CAAC,oBAAqB,iBAAiB,EAC9C,KAAM,OACR,CACF,CACF,CAAC,CACH",
4
+ "sourcesContent": ["// import { createBrowserInspector } from \"@statelyai/inspect\";\nimport { type Either, Left, Maybe, Nothing, Right } from \"purify-ts\";\nimport { type Actor, assign, createActor, emit, setup } from \"xstate\";\n\nimport { GetAppAndVersionCommand } from \"@api/command/os/GetAppAndVersionCommand\";\nimport { CommandUtils } from \"@api/command/utils/CommandUtils\";\nimport { type ApduResponse } from \"@api/device-session/ApduResponse\";\nimport { type DmkError, UnknownDeviceExchangeError } from \"@api/Error\";\nimport { type DeviceId } from \"@api/types\";\n\nimport { type DeviceApduSender } from \"./DeviceApduSender\";\nimport {\n AlreadySendingApduError,\n DeviceDisconnectedBeforeSendingApdu,\n DeviceDisconnectedWhileSendingError,\n} from \"./Errors\";\n\n// const { inspect } = createBrowserInspector();\n\ntype DeviceDisconnectedEvent = {\n type: \"DeviceDisconnected\";\n};\n\ntype DeviceConnectedEvent = {\n type: \"DeviceConnected\";\n};\n\ntype ApduResponseReceived = {\n type: \"ApduResponseReceived\";\n apduResponse: ApduResponse;\n};\n\ntype ApduSendingError = {\n type: \"ApduSendingError\";\n error: DmkError;\n};\n\ntype SendApduCalled = {\n type: \"SendApduCalled\";\n apdu: Uint8Array;\n triggersDisconnection: boolean;\n abortTimeout?: number;\n responseCallback: (response: Either<DmkError, ApduResponse>) => void;\n};\n\ntype ReconnectionTimedOut = {\n type: \"ReconnectionTimedOut\";\n};\n\ntype CloseConnectionCalled = {\n type: \"CloseConnectionCalled\";\n};\n\nexport type Events =\n | DeviceDisconnectedEvent\n | DeviceConnectedEvent\n | ApduResponseReceived\n | ApduSendingError\n | SendApduCalled\n | CloseConnectionCalled\n | ReconnectionTimedOut;\n\nexport type DeviceConnectionStateMachineParams<Dependencies> = {\n deviceId: DeviceId;\n deviceApduSender: DeviceApduSender<Dependencies>;\n timeoutDuration: number;\n tryToReconnect: (timeoutDuration: number) => void;\n onTerminated: () => void;\n};\n\nexport class DeviceConnectionStateMachine<Dependencies> {\n private deviceId: DeviceId;\n private deviceAdpuSender: DeviceApduSender<Dependencies>;\n\n private machineActor: Actor<ReturnType<typeof makeStateMachine>>;\n\n private timeoutDuration: number;\n private timeout: ReturnType<typeof setTimeout> | null = null;\n\n startReconnectionTimeout() {\n this.timeout = setTimeout(() => {\n this.machineActor.send({ type: \"ReconnectionTimedOut\" });\n }, this.timeoutDuration);\n }\n\n constructor(params: DeviceConnectionStateMachineParams<Dependencies>) {\n this.deviceId = params.deviceId;\n this.deviceAdpuSender = params.deviceApduSender;\n this.timeoutDuration = params.timeoutDuration;\n this.machineActor = createActor(\n makeStateMachine({\n sendApduFn: (apdu, triggersDisconnection, abortTimeout) =>\n this.sendApduToDeviceConnection(\n apdu,\n triggersDisconnection,\n abortTimeout,\n ),\n startReconnectionTimeout: () => this.startReconnectionTimeout(),\n cancelReconnectionTimeout: () => {\n if (this.timeout) {\n clearTimeout(this.timeout);\n this.timeout = null;\n }\n },\n tryToReconnect: () => {\n params.tryToReconnect(this.timeoutDuration);\n },\n onTerminated: params.onTerminated,\n closeConnection: () => {\n this.deviceAdpuSender.closeConnection();\n },\n }),\n // {\n // // inspect,\n // },\n );\n this.machineActor.start();\n }\n\n private sendApduToDeviceConnection(\n apdu: Uint8Array,\n triggersDisconnection?: boolean,\n abortTimeout?: number,\n ) {\n this.deviceAdpuSender\n .sendApdu(apdu, triggersDisconnection, abortTimeout)\n .then((response) => {\n response.caseOf({\n Left: (error) => {\n this.machineActor.send({ type: \"ApduSendingError\", error });\n },\n Right: (apduResponse) => {\n this.machineActor.send({\n type: \"ApduResponseReceived\",\n apduResponse,\n });\n },\n });\n })\n .catch((error) => {\n this.machineActor.send({\n type: \"ApduSendingError\",\n error: new UnknownDeviceExchangeError(error),\n });\n });\n }\n\n /**\n * Called by the transport\n */\n\n public getDependencies(): Dependencies {\n return this.deviceAdpuSender.getDependencies();\n }\n\n public setDependencies(dependencies: Dependencies) {\n this.deviceAdpuSender.setDependencies(dependencies);\n }\n\n public getDeviceId() {\n return this.deviceId;\n }\n\n public sendApdu(\n apdu: Uint8Array,\n triggersDisconnection?: boolean,\n abortTimeout?: number,\n ): Promise<Either<DmkError, ApduResponse>> {\n return new Promise((responseCallback) => {\n this.machineActor.send({\n type: \"SendApduCalled\",\n apdu,\n triggersDisconnection: !!triggersDisconnection,\n abortTimeout,\n responseCallback,\n });\n });\n }\n\n public async setupConnection() {\n await this.deviceAdpuSender.setupConnection();\n }\n\n // State Machine Events\n\n public eventDeviceConnected() {\n this.machineActor.send({ type: \"DeviceConnected\" });\n }\n\n public eventDeviceDisconnected() {\n this.machineActor.send({ type: \"DeviceDisconnected\" });\n }\n\n public closeConnection() {\n this.machineActor.send({ type: \"CloseConnectionCalled\" });\n }\n}\n\nfunction makeStateMachine({\n sendApduFn,\n startReconnectionTimeout,\n cancelReconnectionTimeout,\n tryToReconnect,\n onTerminated,\n closeConnection,\n}: {\n sendApduFn: (\n apdu: Uint8Array,\n triggersDisconnection: boolean,\n abortTimeout?: number,\n ) => void;\n startReconnectionTimeout: () => void;\n cancelReconnectionTimeout: () => void;\n tryToReconnect: () => void;\n onTerminated: () => void;\n closeConnection: () => void;\n}) {\n return setup({\n types: {} as {\n context: {\n apduInProgress: Maybe<{\n apdu: Uint8Array;\n triggersDisconnection: boolean;\n abortTimeout?: number;\n responseCallback: (response: Either<DmkError, ApduResponse>) => void;\n }>;\n apduResponse: Maybe<ApduResponse>;\n };\n events: Events;\n },\n actions: {\n // event transitions\n startTimer: () => {\n startReconnectionTimeout();\n },\n cancelTimer: () => {\n cancelReconnectionTimeout();\n },\n reconnectionTimeoutEvent: emit({ type: \"ReconnectionTimedOut\" }),\n sendApdu: ({ context }) => {\n context.apduInProgress.map(({ apdu, abortTimeout }) => {\n sendApduFn(apdu, false, abortTimeout);\n });\n },\n sendApduResponse: (\n { context },\n params: { response: Either<DmkError, ApduResponse> },\n ) => {\n context.apduInProgress.map(({ responseCallback }) =>\n responseCallback(params.response),\n );\n },\n sendGetAppAndVersion: () => {\n sendApduFn(new GetAppAndVersionCommand().getApdu().getRawApdu(), false);\n },\n tryToReconnect: () => {\n tryToReconnect();\n },\n clearApduInProgress: assign({\n apduInProgress: Nothing,\n }),\n clearApduResponse: assign({\n apduResponse: Nothing,\n }),\n signalTermination: () => {\n onTerminated();\n },\n closeConnection: () => {\n closeConnection(); // ASK: how do we handle errors ?\n },\n },\n guards: {\n isApduThatTriggersDisconnection: ({ context, event }) => {\n if (event.type !== \"ApduResponseReceived\") {\n return false;\n }\n return context.apduInProgress.caseOf({\n /**\n * If the apdu is known as one that triggers a disconnection,\n * and if it's a success response,\n * then will trigger a disconnection (on Ledger OS prior to the IO revamp).\n */\n Just: ({ triggersDisconnection, apdu }) =>\n (triggersDisconnection ||\n CommandUtils.isApduThatTriggersDisconnection(apdu)) &&\n CommandUtils.isSuccessResponse(event.apduResponse),\n Nothing: () => false,\n });\n },\n isSendApduBusyError: ({ event }) => {\n if (event.type !== \"ApduResponseReceived\") {\n return false;\n }\n return (\n event.apduResponse.statusCode[0] === 0x66 &&\n event.apduResponse.statusCode[1] === 0x01\n );\n },\n },\n }).createMachine({\n /** @xstate-layout N4IgpgJg5mDOIC5QTANwJYGMwGED2AdgWJgC7qEB0+RJpkAxACJpZgukCGmAFpANoAGALqJQABzyx05QmJAAPRAA4A7AGZKywQEYAnAFYATMoAsBg6fUA2ADQgAnolUnKBjUdXXVpnUb0aAL6B9igY2DTEZBQE1IRR9BAMAMpgBBAAguIQAK44nAA2BQIi8pLSsgTySgjW6oKU6uo61kbWyh06Vsr2TgjqAZR6HUaWXcrqBmrBoawR8XQxcbRkjDgFUrgL0YT5RSWiSCDlMjHVKnrWjaO6ev6qlnp6vYim1qaN9YLqGuPKOjpVDMQGE2JFFlRUul0AQoFlcgx4TkAEpwSQEWBgVHYdCoA5lKSnORHGpNVSUPwGXQDQSmNTDF4IZTWPRDJotUw+HwAnTA0HzFaVShQiAwuHZHKIiWo2DozHYsC4gQ6Q4SQmVc79TxDIzqG6eJq+VSM94NPQ6CYuUzmQGCax8uZbQVLEVipFS3Ku2EAUQATr68L6hKrjuqziTEJNNHrTG1dIIDE8jLTGVTlJQboI2i56QZeSEQY7wTtYl7xQiWOF2GAuLx8UcThqIwh-OmdBZPF0qQCBoydIJlAZKK0jP4bHntBaHVXi0Ky+71ptZzE9sUIMGCRVw6Aau2dJQ6WZlMM-D9+89HIh++mbndVHpdNYLAnp2DtnO0qLYe6RUjV-W1S3Ykd0QABac1KFpbx3kHCxumNS9ak5SDTHNax0NUDRfFMV8BQSJYAHVOFOWEADFA2xd8YmYR0MlIWs+HXUoGzDYDFEQQx90mVozABJ9BAvPo6iuFpRgtQRdDUWNcKdfCqCIkioHI31KOdQgUk-P9CjXDcWKAqpmx0dR-gpCTaXNUxvh7RkvCHWlaWM9RfC6dCZOXeTiPIMiKJIKj1NUuSCAAFXQABbSAAHkclIXTAKJAyQIQLpBHJAEXB8AS1HvdRGT0a0D2ZZpBxjSc3L82IFK8pSfMwcqGEXTF3IIf8mJDRtt3YpLLPJZMWkmTtzJyxD+1UBofifVQOm8YyWjKtSKs8sVlICiECAImQeAARRyMAdogX8JRoqs6IYgDQ30zUjJ8CkWQmYZbOsFLGWzUyzE5bssx8ObAsoSqlpq8r1tILadr2g6ERWksQvCiAopi5i4qbRKjH7Bo4N1dsvFjOxEIeIwUPQ9o9AGSYvG+1bfsW7yVN8+agZB3bIHByUGtk1aWti874s1FGJOHYy6gTLo3lMVN7wPBNVAtbRRg0IEC35NmS0pxTltpwL6e2xn9s0w7mY5hGuaRzrAWZIYBJpc0pd1E18tNMZLOMAwnOCAsCDwFB4CORWms3bnm1AozWSgrHYMsYyEL6FGKXcDleMMO5rXJ5XZ0gP3jZqB4evaLwXEeqwnJNKYDypWlzHePwcIVotyuFT83QldOOpqWNU30A8rEmrMjPcAJk6FP7qch432rY3dxnN1onlaZ9idy5NILuCxl+UEwrH7wiqeqmnarpjatbB3Xcibser3eckfmd3xOkrnpce0DMjHMeoAgLjeqCCsBfVCmFOESE+EqdSfnmNwLJjBPBSs0QwuV3CQWPN3AwT4LTtldoEIAA */\n id: \"deviceConnection\",\n initial: \"Connected\",\n context: {\n apduInProgress: Nothing,\n apduResponse: Nothing,\n },\n states: {\n Connected: {\n on: {\n DeviceDisconnected: {\n target: \"WaitingForReconnection\",\n },\n SendApduCalled: {\n target: \"SendingApdu\",\n actions: assign({\n apduInProgress: ({ event }) => {\n return Maybe.of({\n apdu: event.apdu,\n triggersDisconnection: event.triggersDisconnection,\n abortTimeout: event.abortTimeout,\n responseCallback: event.responseCallback,\n });\n },\n }),\n },\n CloseConnectionCalled: {\n target: \"Terminated\",\n },\n },\n },\n SendingApdu: {\n entry: \"sendApdu\",\n on: {\n ApduResponseReceived: [\n {\n guard: \"isApduThatTriggersDisconnection\",\n target: \"WaitingForDisconnection\",\n actions: [\n assign({\n apduResponse: ({ event }) => Maybe.of(event.apduResponse),\n }),\n ],\n },\n {\n target: \"Connected\",\n actions: [\n {\n type: \"sendApduResponse\",\n // https://stately.ai/docs/actions#dynamic-action-parameters\n params: ({ event }) => {\n return {\n response: Right(event.apduResponse),\n };\n },\n },\n { type: \"clearApduInProgress\" },\n ],\n },\n ],\n ApduSendingError: {\n target: \"Connected\",\n actions: [\n {\n type: \"sendApduResponse\",\n // https://stately.ai/docs/actions#dynamic-action-parameters\n params: ({ event }) => {\n return {\n response: Left(event.error),\n };\n },\n },\n \"clearApduInProgress\",\n ],\n },\n DeviceDisconnected: {\n target: \"WaitingForReconnection\",\n actions: [\n {\n type: \"sendApduResponse\",\n params: {\n response: Left(new DeviceDisconnectedWhileSendingError()),\n },\n },\n \"clearApduInProgress\",\n ],\n },\n CloseConnectionCalled: {\n target: \"Terminated\",\n actions: [\n {\n type: \"sendApduResponse\",\n params: {\n response: Left(new DeviceDisconnectedWhileSendingError()),\n },\n },\n \"clearApduInProgress\",\n ],\n },\n SendApduCalled: {\n actions: ({ event }) => {\n event.responseCallback(Left(new AlreadySendingApduError()));\n },\n },\n },\n },\n WaitingForDisconnection: {\n entry: [\"sendGetAppAndVersion\"],\n exit: [\n {\n type: \"sendApduResponse\",\n params: ({ context }) => {\n return {\n response: context.apduResponse.caseOf({\n Just: (apduResponse) => Right(apduResponse),\n Nothing: () => Left(new UnknownDeviceExchangeError()),\n }),\n };\n },\n },\n { type: \"clearApduInProgress\" },\n { type: \"clearApduResponse\" },\n ],\n on: {\n ApduResponseReceived: [\n {\n guard: \"isSendApduBusyError\",\n actions: [\"sendGetAppAndVersion\"],\n target: \"WaitingForDisconnection\",\n },\n {\n target: \"Connected\",\n },\n ],\n ApduSendingError: [\n {\n target: \"WaitingForReconnection\",\n },\n ],\n SendApduCalled: {\n actions: ({ event }) => {\n event.responseCallback(Left(new AlreadySendingApduError()));\n },\n },\n DeviceDisconnected: {\n target: \"WaitingForReconnection\",\n },\n CloseConnectionCalled: {\n target: \"Terminated\",\n },\n },\n },\n WaitingForReconnection: {\n entry: [\"startTimer\", \"tryToReconnect\"],\n on: {\n DeviceConnected: {\n target: \"Connected\",\n actions: \"cancelTimer\",\n },\n SendApduCalled: {\n target: \"WaitingForReconnectionWithQueuedSendApdu\",\n actions: assign({\n apduInProgress: ({ event }) => {\n return Maybe.of({\n apdu: event.apdu,\n triggersDisconnection: event.triggersDisconnection,\n abortTimeout: event.abortTimeout,\n responseCallback: event.responseCallback,\n });\n },\n }),\n },\n ReconnectionTimedOut: {\n target: \"Terminated\",\n },\n CloseConnectionCalled: {\n target: \"Terminated\",\n },\n },\n },\n WaitingForReconnectionWithQueuedSendApdu: {\n on: {\n DeviceConnected: {\n target: \"SendingApdu\",\n actions: \"cancelTimer\",\n },\n ReconnectionTimedOut: {\n target: \"Terminated\",\n actions: [\n {\n type: \"sendApduResponse\",\n params: {\n response: Left(new DeviceDisconnectedBeforeSendingApdu()),\n },\n },\n {\n type: \"clearApduInProgress\",\n },\n ],\n },\n CloseConnectionCalled: {\n target: \"Terminated\",\n actions: [\n {\n type: \"sendApduResponse\",\n params: {\n response: Left(new DeviceDisconnectedWhileSendingError()),\n },\n },\n \"clearApduInProgress\",\n ],\n },\n SendApduCalled: {\n actions: ({ event }) => {\n event.responseCallback(Left(new AlreadySendingApduError()));\n },\n },\n },\n },\n // TODO: ADD INACTIVE STATE\n Terminated: {\n entry: [\"signalTermination\", \"closeConnection\"],\n type: \"final\",\n },\n },\n });\n}\n"],
5
+ "mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,kCAAAE,IAAA,eAAAC,EAAAH,GACA,IAAAI,EAAyD,qBACzDC,EAA6D,kBAE7DC,EAAwC,mDACxCC,EAA6B,2CAE7BC,EAA0D,sBAI1DC,EAIO,oBAuDA,MAAMP,CAA2C,CAC9C,SACA,iBAEA,aAEA,gBACA,QAAgD,KAExD,0BAA2B,CACzB,KAAK,QAAU,WAAW,IAAM,CAC9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BAAgB,EACtC,GAAI,CACF,gBAAiB,CACf,OAAQ,YACR,QAAS,aACX,EACA,eAAgB,CACd,OAAQ,2CACR,WAAS,UAAO,CACd,eAAgB,CAAC,CAAE,MAAAA,CAAM,IAChB,QAAM,GAAG,CACd,KAAMA,EAAM,KACZ,sBAAuBA,EAAM,sBAC7B,aAAcA,EAAM,aACpB,iBAAkBA,EAAM,gBAC1B,CAAC,CAEL,CAAC,CACH,EACA,qBAAsB,CACpB,OAAQ,YACV,EACA,sBAAuB,CACrB,OAAQ,YACV,CACF,CACF,EACA,yCAA0C,CACxC,GAAI,CACF,gBAAiB,CACf,OAAQ,cACR,QAAS,aACX,EACA,qBAAsB,CACpB,OAAQ,aACR,QAAS,CACP,CACE,KAAM,mBACN,OAAQ,CACN,YAAU,QAAK,IAAI,qCAAqC,CAC1D,CACF,EACA,CACE,KAAM,qBACR,CACF,CACF,EACA,sBAAuB,CACrB,OAAQ,aACR,QAAS,CACP,CACE,KAAM,mBACN,OAAQ,CACN,YAAU,QAAK,IAAI,qCAAqC,CAC1D,CACF,EACA,qBACF,CACF,EACA,eAAgB,CACd,QAAS,CAAC,CAAE,MAAAA,CAAM,IAAM,CACtBA,EAAM,oBAAiB,QAAK,IAAI,yBAAyB,CAAC,CAC5D,CACF,CACF,CACF,EAEA,WAAY,CACV,MAAO,CAAC,oBAAqB,iBAAiB,EAC9C,KAAM,OACR,CACF,CACF,CAAC,CACH",
6
6
  "names": ["DeviceConnectionStateMachine_exports", "__export", "DeviceConnectionStateMachine", "__toCommonJS", "import_purify_ts", "import_xstate", "import_GetAppAndVersionCommand", "import_CommandUtils", "import_Error", "import_Errors", "params", "makeStateMachine", "apdu", "triggersDisconnection", "abortTimeout", "response", "error", "apduResponse", "dependencies", "responseCallback", "sendApduFn", "startReconnectionTimeout", "cancelReconnectionTimeout", "tryToReconnect", "onTerminated", "closeConnection", "context", "event"]
7
7
  }
@@ -1,2 +1,2 @@
1
- "use strict";var s=Object.defineProperty;var c=Object.getOwnPropertyDescriptor;var a=Object.getOwnPropertyNames;var i=Object.prototype.hasOwnProperty;var l=(o,e)=>{for(var r in e)s(o,r,{get:e[r],enumerable:!0})},u=(o,e,r,d)=>{if(e&&typeof e=="object"||typeof e=="function")for(let t of a(e))!i.call(o,t)&&t!==r&&s(o,t,{get:()=>e[t],enumerable:!(d=c(e,t))||d.enumerable});return o};var p=o=>u(s({},"__esModule",{value:!0}),o);var z={};l(z,{AlreadySendingApduError:()=>C,DeviceAlreadyConnectedError:()=>E,DeviceDisconnectedBeforeSendingApdu:()=>f,DeviceDisconnectedWhileSendingError:()=>T,DeviceNotInitializedError:()=>S,DeviceNotRecognizedError:()=>y,DisconnectError:()=>_,GeneralDmkError:()=>n,NoAccessibleDeviceError:()=>v,NoTransportProvidedError:()=>h,NoTransportsProvidedError:()=>N,OpeningConnectionError:()=>x,ReconnectionFailedError:()=>A,SendApduConcurrencyError:()=>k,SendApduTimeoutError:()=>w,TransportAlreadyExistsError:()=>m,TransportNotSupportedError:()=>D,UnknownDeviceError:()=>g});module.exports=p(z);class n{_tag="GeneralDmkError";originalError;constructor(e){e instanceof Error?this.originalError=e:e!==void 0&&(this.originalError=new Error(String(e)))}}class E extends n{constructor(r){super(r);this.err=r}_tag="DeviceAlreadyDiscoveredError"}class y extends n{constructor(r){super(r);this.err=r}_tag="DeviceNotRecognizedError"}class v extends n{constructor(r){super(r);this.err=r}_tag="NoAccessibleDeviceError"}class x extends n{_tag="ConnectionOpeningError";constructor(e){super(e)}}class g extends n{constructor(r){super(r);this.err=r}_tag="UnknownDeviceError"}class D extends n{constructor(r){super(r);this.err=r}_tag="TransportNotSupportedError"}class k extends n{constructor(r){super(r);this.err=r}_tag="SendApduConcurrencyError"}class w extends n{constructor(r){super(r);this.err=r}_tag="SendApduTimeoutError"}class _ extends n{constructor(r){super(r);this.err=r}_tag="DisconnectError"}class A extends n{constructor(r){super(r);this.err=r}_tag="ReconnectionFailedError"}class S extends n{constructor(r){super(r);this.err=r}_tag="DeviceNotInitializedError"}class N extends n{constructor(r){super(r);this.err=r}_tag="NoTransportsProvidedError"}class m extends n{constructor(r){super(r);this.err=r}_tag="TransportAlreadyExistsError"}class T extends n{constructor(r){super(r);this.err=r}_tag="DeviceDisconnectedWhileSendingError"}class C extends n{constructor(r){super(r);this.err=r}_tag="AlreadySendingApduError"}class f extends n{constructor(r){super(r);this.err=r}_tag="DeviceDisconnectedBeforeSendingApdu"}class h extends n{constructor(r){super(r);this.err=r}_tag="NoTransportProvidedError"}0&&(module.exports={AlreadySendingApduError,DeviceAlreadyConnectedError,DeviceDisconnectedBeforeSendingApdu,DeviceDisconnectedWhileSendingError,DeviceNotInitializedError,DeviceNotRecognizedError,DisconnectError,GeneralDmkError,NoAccessibleDeviceError,NoTransportProvidedError,NoTransportsProvidedError,OpeningConnectionError,ReconnectionFailedError,SendApduConcurrencyError,SendApduTimeoutError,TransportAlreadyExistsError,TransportNotSupportedError,UnknownDeviceError});
1
+ "use strict";var s=Object.defineProperty;var c=Object.getOwnPropertyDescriptor;var a=Object.getOwnPropertyNames;var i=Object.prototype.hasOwnProperty;var l=(o,e)=>{for(var r in e)s(o,r,{get:e[r],enumerable:!0})},u=(o,e,r,d)=>{if(e&&typeof e=="object"||typeof e=="function")for(let t of a(e))!i.call(o,t)&&t!==r&&s(o,t,{get:()=>e[t],enumerable:!(d=c(e,t))||d.enumerable});return o};var p=o=>u(s({},"__esModule",{value:!0}),o);var z={};l(z,{AlreadySendingApduError:()=>f,DeviceAlreadyConnectedError:()=>E,DeviceDisconnectedBeforeSendingApdu:()=>R,DeviceDisconnectedWhileSendingError:()=>C,DeviceNotInitializedError:()=>m,DeviceNotRecognizedError:()=>y,DisconnectError:()=>_,GeneralDmkError:()=>n,NoAccessibleDeviceError:()=>x,NoTransportProvidedError:()=>h,NoTransportsProvidedError:()=>N,OpeningConnectionError:()=>v,ReconnectionFailedError:()=>S,SendApduConcurrencyError:()=>D,SendApduEmptyResponseError:()=>A,SendApduTimeoutError:()=>w,TransportAlreadyExistsError:()=>T,TransportNotSupportedError:()=>k,UnknownDeviceError:()=>g});module.exports=p(z);class n{_tag="GeneralDmkError";originalError;constructor(e){e instanceof Error?this.originalError=e:e!==void 0&&(this.originalError=new Error(String(e)))}}class E extends n{constructor(r){super(r);this.err=r}_tag="DeviceAlreadyDiscoveredError"}class y extends n{constructor(r){super(r);this.err=r}_tag="DeviceNotRecognizedError"}class x extends n{constructor(r){super(r);this.err=r}_tag="NoAccessibleDeviceError"}class v extends n{_tag="ConnectionOpeningError";constructor(e){super(e)}}class g extends n{constructor(r){super(r);this.err=r}_tag="UnknownDeviceError"}class k extends n{constructor(r){super(r);this.err=r}_tag="TransportNotSupportedError"}class D extends n{constructor(r){super(r);this.err=r}_tag="SendApduConcurrencyError"}class w extends n{constructor(r){super(r);this.err=r}_tag="SendApduTimeoutError"}class A extends n{constructor(r){super(r);this.err=r}_tag="SendApduEmptyResponseError"}class _ extends n{constructor(r){super(r);this.err=r}_tag="DisconnectError"}class S extends n{constructor(r){super(r);this.err=r}_tag="ReconnectionFailedError"}class m extends n{constructor(r){super(r);this.err=r}_tag="DeviceNotInitializedError"}class N extends n{constructor(r){super(r);this.err=r}_tag="NoTransportsProvidedError"}class T extends n{constructor(r){super(r);this.err=r}_tag="TransportAlreadyExistsError"}class C extends n{constructor(r){super(r);this.err=r}_tag="DeviceDisconnectedWhileSendingError"}class f extends n{constructor(r){super(r);this.err=r}_tag="AlreadySendingApduError"}class R extends n{constructor(r){super(r);this.err=r}_tag="DeviceDisconnectedBeforeSendingApdu"}class h extends n{constructor(r){super(r);this.err=r}_tag="NoTransportProvidedError"}0&&(module.exports={AlreadySendingApduError,DeviceAlreadyConnectedError,DeviceDisconnectedBeforeSendingApdu,DeviceDisconnectedWhileSendingError,DeviceNotInitializedError,DeviceNotRecognizedError,DisconnectError,GeneralDmkError,NoAccessibleDeviceError,NoTransportProvidedError,NoTransportsProvidedError,OpeningConnectionError,ReconnectionFailedError,SendApduConcurrencyError,SendApduEmptyResponseError,SendApduTimeoutError,TransportAlreadyExistsError,TransportNotSupportedError,UnknownDeviceError});
2
2
  //# sourceMappingURL=Errors.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../../src/api/transport/model/Errors.ts"],
4
- "sourcesContent": ["import { type DmkError } from \"@api/Error\";\n\nexport type ConnectError =\n | UnknownDeviceError\n | OpeningConnectionError\n | DeviceAlreadyConnectedError;\n\nexport class GeneralDmkError implements DmkError {\n _tag = \"GeneralDmkError\";\n originalError?: unknown;\n constructor(err?: unknown) {\n if (err instanceof Error) {\n this.originalError = err;\n } else if (err !== undefined) {\n this.originalError = new Error(String(err));\n }\n }\n}\n\nexport class DeviceAlreadyConnectedError extends GeneralDmkError {\n override readonly _tag = \"DeviceAlreadyDiscoveredError\";\n constructor(readonly err?: unknown) {\n super(err);\n }\n}\n\nexport class DeviceNotRecognizedError extends GeneralDmkError {\n override readonly _tag = \"DeviceNotRecognizedError\";\n constructor(readonly err?: unknown) {\n super(err);\n }\n}\n\nexport class NoAccessibleDeviceError extends GeneralDmkError {\n override readonly _tag = \"NoAccessibleDeviceError\";\n constructor(readonly err?: unknown) {\n super(err);\n }\n}\n\nexport class OpeningConnectionError extends GeneralDmkError {\n override _tag = \"ConnectionOpeningError\";\n constructor(err?: unknown) {\n super(err);\n }\n}\n\nexport class UnknownDeviceError extends GeneralDmkError {\n override readonly _tag = \"UnknownDeviceError\";\n constructor(readonly err?: unknown) {\n super(err);\n }\n}\n\nexport class TransportNotSupportedError extends GeneralDmkError {\n override readonly _tag = \"TransportNotSupportedError\";\n constructor(readonly err?: unknown) {\n super(err);\n }\n}\nexport class SendApduConcurrencyError extends GeneralDmkError {\n override readonly _tag = \"SendApduConcurrencyError\";\n constructor(readonly err?: unknown) {\n super(err);\n }\n}\n\nexport class SendApduTimeoutError extends GeneralDmkError {\n override readonly _tag = \"SendApduTimeoutError\";\n constructor(readonly err?: unknown) {\n super(err);\n }\n}\nexport class DisconnectError extends GeneralDmkError {\n override readonly _tag = \"DisconnectError\";\n constructor(readonly err?: unknown) {\n super(err);\n }\n}\n\nexport class ReconnectionFailedError extends GeneralDmkError {\n override readonly _tag = \"ReconnectionFailedError\";\n constructor(readonly err?: unknown) {\n super(err);\n }\n}\n\nexport class DeviceNotInitializedError extends GeneralDmkError {\n override readonly _tag = \"DeviceNotInitializedError\";\n constructor(readonly err?: unknown) {\n super(err);\n }\n}\n\nexport class NoTransportsProvidedError extends GeneralDmkError {\n override readonly _tag = \"NoTransportsProvidedError\";\n constructor(readonly err?: unknown) {\n super(err);\n }\n}\n\nexport class TransportAlreadyExistsError extends GeneralDmkError {\n override readonly _tag = \"TransportAlreadyExistsError\";\n constructor(readonly err?: unknown) {\n super(err);\n }\n}\n\nexport class DeviceDisconnectedWhileSendingError extends GeneralDmkError {\n override readonly _tag = \"DeviceDisconnectedWhileSendingError\";\n constructor(readonly err?: unknown) {\n super(err);\n }\n}\n\nexport class AlreadySendingApduError extends GeneralDmkError {\n override readonly _tag = \"AlreadySendingApduError\";\n constructor(readonly err?: unknown) {\n super(err);\n }\n}\n\nexport class DeviceDisconnectedBeforeSendingApdu extends GeneralDmkError {\n override readonly _tag = \"DeviceDisconnectedBeforeSendingApdu\";\n constructor(readonly err?: unknown) {\n super(err);\n }\n}\n\nexport class NoTransportProvidedError extends GeneralDmkError {\n override readonly _tag = \"NoTransportProvidedError\";\n constructor(readonly err?: unknown) {\n super(err);\n }\n}\n"],
5
- "mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,6BAAAE,EAAA,gCAAAC,EAAA,wCAAAC,EAAA,wCAAAC,EAAA,8BAAAC,EAAA,6BAAAC,EAAA,oBAAAC,EAAA,oBAAAC,EAAA,4BAAAC,EAAA,6BAAAC,EAAA,8BAAAC,EAAA,2BAAAC,EAAA,4BAAAC,EAAA,6BAAAC,EAAA,yBAAAC,EAAA,gCAAAC,EAAA,+BAAAC,EAAA,uBAAAC,IAAA,eAAAC,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,KAAO,yBAI3B,CAEO,MAAMf,UAAkCG,CAAgB,CAE7D,YAAqBY,EAAe,CAClC,MAAMA,CAAG,EADU,SAAAA,CAErB,CAHkB,KAAO,2BAI3B,CAEO,MAAMT,UAAkCH,CAAgB,CAE7D,YAAqBY,EAAe,CAClC,MAAMA,CAAG,EADU,SAAAA,CAErB,CAHkB,KAAO,2BAI3B,CAEO,MAAMJ,UAAoCR,CAAgB,CAE/D,YAAqBY,EAAe,CAClC,MAAMA,CAAG,EADU,SAAAA,CAErB,CAHkB,KAAO,6BAI3B,CAEO,MAAMhB,UAA4CI,CAAgB,CAEvE,YAAqBY,EAAe,CAClC,MAAMA,CAAG,EADU,SAAAA,CAErB,CAHkB,KAAO,qCAI3B,CAEO,MAAMnB,UAAgCO,CAAgB,CAE3D,YAAqBY,EAAe,CAClC,MAAMA,CAAG,EADU,SAAAA,CAErB,CAHkB,KAAO,yBAI3B,CAEO,MAAMjB,UAA4CK,CAAgB,CAEvE,YAAqBY,EAAe,CAClC,MAAMA,CAAG,EADU,SAAAA,CAErB,CAHkB,KAAO,qCAI3B,CAEO,MAAMV,UAAiCF,CAAgB,CAE5D,YAAqBY,EAAe,CAClC,MAAMA,CAAG,EADU,SAAAA,CAErB,CAHkB,KAAO,0BAI3B",
6
- "names": ["Errors_exports", "__export", "AlreadySendingApduError", "DeviceAlreadyConnectedError", "DeviceDisconnectedBeforeSendingApdu", "DeviceDisconnectedWhileSendingError", "DeviceNotInitializedError", "DeviceNotRecognizedError", "DisconnectError", "GeneralDmkError", "NoAccessibleDeviceError", "NoTransportProvidedError", "NoTransportsProvidedError", "OpeningConnectionError", "ReconnectionFailedError", "SendApduConcurrencyError", "SendApduTimeoutError", "TransportAlreadyExistsError", "TransportNotSupportedError", "UnknownDeviceError", "__toCommonJS", "err"]
4
+ "sourcesContent": ["import { type DmkError } from \"@api/Error\";\n\nexport type ConnectError =\n | UnknownDeviceError\n | OpeningConnectionError\n | DeviceAlreadyConnectedError;\n\nexport class GeneralDmkError implements DmkError {\n _tag = \"GeneralDmkError\";\n originalError?: unknown;\n constructor(err?: unknown) {\n if (err instanceof Error) {\n this.originalError = err;\n } else if (err !== undefined) {\n this.originalError = new Error(String(err));\n }\n }\n}\n\nexport class DeviceAlreadyConnectedError extends GeneralDmkError {\n override readonly _tag = \"DeviceAlreadyDiscoveredError\";\n constructor(readonly err?: unknown) {\n super(err);\n }\n}\n\nexport class DeviceNotRecognizedError extends GeneralDmkError {\n override readonly _tag = \"DeviceNotRecognizedError\";\n constructor(readonly err?: unknown) {\n super(err);\n }\n}\n\nexport class NoAccessibleDeviceError extends GeneralDmkError {\n override readonly _tag = \"NoAccessibleDeviceError\";\n constructor(readonly err?: unknown) {\n super(err);\n }\n}\n\nexport class OpeningConnectionError extends GeneralDmkError {\n override _tag = \"ConnectionOpeningError\";\n constructor(err?: unknown) {\n super(err);\n }\n}\n\nexport class UnknownDeviceError extends GeneralDmkError {\n override readonly _tag = \"UnknownDeviceError\";\n constructor(readonly err?: unknown) {\n super(err);\n }\n}\n\nexport class TransportNotSupportedError extends GeneralDmkError {\n override readonly _tag = \"TransportNotSupportedError\";\n constructor(readonly err?: unknown) {\n super(err);\n }\n}\nexport class SendApduConcurrencyError extends GeneralDmkError {\n override readonly _tag = \"SendApduConcurrencyError\";\n constructor(readonly err?: unknown) {\n super(err);\n }\n}\n\nexport class SendApduTimeoutError extends GeneralDmkError {\n override readonly _tag = \"SendApduTimeoutError\";\n constructor(readonly err?: unknown) {\n super(err);\n }\n}\n\nexport class SendApduEmptyResponseError extends GeneralDmkError {\n override readonly _tag = \"SendApduEmptyResponseError\";\n constructor(readonly err?: unknown) {\n super(err);\n }\n}\n\nexport class DisconnectError extends GeneralDmkError {\n override readonly _tag = \"DisconnectError\";\n constructor(readonly err?: unknown) {\n super(err);\n }\n}\n\nexport class ReconnectionFailedError extends GeneralDmkError {\n override readonly _tag = \"ReconnectionFailedError\";\n constructor(readonly err?: unknown) {\n super(err);\n }\n}\n\nexport class DeviceNotInitializedError extends GeneralDmkError {\n override readonly _tag = \"DeviceNotInitializedError\";\n constructor(readonly err?: unknown) {\n super(err);\n }\n}\n\nexport class NoTransportsProvidedError extends GeneralDmkError {\n override readonly _tag = \"NoTransportsProvidedError\";\n constructor(readonly err?: unknown) {\n super(err);\n }\n}\n\nexport class TransportAlreadyExistsError extends GeneralDmkError {\n override readonly _tag = \"TransportAlreadyExistsError\";\n constructor(readonly err?: unknown) {\n super(err);\n }\n}\n\nexport class DeviceDisconnectedWhileSendingError extends GeneralDmkError {\n override readonly _tag = \"DeviceDisconnectedWhileSendingError\";\n constructor(readonly err?: unknown) {\n super(err);\n }\n}\n\nexport class AlreadySendingApduError extends GeneralDmkError {\n override readonly _tag = \"AlreadySendingApduError\";\n constructor(readonly err?: unknown) {\n super(err);\n }\n}\n\nexport class DeviceDisconnectedBeforeSendingApdu extends GeneralDmkError {\n override readonly _tag = \"DeviceDisconnectedBeforeSendingApdu\";\n constructor(readonly err?: unknown) {\n super(err);\n }\n}\n\nexport class NoTransportProvidedError extends GeneralDmkError {\n override readonly _tag = \"NoTransportProvidedError\";\n constructor(readonly err?: unknown) {\n super(err);\n }\n}\n"],
5
+ "mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,6BAAAE,EAAA,gCAAAC,EAAA,wCAAAC,EAAA,wCAAAC,EAAA,8BAAAC,EAAA,6BAAAC,EAAA,oBAAAC,EAAA,oBAAAC,EAAA,4BAAAC,EAAA,6BAAAC,EAAA,8BAAAC,EAAA,2BAAAC,EAAA,4BAAAC,EAAA,6BAAAC,EAAA,+BAAAC,EAAA,yBAAAC,EAAA,gCAAAC,EAAA,+BAAAC,EAAA,uBAAAC,IAAA,eAAAC,EAAArB,GAOO,MAAMS,CAAoC,CAC/C,KAAO,kBACP,cACA,YAAYa,EAAe,CACrBA,aAAe,MACjB,KAAK,cAAgBA,EACZA,IAAQ,SACjB,KAAK,cAAgB,IAAI,MAAM,OAAOA,CAAG,CAAC,EAE9C,CACF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EAAe,CAClC,MAAMA,CAAG,EADU,SAAAA,CAErB,CAHkB,KAAO,2BAI3B,CAEO,MAAMV,UAAkCH,CAAgB,CAE7D,YAAqBa,EAAe,CAClC,MAAMA,CAAG,EADU,SAAAA,CAErB,CAHkB,KAAO,2BAI3B,CAEO,MAAMJ,UAAoCT,CAAgB,CAE/D,YAAqBa,EAAe,CAClC,MAAMA,CAAG,EADU,SAAAA,CAErB,CAHkB,KAAO,6BAI3B,CAEO,MAAMjB,UAA4CI,CAAgB,CAEvE,YAAqBa,EAAe,CAClC,MAAMA,CAAG,EADU,SAAAA,CAErB,CAHkB,KAAO,qCAI3B,CAEO,MAAMpB,UAAgCO,CAAgB,CAE3D,YAAqBa,EAAe,CAClC,MAAMA,CAAG,EADU,SAAAA,CAErB,CAHkB,KAAO,yBAI3B,CAEO,MAAMlB,UAA4CK,CAAgB,CAEvE,YAAqBa,EAAe,CAClC,MAAMA,CAAG,EADU,SAAAA,CAErB,CAHkB,KAAO,qCAI3B,CAEO,MAAMX,UAAiCF,CAAgB,CAE5D,YAAqBa,EAAe,CAClC,MAAMA,CAAG,EADU,SAAAA,CAErB,CAHkB,KAAO,0BAI3B",
6
+ "names": ["Errors_exports", "__export", "AlreadySendingApduError", "DeviceAlreadyConnectedError", "DeviceDisconnectedBeforeSendingApdu", "DeviceDisconnectedWhileSendingError", "DeviceNotInitializedError", "DeviceNotRecognizedError", "DisconnectError", "GeneralDmkError", "NoAccessibleDeviceError", "NoTransportProvidedError", "NoTransportsProvidedError", "OpeningConnectionError", "ReconnectionFailedError", "SendApduConcurrencyError", "SendApduEmptyResponseError", "SendApduTimeoutError", "TransportAlreadyExistsError", "TransportNotSupportedError", "UnknownDeviceError", "__toCommonJS", "err"]
7
7
  }
@@ -1,2 +1,2 @@
1
- "use strict";var e=Object.defineProperty;var o=Object.getOwnPropertyDescriptor;var f=Object.getOwnPropertyNames;var x=Object.prototype.hasOwnProperty;var a=(t,r)=>{for(var n in r)e(t,n,{get:r[n],enumerable:!0})},g=(t,r,n,s)=>{if(r&&typeof r=="object"||typeof r=="function")for(let i of f(r))!x.call(t,i)&&i!==n&&e(t,i,{get:()=>r[i],enumerable:!(s=o(r,i))||s.enumerable});return t};var p=t=>g(e({},"__esModule",{value:!0}),t);var c={};a(c,{bufferToHexaString:()=>A,hexaStringToBuffer:()=>S,isHexaString:()=>y});module.exports=p(c);const y=t=>typeof t=="string"&&/^0x[0-9a-fA-F]*$/.test(t),S=t=>{if(t.startsWith("0x")&&(t=t.slice(2)),t.length===0)return new Uint8Array;if(t.length%2!==0&&(t="0"+t),/^[0-9a-fA-F]*$/.test(t)===!1)return null;const r=t.match(/.{1,2}/g)?.map(n=>parseInt(n,16));return!r||r.some(isNaN)?null:new Uint8Array(r)},A=t=>`0x${Array.from(t,r=>r.toString(16).padStart(2,"0")).join("")}`;0&&(module.exports={bufferToHexaString,hexaStringToBuffer,isHexaString});
1
+ "use strict";var f=Object.defineProperty;var o=Object.getOwnPropertyDescriptor;var x=Object.getOwnPropertyNames;var a=Object.prototype.hasOwnProperty;var s=(r,t)=>{for(var n in t)f(r,n,{get:t[n],enumerable:!0})},g=(r,t,n,e)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of x(t))!a.call(r,i)&&i!==n&&f(r,i,{get:()=>t[i],enumerable:!(e=o(t,i))||e.enumerable});return r};var u=r=>g(f({},"__esModule",{value:!0}),r);var c={};s(c,{bufferToHexaString:()=>y,hexaStringToBuffer:()=>S,isHexaString:()=>p});module.exports=u(c);function p(r){return typeof r=="string"&&/^0x[0-9a-fA-F]*$/.test(r)}function S(r){if(r.startsWith("0x")&&(r=r.slice(2)),r.length===0)return new Uint8Array;if(r.length%2!==0&&(r="0"+r),/^[0-9a-fA-F]*$/.test(r)===!1)return null;const t=r.match(/.{1,2}/g)?.map(n=>parseInt(n,16));return!t||t.some(isNaN)?null:new Uint8Array(t)}function y(r,t=!0){return`${t?"0x":""}${Array.from(r,e=>e.toString(16).padStart(2,"0")).join("")}`}0&&(module.exports={bufferToHexaString,hexaStringToBuffer,isHexaString});
2
2
  //# sourceMappingURL=HexaString.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../src/api/utils/HexaString.ts"],
4
- "sourcesContent": ["export type HexaString = `0x${string}`;\n\nexport const isHexaString = (value: unknown): value is HexaString => {\n return typeof value === \"string\" && /^0x[0-9a-fA-F]*$/.test(value);\n};\n\nexport const hexaStringToBuffer = (value: string): Uint8Array | null => {\n if (value.startsWith(\"0x\")) {\n value = value.slice(2);\n }\n if (value.length === 0) {\n return new Uint8Array();\n }\n if (value.length % 2 !== 0) {\n value = \"0\" + value;\n }\n if (/^[0-9a-fA-F]*$/.test(value) === false) {\n return null;\n }\n const bytes = value.match(/.{1,2}/g)?.map((byte) => parseInt(byte, 16));\n if (!bytes || bytes.some(isNaN)) {\n return null;\n }\n return new Uint8Array(bytes);\n};\n\nexport const bufferToHexaString = (value: Uint8Array): HexaString => {\n return `0x${Array.from(value, (byte) =>\n byte.toString(16).padStart(2, \"0\"),\n ).join(\"\")}`;\n};\n"],
5
- "mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,wBAAAE,EAAA,uBAAAC,EAAA,iBAAAC,IAAA,eAAAC,EAAAL,GAEO,MAAMI,EAAgBE,GACpB,OAAOA,GAAU,UAAY,mBAAmB,KAAKA,CAAK,EAGtDH,EAAsBG,GAAqC,CAItE,GAHIA,EAAM,WAAW,IAAI,IACvBA,EAAQA,EAAM,MAAM,CAAC,GAEnBA,EAAM,SAAW,EACnB,OAAO,IAAI,WAKb,GAHIA,EAAM,OAAS,IAAM,IACvBA,EAAQ,IAAMA,GAEZ,iBAAiB,KAAKA,CAAK,IAAM,GACnC,OAAO,KAET,MAAMC,EAAQD,EAAM,MAAM,SAAS,GAAG,IAAKE,GAAS,SAASA,EAAM,EAAE,CAAC,EACtE,MAAI,CAACD,GAASA,EAAM,KAAK,KAAK,EACrB,KAEF,IAAI,WAAWA,CAAK,CAC7B,EAEaL,EAAsBI,GAC1B,KAAK,MAAM,KAAKA,EAAQE,GAC7BA,EAAK,SAAS,EAAE,EAAE,SAAS,EAAG,GAAG,CACnC,EAAE,KAAK,EAAE,CAAC",
6
- "names": ["HexaString_exports", "__export", "bufferToHexaString", "hexaStringToBuffer", "isHexaString", "__toCommonJS", "value", "bytes", "byte"]
4
+ "sourcesContent": ["export type HexaString = `0x${string}`;\n\nexport function isHexaString(value: unknown): value is HexaString {\n return typeof value === \"string\" && /^0x[0-9a-fA-F]*$/.test(value);\n}\n\nexport function hexaStringToBuffer(value: string): Uint8Array | null {\n if (value.startsWith(\"0x\")) {\n value = value.slice(2);\n }\n if (value.length === 0) {\n return new Uint8Array();\n }\n if (value.length % 2 !== 0) {\n value = \"0\" + value;\n }\n if (/^[0-9a-fA-F]*$/.test(value) === false) {\n return null;\n }\n const bytes = value.match(/.{1,2}/g)?.map((byte) => parseInt(byte, 16));\n if (!bytes || bytes.some(isNaN)) {\n return null;\n }\n return new Uint8Array(bytes);\n}\n\nexport function bufferToHexaString(\n value: Uint8Array,\n withPrefix?: true,\n): HexaString;\nexport function bufferToHexaString(\n value: Uint8Array,\n withPrefix?: false,\n): string;\nexport function bufferToHexaString(\n value: Uint8Array,\n withPrefix: boolean = true,\n): HexaString | string {\n const prefix = withPrefix ? \"0x\" : \"\";\n return `${prefix}${Array.from(value, (byte) =>\n byte.toString(16).padStart(2, \"0\"),\n ).join(\"\")}`;\n}\n"],
5
+ "mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,wBAAAE,EAAA,uBAAAC,EAAA,iBAAAC,IAAA,eAAAC,EAAAL,GAEO,SAASI,EAAaE,EAAqC,CAChE,OAAO,OAAOA,GAAU,UAAY,mBAAmB,KAAKA,CAAK,CACnE,CAEO,SAASH,EAAmBG,EAAkC,CAInE,GAHIA,EAAM,WAAW,IAAI,IACvBA,EAAQA,EAAM,MAAM,CAAC,GAEnBA,EAAM,SAAW,EACnB,OAAO,IAAI,WAKb,GAHIA,EAAM,OAAS,IAAM,IACvBA,EAAQ,IAAMA,GAEZ,iBAAiB,KAAKA,CAAK,IAAM,GACnC,OAAO,KAET,MAAMC,EAAQD,EAAM,MAAM,SAAS,GAAG,IAAKE,GAAS,SAASA,EAAM,EAAE,CAAC,EACtE,MAAI,CAACD,GAASA,EAAM,KAAK,KAAK,EACrB,KAEF,IAAI,WAAWA,CAAK,CAC7B,CAUO,SAASL,EACdI,EACAG,EAAsB,GACD,CAErB,MAAO,GADQA,EAAa,KAAO,EACnB,GAAG,MAAM,KAAKH,EAAQE,GACpCA,EAAK,SAAS,EAAE,EAAE,SAAS,EAAG,GAAG,CACnC,EAAE,KAAK,EAAE,CAAC,EACZ",
6
+ "names": ["HexaString_exports", "__export", "bufferToHexaString", "hexaStringToBuffer", "isHexaString", "__toCommonJS", "value", "bytes", "byte", "withPrefix"]
7
7
  }
@@ -1,2 +1,2 @@
1
- "use strict";var e=require("./HexaString");describe("HexaString",()=>{describe("isHexaString function",()=>{it("should return true if the value is a valid hex string",()=>{const t=(0,e.isHexaString)("0x1234abc");expect(t).toBeTruthy()}),it("should return true if no data",()=>{const t=(0,e.isHexaString)("0x");expect(t).toBeTruthy()}),it("should return false if the value contain an invalid letter",()=>{const t=(0,e.isHexaString)("0x1234z");expect(t).toBeFalsy()}),it("should return false if the value does not start with 0x",()=>{const t=(0,e.isHexaString)("1234abc");expect(t).toBeFalsy()}),it("should return false for an epmty string",()=>{const t=(0,e.isHexaString)("");expect(t).toBeFalsy()}),it.each([123,[],{},null,void 0,!0])("should return false for invalid input %p",u=>{const t=(0,e.isHexaString)(u);expect(t).toBeFalsy()})}),describe("hexaStringToBuffer function",()=>{it("should convert empty input to empty buffer",()=>{const t=(0,e.hexaStringToBuffer)("");expect(t).toStrictEqual(new Uint8Array)}),it("should fail on invalid string",()=>{const t=(0,e.hexaStringToBuffer)("bonjour");expect(t).toStrictEqual(null)}),it("should fail on invalid string with valid numbers",()=>{const t=(0,e.hexaStringToBuffer)("0x012n34");expect(t).toStrictEqual(null)}),it("should convert correct hexadecimal string",()=>{const t=(0,e.hexaStringToBuffer)("1a35669f0100");expect(t).toStrictEqual(new Uint8Array([26,53,102,159,1,0]))}),it("should support 0x prefix",()=>{const t=(0,e.hexaStringToBuffer)("0x1a35");expect(t).toStrictEqual(new Uint8Array([26,53]))}),it("should be case insensitive",()=>{const t=(0,e.hexaStringToBuffer)("0xcCDd");expect(t).toStrictEqual(new Uint8Array([204,221]))}),it("should pad with 0",()=>{const t=(0,e.hexaStringToBuffer)("0xa35");expect(t).toStrictEqual(new Uint8Array([10,53]))})}),describe("bufferToHexaString function",()=>{it("should convert a buffer into a hexa string",()=>{const u=Uint8Array.from([0,1,2,255,254]),t=(0,e.bufferToHexaString)(u);expect(t).toStrictEqual("0x000102fffe")})})});
1
+ "use strict";var e=require("./HexaString");describe("HexaString",()=>{describe("isHexaString function",()=>{it("should return true if the value is a valid hex string",()=>{const t=(0,e.isHexaString)("0x1234abc");expect(t).toBeTruthy()}),it("should return true if no data",()=>{const t=(0,e.isHexaString)("0x");expect(t).toBeTruthy()}),it("should return false if the value contain an invalid letter",()=>{const t=(0,e.isHexaString)("0x1234z");expect(t).toBeFalsy()}),it("should return false if the value does not start with 0x",()=>{const t=(0,e.isHexaString)("1234abc");expect(t).toBeFalsy()}),it("should return false for an epmty string",()=>{const t=(0,e.isHexaString)("");expect(t).toBeFalsy()}),it.each([123,[],{},null,void 0,!0])("should return false for invalid input %p",r=>{const t=(0,e.isHexaString)(r);expect(t).toBeFalsy()})}),describe("hexaStringToBuffer function",()=>{it("should convert empty input to empty buffer",()=>{const t=(0,e.hexaStringToBuffer)("");expect(t).toStrictEqual(new Uint8Array)}),it("should fail on invalid string",()=>{const t=(0,e.hexaStringToBuffer)("bonjour");expect(t).toStrictEqual(null)}),it("should fail on invalid string with valid numbers",()=>{const t=(0,e.hexaStringToBuffer)("0x012n34");expect(t).toStrictEqual(null)}),it("should convert correct hexadecimal string",()=>{const t=(0,e.hexaStringToBuffer)("1a35669f0100");expect(t).toStrictEqual(new Uint8Array([26,53,102,159,1,0]))}),it("should support 0x prefix",()=>{const t=(0,e.hexaStringToBuffer)("0x1a35");expect(t).toStrictEqual(new Uint8Array([26,53]))}),it("should be case insensitive",()=>{const t=(0,e.hexaStringToBuffer)("0xcCDd");expect(t).toStrictEqual(new Uint8Array([204,221]))}),it("should pad with 0",()=>{const t=(0,e.hexaStringToBuffer)("0xa35");expect(t).toStrictEqual(new Uint8Array([10,53]))})}),describe("bufferToHexaString function",()=>{it("should convert a buffer into a hexa string",()=>{const r=Uint8Array.from([0,1,2,255,254]),t=(0,e.bufferToHexaString)(r);expect(t).toStrictEqual("0x000102fffe")}),it("should convert a buffer into a hexa string without prefix",()=>{const r=Uint8Array.from([0,1,2,255,254]),t=(0,e.bufferToHexaString)(r,!1);expect(t).toStrictEqual("000102fffe")})})});
2
2
  //# sourceMappingURL=HexaString.test.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../src/api/utils/HexaString.test.ts"],
4
- "sourcesContent": ["import {\n bufferToHexaString,\n hexaStringToBuffer,\n isHexaString,\n} from \"./HexaString\";\n\ndescribe(\"HexaString\", () => {\n describe(\"isHexaString function\", () => {\n it(\"should return true if the value is a valid hex string\", () => {\n // GIVEN\n const value = \"0x1234abc\";\n\n // WHEN\n const result = isHexaString(value);\n\n // THEN\n expect(result).toBeTruthy();\n });\n\n it(\"should return true if no data\", () => {\n // GIVEN\n const value = \"0x\";\n\n // WHEN\n const result = isHexaString(value);\n\n // THEN\n expect(result).toBeTruthy();\n });\n\n it(\"should return false if the value contain an invalid letter\", () => {\n // GIVEN\n const value = \"0x1234z\";\n\n // WHEN\n const result = isHexaString(value);\n\n // THEN\n expect(result).toBeFalsy();\n });\n\n it(\"should return false if the value does not start with 0x\", () => {\n // GIVEN\n const value = \"1234abc\";\n\n // WHEN\n const result = isHexaString(value);\n\n // THEN\n expect(result).toBeFalsy();\n });\n\n it(\"should return false for an epmty string\", () => {\n // GIVEN\n const value = \"\";\n\n // WHEN\n const result = isHexaString(value);\n\n // THEN\n expect(result).toBeFalsy();\n });\n\n it.each([123, [], {}, null, undefined, true])(\n \"should return false for invalid input %p\",\n (value) => {\n // WHEN\n const result = isHexaString(value);\n\n // THEN\n expect(result).toBeFalsy();\n },\n );\n });\n\n describe(\"hexaStringToBuffer function\", () => {\n it(\"should convert empty input to empty buffer\", () => {\n // GIVEN\n const value = \"\";\n\n // WHEN\n const result = hexaStringToBuffer(value);\n\n // THEN\n expect(result).toStrictEqual(new Uint8Array());\n });\n\n it(\"should fail on invalid string\", () => {\n // GIVEN\n const value = \"bonjour\";\n\n // WHEN\n const result = hexaStringToBuffer(value);\n\n // THEN\n expect(result).toStrictEqual(null);\n });\n\n it(\"should fail on invalid string with valid numbers\", () => {\n // GIVEN\n const value = \"0x012n34\";\n\n // WHEN\n const result = hexaStringToBuffer(value);\n\n // THEN\n expect(result).toStrictEqual(null);\n });\n\n it(\"should convert correct hexadecimal string\", () => {\n // GIVEN\n const value = \"1a35669f0100\";\n\n // WHEN\n const result = hexaStringToBuffer(value);\n\n // THEN\n expect(result).toStrictEqual(\n new Uint8Array([0x1a, 0x35, 0x66, 0x9f, 0x01, 0x00]),\n );\n });\n\n it(\"should support 0x prefix\", () => {\n // GIVEN\n const value = \"0x1a35\";\n\n // WHEN\n const result = hexaStringToBuffer(value);\n\n // THEN\n expect(result).toStrictEqual(new Uint8Array([0x1a, 0x35]));\n });\n\n it(\"should be case insensitive\", () => {\n // GIVEN\n const value = \"0xcCDd\";\n\n // WHEN\n const result = hexaStringToBuffer(value);\n\n // THEN\n expect(result).toStrictEqual(new Uint8Array([0xcc, 0xdd]));\n });\n\n it(\"should pad with 0\", () => {\n // GIVEN\n const value = \"0xa35\";\n\n // WHEN\n const result = hexaStringToBuffer(value);\n\n // THEN\n expect(result).toStrictEqual(new Uint8Array([0x0a, 0x35]));\n });\n });\n\n describe(\"bufferToHexaString function\", () => {\n it(\"should convert a buffer into a hexa string\", () => {\n // GIVEN\n const value = Uint8Array.from([0, 1, 2, 0xff, 0xfe]);\n\n // WHEN\n const result = bufferToHexaString(value);\n\n // THEN\n expect(result).toStrictEqual(\"0x000102fffe\");\n });\n });\n});\n"],
5
- "mappings": "aAAA,IAAAA,EAIO,wBAEP,SAAS,aAAc,IAAM,CAC3B,SAAS,wBAAyB,IAAM,CACtC,GAAG,wDAAyD,IAAM,CAKhE,MAAMC,KAAS,gBAHD,WAGmB,EAGjC,OAAOA,CAAM,EAAE,WAAW,CAC5B,CAAC,EAED,GAAG,gCAAiC,IAAM,CAKxC,MAAMA,KAAS,gBAHD,IAGmB,EAGjC,OAAOA,CAAM,EAAE,WAAW,CAC5B,CAAC,EAED,GAAG,6DAA8D,IAAM,CAKrE,MAAMA,KAAS,gBAHD,SAGmB,EAGjC,OAAOA,CAAM,EAAE,UAAU,CAC3B,CAAC,EAED,GAAG,0DAA2D,IAAM,CAKlE,MAAMA,KAAS,gBAHD,SAGmB,EAGjC,OAAOA,CAAM,EAAE,UAAU,CAC3B,CAAC,EAED,GAAG,0CAA2C,IAAM,CAKlD,MAAMA,KAAS,gBAHD,EAGmB,EAGjC,OAAOA,CAAM,EAAE,UAAU,CAC3B,CAAC,EAED,GAAG,KAAK,CAAC,IAAK,CAAC,EAAG,CAAC,EAAG,KAAM,OAAW,EAAI,CAAC,EAC1C,2CACCC,GAAU,CAET,MAAMD,KAAS,gBAAaC,CAAK,EAGjC,OAAOD,CAAM,EAAE,UAAU,CAC3B,CACF,CACF,CAAC,EAED,SAAS,8BAA+B,IAAM,CAC5C,GAAG,6CAA8C,IAAM,CAKrD,MAAMA,KAAS,sBAHD,EAGyB,EAGvC,OAAOA,CAAM,EAAE,cAAc,IAAI,UAAY,CAC/C,CAAC,EAED,GAAG,gCAAiC,IAAM,CAKxC,MAAMA,KAAS,sBAHD,SAGyB,EAGvC,OAAOA,CAAM,EAAE,cAAc,IAAI,CACnC,CAAC,EAED,GAAG,mDAAoD,IAAM,CAK3D,MAAMA,KAAS,sBAHD,UAGyB,EAGvC,OAAOA,CAAM,EAAE,cAAc,IAAI,CACnC,CAAC,EAED,GAAG,4CAA6C,IAAM,CAKpD,MAAMA,KAAS,sBAHD,cAGyB,EAGvC,OAAOA,CAAM,EAAE,cACb,IAAI,WAAW,CAAC,GAAM,GAAM,IAAM,IAAM,EAAM,CAAI,CAAC,CACrD,CACF,CAAC,EAED,GAAG,2BAA4B,IAAM,CAKnC,MAAMA,KAAS,sBAHD,QAGyB,EAGvC,OAAOA,CAAM,EAAE,cAAc,IAAI,WAAW,CAAC,GAAM,EAAI,CAAC,CAAC,CAC3D,CAAC,EAED,GAAG,6BAA8B,IAAM,CAKrC,MAAMA,KAAS,sBAHD,QAGyB,EAGvC,OAAOA,CAAM,EAAE,cAAc,IAAI,WAAW,CAAC,IAAM,GAAI,CAAC,CAAC,CAC3D,CAAC,EAED,GAAG,oBAAqB,IAAM,CAK5B,MAAMA,KAAS,sBAHD,OAGyB,EAGvC,OAAOA,CAAM,EAAE,cAAc,IAAI,WAAW,CAAC,GAAM,EAAI,CAAC,CAAC,CAC3D,CAAC,CACH,CAAC,EAED,SAAS,8BAA+B,IAAM,CAC5C,GAAG,6CAA8C,IAAM,CAErD,MAAMC,EAAQ,WAAW,KAAK,CAAC,EAAG,EAAG,EAAG,IAAM,GAAI,CAAC,EAG7CD,KAAS,sBAAmBC,CAAK,EAGvC,OAAOD,CAAM,EAAE,cAAc,cAAc,CAC7C,CAAC,CACH,CAAC,CACH,CAAC",
4
+ "sourcesContent": ["import {\n bufferToHexaString,\n hexaStringToBuffer,\n isHexaString,\n} from \"./HexaString\";\n\ndescribe(\"HexaString\", () => {\n describe(\"isHexaString function\", () => {\n it(\"should return true if the value is a valid hex string\", () => {\n // GIVEN\n const value = \"0x1234abc\";\n\n // WHEN\n const result = isHexaString(value);\n\n // THEN\n expect(result).toBeTruthy();\n });\n\n it(\"should return true if no data\", () => {\n // GIVEN\n const value = \"0x\";\n\n // WHEN\n const result = isHexaString(value);\n\n // THEN\n expect(result).toBeTruthy();\n });\n\n it(\"should return false if the value contain an invalid letter\", () => {\n // GIVEN\n const value = \"0x1234z\";\n\n // WHEN\n const result = isHexaString(value);\n\n // THEN\n expect(result).toBeFalsy();\n });\n\n it(\"should return false if the value does not start with 0x\", () => {\n // GIVEN\n const value = \"1234abc\";\n\n // WHEN\n const result = isHexaString(value);\n\n // THEN\n expect(result).toBeFalsy();\n });\n\n it(\"should return false for an epmty string\", () => {\n // GIVEN\n const value = \"\";\n\n // WHEN\n const result = isHexaString(value);\n\n // THEN\n expect(result).toBeFalsy();\n });\n\n it.each([123, [], {}, null, undefined, true])(\n \"should return false for invalid input %p\",\n (value) => {\n // WHEN\n const result = isHexaString(value);\n\n // THEN\n expect(result).toBeFalsy();\n },\n );\n });\n\n describe(\"hexaStringToBuffer function\", () => {\n it(\"should convert empty input to empty buffer\", () => {\n // GIVEN\n const value = \"\";\n\n // WHEN\n const result = hexaStringToBuffer(value);\n\n // THEN\n expect(result).toStrictEqual(new Uint8Array());\n });\n\n it(\"should fail on invalid string\", () => {\n // GIVEN\n const value = \"bonjour\";\n\n // WHEN\n const result = hexaStringToBuffer(value);\n\n // THEN\n expect(result).toStrictEqual(null);\n });\n\n it(\"should fail on invalid string with valid numbers\", () => {\n // GIVEN\n const value = \"0x012n34\";\n\n // WHEN\n const result = hexaStringToBuffer(value);\n\n // THEN\n expect(result).toStrictEqual(null);\n });\n\n it(\"should convert correct hexadecimal string\", () => {\n // GIVEN\n const value = \"1a35669f0100\";\n\n // WHEN\n const result = hexaStringToBuffer(value);\n\n // THEN\n expect(result).toStrictEqual(\n new Uint8Array([0x1a, 0x35, 0x66, 0x9f, 0x01, 0x00]),\n );\n });\n\n it(\"should support 0x prefix\", () => {\n // GIVEN\n const value = \"0x1a35\";\n\n // WHEN\n const result = hexaStringToBuffer(value);\n\n // THEN\n expect(result).toStrictEqual(new Uint8Array([0x1a, 0x35]));\n });\n\n it(\"should be case insensitive\", () => {\n // GIVEN\n const value = \"0xcCDd\";\n\n // WHEN\n const result = hexaStringToBuffer(value);\n\n // THEN\n expect(result).toStrictEqual(new Uint8Array([0xcc, 0xdd]));\n });\n\n it(\"should pad with 0\", () => {\n // GIVEN\n const value = \"0xa35\";\n\n // WHEN\n const result = hexaStringToBuffer(value);\n\n // THEN\n expect(result).toStrictEqual(new Uint8Array([0x0a, 0x35]));\n });\n });\n\n describe(\"bufferToHexaString function\", () => {\n it(\"should convert a buffer into a hexa string\", () => {\n // GIVEN\n const value = Uint8Array.from([0, 1, 2, 0xff, 0xfe]);\n\n // WHEN\n const result = bufferToHexaString(value);\n\n // THEN\n expect(result).toStrictEqual(\"0x000102fffe\");\n });\n\n it(\"should convert a buffer into a hexa string without prefix\", () => {\n // GIVEN\n const value = Uint8Array.from([0, 1, 2, 0xff, 0xfe]);\n\n // WHEN\n const result = bufferToHexaString(value, false);\n\n // THEN\n expect(result).toStrictEqual(\"000102fffe\");\n });\n });\n});\n"],
5
+ "mappings": "aAAA,IAAAA,EAIO,wBAEP,SAAS,aAAc,IAAM,CAC3B,SAAS,wBAAyB,IAAM,CACtC,GAAG,wDAAyD,IAAM,CAKhE,MAAMC,KAAS,gBAHD,WAGmB,EAGjC,OAAOA,CAAM,EAAE,WAAW,CAC5B,CAAC,EAED,GAAG,gCAAiC,IAAM,CAKxC,MAAMA,KAAS,gBAHD,IAGmB,EAGjC,OAAOA,CAAM,EAAE,WAAW,CAC5B,CAAC,EAED,GAAG,6DAA8D,IAAM,CAKrE,MAAMA,KAAS,gBAHD,SAGmB,EAGjC,OAAOA,CAAM,EAAE,UAAU,CAC3B,CAAC,EAED,GAAG,0DAA2D,IAAM,CAKlE,MAAMA,KAAS,gBAHD,SAGmB,EAGjC,OAAOA,CAAM,EAAE,UAAU,CAC3B,CAAC,EAED,GAAG,0CAA2C,IAAM,CAKlD,MAAMA,KAAS,gBAHD,EAGmB,EAGjC,OAAOA,CAAM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C,GAAG,6CAA8C,IAAM,CAErD,MAAMC,EAAQ,WAAW,KAAK,CAAC,EAAG,EAAG,EAAG,IAAM,GAAI,CAAC,EAG7CD,KAAS,sBAAmBC,CAAK,EAGvC,OAAOD,CAAM,EAAE,cAAc,cAAc,CAC7C,CAAC,EAED,GAAG,4DAA6D,IAAM,CAEpE,MAAMC,EAAQ,WAAW,KAAK,CAAC,EAAG,EAAG,EAAG,IAAM,GAAI,CAAC,EAG7CD,KAAS,sBAAmBC,EAAO,EAAK,EAG9C,OAAOD,CAAM,EAAE,cAAc,YAAY,CAC3C,CAAC,CACH,CAAC,CACH,CAAC",
6
6
  "names": ["import_HexaString", "result", "value"]
7
7
  }
@@ -1,2 +1,2 @@
1
- "use strict";var p=Object.defineProperty;var F=Object.getOwnPropertyDescriptor;var H=Object.getOwnPropertyNames;var C=Object.prototype.hasOwnProperty;var D=(o,e)=>{for(var r in e)p(o,r,{get:e[r],enumerable:!0})},G=(o,e,r,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of H(e))!C.call(o,n)&&n!==r&&p(o,n,{get:()=>e[n],enumerable:!(t=F(e,n))||t.enumerable});return o};var P=o=>G(p({},"__esModule",{value:!0}),o),_=(o,e,r,t)=>{for(var n=t>1?void 0:t?F(e,r):e,s=o.length-1,m;s>=0;s--)(m=o[s])&&(n=(t?m(e,r,n):m(n))||n);return t&&n&&p(e,r,n),n},f=(o,e)=>(r,t)=>e(r,t,o);var z={};D(z,{DefaultApduReceiverService:()=>g});module.exports=P(z);var d=require("inversify"),a=require("purify-ts"),A=require("uuid"),y=require("../../../api/device-session/ApduResponse"),i=require("../../../api/device-session/data/FramerConst"),h=require("../../../api/device-session/utils/FramerUtils"),l=require("../../device-session/data/ApduResponseConst"),u=require("../../device-session/model/Errors"),E=require("../../device-session/model/Frame"),b=require("../../device-session/model/FrameHeader"),v=require("../../logger-publisher/di/loggerTypes");let g=class{_channel;_logger;_pendingFrames;constructor({channel:e=a.Maybe.zero()},r){this._channel=e,this._logger=r("ApduReceiverService"),this._pendingFrames=[]}handleFrame(e){return this.getFrameFromBytes(e).map(t=>{if(this._logger.debug("handle frame",{data:{frame:t.getRawData()}}),this._pendingFrames.push(t),!this._pendingFrames[0])return a.Nothing;const n=this._pendingFrames[0].getHeader().getDataLength();return this.getCompleteFrame(n)})}getCompleteFrame(e){return e.chain(r=>{if(!this.isComplete(r))return this._logger.debug("frame is not complete, waiting for more"),a.Nothing;const t=h.FramerUtils.getFirstBytesFrom(this.concatFrames(this._pendingFrames),r),n=h.FramerUtils.getFirstBytesFrom(t,t.length-l.APDU_RESPONSE_STATUS_CODE_LENGTH),s=h.FramerUtils.getLastBytesFrom(t,l.APDU_RESPONSE_STATUS_CODE_LENGTH);return this._pendingFrames=[],(0,a.Just)(new y.ApduResponse({data:n,statusCode:s}))})}getFrameFromBytes(e){const r=this._channel.caseOf({Just:()=>i.CHANNEL_LENGTH,Nothing:()=>0}),t=e.slice(r,r+i.HEAD_TAG_LENGTH),n=e.slice(r+i.HEAD_TAG_LENGTH,r+i.HEAD_TAG_LENGTH+i.INDEX_LENGTH),s=n.reduce((T,U)=>T+U,0)===0;if(!s&&this._pendingFrames.length===0)return(0,a.Left)(new u.ReceiverApduError);const m=r+i.HEAD_TAG_LENGTH+i.INDEX_LENGTH,c=s?i.APDU_DATA_LENGTH_LENGTH:0;if(e.length<r+i.HEAD_TAG_LENGTH+i.INDEX_LENGTH+c)return(0,a.Left)(new u.ReceiverApduError("Unable to parse header from apdu"));const L=s?(0,a.Just)(e.slice(m,m+c)):a.Nothing,R=m+c,S=e.slice(R),N=new E.Frame({header:new b.FrameHeader({uuid:(0,A.v4)(),channel:this._channel,dataSize:L,headTag:t,index:n,length:r+i.HEAD_TAG_LENGTH+i.INDEX_LENGTH+c}),data:S});return(0,a.Right)(N)}isComplete(e){return this._pendingFrames.reduce((t,n)=>t+n.getData().length,0)>=e}concatFrames(e){return e.reduce((r,t)=>Uint8Array.from([...r,...t.getData()]),new Uint8Array(0))}};g=_([(0,d.injectable)(),f(1,(0,d.inject)(v.loggerTypes.LoggerPublisherServiceFactory))],g);0&&(module.exports={DefaultApduReceiverService});
1
+ "use strict";var p=Object.defineProperty;var F=Object.getOwnPropertyDescriptor;var H=Object.getOwnPropertyNames;var C=Object.prototype.hasOwnProperty;var D=(o,e)=>{for(var r in e)p(o,r,{get:e[r],enumerable:!0})},G=(o,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let t of H(e))!C.call(o,t)&&t!==r&&p(o,t,{get:()=>e[t],enumerable:!(n=F(e,t))||n.enumerable});return o};var P=o=>G(p({},"__esModule",{value:!0}),o),_=(o,e,r,n)=>{for(var t=n>1?void 0:n?F(e,r):e,s=o.length-1,m;s>=0;s--)(m=o[s])&&(t=(n?m(e,r,t):m(t))||t);return n&&t&&p(e,r,t),t},A=(o,e)=>(r,n)=>e(r,n,o);var z={};D(z,{DefaultApduReceiverService:()=>c});module.exports=P(z);var d=require("inversify"),a=require("purify-ts"),f=require("uuid"),y=require("../../../api/device-session/ApduResponse"),i=require("../../../api/device-session/data/FramerConst"),h=require("../../../api/device-session/utils/FramerUtils"),l=require("../../device-session/data/ApduResponseConst"),u=require("../../device-session/model/Errors"),v=require("../../device-session/model/Frame"),E=require("../../device-session/model/FrameHeader"),L=require("../../logger-publisher/di/loggerTypes");let c=class{_channel;_logger;_pendingFrames;constructor({channel:e=a.Maybe.zero()},r){this._channel=e,this._logger=r("ApduReceiverService"),this._pendingFrames=[]}handleFrame(e){return this.getFrameFromBytes(e).map(n=>{if(this._pendingFrames.push(n),!this._pendingFrames[0])return a.Nothing;const t=this._pendingFrames[0].getHeader().getDataLength();return this.getCompleteFrame(t)})}getCompleteFrame(e){return e.chain(r=>{if(!this.isComplete(r))return this._logger.debug("frame is not complete, waiting for more"),a.Nothing;const n=h.FramerUtils.getFirstBytesFrom(this.concatFrames(this._pendingFrames),r),t=h.FramerUtils.getFirstBytesFrom(n,n.length-l.APDU_RESPONSE_STATUS_CODE_LENGTH),s=h.FramerUtils.getLastBytesFrom(n,l.APDU_RESPONSE_STATUS_CODE_LENGTH);return this._pendingFrames=[],(0,a.Just)(new y.ApduResponse({data:t,statusCode:s}))})}getFrameFromBytes(e){const r=this._channel.caseOf({Just:()=>i.CHANNEL_LENGTH,Nothing:()=>0}),n=e.slice(r,r+i.HEAD_TAG_LENGTH),t=e.slice(r+i.HEAD_TAG_LENGTH,r+i.HEAD_TAG_LENGTH+i.INDEX_LENGTH),s=t.reduce((T,U)=>T+U,0)===0;if(!s&&this._pendingFrames.length===0)return(0,a.Left)(new u.ReceiverApduError);const m=r+i.HEAD_TAG_LENGTH+i.INDEX_LENGTH,g=s?i.APDU_DATA_LENGTH_LENGTH:0;if(e.length<r+i.HEAD_TAG_LENGTH+i.INDEX_LENGTH+g)return(0,a.Left)(new u.ReceiverApduError("Unable to parse header from apdu"));const b=s?(0,a.Just)(e.slice(m,m+g)):a.Nothing,S=m+g,N=e.slice(S),R=new v.Frame({header:new E.FrameHeader({uuid:(0,f.v4)(),channel:this._channel,dataSize:b,headTag:n,index:t,length:r+i.HEAD_TAG_LENGTH+i.INDEX_LENGTH+g}),data:N});return(0,a.Right)(R)}isComplete(e){return this._pendingFrames.reduce((n,t)=>n+t.getData().length,0)>=e}concatFrames(e){return e.reduce((r,n)=>Uint8Array.from([...r,...n.getData()]),new Uint8Array(0))}};c=_([(0,d.injectable)(),A(1,(0,d.inject)(L.loggerTypes.LoggerPublisherServiceFactory))],c);0&&(module.exports={DefaultApduReceiverService});
2
2
  //# sourceMappingURL=DefaultApduReceiverService.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../../src/internal/device-session/service/DefaultApduReceiverService.ts"],
4
- "sourcesContent": ["import { inject, injectable } from \"inversify\";\nimport { Either, Just, Left, Maybe, Nothing, Right } from \"purify-ts\";\nimport { v4 } from \"uuid\";\n\nimport { ApduResponse } from \"@api/device-session/ApduResponse\";\nimport {\n APDU_DATA_LENGTH_LENGTH,\n CHANNEL_LENGTH,\n HEAD_TAG_LENGTH,\n INDEX_LENGTH,\n} from \"@api/device-session/data/FramerConst\";\nimport {\n type ApduReceiverConstructorArgs,\n ApduReceiverService,\n} from \"@api/device-session/service/ApduReceiverService\";\nimport { FramerUtils } from \"@api/device-session/utils/FramerUtils\";\nimport { LoggerPublisherService } from \"@api/logger-publisher/service/LoggerPublisherService\";\nimport { APDU_RESPONSE_STATUS_CODE_LENGTH } from \"@internal/device-session/data/ApduResponseConst\";\nimport { ReceiverApduError } from \"@internal/device-session/model/Errors\";\nimport { Frame } from \"@internal/device-session/model/Frame\";\nimport { FrameHeader } from \"@internal/device-session/model/FrameHeader\";\nimport { loggerTypes } from \"@internal/logger-publisher/di/loggerTypes\";\n\n@injectable()\nexport class DefaultApduReceiverService implements ApduReceiverService {\n private readonly _channel: Maybe<Uint8Array>;\n private readonly _logger: LoggerPublisherService;\n private _pendingFrames: Frame[];\n\n constructor(\n { channel = Maybe.zero() }: ApduReceiverConstructorArgs,\n @inject(loggerTypes.LoggerPublisherServiceFactory)\n loggerModuleFactory: (tag: string) => LoggerPublisherService,\n ) {\n this._channel = channel;\n this._logger = loggerModuleFactory(\"ApduReceiverService\");\n this._pendingFrames = [];\n }\n\n /*\n * Return\n * - A complete ApduResponse\n * - Or a Nothing if not all the data has been received\n * - Or a ReceiverApduError if the apdu is not formatted correctly\n *\n * @param Uint8Array\n */\n public handleFrame(\n frameBytes: Uint8Array,\n ): Either<ReceiverApduError, Maybe<ApduResponse>> {\n const frame = this.getFrameFromBytes(frameBytes);\n\n return frame.map((value) => {\n this._logger.debug(\"handle frame\", {\n data: { frame: value.getRawData() },\n });\n this._pendingFrames.push(value);\n if (!this._pendingFrames[0]) {\n return Nothing;\n }\n const dataSize = this._pendingFrames[0].getHeader().getDataLength();\n return this.getCompleteFrame(dataSize);\n });\n }\n\n /*\n * Return\n * - A complete ApduResponse\n * - Or a Nothing if not all the data has been received\n *\n * @param Maybe<number>\n */\n private getCompleteFrame(dataSize: Maybe<number>): Maybe<ApduResponse> {\n return dataSize.chain((value) => {\n if (!this.isComplete(value)) {\n this._logger.debug(\"frame is not complete, waiting for more\");\n return Nothing;\n }\n\n const concatenatedFramesData = FramerUtils.getFirstBytesFrom(\n this.concatFrames(this._pendingFrames),\n value,\n );\n const data = FramerUtils.getFirstBytesFrom(\n concatenatedFramesData,\n concatenatedFramesData.length - APDU_RESPONSE_STATUS_CODE_LENGTH,\n );\n const statusCode = FramerUtils.getLastBytesFrom(\n concatenatedFramesData,\n APDU_RESPONSE_STATUS_CODE_LENGTH,\n );\n\n this._pendingFrames = [];\n\n return Just(\n new ApduResponse({\n data: data,\n statusCode,\n }),\n );\n });\n }\n\n /*\n * Parse an Uint8Array to a Frame\n * Return an error if the frame is not formatted correctly\n *\n * @param Uint8Array\n */\n private getFrameFromBytes(\n rawFrame: Uint8Array,\n ): Either<ReceiverApduError, Frame> {\n const channelSize = this._channel.caseOf({\n Just: () => CHANNEL_LENGTH,\n Nothing: () => 0,\n });\n\n const headTag = rawFrame.slice(channelSize, channelSize + HEAD_TAG_LENGTH);\n const index = rawFrame.slice(\n channelSize + HEAD_TAG_LENGTH,\n channelSize + HEAD_TAG_LENGTH + INDEX_LENGTH,\n );\n\n const isFirstIndex = index.reduce((curr, val) => curr + val, 0) === 0;\n\n if (!isFirstIndex && this._pendingFrames.length === 0) {\n return Left(new ReceiverApduError());\n }\n\n const dataSizeIndex = channelSize + HEAD_TAG_LENGTH + INDEX_LENGTH;\n const dataSizeLength = isFirstIndex ? APDU_DATA_LENGTH_LENGTH : 0;\n\n if (\n rawFrame.length <\n channelSize + HEAD_TAG_LENGTH + INDEX_LENGTH + dataSizeLength\n ) {\n return Left(new ReceiverApduError(\"Unable to parse header from apdu\"));\n }\n\n const dataSize = isFirstIndex\n ? Just(rawFrame.slice(dataSizeIndex, dataSizeIndex + dataSizeLength))\n : Nothing;\n\n const dataIndex = dataSizeIndex + dataSizeLength;\n const data = rawFrame.slice(dataIndex);\n\n const frame = new Frame({\n header: new FrameHeader({\n uuid: v4(),\n channel: this._channel,\n dataSize,\n headTag,\n index,\n length: channelSize + HEAD_TAG_LENGTH + INDEX_LENGTH + dataSizeLength,\n }),\n data,\n });\n\n return Right(frame);\n }\n\n /*\n * Return true if all the datas has been received\n *\n * @param number\n */\n private isComplete(dataSize: number): boolean {\n const totalReceiveLength = this._pendingFrames.reduce(\n (prev, curr) => prev + curr.getData().length,\n 0,\n );\n\n return totalReceiveLength >= dataSize;\n }\n\n private concatFrames(frames: Frame[]): Uint8Array {\n return frames.reduce(\n (prev: Uint8Array, curr: Frame) =>\n Uint8Array.from([...prev, ...curr.getData()]),\n new Uint8Array(0),\n );\n }\n}\n"],
5
- "mappings": "okBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,gCAAAE,IAAA,eAAAC,EAAAH,GAAA,IAAAI,EAAmC,qBACnCC,EAA0D,qBAC1DC,EAAmB,gBAEnBC,EAA6B,4CAC7BC,EAKO,gDAKPC,EAA4B,iDAE5BC,EAAiD,2DACjDC,EAAkC,iDAClCC,EAAsB,gDACtBC,EAA4B,sDAC5BC,EAA4B,qDAGrB,IAAMC,EAAN,KAAgE,CACpD,SACA,QACT,eAER,YACE,CAAE,QAAAC,EAAU,QAAM,KAAK,CAAE,EAEzBC,EACA,CACA,KAAK,SAAWD,EAChB,KAAK,QAAUC,EAAoB,qBAAqB,EACxD,KAAK,eAAiB,CAAC,CACzB,CAUO,YACLC,EACgD,CAGhD,OAFc,KAAK,kBAAkBA,CAAU,EAElC,IAAKC,GAAU,CAK1B,GAJA,KAAK,QAAQ,MAAM,eAAgB,CACjC,KAAM,CAAE,MAAOA,EAAM,WAAW,CAAE,CACpC,CAAC,EACD,KAAK,eAAe,KAAKA,CAAK,EAC1B,CAAC,KAAK,eAAe,CAAC,EACxB,OAAO,UAET,MAAMC,EAAW,KAAK,eAAe,CAAC,EAAE,UAAU,EAAE,cAAc,EAClE,OAAO,KAAK,iBAAiBA,CAAQ,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AkB,eAAeO,CACzD,CAAC,EACD,KAAAV,CACF,CAAC,EAED,SAAO,SAAMY,CAAK,CACpB,CAOQ,WAAWd,EAA2B,CAM5C,OAL2B,KAAK,eAAe,OAC7C,CAACe,EAAMN,IAASM,EAAON,EAAK,QAAQ,EAAE,OACtC,CACF,GAE6BT,CAC/B,CAEQ,aAAagB,EAA6B,CAChD,OAAOA,EAAO,OACZ,CAACD,EAAkBN,IACjB,WAAW,KAAK,CAAC,GAAGM,EAAM,GAAGN,EAAK,QAAQ,CAAC,CAAC,EAC9C,IAAI,WAAW,CAAC,CAClB,CACF,CACF,EA9Jad,EAANsB,EAAA,IADN,cAAW,EAQPC,EAAA,eAAO,cAAY,6BAA6B,IAPxCvB",
4
+ "sourcesContent": ["import { inject, injectable } from \"inversify\";\nimport { Either, Just, Left, Maybe, Nothing, Right } from \"purify-ts\";\nimport { v4 } from \"uuid\";\n\nimport { ApduResponse } from \"@api/device-session/ApduResponse\";\nimport {\n APDU_DATA_LENGTH_LENGTH,\n CHANNEL_LENGTH,\n HEAD_TAG_LENGTH,\n INDEX_LENGTH,\n} from \"@api/device-session/data/FramerConst\";\nimport {\n type ApduReceiverConstructorArgs,\n ApduReceiverService,\n} from \"@api/device-session/service/ApduReceiverService\";\nimport { FramerUtils } from \"@api/device-session/utils/FramerUtils\";\nimport { LoggerPublisherService } from \"@api/logger-publisher/service/LoggerPublisherService\";\nimport { APDU_RESPONSE_STATUS_CODE_LENGTH } from \"@internal/device-session/data/ApduResponseConst\";\nimport { ReceiverApduError } from \"@internal/device-session/model/Errors\";\nimport { Frame } from \"@internal/device-session/model/Frame\";\nimport { FrameHeader } from \"@internal/device-session/model/FrameHeader\";\nimport { loggerTypes } from \"@internal/logger-publisher/di/loggerTypes\";\n\n@injectable()\nexport class DefaultApduReceiverService implements ApduReceiverService {\n private readonly _channel: Maybe<Uint8Array>;\n private readonly _logger: LoggerPublisherService;\n private _pendingFrames: Frame[];\n\n constructor(\n { channel = Maybe.zero() }: ApduReceiverConstructorArgs,\n @inject(loggerTypes.LoggerPublisherServiceFactory)\n loggerModuleFactory: (tag: string) => LoggerPublisherService,\n ) {\n this._channel = channel;\n this._logger = loggerModuleFactory(\"ApduReceiverService\");\n this._pendingFrames = [];\n }\n\n /*\n * Return\n * - A complete ApduResponse\n * - Or a Nothing if not all the data has been received\n * - Or a ReceiverApduError if the apdu is not formatted correctly\n *\n * @param Uint8Array\n */\n public handleFrame(\n frameBytes: Uint8Array,\n ): Either<ReceiverApduError, Maybe<ApduResponse>> {\n const frame = this.getFrameFromBytes(frameBytes);\n\n return frame.map((value) => {\n this._pendingFrames.push(value);\n if (!this._pendingFrames[0]) {\n return Nothing;\n }\n const dataSize = this._pendingFrames[0].getHeader().getDataLength();\n return this.getCompleteFrame(dataSize);\n });\n }\n\n /*\n * Return\n * - A complete ApduResponse\n * - Or a Nothing if not all the data has been received\n *\n * @param Maybe<number>\n */\n private getCompleteFrame(dataSize: Maybe<number>): Maybe<ApduResponse> {\n return dataSize.chain((value) => {\n if (!this.isComplete(value)) {\n this._logger.debug(\"frame is not complete, waiting for more\");\n return Nothing;\n }\n\n const concatenatedFramesData = FramerUtils.getFirstBytesFrom(\n this.concatFrames(this._pendingFrames),\n value,\n );\n const data = FramerUtils.getFirstBytesFrom(\n concatenatedFramesData,\n concatenatedFramesData.length - APDU_RESPONSE_STATUS_CODE_LENGTH,\n );\n const statusCode = FramerUtils.getLastBytesFrom(\n concatenatedFramesData,\n APDU_RESPONSE_STATUS_CODE_LENGTH,\n );\n\n this._pendingFrames = [];\n\n return Just(\n new ApduResponse({\n data: data,\n statusCode,\n }),\n );\n });\n }\n\n /*\n * Parse an Uint8Array to a Frame\n * Return an error if the frame is not formatted correctly\n *\n * @param Uint8Array\n */\n private getFrameFromBytes(\n rawFrame: Uint8Array,\n ): Either<ReceiverApduError, Frame> {\n const channelSize = this._channel.caseOf({\n Just: () => CHANNEL_LENGTH,\n Nothing: () => 0,\n });\n\n const headTag = rawFrame.slice(channelSize, channelSize + HEAD_TAG_LENGTH);\n const index = rawFrame.slice(\n channelSize + HEAD_TAG_LENGTH,\n channelSize + HEAD_TAG_LENGTH + INDEX_LENGTH,\n );\n\n const isFirstIndex = index.reduce((curr, val) => curr + val, 0) === 0;\n\n if (!isFirstIndex && this._pendingFrames.length === 0) {\n return Left(new ReceiverApduError());\n }\n\n const dataSizeIndex = channelSize + HEAD_TAG_LENGTH + INDEX_LENGTH;\n const dataSizeLength = isFirstIndex ? APDU_DATA_LENGTH_LENGTH : 0;\n\n if (\n rawFrame.length <\n channelSize + HEAD_TAG_LENGTH + INDEX_LENGTH + dataSizeLength\n ) {\n return Left(new ReceiverApduError(\"Unable to parse header from apdu\"));\n }\n\n const dataSize = isFirstIndex\n ? Just(rawFrame.slice(dataSizeIndex, dataSizeIndex + dataSizeLength))\n : Nothing;\n\n const dataIndex = dataSizeIndex + dataSizeLength;\n const data = rawFrame.slice(dataIndex);\n\n const frame = new Frame({\n header: new FrameHeader({\n uuid: v4(),\n channel: this._channel,\n dataSize,\n headTag,\n index,\n length: channelSize + HEAD_TAG_LENGTH + INDEX_LENGTH + dataSizeLength,\n }),\n data,\n });\n\n return Right(frame);\n }\n\n /*\n * Return true if all the datas has been received\n *\n * @param number\n */\n private isComplete(dataSize: number): boolean {\n const totalReceiveLength = this._pendingFrames.reduce(\n (prev, curr) => prev + curr.getData().length,\n 0,\n );\n\n return totalReceiveLength >= dataSize;\n }\n\n private concatFrames(frames: Frame[]): Uint8Array {\n return frames.reduce(\n (prev: Uint8Array, curr: Frame) =>\n Uint8Array.from([...prev, ...curr.getData()]),\n new Uint8Array(0),\n );\n }\n}\n"],
5
+ "mappings": "okBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,gCAAAE,IAAA,eAAAC,EAAAH,GAAA,IAAAI,EAAmC,qBACnCC,EAA0D,qBAC1DC,EAAmB,gBAEnBC,EAA6B,4CAC7BC,EAKO,gDAKPC,EAA4B,iDAE5BC,EAAiD,2DACjDC,EAAkC,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EAClD,SAAO,QAAK,IAAI,mBAAmB,EAGrC,MAAMG,EAAgBN,EAAc,kBAAkB,eAChDO,EAAiBJ,EAAe,0BAA0B,EAEhE,GACEJ,EAAS,OACTC,EAAc,kBAAkB,eAAeO,EAE/C,SAAO,QAAK,IAAI,oBAAkB,kCAAkC,CAAC,EAGvE,MAAMZ,EAAWQ,KACb,QAAKJ,EAAS,MAAMO,EAAeA,EAAgBC,CAAc,CAAC,EAClE,UAEEC,EAAYF,EAAgBC,EAC5BV,EAAOE,EAAS,MAAMS,CAAS,EAE/BC,EAAQ,IAAI,QAAM,CACtB,OAAQ,IAAI,cAAY,CACtB,QAAM,MAAG,EACT,QAAS,KAAK,SACd,SAAAd,EACA,QAAAM,EACA,MAAAC,EACA,OAAQF,EAAc,kBAAkB,eAAeO,CACzD,CAAC,EACD,KAAAV,CACF,CAAC,EAED,SAAO,SAAMY,CAAK,CACpB,CAOQ,WAAWd,EAA2B,CAM5C,OAL2B,KAAK,eAAe,OAC7C,CAACe,EAAMN,IAASM,EAAON,EAAK,QAAQ,EAAE,OACtC,CACF,GAE6BT,CAC/B,CAEQ,aAAagB,EAA6B,CAChD,OAAOA,EAAO,OACZ,CAACD,EAAkBN,IACjB,WAAW,KAAK,CAAC,GAAGM,EAAM,GAAGN,EAAK,QAAQ,CAAC,CAAC,EAC9C,IAAI,WAAW,CAAC,CAClB,CACF,CACF,EA3Jad,EAANsB,EAAA,IADN,cAAW,EAQPC,EAAA,eAAO,cAAY,6BAA6B,IAPxCvB",
6
6
  "names": ["DefaultApduReceiverService_exports", "__export", "DefaultApduReceiverService", "__toCommonJS", "import_inversify", "import_purify_ts", "import_uuid", "import_ApduResponse", "import_FramerConst", "import_FramerUtils", "import_ApduResponseConst", "import_Errors", "import_Frame", "import_FrameHeader", "import_loggerTypes", "DefaultApduReceiverService", "channel", "loggerModuleFactory", "frameBytes", "value", "dataSize", "concatenatedFramesData", "data", "statusCode", "rawFrame", "channelSize", "headTag", "index", "isFirstIndex", "curr", "val", "dataSizeIndex", "dataSizeLength", "dataIndex", "frame", "prev", "frames", "__decorateClass", "__decorateParam"]
7
7
  }