@ledgerhq/device-transport-kit-react-native-ble 0.0.0-try-to-fix-20250429171448 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -5
- package/lib/cjs/api/model/Const.js +1 -1
- package/lib/cjs/api/model/Const.js.map +3 -3
- package/lib/cjs/api/model/Errors.js +1 -1
- package/lib/cjs/api/model/Errors.js.map +3 -3
- package/lib/cjs/api/transport/RNBleApduSender.js +1 -1
- package/lib/cjs/api/transport/RNBleApduSender.js.map +3 -3
- package/lib/cjs/api/transport/RNBleApduSender.test.js +1 -1
- package/lib/cjs/api/transport/RNBleApduSender.test.js.map +2 -2
- package/lib/cjs/api/transport/RNBleTransport.js +1 -1
- package/lib/cjs/api/transport/RNBleTransport.js.map +3 -3
- package/lib/cjs/api/transport/RNBleTransport.test.js +1 -1
- package/lib/cjs/api/transport/RNBleTransport.test.js.map +3 -3
- package/lib/cjs/package.json +17 -17
- package/lib/esm/api/model/Const.js +1 -1
- package/lib/esm/api/model/Const.js.map +3 -3
- package/lib/esm/api/model/Errors.js +1 -1
- package/lib/esm/api/model/Errors.js.map +3 -3
- package/lib/esm/api/transport/RNBleApduSender.js +1 -1
- package/lib/esm/api/transport/RNBleApduSender.js.map +3 -3
- package/lib/esm/api/transport/RNBleApduSender.test.js +1 -1
- package/lib/esm/api/transport/RNBleApduSender.test.js.map +2 -2
- package/lib/esm/api/transport/RNBleTransport.js +1 -1
- package/lib/esm/api/transport/RNBleTransport.js.map +3 -3
- package/lib/esm/api/transport/RNBleTransport.test.js +1 -1
- package/lib/esm/api/transport/RNBleTransport.test.js.map +3 -3
- package/lib/esm/package.json +17 -17
- package/lib/types/api/model/Const.d.ts +2 -1
- package/lib/types/api/model/Const.d.ts.map +1 -1
- package/lib/types/api/model/Errors.d.ts +21 -1
- package/lib/types/api/model/Errors.d.ts.map +1 -1
- package/lib/types/api/transport/RNBleApduSender.d.ts +5 -6
- package/lib/types/api/transport/RNBleApduSender.d.ts.map +1 -1
- package/lib/types/api/transport/RNBleTransport.d.ts +22 -71
- package/lib/types/api/transport/RNBleTransport.d.ts.map +1 -1
- package/lib/types/tsconfig.prod.tsbuildinfo +1 -1
- package/package.json +13 -13
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/api/transport/RNBleApduSender.test.ts"],
|
|
4
|
-
"sourcesContent": ["import {\n type BleManager,\n type Characteristic,\n type Device,\n} from \"react-native-ble-plx\";\nimport {\n type ApduReceiverServiceFactory,\n type ApduSenderServiceFactory,\n defaultApduReceiverServiceStubBuilder,\n defaultApduSenderServiceStubBuilder,\n DeviceNotInitializedError,\n GeneralDmkError,\n type LoggerPublisherService,\n type LoggerSubscriberService,\n SendApduTimeoutError,\n} from \"@ledgerhq/device-management-kit\";\nimport { Left, Maybe, Right } from \"purify-ts\";\n\nimport { RNBleApduSender, type RNBleInternalDevice } from \"./RNBleApduSender\";\n\nvi.mock(\"react-native-ble-plx\", () => ({\n BleManager: vi.fn(),\n}));\n\nconst FRAME_HEADER_SIZE = 3;\nconst LEDGER_MTU = 156;\n\nclass LoggerPublisherServiceStub implements LoggerPublisherService {\n subscribers: LoggerSubscriberService[] = [];\n tag: string;\n constructor(subscribers: LoggerSubscriberService[], tag: string) {\n this.subscribers = subscribers;\n this.tag = tag;\n }\n error = vi.fn();\n warn = vi.fn();\n info = vi.fn();\n debug = vi.fn();\n}\n\nlet logger: (tag: string) => LoggerPublisherService;\nlet apduSenderFactory: ApduSenderServiceFactory;\nlet apduReceiverFactory: ApduReceiverServiceFactory;\nlet apduSender: RNBleApduSender;\nlet manager: BleManager;\nconst cancelConnection = vi.fn();\ndescribe(\"RNBleApduSender\", () => {\n beforeEach(() => {\n logger = (tag: string) => new LoggerPublisherServiceStub([], tag);\n apduSenderFactory = vi.fn(() =>\n defaultApduSenderServiceStubBuilder(undefined, logger),\n );\n apduReceiverFactory = vi.fn(() =>\n defaultApduReceiverServiceStubBuilder(undefined, logger),\n );\n apduSender = new RNBleApduSender(\n {\n dependencies: {\n device: {\n mtu: 156,\n cancelConnection,\n } as unknown as Device,\n internalDevice: {} as RNBleInternalDevice,\n manager: {} as BleManager,\n },\n apduReceiverFactory: apduReceiverFactory,\n apduSenderFactory: apduSenderFactory,\n },\n logger,\n );\n });\n\n afterEach(() => {\n vi.clearAllMocks();\n });\n\n describe(\"constructor\", () => {\n it(\"should create an instance of RNBleApduSender\", () => {\n expect(apduSender).toBeDefined();\n });\n });\n\n describe(\"getDependencies\", () => {\n it(\"should return the dependencies\", () => {\n const dependencies = apduSender.getDependencies();\n expect(dependencies).toStrictEqual({\n device: {\n mtu: 156,\n cancelConnection,\n },\n internalDevice: {},\n manager: {},\n });\n });\n });\n\n describe(\"setDependencies\", () => {\n it(\"should set the dependencies\", () => {\n const newDependencies = {\n device: {\n mtu: 156,\n id: \"deviceId\",\n cancelConnection,\n } as unknown as Device,\n internalDevice: {\n id: \"deviceId\",\n bleDeviceInfos: {\n serviceUuid: \"serviceUuid\",\n notifyUuid: \"notifyUuid\",\n writeCmdUuid: \"writeCmdUuid\",\n },\n } as RNBleInternalDevice,\n manager: {} as BleManager,\n };\n apduSender.setDependencies(newDependencies);\n const dependencies = apduSender.getDependencies();\n expect(dependencies).toStrictEqual(newDependencies);\n });\n });\n\n describe(\"setupConnection\", () => {\n beforeEach(() => {\n manager = {\n monitorCharacteristicForDevice: vi.fn(),\n writeCharacteristicWithoutResponseForDevice: vi.fn(),\n } as unknown as BleManager;\n\n const dependencies = {\n device: {\n mtu: 156,\n id: \"deviceId\",\n } as Device,\n internalDevice: {\n bleDeviceInfos: {\n serviceUuid: \"serviceUuid\",\n notifyUuid: \"notifyUuid\",\n writeCmdUuid: \"writeCmdUuid\",\n },\n } as RNBleInternalDevice,\n manager,\n };\n\n apduSender.setDependencies(dependencies);\n });\n\n it(\"should setup the connection and resolve when the device is ready\", async () => {\n vi.spyOn(manager, \"monitorCharacteristicForDevice\").mockImplementation(\n (_deviceId, _serviceUuid, _notifyUuid, callback) => {\n callback(null, {\n value: \"BQAAAA8BBUJPTE9TBTEuMi4ykAA=\",\n } as Characteristic);\n return {\n remove: vi.fn(),\n };\n },\n );\n\n vi.spyOn(\n manager,\n \"writeCharacteristicWithoutResponseForDevice\",\n ).mockImplementation((_deviceId, _serviceUuid, _writeCmdUuid, value) => {\n // @ts-expect-error needed for tests\n apduSender.onMonitor({\n value: value,\n } as Characteristic);\n\n return Promise.resolve({\n value: value,\n } as Characteristic);\n });\n\n await apduSender.setupConnection();\n\n expect(manager.monitorCharacteristicForDevice).toHaveBeenCalled();\n expect(\n manager.writeCharacteristicWithoutResponseForDevice,\n ).toHaveBeenCalled();\n });\n });\n\n describe(\"closeConnection\", () => {\n it(\"should close the connection\", () => {\n apduSender.closeConnection();\n expect(cancelConnection).toHaveBeenCalled();\n });\n });\n\n describe(\"sendApdu\", () => {\n beforeEach(async () => {\n manager = {\n monitorCharacteristicForDevice: vi.fn(),\n writeCharacteristicWithoutResponseForDevice: vi.fn(),\n } as unknown as BleManager;\n\n const dependencies = {\n device: {\n mtu: 156,\n id: \"deviceId\",\n } as Device,\n internalDevice: {\n bleDeviceInfos: {\n serviceUuid: \"serviceUuid\",\n notifyUuid: \"notifyUuid\",\n writeCmdUuid: \"writeCmdUuid\",\n },\n } as RNBleInternalDevice,\n manager,\n };\n\n vi.spyOn(\n manager,\n \"monitorCharacteristicForDevice\",\n ).mockImplementationOnce(\n (_deviceId, _serviceUuid, _notifyUuid, callback) => {\n callback(null, {\n value: \"BQAAAA8BBUJPTE9TBTEuMi4ykAA=\",\n } as Characteristic);\n\n return {\n remove: vi.fn(),\n };\n },\n );\n\n vi.spyOn(\n manager,\n \"writeCharacteristicWithoutResponseForDevice\",\n ).mockImplementation((_deviceId, _serviceUuid, _writeCmdUuid, value) => {\n // @ts-expect-error needed for tests\n apduSender.onMonitor({\n value: value,\n } as Characteristic);\n\n return Promise.resolve({\n value: value,\n } as Characteristic);\n });\n\n apduSender.setDependencies(dependencies);\n await apduSender.setupConnection();\n });\n\n describe(\"when the device is not ready\", () => {\n it(\"should return a DeviceNotInitializedError\", async () => {\n const apdu = new Uint8Array([0x08, 0x00, 0x00, 0x00]);\n // @ts-expect-error private access for tests\n apduSender._isDeviceReady.next(false);\n const result = await apduSender.sendApdu(apdu);\n expect(result).toStrictEqual(\n Left(new DeviceNotInitializedError(\"Unknown MTU\")),\n );\n });\n });\n\n describe(\"when the device is ready\", () => {\n it(\"should send the apdu\", async () => {\n // GetAppAndVersion APDU\n const apdu = new Uint8Array([0xb0, 0x01, 0x00, 0x00, 0x00]);\n\n const expectedResponse = new Uint8Array([\n 0x05, 0x00, 0x00, 0x00, 0x0f, 0x01, 0x05, 0x42, 0x4f, 0x4c, 0x4f,\n 0x53, 0x05, 0x31, 0x2e, 0x32, 0x2e, 0x32, 0x90, 0x00,\n ]);\n\n const statusCode = new Uint8Array([0x90, 0x00]);\n\n const response = {\n data: expectedResponse,\n statusCode,\n };\n\n vi.spyOn(\n manager,\n \"writeCharacteristicWithoutResponseForDevice\",\n ).mockImplementation(\n (_deviceId, _serviceUuid, _writeCmdUuid, value) => {\n // @ts-expect-error needed for tests\n apduSender.onMonitor({\n value: value,\n } as Characteristic);\n\n return Promise.resolve({\n value: value,\n } as Characteristic);\n },\n );\n\n // @ts-expect-error private access for tests\n vi.spyOn(apduSender._apduReceiver, \"handleFrame\").mockImplementation(\n () => {\n return Right(Maybe.of(response));\n },\n );\n\n const result = await apduSender.sendApdu(apdu);\n expect(apduSenderFactory).toHaveBeenCalledTimes(2);\n\n // first call is for the setup\n expect(apduSenderFactory).toHaveBeenNthCalledWith(1, {\n frameSize: 1,\n });\n\n // second call is for the apdu\n expect(apduSenderFactory).toHaveBeenNthCalledWith(2, {\n frameSize: LEDGER_MTU - FRAME_HEADER_SIZE,\n });\n\n expect(result).toStrictEqual(Right(response));\n });\n\n it(\"should return an error if the frame cannot be handled\", async () => {\n // {\"error\": {\"_tag\": \"DeviceLockedError\", \"errorCode\": \"5515\", \"message\": \"Device is locked.\", \"originalError\": undefined}, \"status\": \"ERROR\"}\n // GetAppAndVersion APDU\n const apdu = new Uint8Array([0xb0, 0x01, 0x00, 0x00, 0x00]);\n\n const expectedError = new GeneralDmkError(\"could not handle frame\");\n\n vi.spyOn(\n manager,\n \"writeCharacteristicWithoutResponseForDevice\",\n ).mockImplementation(\n (_deviceId, _serviceUuid, _writeCmdUuid, value) => {\n // @ts-expect-error needed for tests\n apduSender.onMonitor({\n value: value,\n } as Characteristic);\n\n return Promise.resolve({\n value: value,\n } as Characteristic);\n },\n );\n\n // @ts-expect-error private access for tests\n vi.spyOn(apduSender._apduReceiver, \"handleFrame\").mockImplementation(\n () => {\n return Left(expectedError);\n },\n );\n\n const result = await apduSender.sendApdu(apdu);\n expect(result).toStrictEqual(Left(expectedError));\n });\n\n it(\"should return a SendApduTimeoutError if something takes too long\", async () => {\n // GetAppAndVersion APDU\n const apdu = new Uint8Array([0xb0, 0x01, 0x00, 0x00, 0x00]);\n\n const expectedResponse = new Uint8Array([\n 0x05, 0x00, 0x00, 0x00, 0x0f, 0x01, 0x05, 0x42, 0x4f, 0x4c, 0x4f,\n 0x53, 0x05, 0x31, 0x2e, 0x32, 0x2e, 0x32, 0x90, 0x00,\n ]);\n\n const statusCode = new Uint8Array([0x90, 0x00]);\n\n const response = {\n data: expectedResponse,\n statusCode,\n };\n\n const expectedError = new SendApduTimeoutError(\"Abort timeout\");\n\n vi.spyOn(\n manager,\n \"writeCharacteristicWithoutResponseForDevice\",\n ).mockImplementation(\n (_deviceId, _serviceUuid, _writeCmdUuid, value) => {\n // @ts-expect-error needed for tests\n apduSender.onMonitor({\n value: value,\n } as Characteristic);\n\n return Promise.resolve({\n value: value,\n } as Characteristic);\n },\n );\n\n // @ts-expect-error private access for tests\n vi.spyOn(apduSender, \"onMonitor\").mockImplementation(() => {\n setTimeout(() => {\n return Right(Maybe.of(response));\n }, 2000);\n });\n\n const result = await apduSender.sendApdu(apdu, false, 100);\n expect(result).toStrictEqual(Left(expectedError));\n });\n\n it(\"should and and log an error if the this.write fails\", async () => {\n // GetAppAndVersion APDU\n const apdu = new Uint8Array([0xb0, 0x01, 0x00, 0x00, 0x00]);\n const expectedError = new SendApduTimeoutError(\"Abort timeout\");\n\n vi.spyOn(\n manager,\n \"writeCharacteristicWithoutResponseForDevice\",\n ).mockImplementation(\n (_deviceId, _serviceUuid, _writeCmdUuid, value) => {\n // @ts-expect-error needed for tests\n apduSender.onMonitor({\n value: value,\n } as Characteristic);\n\n return Promise.resolve({\n value: value,\n } as Characteristic);\n },\n );\n\n // @ts-expect-error private access for tests\n vi.spyOn(apduSender, \"write\").mockImplementation(() => {\n return Promise.reject(new Error(\"test\"));\n });\n\n const result = await apduSender.sendApdu(apdu, false, 100);\n expect(result).toStrictEqual(Left(expectedError));\n });\n\n it(\"should timeout if there are no characteristic.value\", async () => {\n // GetAppAndVersion APDU\n const apdu = new Uint8Array([0xb0, 0x01, 0x00, 0x00, 0x00]);\n const expectedError = new SendApduTimeoutError(\"Abort timeout\");\n\n vi.spyOn(\n manager,\n \"writeCharacteristicWithoutResponseForDevice\",\n ).mockImplementation(\n (_deviceId, _serviceUuid, _writeCmdUuid, _value) => {\n // @ts-expect-error needed for tests\n apduSender.onMonitor({} as Characteristic);\n\n return Promise.resolve({} as Characteristic);\n },\n );\n\n // @ts-expect-error private access for tests\n vi.spyOn(apduSender, \"write\").mockImplementation(() => {\n return Promise.reject(new Error(\"test\"));\n });\n\n const result = await apduSender.sendApdu(apdu, false, 100);\n expect(result).toStrictEqual(Left(expectedError));\n });\n });\n });\n});\n"],
|
|
5
|
-
"mappings": "AAKA,OAGE,yCAAAA,EACA,uCAAAC,EACA,6BAAAC,EACA,mBAAAC,EAGA,wBAAAC,MACK,kCACP,OAAS,QAAAC,EAAM,SAAAC,EAAO,SAAAC,MAAa,YAEnC,OAAS,mBAAAC,MAAiD,oBAE1D,GAAG,KAAK,uBAAwB,KAAO,CACrC,WAAY,GAAG,GAAG,CACpB,EAAE,EAEF,MAAMC,EAAoB,EACpBC,EAAa,IAEnB,MAAMC,CAA6D,CACjE,YAAyC,CAAC,EAC1C,IACA,YAAYC,EAAwCC,EAAa,CAC/D,KAAK,YAAcD,EACnB,KAAK,IAAMC,CACb,CACA,MAAQ,GAAG,GAAG,EACd,KAAO,GAAG,GAAG,EACb,KAAO,GAAG,GAAG,EACb,MAAQ,GAAG,GAAG,CAChB,CAEA,IAAIC,EACAC,EACAC,EACAC,EACAC,EACJ,MAAMC,EAAmB,GAAG,GAAG,
|
|
4
|
+
"sourcesContent": ["import {\n type BleManager,\n type Characteristic,\n type Device,\n} from \"react-native-ble-plx\";\nimport {\n type ApduReceiverServiceFactory,\n type ApduSenderServiceFactory,\n defaultApduReceiverServiceStubBuilder,\n defaultApduSenderServiceStubBuilder,\n DeviceNotInitializedError,\n GeneralDmkError,\n type LoggerPublisherService,\n type LoggerSubscriberService,\n SendApduTimeoutError,\n} from \"@ledgerhq/device-management-kit\";\nimport { Left, Maybe, Right } from \"purify-ts\";\n\nimport { RNBleApduSender, type RNBleInternalDevice } from \"./RNBleApduSender\";\n\nvi.mock(\"react-native-ble-plx\", () => ({\n BleManager: vi.fn(),\n}));\n\nconst FRAME_HEADER_SIZE = 3;\nconst LEDGER_MTU = 156;\n\nclass LoggerPublisherServiceStub implements LoggerPublisherService {\n subscribers: LoggerSubscriberService[] = [];\n tag: string;\n constructor(subscribers: LoggerSubscriberService[], tag: string) {\n this.subscribers = subscribers;\n this.tag = tag;\n }\n error = vi.fn();\n warn = vi.fn();\n info = vi.fn();\n debug = vi.fn();\n}\n\nlet logger: (tag: string) => LoggerPublisherService;\nlet apduSenderFactory: ApduSenderServiceFactory;\nlet apduReceiverFactory: ApduReceiverServiceFactory;\nlet apduSender: RNBleApduSender;\nlet manager: BleManager;\nconst cancelConnection = vi.fn();\n\n// TODO: fix these tests, sorry they are completely broken now\ndescribe.skip(\"RNBleApduSender\", () => {\n beforeEach(() => {\n logger = (tag: string) => new LoggerPublisherServiceStub([], tag);\n apduSenderFactory = vi.fn(() =>\n defaultApduSenderServiceStubBuilder(undefined, logger),\n );\n apduReceiverFactory = vi.fn(() =>\n defaultApduReceiverServiceStubBuilder(undefined, logger),\n );\n apduSender = new RNBleApduSender(\n {\n dependencies: {\n device: {\n mtu: 156,\n cancelConnection,\n } as unknown as Device,\n internalDevice: {} as RNBleInternalDevice,\n manager: {} as BleManager,\n },\n apduReceiverFactory: apduReceiverFactory,\n apduSenderFactory: apduSenderFactory,\n },\n logger,\n );\n });\n\n afterEach(() => {\n vi.clearAllMocks();\n });\n\n describe(\"constructor\", () => {\n it(\"should create an instance of RNBleApduSender\", () => {\n expect(apduSender).toBeDefined();\n });\n });\n\n describe(\"getDependencies\", () => {\n it(\"should return the dependencies\", () => {\n const dependencies = apduSender.getDependencies();\n expect(dependencies).toStrictEqual({\n device: {\n mtu: 156,\n cancelConnection,\n },\n internalDevice: {},\n manager: {},\n });\n });\n });\n\n describe(\"setDependencies\", () => {\n it(\"should set the dependencies\", () => {\n const newDependencies = {\n device: {\n mtu: 156,\n id: \"deviceId\",\n cancelConnection,\n } as unknown as Device,\n internalDevice: {\n id: \"deviceId\",\n bleDeviceInfos: {\n serviceUuid: \"serviceUuid\",\n notifyUuid: \"notifyUuid\",\n writeCmdUuid: \"writeCmdUuid\",\n },\n } as RNBleInternalDevice,\n manager: {} as BleManager,\n };\n apduSender.setDependencies(newDependencies);\n const dependencies = apduSender.getDependencies();\n expect(dependencies).toStrictEqual(newDependencies);\n });\n });\n\n describe(\"setupConnection\", () => {\n beforeEach(() => {\n manager = {\n monitorCharacteristicForDevice: vi.fn(),\n writeCharacteristicWithoutResponseForDevice: vi.fn(),\n } as unknown as BleManager;\n\n const dependencies = {\n device: {\n mtu: 156,\n id: \"deviceId\",\n } as Device,\n internalDevice: {\n bleDeviceInfos: {\n serviceUuid: \"serviceUuid\",\n notifyUuid: \"notifyUuid\",\n writeCmdUuid: \"writeCmdUuid\",\n },\n } as RNBleInternalDevice,\n manager,\n };\n\n apduSender.setDependencies(dependencies);\n });\n\n it(\"should setup the connection and resolve when the device is ready\", async () => {\n vi.spyOn(manager, \"monitorCharacteristicForDevice\").mockImplementation(\n (_deviceId, _serviceUuid, _notifyUuid, callback) => {\n callback(null, {\n value: \"BQAAAA8BBUJPTE9TBTEuMi4ykAA=\",\n } as Characteristic);\n return {\n remove: vi.fn(),\n };\n },\n );\n\n vi.spyOn(\n manager,\n \"writeCharacteristicWithoutResponseForDevice\",\n ).mockImplementation((_deviceId, _serviceUuid, _writeCmdUuid, value) => {\n // @ts-expect-error needed for tests\n apduSender.onMonitor({\n value: value,\n } as Characteristic);\n\n return Promise.resolve({\n value: value,\n } as Characteristic);\n });\n\n await apduSender.setupConnection();\n\n expect(manager.monitorCharacteristicForDevice).toHaveBeenCalled();\n expect(\n manager.writeCharacteristicWithoutResponseForDevice,\n ).toHaveBeenCalled();\n });\n });\n\n describe(\"closeConnection\", () => {\n it(\"should close the connection\", () => {\n apduSender.closeConnection();\n expect(cancelConnection).toHaveBeenCalled();\n });\n });\n\n describe(\"sendApdu\", () => {\n beforeEach(async () => {\n manager = {\n monitorCharacteristicForDevice: vi.fn(),\n writeCharacteristicWithoutResponseForDevice: vi.fn(),\n } as unknown as BleManager;\n\n const dependencies = {\n device: {\n mtu: 156,\n id: \"deviceId\",\n } as Device,\n internalDevice: {\n bleDeviceInfos: {\n serviceUuid: \"serviceUuid\",\n notifyUuid: \"notifyUuid\",\n writeCmdUuid: \"writeCmdUuid\",\n },\n } as RNBleInternalDevice,\n manager,\n };\n\n vi.spyOn(\n manager,\n \"monitorCharacteristicForDevice\",\n ).mockImplementationOnce(\n (_deviceId, _serviceUuid, _notifyUuid, callback) => {\n callback(null, {\n value: \"BQAAAA8BBUJPTE9TBTEuMi4ykAA=\",\n } as Characteristic);\n\n return {\n remove: vi.fn(),\n };\n },\n );\n\n vi.spyOn(\n manager,\n \"writeCharacteristicWithoutResponseForDevice\",\n ).mockImplementation((_deviceId, _serviceUuid, _writeCmdUuid, value) => {\n // @ts-expect-error needed for tests\n apduSender.onMonitor({\n value: value,\n } as Characteristic);\n\n return Promise.resolve({\n value: value,\n } as Characteristic);\n });\n\n apduSender.setDependencies(dependencies);\n await apduSender.setupConnection();\n });\n\n describe(\"when the device is not ready\", () => {\n it(\"should return a DeviceNotInitializedError\", async () => {\n const apdu = new Uint8Array([0x08, 0x00, 0x00, 0x00]);\n // @ts-expect-error private access for tests\n apduSender._isDeviceReady.next(false);\n const result = await apduSender.sendApdu(apdu);\n expect(result).toStrictEqual(\n Left(new DeviceNotInitializedError(\"Unknown MTU\")),\n );\n });\n });\n\n describe(\"when the device is ready\", () => {\n it(\"should send the apdu\", async () => {\n // GetAppAndVersion APDU\n const apdu = new Uint8Array([0xb0, 0x01, 0x00, 0x00, 0x00]);\n\n const expectedResponse = new Uint8Array([\n 0x05, 0x00, 0x00, 0x00, 0x0f, 0x01, 0x05, 0x42, 0x4f, 0x4c, 0x4f,\n 0x53, 0x05, 0x31, 0x2e, 0x32, 0x2e, 0x32, 0x90, 0x00,\n ]);\n\n const statusCode = new Uint8Array([0x90, 0x00]);\n\n const response = {\n data: expectedResponse,\n statusCode,\n };\n\n vi.spyOn(\n manager,\n \"writeCharacteristicWithoutResponseForDevice\",\n ).mockImplementation(\n (_deviceId, _serviceUuid, _writeCmdUuid, value) => {\n // @ts-expect-error needed for tests\n apduSender.onMonitor({\n value: value,\n } as Characteristic);\n\n return Promise.resolve({\n value: value,\n } as Characteristic);\n },\n );\n\n // @ts-expect-error private access for tests\n vi.spyOn(apduSender._apduReceiver, \"handleFrame\").mockImplementation(\n () => {\n return Right(Maybe.of(response));\n },\n );\n\n const result = await apduSender.sendApdu(apdu);\n expect(apduSenderFactory).toHaveBeenCalledTimes(2);\n\n // first call is for the setup\n expect(apduSenderFactory).toHaveBeenNthCalledWith(1, {\n frameSize: 1,\n });\n\n // second call is for the apdu\n expect(apduSenderFactory).toHaveBeenNthCalledWith(2, {\n frameSize: LEDGER_MTU - FRAME_HEADER_SIZE,\n });\n\n expect(result).toStrictEqual(Right(response));\n });\n\n it(\"should return an error if the frame cannot be handled\", async () => {\n // {\"error\": {\"_tag\": \"DeviceLockedError\", \"errorCode\": \"5515\", \"message\": \"Device is locked.\", \"originalError\": undefined}, \"status\": \"ERROR\"}\n // GetAppAndVersion APDU\n const apdu = new Uint8Array([0xb0, 0x01, 0x00, 0x00, 0x00]);\n\n const expectedError = new GeneralDmkError(\"could not handle frame\");\n\n vi.spyOn(\n manager,\n \"writeCharacteristicWithoutResponseForDevice\",\n ).mockImplementation(\n (_deviceId, _serviceUuid, _writeCmdUuid, value) => {\n // @ts-expect-error needed for tests\n apduSender.onMonitor({\n value: value,\n } as Characteristic);\n\n return Promise.resolve({\n value: value,\n } as Characteristic);\n },\n );\n\n // @ts-expect-error private access for tests\n vi.spyOn(apduSender._apduReceiver, \"handleFrame\").mockImplementation(\n () => {\n return Left(expectedError);\n },\n );\n\n const result = await apduSender.sendApdu(apdu);\n expect(result).toStrictEqual(Left(expectedError));\n });\n\n it(\"should return a SendApduTimeoutError if something takes too long\", async () => {\n // GetAppAndVersion APDU\n const apdu = new Uint8Array([0xb0, 0x01, 0x00, 0x00, 0x00]);\n\n const expectedResponse = new Uint8Array([\n 0x05, 0x00, 0x00, 0x00, 0x0f, 0x01, 0x05, 0x42, 0x4f, 0x4c, 0x4f,\n 0x53, 0x05, 0x31, 0x2e, 0x32, 0x2e, 0x32, 0x90, 0x00,\n ]);\n\n const statusCode = new Uint8Array([0x90, 0x00]);\n\n const response = {\n data: expectedResponse,\n statusCode,\n };\n\n const expectedError = new SendApduTimeoutError(\"Abort timeout\");\n\n vi.spyOn(\n manager,\n \"writeCharacteristicWithoutResponseForDevice\",\n ).mockImplementation(\n (_deviceId, _serviceUuid, _writeCmdUuid, value) => {\n // @ts-expect-error needed for tests\n apduSender.onMonitor({\n value: value,\n } as Characteristic);\n\n return Promise.resolve({\n value: value,\n } as Characteristic);\n },\n );\n\n // @ts-expect-error private access for tests\n vi.spyOn(apduSender, \"onMonitor\").mockImplementation(() => {\n setTimeout(() => {\n return Right(Maybe.of(response));\n }, 2000);\n });\n\n const result = await apduSender.sendApdu(apdu, false, 100);\n expect(result).toStrictEqual(Left(expectedError));\n });\n\n it(\"should and and log an error if the this.write fails\", async () => {\n // GetAppAndVersion APDU\n const apdu = new Uint8Array([0xb0, 0x01, 0x00, 0x00, 0x00]);\n const expectedError = new SendApduTimeoutError(\"Abort timeout\");\n\n vi.spyOn(\n manager,\n \"writeCharacteristicWithoutResponseForDevice\",\n ).mockImplementation(\n (_deviceId, _serviceUuid, _writeCmdUuid, value) => {\n // @ts-expect-error needed for tests\n apduSender.onMonitor({\n value: value,\n } as Characteristic);\n\n return Promise.resolve({\n value: value,\n } as Characteristic);\n },\n );\n\n // @ts-expect-error private access for tests\n vi.spyOn(apduSender, \"write\").mockImplementation(() => {\n return Promise.reject(new Error(\"test\"));\n });\n\n const result = await apduSender.sendApdu(apdu, false, 100);\n expect(result).toStrictEqual(Left(expectedError));\n });\n\n it(\"should timeout if there are no characteristic.value\", async () => {\n // GetAppAndVersion APDU\n const apdu = new Uint8Array([0xb0, 0x01, 0x00, 0x00, 0x00]);\n const expectedError = new SendApduTimeoutError(\"Abort timeout\");\n\n vi.spyOn(\n manager,\n \"writeCharacteristicWithoutResponseForDevice\",\n ).mockImplementation(\n (_deviceId, _serviceUuid, _writeCmdUuid, _value) => {\n // @ts-expect-error needed for tests\n apduSender.onMonitor({} as Characteristic);\n\n return Promise.resolve({} as Characteristic);\n },\n );\n\n // @ts-expect-error private access for tests\n vi.spyOn(apduSender, \"write\").mockImplementation(() => {\n return Promise.reject(new Error(\"test\"));\n });\n\n const result = await apduSender.sendApdu(apdu, false, 100);\n expect(result).toStrictEqual(Left(expectedError));\n });\n });\n });\n});\n"],
|
|
5
|
+
"mappings": "AAKA,OAGE,yCAAAA,EACA,uCAAAC,EACA,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CACxC,EAED,MAAMY,EAAS,MAAMZ,EAAW,SAASW,EAAM,GAAO,GAAG,EACzD,OAAOC,CAAM,EAAE,cAAcxB,EAAK4B,CAAa,CAAC,CAClD,CAAC,EAED,GAAG,sDAAuD,SAAY,CAEpE,MAAML,EAAO,IAAI,WAAW,CAAC,IAAM,EAAM,EAAM,EAAM,CAAI,CAAC,EACpDK,EAAgB,IAAI7B,EAAqB,eAAe,EAE9D,GAAG,MACDc,EACA,6CACF,EAAE,mBACA,CAACI,EAAWC,EAAcG,EAAeQ,KAEvCjB,EAAW,UAAU,CAAC,CAAmB,EAElC,QAAQ,QAAQ,CAAC,CAAmB,EAE/C,EAGA,GAAG,MAAMA,EAAY,OAAO,EAAE,mBAAmB,IACxC,QAAQ,OAAO,IAAI,MAAM,MAAM,CAAC,CACxC,EAED,MAAMY,EAAS,MAAMZ,EAAW,SAASW,EAAM,GAAO,GAAG,EACzD,OAAOC,CAAM,EAAE,cAAcxB,EAAK4B,CAAa,CAAC,CAClD,CAAC,CACH,CAAC,CACH,CAAC,CACH,CAAC",
|
|
6
6
|
"names": ["defaultApduReceiverServiceStubBuilder", "defaultApduSenderServiceStubBuilder", "DeviceNotInitializedError", "GeneralDmkError", "SendApduTimeoutError", "Left", "Maybe", "Right", "RNBleApduSender", "FRAME_HEADER_SIZE", "LEDGER_MTU", "LoggerPublisherServiceStub", "subscribers", "tag", "logger", "apduSenderFactory", "apduReceiverFactory", "apduSender", "manager", "cancelConnection", "dependencies", "newDependencies", "_deviceId", "_serviceUuid", "_notifyUuid", "callback", "_writeCmdUuid", "value", "apdu", "result", "expectedResponse", "statusCode", "response", "expectedError", "_value"]
|
|
7
7
|
}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{PermissionsAndroid as f,Platform as g}from"react-native";import{BleManager as T}from"react-native-ble-plx";import{DeviceConnectionStateMachine as C,OpeningConnectionError as B,ReconnectionFailedError as N,TransportConnectedDevice as h,UnknownDeviceError as b}from"@ledgerhq/device-management-kit";import{EitherAsync as u,Maybe as o,Nothing as A,Right as _}from"purify-ts";import{delay as E,EMPTY as w,from as v,map as O,mergeWith as M,Observable as S,repeat as R,retry as L,switchMap as l,throwError as F,timer as P}from"rxjs";import{BLE_DISCONNECT_TIMEOUT as m,CONNECTION_LOST_DELAY as U,DEFAULT_MTU as y}from"../model/Const";import{BleNotSupported as H,DeviceConnectionNotFound as x,InternalDeviceNotFound as z}from"../model/Errors";import{RNBleApduSender as q}from"../transport/RNBleApduSender";const Q="RN_BLE";class J{constructor(e,i,t,s,n=g,r=f,c=()=>new T,d=p=>new C(p),a=(p,I)=>new q(p,I)){this._deviceModelDataSource=e;this._loggerServiceFactory=i;this._apduSenderFactory=t;this._apduReceiverFactory=s;this._platform=n;this._permissionsAndroid=r;this._deviceConnectionStateMachineFactory=d;this._deviceApduSenderFactory=a;this._logger=i("ReactNativeBleTransport"),this._manager=c(),this._isSupported=o.zero(),this._internalDevicesById=new Map,this._deviceConnectionsById=new Map,this.requestPermission(),this._reconnectionSubscription=o.zero(),this._lastScanTimestamp=o.zero()}_logger;_isSupported;_internalDevicesById;_deviceConnectionsById;_manager;identifier="RN_BLE";_reconnectionSubscription;_lastScanTimestamp;_disconnectHandlersById=new Map;_startDiscovering(){const e=this._deviceModelDataSource.getBluetoothServices();return v(this.requestPermission()).pipe(l(i=>{if(!i)throw new H("BLE not supported");return this._discoverKnownDevices(e)}),M(this._discoverNewDevices(e)))}startDiscovering(){return this._startDiscovering()}async stopDiscovering(){await this._manager.stopDeviceScan()}async connect(e){const i=this._deviceConnectionsById.get(e.deviceId);if(i){const t=this._internalDevicesById.get(e.deviceId);return _(new h({id:e.deviceId,deviceModel:t.discoveredDevice.deviceModel,type:"BLE",sendApdu:(...s)=>i.sendApdu(...s),transport:this.identifier}))}return await this._safeCancel(e.deviceId),await this._manager.stopDeviceScan(),u(async({liftEither:t,throwE:s})=>{const n=await t(o.fromNullable(this._internalDevicesById.get(e.deviceId)).toEither(new b(`Unknown device ${e.deviceId}`)));this._disconnectHandlersById.set(n.id,e.onDisconnect);let r;try{r=await this._manager.connectToDevice(e.deviceId,{requestMTU:y}),await this._manager.discoverAllServicesAndCharacteristicsForDevice(e.deviceId)}catch(a){return s(new B(a))}const c=this._deviceApduSenderFactory({apduSenderFactory:this._apduSenderFactory,apduReceiverFactory:this._apduReceiverFactory,dependencies:{device:r,internalDevice:n,manager:this._manager}},this._loggerServiceFactory),d=this._deviceConnectionStateMachineFactory({deviceId:e.deviceId,deviceApduSender:c,timeoutDuration:m,onTerminated:()=>{const a=this._disconnectHandlersById.get(e.deviceId);a&&a(e.deviceId),this._deviceConnectionsById.delete(e.deviceId),this._internalDevicesById.get(e.deviceId)?.disconnectionSubscription.remove()}});return await c.setupConnection(),this._deviceConnectionsById.set(e.deviceId,d),n.disconnectionSubscription=this._manager.onDeviceDisconnected(e.deviceId,(...a)=>this._handleDeviceDisconnected(...a)),n.lastDiscoveredTimeStamp=o.zero(),new h({id:n.id,deviceModel:n.discoveredDevice.deviceModel,type:"BLE",sendApdu:(...a)=>d.sendApdu(...a),transport:this.identifier})}).run()}async disconnect(e){const i=e.connectedDevice.id;o.fromNullable(this._deviceConnectionsById.get(i)).map(r=>r.closeConnection()),this._deviceConnectionsById.delete(i);const s=this._internalDevicesById.get(i);s&&(s.disconnectionSubscription.remove(),this._internalDevicesById.delete(i)),this._reconnectionSubscription.isJust()&&(this._reconnectionSubscription.map(r=>r.unsubscribe()),this._reconnectionSubscription=o.zero()),await this._safeCancel(i);const n=this._disconnectHandlersById.get(i);return n&&(n(i),this._disconnectHandlersById.delete(i)),Promise.resolve(_(void 0))}listenToAvailableDevices(){const e={};return this._startDiscovering().pipe(O(i=>(e[i.id]=i,Object.values(e).filter(t=>t.rssi!==null))))}isSupported(){return this._isSupported.caseOf({Just:e=>e,Nothing:()=>{throw new Error("Should initialize permission")}})}getIdentifier(){return this.identifier}async requestPermission(){if(this._platform.OS==="ios")return this._isSupported=o.of(!0),!0;if(this._platform.OS==="android"&&this._permissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION){if(parseInt(this._platform.Version.toString(),10)<31){const i=await this._permissionsAndroid.request(this._permissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION);this._isSupported=o.of(i===this._permissionsAndroid.RESULTS.GRANTED)}if(this._permissionsAndroid.PERMISSIONS.BLUETOOTH_SCAN&&this._permissionsAndroid.PERMISSIONS.BLUETOOTH_CONNECT){const i=await this._permissionsAndroid.requestMultiple([this._permissionsAndroid.PERMISSIONS.BLUETOOTH_SCAN,this._permissionsAndroid.PERMISSIONS.BLUETOOTH_CONNECT,this._permissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION]);return this._isSupported=o.of(i["android.permission.BLUETOOTH_CONNECT"]===this._permissionsAndroid.RESULTS.GRANTED&&i["android.permission.BLUETOOTH_SCAN"]===this._permissionsAndroid.RESULTS.GRANTED&&i["android.permission.ACCESS_FINE_LOCATION"]===this._permissionsAndroid.RESULTS.GRANTED),!0}}return this._logger.error("Permission have not been granted",{data:{isSupported:this._isSupported.extract()}}),this._isSupported=o.of(!1),!1}_getDiscoveredDeviceFrom(e,i){const t=o.fromNullable(o.fromNullable(e?.serviceUUIDs?.find(n=>i.includes(n))).orDefaultLazy(()=>o.fromNullable(this._internalDevicesById.get(e.id)).mapOrDefault(n=>n.bleDeviceInfos.serviceUuid,""))),s=o.fromNullable(this._internalDevicesById.get(e.id));return s.isJust()?s.map(n=>({bleDeviceInfos:n.bleDeviceInfos,discoveredDevice:{...n.discoveredDevice,rssi:e.rssi||void 0}})):t.mapOrDefault(n=>{const r=this._deviceModelDataSource.getBluetoothServicesInfos();return o.fromNullable(r[n]).map(d=>({discoveredDevice:{id:e.id,name:e.localName||d.deviceModel.productName,deviceModel:d.deviceModel,transport:this.identifier,rssi:e.rssi||void 0},bleDeviceInfos:d}))},A)}_isDiscoveredDeviceDelayOver(e){return e.lastDiscoveredTimeStamp.caseOf({Just:i=>Date.now()>i+U,Nothing:()=>!1})}async _handleLostDiscoveredDevices(e){for(const i of this._internalDevicesById.values())this._isDiscoveredDeviceDelayOver(i)&&!await this._manager.isDeviceConnected(i.id)&&(this._internalDevicesById.delete(i.id),e.next({...i.discoveredDevice,rssi:null}))}_emitDiscoveredDevice(e,i,t){e.next(t);const s={id:t.id,bleDeviceInfos:i,discoveredDevice:t,lastDiscoveredTimeStamp:o.of(Date.now())};this._internalDevicesById.set(t.id,{...s,disconnectionSubscription:this._manager.onDeviceDisconnected(t.id,()=>{e.next({...t,rssi:null})})})}_discoverNewDevices(e){return this._lastScanTimestamp.mapOrDefault(i=>Date.now()-i<5e3,!1)?v([...this._internalDevicesById.values()].map(i=>i.discoveredDevice)):new S(i=>(this._lastScanTimestamp=o.of(Date.now()),this._manager.startDeviceScan(null,{allowDuplicates:!0},(t,s)=>{if(t||!s){i.error(t);return}this._getDiscoveredDeviceFrom(s,e).map(({discoveredDevice:n,bleDeviceInfos:r})=>{this._emitDiscoveredDevice(i,r,n)}),this._handleLostDiscoveredDevices(i)}),{unsubscribe:async()=>{await this._manager.stopDeviceScan(),i.unsubscribe()}}))}_discoverKnownDevices(e){return v(this._manager.connectedDevices(e)).pipe(l(i=>new S(t=>{for(const s of i)s.readRSSI().then(n=>{n.discoverAllServicesAndCharacteristics().then(r=>{r.services().then(()=>{this._getDiscoveredDeviceFrom(r,e).map(({bleDeviceInfos:c,discoveredDevice:d})=>{this._emitDiscoveredDevice(t,c,d)})})})})})),R({delay:m/5}))}_handleDeviceDisconnected(e,i){if(!i){this._logger.debug("[_handleDeviceDisconnected] disconnected handler didn't find device");return}if(!i?.id||!this._deviceConnectionsById.has(i?.id))return;if(e){this._logger.error("device disconnected error",{data:{error:e,device:i}});return}const t=i.id;if(this._reconnectionSubscription.isJust())return;o.fromNullable(this._deviceConnectionsById.get(t)).map(r=>r.eventDeviceDetached());const s=this._internalDevicesById.get(t);s&&s.disconnectionSubscription.remove();const n=v([0]).pipe(l(async()=>{await this._safeCancel(t)}),E(2e3),l(async()=>{await this._manager.stopDeviceScan();const r=await this._manager.connectToDevice(t,{requestMTU:y}).then(async c=>await c.discoverAllServicesAndCharacteristics());return await this._handleDeviceReconnected(r),r}),L({delay:(r,c)=>r?F(()=>new N(r)):c===5?w:P(0)}));this._reconnectionSubscription=o.of(n.subscribe({next:r=>this._logger.debug("[_handleDeviceDisconnected] Reconnected to device",{data:{id:r.id}}),complete:()=>{this._reconnectionSubscription=o.zero()},error:r=>{this._logger.error("[_handleDeviceDisconnected] All reconnection attempts failed",{data:{e:r}}),o.fromNullable(this._deviceConnectionsById.get(t)).map(c=>c.closeConnection()),this._reconnectionSubscription=o.zero()}}))}async _handleDeviceReconnected(e){const i=o.fromNullable(this._deviceConnectionsById.get(e.id)).toEither(new x),t=o.fromNullable(this._internalDevicesById.get(e.id)).toEither(new z);return u(async({liftEither:s})=>{const n=await s(i),r=await s(t);n.setDependencies({device:e,manager:this._manager,internalDevice:r}),await n.setupConnection(),n.eventDeviceAttached()}).run()}async _safeCancel(e){typeof this._manager.cancelDeviceConnection=="function"&&await this._manager.cancelDeviceConnection(e).catch(i=>this._logger.error("[_safeCancel] cancelDeviceConnection failed",{data:{e:i}}))}}const X=({deviceModelDataSource:D,loggerServiceFactory:e,apduSenderServiceFactory:i,apduReceiverServiceFactory:t})=>new J(D,e,i,t);export{J as RNBleTransport,X as RNBleTransportFactory,Q as rnBleTransportIdentifier};
|
|
1
|
+
import{PermissionsAndroid as N,Platform as f}from"react-native";import{BleError as A,BleManager as B,State as M}from"react-native-ble-plx";import{DeviceConnectionStateMachine as w,OpeningConnectionError as I,TransportConnectedDevice as b,UnknownDeviceError as O}from"@ledgerhq/device-management-kit";import{Either as y,EitherAsync as T,Left as R,Maybe as s,Nothing as u,Right as h}from"purify-ts";import{BehaviorSubject as S,filter as U,finalize as L,from as D,map as F,retry as P,switchMap as p,throttleTime as j,throwError as x}from"rxjs";import{BLE_DISCONNECT_TIMEOUT_ANDROID as z,BLE_DISCONNECT_TIMEOUT_IOS as H,CONNECTION_LOST_DELAY as q,DEFAULT_MTU as C}from"../model/Const";import{BleNotSupported as k,DeviceConnectionNotFound as G,NoDeviceModelFoundError as J,PeerRemovedPairingError as $}from"../model/Errors";import{RNBleApduSender as V}from"../transport/RNBleApduSender";const te="RN_BLE";class Y{constructor(e,i,n,c,r,t=f,v=N,a=d=>new w(d),g=(d,l)=>new V(d,l)){this._deviceModelDataSource=e;this._loggerServiceFactory=i;this._apduSenderFactory=n;this._apduReceiverFactory=c;this._manager=r;this._platform=t;this._permissionsAndroid=v;this._deviceConnectionStateMachineFactory=a;this._deviceApduSenderFactory=g;this._logger=i("ReactNativeBleTransport"),this._isSupported=s.zero(),this._deviceConnectionsById=new Map,this._reconnectionSubscription=s.zero(),this._manager.onStateChange(d=>{this._bleStateSubject.next(d)},!0)}_logger;_isSupported;_deviceConnectionsById;identifier="RN_BLE";_reconnectionSubscription;_bleStateSubject=new S(M.Unknown);startDiscovering(){return D([])}async stopDiscovering(){await this._stopScanning()}_maybeScanningSubject=u;_scannedDevicesSubject=new S([]);_startedScanningSubscriber=void 0;_startScanning(){this._startedScanningSubscriber==null&&(this._scannedDevicesSubject.next([]),this._startedScanningSubscriber=D(this._bleStateSubject).pipe(U(e=>e==="PoweredOn"),p(()=>this.requestPermission()),p(e=>{if(!e)return x(()=>new k("BLE not supported"));const i=new S([]);this._maybeScanningSubject=s.of(i);const n=new Map;this._logger.info("[RNBleTransport][startScanning] startDeviceScan"),this._manager.startDeviceScan(this._deviceModelDataSource.getBluetoothServices(),{allowDuplicates:!0},(r,t)=>{if(r||!t){i.error(r||new Error("scan error"));return}n.set(t.id,{device:t,timestamp:Date.now()}),i.next(Array.from(n.values()))});const c=setInterval(()=>{i.next(Array.from(n.values()))},1e3);return i.asObservable().pipe(L(()=>{this._logger.debug("[RNBleTransport][startScanning] finalize"),i.complete(),clearInterval(c),this._maybeScanningSubject=u,this._manager.stopDeviceScan()}))}),j(1e3)).subscribe({next:e=>{this._logger.debug("[RNBleTransport][startScanning] onNext called with devices",{data:{devices:e}}),this._scannedDevicesSubject.next(e)},error:e=>{this._logger.error("Error while scanning",{data:{error:e}})}}))}async _stopScanning(){this._maybeScanningSubject.map(e=>{e.complete(),this._maybeScanningSubject=u}),await this._manager.stopDeviceScan(),this._startedScanningSubscriber?.unsubscribe(),this._startedScanningSubscriber=void 0}listenToAvailableDevices(){return this._startScanning(),this._scannedDevicesSubject.asObservable().pipe(F(e=>{const i=Array.from(this._deviceConnectionsById.values()).map(t=>this._mapDeviceToTransportDiscoveredDevice(t.getDependencies().device,[t.getDependencies().internalDevice.bleDeviceInfos.serviceUuid])),n=y.rights(i),c=e.filter(({timestamp:t})=>t>Date.now()-q).sort((t,v)=>(v.device.rssi??-1/0)-(t.device.rssi??-1/0)).map(({device:t})=>this._mapDeviceToTransportDiscoveredDevice(t,t.serviceUUIDs)).filter(t=>!!t),r=y.rights(c);return[...n,...r]}))}_mapServicesUUIDsToBluetoothDeviceInfo(e){for(const i of e||[]){const n=this._deviceModelDataSource.getBluetoothServicesInfos()[i];if(n)return h(n)}return R(new J(`No device model found for [uuids=${e}]`))}_mapServicesUUIDsToDeviceModel(e){return this._mapServicesUUIDsToBluetoothDeviceInfo(e).map(n=>n.deviceModel)}_mapDeviceToTransportDiscoveredDevice(e,i){return this._mapServicesUUIDsToDeviceModel(i).map(c=>({id:e.id,name:e.localName||e.name||"",deviceModel:c,transport:this.identifier,rssi:e.rssi||void 0}))}async connect(e){const i=this._deviceConnectionsById.get(e.deviceId);if(i){const n=i.getDependencies().internalDevice.bleDeviceInfos.deviceModel;return h(new b({id:e.deviceId,deviceModel:n,type:"BLE",sendApdu:(...c)=>i.sendApdu(...c),transport:this.identifier}))}return await this._stopScanning(),await this._safeCancel(e.deviceId),T(async({throwE:n})=>{let c,r=[];try{await this._manager.connectToDevice(e.deviceId,{requestMTU:C}),c=await this._manager.discoverAllServicesAndCharacteristicsForDevice(e.deviceId),r=(await c.services()).map(o=>o.uuid)}catch(o){return o instanceof A&&o.iosErrorCode===14?n(new $(o)):n(new I(o))}const t=this._manager.onDeviceDisconnected(c.id,(o,E)=>{this._handleDeviceDisconnected(o,E)}),v=this._mapServicesUUIDsToBluetoothDeviceInfo(r).caseOf({Right:o=>o,Left:o=>n(new I(o))}),a=v.deviceModel,g={id:c.id,bleDeviceInfos:v},d=this._deviceApduSenderFactory({apduSenderFactory:this._apduSenderFactory,apduReceiverFactory:this._apduReceiverFactory,dependencies:{device:c,internalDevice:g,manager:this._manager}},this._loggerServiceFactory),l=f.OS==="ios"?H:z,m=this._deviceConnectionStateMachineFactory({deviceId:e.deviceId,deviceApduSender:d,timeoutDuration:l,onTerminated:()=>{try{this._safeCancel(e.deviceId),e.onDisconnect(e.deviceId),this._deviceConnectionsById.delete(e.deviceId),t.remove(),this._reconnectionSubscription.isJust()&&(this._reconnectionSubscription.map(o=>o.unsubscribe()),this._reconnectionSubscription=s.zero())}catch(o){this._logger.error("Error in termination of device connection",{data:{e:o}})}}});return await d.setupConnection().catch(o=>{throw this._safeCancel(e.deviceId),t.remove(),o}),this._deviceConnectionsById.set(e.deviceId,m),new b({id:c.id,deviceModel:a,type:"BLE",sendApdu:(...o)=>m.sendApdu(...o),transport:this.identifier})}).run()}async disconnect(e){const i=e.connectedDevice.id,n=this._deviceConnectionsById.get(i);if(!n)throw new O(`No connected device found with id ${i}`);return n.closeConnection(),Promise.resolve(h(void 0))}isSupported(){return this._isSupported.caseOf({Just:e=>e,Nothing:()=>{throw new Error("Should initialize permission")}})}getIdentifier(){return this.identifier}async requestPermission(){if(this._platform.OS==="ios")return this._isSupported=s.of(!0),!0;if(this._platform.OS==="android"&&this._permissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION){if(parseInt(this._platform.Version.toString(),10)<31){const i=await this._permissionsAndroid.request(this._permissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION);this._isSupported=s.of(i===this._permissionsAndroid.RESULTS.GRANTED)}if(this._permissionsAndroid.PERMISSIONS.BLUETOOTH_SCAN&&this._permissionsAndroid.PERMISSIONS.BLUETOOTH_CONNECT){const i=await this._permissionsAndroid.requestMultiple([this._permissionsAndroid.PERMISSIONS.BLUETOOTH_SCAN,this._permissionsAndroid.PERMISSIONS.BLUETOOTH_CONNECT,this._permissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION]);return this._isSupported=s.of(i["android.permission.BLUETOOTH_CONNECT"]===this._permissionsAndroid.RESULTS.GRANTED&&i["android.permission.BLUETOOTH_SCAN"]===this._permissionsAndroid.RESULTS.GRANTED&&i["android.permission.ACCESS_FINE_LOCATION"]===this._permissionsAndroid.RESULTS.GRANTED),!0}}return this._logger.error("Permission have not been granted",{data:{isSupported:this._isSupported.extract()}}),this._isSupported=s.of(!1),!1}_handleDeviceDisconnected(e,i){if(this._logger.debug("[RNBLE][_handleDeviceDisconnected]",{data:{error:e,device:i}}),!i){this._logger.debug("[_handleDeviceDisconnected] disconnected handler didn't find device");return}if(!i?.id||!this._deviceConnectionsById.has(i?.id))return;if(e){this._logger.error("device disconnected error",{data:{error:e,device:i}});return}const n=i.id;if(this._reconnectionSubscription.isJust())return;s.fromNullable(this._deviceConnectionsById.get(n)).map(r=>r.eventDeviceDetached());const c=D([0]).pipe(p(async()=>{await this._stopScanning(),await this._safeCancel(n)}),p(async()=>{this._logger.debug("[_handleDeviceDisconnected] reconnecting to device",{data:{id:i.id}});const r=await this._manager.connectToDevice(n,{requestMTU:C,timeout:2e3});this._logger.debug("[_handleDeviceDisconnected] reconnected to device",{data:{id:i.id}});const t=await r.discoverAllServicesAndCharacteristics();return this._logger.debug("[_handleDeviceDisconnected] discovered all services and characteristics",{data:{reconnectedDeviceUsable:t}}),await this._handleDeviceReconnected(t),t}),P(5));this._reconnectionSubscription=s.of(c.subscribe({next:r=>this._logger.debug("[_handleDeviceDisconnected] Reconnected to device",{data:{id:r.id}}),complete:()=>{this._reconnectionSubscription=s.zero()},error:r=>{this._logger.error("[_handleDeviceDisconnected] All reconnection attempts failed",{data:{e:r}}),s.fromNullable(this._deviceConnectionsById.get(n)).map(t=>t.closeConnection()),this._reconnectionSubscription=s.zero()}}))}async _handleDeviceReconnected(e){const i=s.fromNullable(this._deviceConnectionsById.get(e.id)).toEither(new G);return T(async({liftEither:n,throwE:c})=>{const r=await n(i),t=(await e.services()).map(a=>a.uuid),v=this._mapServicesUUIDsToBluetoothDeviceInfo(t).caseOf({Right:a=>({id:e.id,bleDeviceInfos:a}),Left:a=>(this._logger.error("Error in mapping services UUIDs to Bluetooth device info",{data:{error:a}}),c(a))});r.setDependencies({device:e,manager:this._manager,internalDevice:v}),await r.setupConnection().catch(a=>{throw this._safeCancel(e.id),a}),r.eventDeviceAttached()}).run()}async _safeCancel(e){if(typeof this._manager.cancelDeviceConnection=="function"){const i=await this._manager.connectedDevices(this._deviceModelDataSource.getBluetoothServices());for(const n of i)n.id===e&&await this._manager.cancelDeviceConnection(e)}}}const re=({deviceModelDataSource:_,loggerServiceFactory:e,apduSenderServiceFactory:i,apduReceiverServiceFactory:n})=>new Y(_,e,i,n,new B);export{Y as RNBleTransport,re as RNBleTransportFactory,te as rnBleTransportIdentifier};
|
|
2
2
|
//# sourceMappingURL=RNBleTransport.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/api/transport/RNBleTransport.ts"],
|
|
4
|
-
"sourcesContent": ["import { PermissionsAndroid, Platform } from \"react-native\";\nimport { type BleError, BleManager, type Device } from \"react-native-ble-plx\";\nimport {\n type ApduReceiverServiceFactory,\n type ApduSenderServiceFactory,\n type BleDeviceInfos,\n type ConnectError,\n DeviceConnectionStateMachine,\n type DeviceConnectionStateMachineParams,\n type DeviceId,\n type DeviceModelDataSource,\n type DisconnectHandler,\n type DmkError,\n type LoggerPublisherService,\n OpeningConnectionError,\n ReconnectionFailedError,\n type Transport,\n TransportConnectedDevice,\n type TransportDiscoveredDevice,\n type TransportFactory,\n type TransportIdentifier,\n UnknownDeviceError,\n} from \"@ledgerhq/device-management-kit\";\nimport { type Either, EitherAsync, Maybe, Nothing, Right } from \"purify-ts\";\nimport {\n delay,\n EMPTY,\n from,\n map,\n mergeWith,\n Observable,\n repeat,\n retry,\n type Subscriber,\n type Subscription,\n switchMap,\n throwError,\n timer,\n} from \"rxjs\";\n\nimport {\n BLE_DISCONNECT_TIMEOUT,\n CONNECTION_LOST_DELAY,\n DEFAULT_MTU,\n} from \"@api/model/Const\";\nimport {\n BleNotSupported,\n DeviceConnectionNotFound,\n InternalDeviceNotFound,\n} from \"@api/model/Errors\";\nimport {\n RNBleApduSender,\n type RNBleApduSenderConstructorArgs,\n type RNBleApduSenderDependencies,\n type RNBleInternalDevice,\n} from \"@api/transport/RNBleApduSender\";\n\nexport const rnBleTransportIdentifier = \"RN_BLE\";\n\nexport class RNBleTransport implements Transport {\n private _logger: LoggerPublisherService;\n private _isSupported: Maybe<boolean>;\n private _internalDevicesById: Map<DeviceId, RNBleInternalDevice>;\n private _deviceConnectionsById: Map<\n DeviceId,\n DeviceConnectionStateMachine<RNBleApduSenderDependencies>\n >;\n private readonly _manager: BleManager;\n private readonly identifier: TransportIdentifier = \"RN_BLE\";\n private _reconnectionSubscription: Maybe<Subscription>;\n private _lastScanTimestamp: Maybe<number>;\n private _disconnectHandlersById: Map<DeviceId, DisconnectHandler> = new Map();\n\n constructor(\n private readonly _deviceModelDataSource: DeviceModelDataSource,\n private readonly _loggerServiceFactory: (\n tag: string,\n ) => LoggerPublisherService,\n private readonly _apduSenderFactory: ApduSenderServiceFactory,\n private readonly _apduReceiverFactory: ApduReceiverServiceFactory,\n private readonly _platform: Platform = Platform,\n private readonly _permissionsAndroid: PermissionsAndroid = PermissionsAndroid,\n _bleManagerFactory: () => BleManager = () => new BleManager(),\n private readonly _deviceConnectionStateMachineFactory: (\n args: DeviceConnectionStateMachineParams<RNBleApduSenderDependencies>,\n ) => DeviceConnectionStateMachine<RNBleApduSenderDependencies> = (args) =>\n new DeviceConnectionStateMachine(args),\n private readonly _deviceApduSenderFactory: (\n args: RNBleApduSenderConstructorArgs,\n loggerFactory: (tag: string) => LoggerPublisherService,\n ) => RNBleApduSender = (args, loggerFactory) =>\n new RNBleApduSender(args, loggerFactory),\n ) {\n this._logger = _loggerServiceFactory(\"ReactNativeBleTransport\");\n this._manager = _bleManagerFactory();\n this._isSupported = Maybe.zero();\n this._internalDevicesById = new Map();\n this._deviceConnectionsById = new Map();\n this.requestPermission();\n this._reconnectionSubscription = Maybe.zero();\n this._lastScanTimestamp = Maybe.zero();\n }\n\n private _startDiscovering() {\n const ledgerUuids = this._deviceModelDataSource.getBluetoothServices();\n return from(this.requestPermission()).pipe(\n switchMap((isSupported) => {\n if (!isSupported) {\n throw new BleNotSupported(\"BLE not supported\");\n }\n return this._discoverKnownDevices(ledgerUuids);\n }),\n mergeWith(this._discoverNewDevices(ledgerUuids)),\n );\n }\n\n /**\n * Starts the discovery process to find Bluetooth devices that match specific criteria.\n *\n * This method clears the internal device cache and requests necessary permissions\n * before initiating the discovery of both known and new devices. If the Bluetooth\n * Low Energy (BLE) feature is not supported, an error is thrown.\n *\n * @return {Observable<TransportDiscoveredDevice>} An observable emitting discovered devices\n * that match the specified Bluetooth services.\n */\n startDiscovering(): Observable<TransportDiscoveredDevice> {\n return this._startDiscovering();\n }\n\n /**\n * Stops the device scanning operation currently in progress.\n *\n * @return {Promise<void>} A promise that resolves once the device scanning has been successfully stopped.\n */\n async stopDiscovering(): Promise<void> {\n await this._manager.stopDeviceScan();\n }\n\n /**\n * Establishes a connection to a device and configures the necessary parameters for communication.\n *\n * @param {Object} params - An object containing parameters required for the connection.\n * @param {DeviceId} params.deviceId - The unique identifier of the device to connect to.\n * @param {DisconnectHandler} params.onDisconnect - A callback function to handle device disconnection.\n * @returns {Promise<Either<ConnectError, TransportConnectedDevice>>} A promise resolving to either a connection error or a successfully connected device.\n */\n async connect(params: {\n deviceId: DeviceId;\n onDisconnect: DisconnectHandler;\n }): Promise<Either<ConnectError, TransportConnectedDevice>> {\n const existing = this._deviceConnectionsById.get(params.deviceId);\n if (existing) {\n const cachedDevice = this._internalDevicesById.get(params.deviceId)!;\n return Right(\n new TransportConnectedDevice({\n id: params.deviceId,\n deviceModel: cachedDevice.discoveredDevice.deviceModel,\n type: \"BLE\",\n sendApdu: (...a) => existing.sendApdu(...a),\n transport: this.identifier,\n }),\n );\n }\n\n await this._safeCancel(params.deviceId);\n\n await this._manager.stopDeviceScan();\n\n return EitherAsync<ConnectError, TransportConnectedDevice>(\n async ({ liftEither, throwE }) => {\n const internalDevice = await liftEither(\n Maybe.fromNullable(\n this._internalDevicesById.get(params.deviceId),\n ).toEither(\n new UnknownDeviceError(`Unknown device ${params.deviceId}`),\n ),\n );\n\n this._disconnectHandlersById.set(\n internalDevice.id,\n params.onDisconnect,\n );\n\n let device: Device;\n try {\n device = await this._manager.connectToDevice(params.deviceId, {\n requestMTU: DEFAULT_MTU,\n });\n\n await this._manager.discoverAllServicesAndCharacteristicsForDevice(\n params.deviceId,\n );\n } catch (error) {\n return throwE(new OpeningConnectionError(error));\n }\n\n const deviceApduSender = this._deviceApduSenderFactory(\n {\n apduSenderFactory: this._apduSenderFactory,\n apduReceiverFactory: this._apduReceiverFactory,\n dependencies: { device, internalDevice, manager: this._manager },\n },\n this._loggerServiceFactory,\n );\n\n const deviceConnectionStateMachine =\n this._deviceConnectionStateMachineFactory({\n deviceId: params.deviceId,\n deviceApduSender,\n timeoutDuration: BLE_DISCONNECT_TIMEOUT,\n onTerminated: () => {\n const handler = this._disconnectHandlersById.get(params.deviceId);\n if (handler) handler(params.deviceId);\n this._deviceConnectionsById.delete(params.deviceId);\n this._internalDevicesById\n .get(params.deviceId)\n ?.disconnectionSubscription.remove();\n },\n });\n\n await deviceApduSender.setupConnection();\n\n this._deviceConnectionsById.set(\n params.deviceId,\n deviceConnectionStateMachine,\n );\n\n internalDevice.disconnectionSubscription =\n this._manager.onDeviceDisconnected(params.deviceId, (...args) =>\n this._handleDeviceDisconnected(...args),\n );\n\n internalDevice.lastDiscoveredTimeStamp = Maybe.zero();\n\n return new TransportConnectedDevice({\n id: internalDevice.id,\n deviceModel: internalDevice.discoveredDevice.deviceModel,\n type: \"BLE\",\n sendApdu: (...args) => deviceConnectionStateMachine.sendApdu(...args),\n transport: this.identifier,\n });\n },\n ).run();\n }\n\n /**\n * Terminates the connection with the connected device and cleans up related resources.\n *\n * @param {TransportConnectedDevice} params.connectedDevice - The connected device to be disconnected.\n * @return {Promise<Either<DmkError, void>>} A promise resolving to either a success (void) or a failure (DmkError) value.\n */\n async disconnect(params: {\n connectedDevice: TransportConnectedDevice;\n }): Promise<Either<DmkError, void>> {\n const deviceId = params.connectedDevice.id;\n const machineM = Maybe.fromNullable(\n this._deviceConnectionsById.get(deviceId),\n );\n machineM.map((sm) => sm.closeConnection());\n this._deviceConnectionsById.delete(deviceId);\n\n const internal = this._internalDevicesById.get(deviceId);\n if (internal) {\n internal.disconnectionSubscription.remove();\n this._internalDevicesById.delete(deviceId);\n }\n\n if (this._reconnectionSubscription.isJust()) {\n this._reconnectionSubscription.map((sub) => sub.unsubscribe());\n this._reconnectionSubscription = Maybe.zero();\n }\n\n await this._safeCancel(deviceId);\n\n const handler = this._disconnectHandlersById.get(deviceId);\n if (handler) {\n handler(deviceId);\n this._disconnectHandlersById.delete(deviceId);\n }\n\n return Promise.resolve(Right(undefined));\n }\n\n /**\n * Listens to known devices and emits updates when new devices are discovered or when properties of existing devices are updated.\n *\n * @return {Observable<TransportDiscoveredDevice[]>} An observable stream of discovered devices, containing device information as an array of TransportDiscoveredDevice objects.\n */\n listenToAvailableDevices(): Observable<TransportDiscoveredDevice[]> {\n const scannedDeviceMap: Record<DeviceId, TransportDiscoveredDevice> = {};\n return this._startDiscovering().pipe(\n map((discoveredDevice) => {\n scannedDeviceMap[discoveredDevice.id] = discoveredDevice;\n return Object.values(scannedDeviceMap).filter(\n (device) => device.rssi !== null,\n );\n }),\n );\n }\n\n /**\n * Determines if the feature or permission is supported.\n *\n * This method evaluates the current state of the `_isSupported` property to determine\n * whether the relevant feature is supported or throws an error if its state has\n * not been initialized properly.\n *\n * @return {boolean} Returns `true` if the feature is supported, otherwise `false`.\n * Throws an error if the `_isSupported` property has not been initialized.\n */\n isSupported(): boolean {\n return this._isSupported.caseOf({\n Just: (isSupported) => isSupported,\n Nothing: () => {\n throw new Error(\"Should initialize permission\");\n },\n });\n }\n\n /**\n * Retrieves the transport identifier associated with the object.\n *\n * @return {TransportIdentifier} The transport identifier.\n */\n getIdentifier(): TransportIdentifier {\n return this.identifier;\n }\n\n /**\n * Requests the necessary permissions based on the operating system.\n * For iOS, it automatically sets the permissions as granted.\n * For Android, it checks and requests location, Bluetooth scan, and Bluetooth connect permissions, depending on the API level.\n * If permissions are granted, updates the internal support state and logs the result.\n *\n * @return {Promise<boolean>} A promise that resolves to true if the required permissions are granted, otherwise false.\n */\n async requestPermission(): Promise<boolean> {\n if (this._platform.OS === \"ios\") {\n this._isSupported = Maybe.of(true);\n return true;\n }\n\n if (\n this._platform.OS === \"android\" &&\n this._permissionsAndroid.PERMISSIONS[\"ACCESS_FINE_LOCATION\"]\n ) {\n const apiLevel = parseInt(this._platform.Version.toString(), 10);\n\n if (apiLevel < 31) {\n const granted = await this._permissionsAndroid.request(\n this._permissionsAndroid.PERMISSIONS[\"ACCESS_FINE_LOCATION\"],\n );\n this._isSupported = Maybe.of(\n granted === this._permissionsAndroid.RESULTS[\"GRANTED\"],\n );\n }\n if (\n this._permissionsAndroid.PERMISSIONS[\"BLUETOOTH_SCAN\"] &&\n this._permissionsAndroid.PERMISSIONS[\"BLUETOOTH_CONNECT\"]\n ) {\n const result = await this._permissionsAndroid.requestMultiple([\n this._permissionsAndroid.PERMISSIONS[\"BLUETOOTH_SCAN\"],\n this._permissionsAndroid.PERMISSIONS[\"BLUETOOTH_CONNECT\"],\n this._permissionsAndroid.PERMISSIONS[\"ACCESS_FINE_LOCATION\"],\n ]);\n\n this._isSupported = Maybe.of(\n result[\"android.permission.BLUETOOTH_CONNECT\"] ===\n this._permissionsAndroid.RESULTS[\"GRANTED\"] &&\n result[\"android.permission.BLUETOOTH_SCAN\"] ===\n this._permissionsAndroid.RESULTS[\"GRANTED\"] &&\n result[\"android.permission.ACCESS_FINE_LOCATION\"] ===\n this._permissionsAndroid.RESULTS[\"GRANTED\"],\n );\n\n return true;\n }\n }\n\n this._logger.error(\"Permission have not been granted\", {\n data: { isSupported: this._isSupported.extract() },\n });\n\n this._isSupported = Maybe.of(false);\n return false;\n }\n\n /**\n * Retrieves a discovered device and its BLE device information, if available, from the provided input.\n *\n * @param {Device} rnDevice - The Bluetooth device to analyze for discovery.\n * @param {string[]} ledgerUuids - A list of UUIDs associated with the target Ledger devices.\n * @return {Maybe<{ bleDeviceInfos: BleDeviceInfos; discoveredDevice: TransportDiscoveredDevice }>} A Maybe object containing the discovered device and its BLE information, or Nothing if the device or information cannot be determined.\n */\n private _getDiscoveredDeviceFrom(\n rnDevice: Device,\n ledgerUuids: string[],\n ): Maybe<{\n bleDeviceInfos: BleDeviceInfos;\n discoveredDevice: TransportDiscoveredDevice;\n }> {\n const maybeUuid = Maybe.fromNullable(\n Maybe.fromNullable(\n rnDevice?.serviceUUIDs?.find((uuid) => ledgerUuids.includes(uuid)),\n ).orDefaultLazy(() =>\n Maybe.fromNullable(\n this._internalDevicesById.get(rnDevice.id),\n ).mapOrDefault((iDevice) => iDevice.bleDeviceInfos.serviceUuid, \"\"),\n ),\n );\n\n const existingInternalDevice = Maybe.fromNullable(\n this._internalDevicesById.get(rnDevice.id),\n );\n\n if (existingInternalDevice.isJust()) {\n return existingInternalDevice.map((internalDevice) => ({\n bleDeviceInfos: internalDevice.bleDeviceInfos,\n discoveredDevice: {\n ...internalDevice.discoveredDevice,\n rssi: rnDevice.rssi || undefined,\n },\n }));\n }\n\n return maybeUuid.mapOrDefault((uuid) => {\n const serviceToBleInfos =\n this._deviceModelDataSource.getBluetoothServicesInfos();\n const maybeBleDeviceInfos = Maybe.fromNullable(serviceToBleInfos[uuid]);\n\n return maybeBleDeviceInfos.map((bleDeviceInfos) => {\n const discoveredDevice: TransportDiscoveredDevice = {\n id: rnDevice.id,\n name: rnDevice.localName || bleDeviceInfos.deviceModel.productName,\n deviceModel: bleDeviceInfos.deviceModel,\n transport: this.identifier,\n rssi: rnDevice.rssi || undefined,\n };\n\n return {\n discoveredDevice,\n bleDeviceInfos,\n };\n });\n }, Nothing);\n }\n\n /**\n * Determines whether the delay since the device was last discovered has exceeded a predefined threshold.\n *\n * @param {RNBleInternalDevice} internalDevice - The internal device object containing the last discovered timestamp.\n * @return {boolean} - Returns true if the delay is over, otherwise false.\n */\n private _isDiscoveredDeviceDelayOver(internalDevice: RNBleInternalDevice) {\n return internalDevice.lastDiscoveredTimeStamp.caseOf({\n Just: (lastDiscoveredTimeStamp) => {\n return Date.now() > lastDiscoveredTimeStamp + CONNECTION_LOST_DELAY;\n },\n Nothing: () => {\n return false;\n },\n });\n }\n\n /**\n * Handles the processing of devices that have been determined to be \"lost\" by iterating\n * through a collection of internal devices, identifying lost devices, updating their status,\n * and notifying a subscriber about the change.\n *\n * @param {Subscriber<TransportDiscoveredDevice>} subscriber - The observer that will be notified\n * when a device is marked as lost, including updated device information with its availability set to false.\n * @return {void} This method does not return a value.\n */\n private async _handleLostDiscoveredDevices(\n subscriber: Subscriber<TransportDiscoveredDevice>,\n ) {\n for (const internalDevice of this._internalDevicesById.values()) {\n if (\n this._isDiscoveredDeviceDelayOver(internalDevice) &&\n !(await this._manager.isDeviceConnected(internalDevice.id))\n ) {\n this._internalDevicesById.delete(internalDevice.id);\n subscriber.next({\n ...internalDevice.discoveredDevice,\n rssi: null,\n });\n }\n }\n }\n\n /**\n * Emits a discovered device to the provided subscriber and manages internal state\n * for the discovered device, including handling its availability status and disconnection events.\n *\n * @param {Subscriber<TransportDiscoveredDevice>} subscriber The subscriber to emit the discovered device to.\n * @param {BleDeviceInfos} bleDeviceInfos The BLE device information associated with the discovered device.\n * @param {TransportDiscoveredDevice} discoveredDevice The newly discovered device to be emitted.\n * @return {void} */\n private _emitDiscoveredDevice(\n subscriber: Subscriber<TransportDiscoveredDevice>,\n bleDeviceInfos: BleDeviceInfos,\n discoveredDevice: TransportDiscoveredDevice,\n ) {\n subscriber.next(discoveredDevice);\n const internalDevice = {\n id: discoveredDevice.id,\n bleDeviceInfos,\n discoveredDevice,\n lastDiscoveredTimeStamp: Maybe.of(Date.now()),\n };\n this._internalDevicesById.set(discoveredDevice.id, {\n ...internalDevice,\n disconnectionSubscription: this._manager.onDeviceDisconnected(\n discoveredDevice.id,\n () => {\n subscriber.next({\n ...discoveredDevice,\n rssi: null,\n });\n },\n ),\n });\n }\n\n /**\n * Discovers new devices by scanning for BLE devices and filtering them based on the provided ledger UUIDs.\n *\n * @param {string[]} ledgerUuids - An array of UUIDs used to identify relevant ledger devices.\n * @return {Observable<TransportDiscoveredDevice>} An observable that emits discovered devices matching the provided UUIDs.\n */\n private _discoverNewDevices(\n ledgerUuids: string[],\n ): Observable<TransportDiscoveredDevice> {\n if (\n this._lastScanTimestamp.mapOrDefault(\n (lastScanTimestamp) => Date.now() - lastScanTimestamp < 5000,\n false,\n )\n ) {\n return from(\n [...this._internalDevicesById.values()].map(\n (iDevice) => iDevice.discoveredDevice,\n ),\n );\n }\n\n return new Observable<TransportDiscoveredDevice>((subscriber) => {\n this._lastScanTimestamp = Maybe.of(Date.now());\n this._manager.startDeviceScan(\n null,\n { allowDuplicates: true },\n (error, device) => {\n if (error || !device) {\n subscriber.error(error);\n return;\n }\n\n this._getDiscoveredDeviceFrom(device, ledgerUuids).map(\n ({ discoveredDevice, bleDeviceInfos }) => {\n this._emitDiscoveredDevice(\n subscriber,\n bleDeviceInfos,\n discoveredDevice,\n );\n },\n );\n\n this._handleLostDiscoveredDevices(subscriber);\n },\n );\n\n return {\n unsubscribe: async () => {\n await this._manager.stopDeviceScan();\n subscriber.unsubscribe();\n },\n };\n });\n }\n\n /**\n * Discovers and emits known ledger devices based on the provided UUIDs.\n *\n * @param {string[]} ledgerUuids - An array of UUIDs representing the target ledger devices to discover.\n * @return {Observable<TransportDiscoveredDevice>} An Observable that emits discovered devices matching the provided UUIDs.\n */\n private _discoverKnownDevices(\n ledgerUuids: string[],\n ): Observable<TransportDiscoveredDevice> {\n return from(this._manager.connectedDevices(ledgerUuids)).pipe(\n switchMap(\n (devices) =>\n new Observable<TransportDiscoveredDevice>((subscriber) => {\n for (const fromDevice of devices) {\n fromDevice.readRSSI().then((deviceWithRssi) => {\n deviceWithRssi\n .discoverAllServicesAndCharacteristics()\n .then((device) => {\n device.services().then(() => {\n this._getDiscoveredDeviceFrom(device, ledgerUuids).map(\n ({ bleDeviceInfos, discoveredDevice }) => {\n this._emitDiscoveredDevice(\n subscriber,\n bleDeviceInfos,\n discoveredDevice,\n );\n },\n );\n });\n });\n });\n }\n }),\n ),\n repeat({ delay: BLE_DISCONNECT_TIMEOUT / 5 }),\n );\n }\n\n /**\n * Handles the event when a Bluetooth device gets disconnected. This method attempts\n * to reconnect to the device, retries a certain number of times on failure, and\n * invokes a callback if the reconnection does not succeed.\n *\n * @param {BleError | null} error - The error object representing the reason for the disconnection, or null if no error occurred.\n * @param {Device | null} device - The Bluetooth device that was disconnected, or null if no device is provided.\n * @return {void}\n */\n private _handleDeviceDisconnected(\n error: BleError | null,\n device: Device | null,\n ) {\n if (!device) {\n this._logger.debug(\n \"[_handleDeviceDisconnected] disconnected handler didn't find device\",\n );\n return;\n }\n if (!device?.id || !this._deviceConnectionsById.has(device?.id)) return;\n if (error) {\n this._logger.error(\"device disconnected error\", {\n data: { error, device },\n });\n return;\n }\n const deviceId = device.id;\n if (this._reconnectionSubscription.isJust()) {\n return;\n }\n\n Maybe.fromNullable(this._deviceConnectionsById.get(deviceId)).map((sm) =>\n sm.eventDeviceDetached(),\n );\n\n const cachedDevice = this._internalDevicesById.get(deviceId);\n if (cachedDevice) {\n cachedDevice.disconnectionSubscription.remove();\n }\n\n const reconnect$ = from([0]).pipe(\n switchMap(async () => {\n await this._safeCancel(deviceId);\n }),\n delay(2000),\n switchMap(async () => {\n await this._manager.stopDeviceScan();\n const reconnected = await this._manager\n .connectToDevice(deviceId, { requestMTU: DEFAULT_MTU })\n .then(\n async (connectedDevice) =>\n await connectedDevice.discoverAllServicesAndCharacteristics(),\n );\n await this._handleDeviceReconnected(reconnected);\n return reconnected;\n }),\n retry({\n delay: (err, retryCount) => {\n if (err) {\n return throwError(() => new ReconnectionFailedError(err));\n }\n if (retryCount === 5) {\n return EMPTY;\n }\n return timer(0);\n },\n }),\n );\n\n this._reconnectionSubscription = Maybe.of(\n reconnect$.subscribe({\n next: (d) =>\n this._logger.debug(\n \"[_handleDeviceDisconnected] Reconnected to device\",\n { data: { id: d.id } },\n ),\n complete: () => {\n this._reconnectionSubscription = Maybe.zero();\n },\n error: (e) => {\n this._logger.error(\n \"[_handleDeviceDisconnected] All reconnection attempts failed\",\n { data: { e } },\n );\n Maybe.fromNullable(this._deviceConnectionsById.get(deviceId)).map(\n (sm) => sm.closeConnection(),\n );\n this._reconnectionSubscription = Maybe.zero();\n },\n }),\n );\n }\n\n /**\n * Handles the reconnection of a device. Configures the device connection and its corresponding\n * internal device upon reconnection, including updating the connection state, registering\n * callbacks for write and monitor operations, and initiating a reconnect operation.\n *\n * @param {Device} device - The device object that has been reconnected. Contains device details,\n * such as the device ID.\n * @return {Promise<Either<DeviceConnectionNotFound | InternalDeviceNotFound, void>>} A promise that completes when the device reconnection has been fully\n * configured. Resolves with no value or rejects if an error occurs during\n * the reconnection process.\n */\n private async _handleDeviceReconnected(device: Device) {\n const errorOrDeviceConnection = Maybe.fromNullable(\n this._deviceConnectionsById.get(device.id),\n ).toEither(new DeviceConnectionNotFound());\n\n const errorOrInternalDevice = Maybe.fromNullable(\n this._internalDevicesById.get(device.id),\n ).toEither(new InternalDeviceNotFound());\n\n return EitherAsync(async ({ liftEither }) => {\n const deviceConnectionStateMachine = await liftEither(\n errorOrDeviceConnection,\n );\n\n const internalDevice = await liftEither(errorOrInternalDevice);\n\n deviceConnectionStateMachine.setDependencies({\n device,\n manager: this._manager,\n internalDevice,\n });\n\n await deviceConnectionStateMachine.setupConnection();\n\n deviceConnectionStateMachine.eventDeviceAttached();\n }).run();\n }\n\n private async _safeCancel(deviceId: DeviceId) {\n // only invoke if the BleManager under test actually has it\n if (typeof this._manager.cancelDeviceConnection === \"function\") {\n await this._manager.cancelDeviceConnection(deviceId).catch((e) =>\n this._logger.error(\"[_safeCancel] cancelDeviceConnection failed\", {\n data: { e },\n }),\n );\n }\n }\n}\n\nexport const RNBleTransportFactory: TransportFactory = ({\n deviceModelDataSource,\n loggerServiceFactory,\n apduSenderServiceFactory,\n apduReceiverServiceFactory,\n}) =>\n new RNBleTransport(\n deviceModelDataSource,\n loggerServiceFactory,\n apduSenderServiceFactory,\n apduReceiverServiceFactory,\n );\n"],
|
|
5
|
-
"mappings": "AAAA,OAAS,sBAAAA,EAAoB,YAAAC,MAAgB,eAC7C,
|
|
6
|
-
"names": ["PermissionsAndroid", "Platform", "BleManager", "
|
|
4
|
+
"sourcesContent": ["import { PermissionsAndroid, Platform } from \"react-native\";\nimport { BleError, BleManager, type Device, State } from \"react-native-ble-plx\";\nimport {\n type ApduReceiverServiceFactory,\n type ApduSenderServiceFactory,\n type BleDeviceInfos,\n type ConnectError,\n DeviceConnectionStateMachine,\n type DeviceConnectionStateMachineParams,\n type DeviceId,\n type DeviceModelDataSource,\n type DisconnectHandler,\n type DmkError,\n type LoggerPublisherService,\n OpeningConnectionError,\n type Transport,\n TransportConnectedDevice,\n type TransportDeviceModel,\n type TransportDiscoveredDevice,\n type TransportFactory,\n type TransportIdentifier,\n UnknownDeviceError,\n} from \"@ledgerhq/device-management-kit\";\nimport { Either, EitherAsync, Left, Maybe, Nothing, Right } from \"purify-ts\";\nimport {\n BehaviorSubject,\n filter,\n finalize,\n from,\n map,\n type Observable,\n retry,\n type Subscription,\n switchMap,\n throttleTime,\n throwError,\n} from \"rxjs\";\n\nimport {\n BLE_DISCONNECT_TIMEOUT_ANDROID,\n BLE_DISCONNECT_TIMEOUT_IOS,\n CONNECTION_LOST_DELAY,\n DEFAULT_MTU,\n} from \"@api/model/Const\";\nimport {\n BleNotSupported,\n DeviceConnectionNotFound,\n NoDeviceModelFoundError,\n PeerRemovedPairingError,\n} from \"@api/model/Errors\";\nimport {\n RNBleApduSender,\n type RNBleApduSenderConstructorArgs,\n type RNBleApduSenderDependencies,\n type RNBleInternalDevice,\n} from \"@api/transport/RNBleApduSender\";\n\nexport const rnBleTransportIdentifier = \"RN_BLE\";\n\ntype InternalScannedDevice = {\n device: Device;\n timestamp: number;\n};\n\nexport class RNBleTransport implements Transport {\n private _logger: LoggerPublisherService;\n private _isSupported: Maybe<boolean>;\n private _deviceConnectionsById: Map<\n DeviceId,\n DeviceConnectionStateMachine<RNBleApduSenderDependencies>\n >;\n // private readonly _manager: BleManager;\n private readonly identifier: TransportIdentifier = \"RN_BLE\";\n private _reconnectionSubscription: Maybe<Subscription>;\n private readonly _bleStateSubject: BehaviorSubject<State> =\n new BehaviorSubject<State>(State.Unknown);\n\n constructor(\n private readonly _deviceModelDataSource: DeviceModelDataSource,\n private readonly _loggerServiceFactory: (\n tag: string,\n ) => LoggerPublisherService,\n private readonly _apduSenderFactory: ApduSenderServiceFactory,\n private readonly _apduReceiverFactory: ApduReceiverServiceFactory,\n private readonly _manager: BleManager,\n private readonly _platform: Platform = Platform,\n private readonly _permissionsAndroid: PermissionsAndroid = PermissionsAndroid,\n private readonly _deviceConnectionStateMachineFactory: (\n args: DeviceConnectionStateMachineParams<RNBleApduSenderDependencies>,\n ) => DeviceConnectionStateMachine<RNBleApduSenderDependencies> = (args) =>\n new DeviceConnectionStateMachine(args),\n private readonly _deviceApduSenderFactory: (\n args: RNBleApduSenderConstructorArgs,\n loggerFactory: (tag: string) => LoggerPublisherService,\n ) => RNBleApduSender = (args, loggerFactory) =>\n new RNBleApduSender(args, loggerFactory),\n ) {\n this._logger = _loggerServiceFactory(\"ReactNativeBleTransport\");\n this._isSupported = Maybe.zero();\n this._deviceConnectionsById = new Map();\n this._reconnectionSubscription = Maybe.zero();\n this._manager.onStateChange((state) => {\n this._bleStateSubject.next(state);\n }, true);\n }\n\n /**\n * Not implemented for now as the return signature is not really usable.\n * Use listenToAvailableDevices instead.\n */\n startDiscovering(): Observable<TransportDiscoveredDevice> {\n return from([]);\n }\n\n /**\n * Stops the device scanning operation currently in progress.\n *\n * @return {Promise<void>} A promise that resolves once the device scanning has been successfully stopped.\n */\n async stopDiscovering(): Promise<void> {\n await this._stopScanning();\n }\n\n private _maybeScanningSubject: Maybe<\n BehaviorSubject<InternalScannedDevice[]>\n > = Nothing;\n\n private _scannedDevicesSubject: BehaviorSubject<InternalScannedDevice[]> =\n new BehaviorSubject<InternalScannedDevice[]>([]);\n private _startedScanningSubscriber: Subscription | undefined = undefined;\n\n private _startScanning() {\n if (this._startedScanningSubscriber != undefined) {\n return;\n }\n\n //Reset the scanned devices list as new scan will start\n this._scannedDevicesSubject.next([]);\n\n this._startedScanningSubscriber = from(this._bleStateSubject)\n .pipe(\n filter((state) => state === \"PoweredOn\"),\n switchMap(() => this.requestPermission()),\n switchMap((isSupported) => {\n if (!isSupported) {\n return throwError(() => new BleNotSupported(\"BLE not supported\"));\n }\n\n const subject = new BehaviorSubject<InternalScannedDevice[]>([]);\n this._maybeScanningSubject = Maybe.of(subject);\n const devicesById = new Map<string, InternalScannedDevice>();\n\n this._logger.info(\"[RNBleTransport][startScanning] startDeviceScan\");\n this._manager.startDeviceScan(\n this._deviceModelDataSource.getBluetoothServices(),\n { allowDuplicates: true },\n (error, rnDevice) => {\n if (error || !rnDevice) {\n subject.error(error || new Error(\"scan error\"));\n return;\n }\n devicesById.set(rnDevice.id, {\n device: rnDevice,\n timestamp: Date.now(),\n });\n subject.next(Array.from(devicesById.values()));\n },\n );\n\n /**\n * In case there is no update from startDeviceScan, we still emit the\n * list of devices. This is useful for instance if there is only 1 device\n * in the vicinity and it just got turned off. It will not \"advertise\"\n * anymore so startDeviceScan won't trigger.\n */\n const interval = setInterval(() => {\n subject.next(Array.from(devicesById.values()));\n }, 1000);\n\n return subject.asObservable().pipe(\n finalize(() => {\n this._logger.debug(\"[RNBleTransport][startScanning] finalize\");\n subject.complete();\n clearInterval(interval);\n this._maybeScanningSubject = Nothing;\n this._manager.stopDeviceScan();\n }),\n );\n }),\n throttleTime(1000),\n )\n .subscribe({\n next: (devices) => {\n this._logger.debug(\n \"[RNBleTransport][startScanning] onNext called with devices\",\n { data: { devices } },\n );\n this._scannedDevicesSubject.next(devices);\n },\n error: (error) => {\n this._logger.error(\"Error while scanning\", { data: { error } });\n },\n });\n }\n\n private async _stopScanning(): Promise<void> {\n this._maybeScanningSubject.map((subject) => {\n subject.complete();\n this._maybeScanningSubject = Nothing;\n });\n\n await this._manager.stopDeviceScan();\n //Stop listening the observable from this._startScanning()\n this._startedScanningSubscriber?.unsubscribe();\n this._startedScanningSubscriber = undefined;\n\n return;\n }\n\n /**\n * Listens to known devices and emits updates when new devices are discovered or when properties of existing devices are updated.\n *\n * @return {Observable<TransportDiscoveredDevice[]>} An observable stream of discovered devices, containing device information as an array of TransportDiscoveredDevice objects.\n */\n listenToAvailableDevices(): Observable<TransportDiscoveredDevice[]> {\n this._startScanning();\n\n return this._scannedDevicesSubject.asObservable().pipe(\n map((internalScannedDevices) => {\n const eitherConnectedDevices = Array.from(\n this._deviceConnectionsById.values(),\n ).map((connection) =>\n this._mapDeviceToTransportDiscoveredDevice(\n connection.getDependencies().device,\n [\n connection.getDependencies().internalDevice.bleDeviceInfos\n .serviceUuid,\n ],\n ),\n );\n\n const connectedDevices = Either.rights(eitherConnectedDevices);\n\n const eitherScannedDevices = internalScannedDevices\n .filter(\n ({ timestamp }) => timestamp > Date.now() - CONNECTION_LOST_DELAY,\n )\n .sort(\n (a, b) =>\n (b.device.rssi ?? -Infinity) - (a.device.rssi ?? -Infinity), // RSSI is a negative value and the higher, the stronger the signal\n )\n .map(({ device }) =>\n this._mapDeviceToTransportDiscoveredDevice(\n device,\n device.serviceUUIDs,\n ),\n )\n .filter((d) => !!d);\n\n const scannedDevices = Either.rights(eitherScannedDevices);\n\n return [...connectedDevices, ...scannedDevices];\n }),\n );\n }\n\n private _mapServicesUUIDsToBluetoothDeviceInfo(\n servicesUUIDs: string[] | null | undefined,\n ): Either<NoDeviceModelFoundError, BleDeviceInfos> {\n for (const serviceUUID of servicesUUIDs || []) {\n const bluetoothServiceInfo =\n this._deviceModelDataSource.getBluetoothServicesInfos()[serviceUUID];\n if (bluetoothServiceInfo) return Right(bluetoothServiceInfo);\n }\n\n return Left(\n new NoDeviceModelFoundError(\n `No device model found for [uuids=${servicesUUIDs}]`,\n ),\n );\n }\n\n private _mapServicesUUIDsToDeviceModel(\n servicesUUIDs: string[] | null | undefined,\n ): Either<NoDeviceModelFoundError, TransportDeviceModel> {\n const bluetoothServiceInfo =\n this._mapServicesUUIDsToBluetoothDeviceInfo(servicesUUIDs);\n return bluetoothServiceInfo.map((info) => info.deviceModel);\n }\n\n private _mapDeviceToTransportDiscoveredDevice(\n device: Device,\n servicesUUIDs: string[] | null | undefined,\n ): Either<NoDeviceModelFoundError, TransportDiscoveredDevice> {\n const deviceModel = this._mapServicesUUIDsToDeviceModel(servicesUUIDs);\n return deviceModel.map((model) => ({\n id: device.id,\n name: device.localName || device.name || \"\",\n deviceModel: model,\n transport: this.identifier,\n rssi: device.rssi || undefined,\n }));\n }\n\n /**\n * Establishes a connection to a device and configures the necessary parameters for communication.\n *\n * @param {Object} params - An object containing parameters required for the connection.\n * @param {DeviceId} params.deviceId - The unique identifier of the device to connect to.\n * @param {DisconnectHandler} params.onDisconnect - A callback function to handle device disconnection.\n * @returns {Promise<Either<ConnectError, TransportConnectedDevice>>} A promise resolving to either a connection error or a successfully connected device.\n */\n async connect(params: {\n deviceId: DeviceId;\n onDisconnect: DisconnectHandler;\n }): Promise<Either<ConnectError, TransportConnectedDevice>> {\n const existing = this._deviceConnectionsById.get(params.deviceId);\n if (existing) {\n const deviceModel =\n existing.getDependencies().internalDevice.bleDeviceInfos.deviceModel;\n return Right(\n new TransportConnectedDevice({\n id: params.deviceId,\n deviceModel: deviceModel,\n type: \"BLE\",\n sendApdu: (...a) => existing.sendApdu(...a),\n transport: this.identifier,\n }),\n );\n }\n\n await this._stopScanning();\n await this._safeCancel(params.deviceId);\n\n return EitherAsync<ConnectError, TransportConnectedDevice>(\n async ({ throwE }) => {\n let device: Device;\n let servicesUUIDs: string[] = [];\n try {\n await this._manager.connectToDevice(params.deviceId, {\n requestMTU: DEFAULT_MTU,\n });\n\n device =\n await this._manager.discoverAllServicesAndCharacteristicsForDevice(\n params.deviceId,\n );\n\n servicesUUIDs = (await device.services()).map((s) => s.uuid);\n } catch (error) {\n if (\n error instanceof BleError &&\n (error.iosErrorCode as number) === 14\n ) {\n /**\n * This happens when the Ledger device reset its pairing, but the\n * iOS system still has that device paired.\n */\n return throwE(new PeerRemovedPairingError(error));\n }\n return throwE(new OpeningConnectionError(error));\n }\n\n const disconnectionSubscription = this._manager.onDeviceDisconnected(\n device.id,\n (error, d) => {\n this._handleDeviceDisconnected(error, d);\n },\n );\n\n const bleDeviceInfos = this._mapServicesUUIDsToBluetoothDeviceInfo(\n servicesUUIDs,\n ).caseOf({\n Right: (info) => {\n return info;\n },\n Left: (error) => {\n return throwE(new OpeningConnectionError(error));\n },\n });\n\n const deviceModel = bleDeviceInfos.deviceModel;\n\n const internalDevice: RNBleInternalDevice = {\n id: device.id,\n bleDeviceInfos,\n };\n\n const deviceApduSender = this._deviceApduSenderFactory(\n {\n apduSenderFactory: this._apduSenderFactory,\n apduReceiverFactory: this._apduReceiverFactory,\n dependencies: { device, internalDevice, manager: this._manager },\n },\n this._loggerServiceFactory,\n );\n\n const reconnectionTimeout =\n Platform.OS === \"ios\"\n ? BLE_DISCONNECT_TIMEOUT_IOS\n : BLE_DISCONNECT_TIMEOUT_ANDROID;\n\n const deviceConnectionStateMachine =\n this._deviceConnectionStateMachineFactory({\n deviceId: params.deviceId,\n deviceApduSender,\n timeoutDuration: reconnectionTimeout,\n onTerminated: () => {\n try {\n this._safeCancel(params.deviceId);\n params.onDisconnect(params.deviceId);\n this._deviceConnectionsById.delete(params.deviceId);\n disconnectionSubscription.remove();\n if (this._reconnectionSubscription.isJust()) {\n this._reconnectionSubscription.map((sub) =>\n sub.unsubscribe(),\n );\n this._reconnectionSubscription = Maybe.zero();\n }\n } catch (e) {\n this._logger.error(\n \"Error in termination of device connection\",\n { data: { e } },\n );\n }\n },\n });\n\n await deviceApduSender.setupConnection().catch((e) => {\n this._safeCancel(params.deviceId);\n disconnectionSubscription.remove();\n throw e;\n });\n\n this._deviceConnectionsById.set(\n params.deviceId,\n deviceConnectionStateMachine,\n );\n\n return new TransportConnectedDevice({\n id: device.id,\n deviceModel: deviceModel,\n type: \"BLE\",\n sendApdu: (...args) => deviceConnectionStateMachine.sendApdu(...args),\n transport: this.identifier,\n });\n },\n ).run();\n }\n\n /**\n * Terminates the connection with the connected device and cleans up related resources.\n *\n * @param {TransportConnectedDevice} params.connectedDevice - The connected device to be disconnected.\n * @return {Promise<Either<DmkError, void>>} A promise resolving to either a success (void) or a failure (DmkError) value.\n */\n async disconnect(params: {\n connectedDevice: TransportConnectedDevice;\n }): Promise<Either<DmkError, void>> {\n const deviceId = params.connectedDevice.id;\n const deviceConnection = this._deviceConnectionsById.get(deviceId);\n if (!deviceConnection) {\n throw new UnknownDeviceError(\n `No connected device found with id ${deviceId}`,\n );\n }\n\n deviceConnection.closeConnection();\n\n return Promise.resolve(Right(undefined));\n }\n\n /**\n * Determines if the feature or permission is supported.\n *\n * This method evaluates the current state of the `_isSupported` property to determine\n * whether the relevant feature is supported or throws an error if its state has\n * not been initialized properly.\n *\n * @return {boolean} Returns `true` if the feature is supported, otherwise `false`.\n * Throws an error if the `_isSupported` property has not been initialized.\n */\n isSupported(): boolean {\n return this._isSupported.caseOf({\n Just: (isSupported) => isSupported,\n Nothing: () => {\n throw new Error(\"Should initialize permission\");\n },\n });\n }\n\n /**\n * Retrieves the transport identifier associated with the object.\n *\n * @return {TransportIdentifier} The transport identifier.\n */\n getIdentifier(): TransportIdentifier {\n return this.identifier;\n }\n\n /**\n * Requests the necessary permissions based on the operating system.\n * For iOS, it automatically sets the permissions as granted.\n * For Android, it checks and requests location, Bluetooth scan, and Bluetooth connect permissions, depending on the API level.\n * If permissions are granted, updates the internal support state and logs the result.\n *\n * @return {Promise<boolean>} A promise that resolves to true if the required permissions are granted, otherwise false.\n */\n async requestPermission(): Promise<boolean> {\n if (this._platform.OS === \"ios\") {\n this._isSupported = Maybe.of(true);\n return true;\n }\n\n if (\n this._platform.OS === \"android\" &&\n this._permissionsAndroid.PERMISSIONS[\"ACCESS_FINE_LOCATION\"]\n ) {\n const apiLevel = parseInt(this._platform.Version.toString(), 10);\n\n if (apiLevel < 31) {\n const granted = await this._permissionsAndroid.request(\n this._permissionsAndroid.PERMISSIONS[\"ACCESS_FINE_LOCATION\"],\n );\n this._isSupported = Maybe.of(\n granted === this._permissionsAndroid.RESULTS[\"GRANTED\"],\n );\n }\n if (\n this._permissionsAndroid.PERMISSIONS[\"BLUETOOTH_SCAN\"] &&\n this._permissionsAndroid.PERMISSIONS[\"BLUETOOTH_CONNECT\"]\n ) {\n const result = await this._permissionsAndroid.requestMultiple([\n this._permissionsAndroid.PERMISSIONS[\"BLUETOOTH_SCAN\"],\n this._permissionsAndroid.PERMISSIONS[\"BLUETOOTH_CONNECT\"],\n this._permissionsAndroid.PERMISSIONS[\"ACCESS_FINE_LOCATION\"],\n ]);\n\n this._isSupported = Maybe.of(\n result[\"android.permission.BLUETOOTH_CONNECT\"] ===\n this._permissionsAndroid.RESULTS[\"GRANTED\"] &&\n result[\"android.permission.BLUETOOTH_SCAN\"] ===\n this._permissionsAndroid.RESULTS[\"GRANTED\"] &&\n result[\"android.permission.ACCESS_FINE_LOCATION\"] ===\n this._permissionsAndroid.RESULTS[\"GRANTED\"],\n );\n\n return true;\n }\n }\n\n this._logger.error(\"Permission have not been granted\", {\n data: { isSupported: this._isSupported.extract() },\n });\n\n this._isSupported = Maybe.of(false);\n return false;\n }\n\n /**\n * Handles the event when a Bluetooth device gets disconnected. This method attempts\n * to reconnect to the device, retries a certain number of times on failure, and\n * invokes a callback if the reconnection does not succeed.\n *\n * @param {BleError | null} error - The error object representing the reason for the disconnection, or null if no error occurred.\n * @param {Device | null} device - The Bluetooth device that was disconnected, or null if no device is provided.\n * @return {void}\n */\n private _handleDeviceDisconnected(\n error: BleError | null,\n device: Device | null,\n ) {\n this._logger.debug(\"[RNBLE][_handleDeviceDisconnected]\", {\n data: { error, device },\n });\n if (!device) {\n this._logger.debug(\n \"[_handleDeviceDisconnected] disconnected handler didn't find device\",\n );\n return;\n }\n if (!device?.id || !this._deviceConnectionsById.has(device?.id)) return;\n if (error) {\n this._logger.error(\"device disconnected error\", {\n data: { error, device },\n });\n return;\n }\n const deviceId = device.id;\n if (this._reconnectionSubscription.isJust()) {\n return;\n }\n\n Maybe.fromNullable(this._deviceConnectionsById.get(deviceId)).map(\n (deviceConnection) => deviceConnection.eventDeviceDetached(),\n );\n\n const reconnect$ = from([0]).pipe(\n switchMap(async () => {\n await this._stopScanning();\n await this._safeCancel(deviceId);\n }),\n switchMap(async () => {\n this._logger.debug(\n \"[_handleDeviceDisconnected] reconnecting to device\",\n { data: { id: device.id } },\n );\n const reconnectedDevice = await this._manager.connectToDevice(\n deviceId,\n { requestMTU: DEFAULT_MTU, timeout: 2000 },\n );\n this._logger.debug(\n \"[_handleDeviceDisconnected] reconnected to device\",\n { data: { id: device.id } },\n );\n const reconnectedDeviceUsable =\n await reconnectedDevice.discoverAllServicesAndCharacteristics();\n this._logger.debug(\n \"[_handleDeviceDisconnected] discovered all services and characteristics\",\n { data: { reconnectedDeviceUsable } },\n );\n await this._handleDeviceReconnected(reconnectedDeviceUsable);\n return reconnectedDeviceUsable;\n }),\n retry(5),\n );\n\n this._reconnectionSubscription = Maybe.of(\n reconnect$.subscribe({\n next: (d) =>\n this._logger.debug(\n \"[_handleDeviceDisconnected] Reconnected to device\",\n { data: { id: d.id } },\n ),\n complete: () => {\n this._reconnectionSubscription = Maybe.zero();\n },\n error: (e) => {\n this._logger.error(\n \"[_handleDeviceDisconnected] All reconnection attempts failed\",\n { data: { e } },\n );\n Maybe.fromNullable(this._deviceConnectionsById.get(deviceId)).map(\n (sm) => sm.closeConnection(),\n );\n this._reconnectionSubscription = Maybe.zero();\n },\n }),\n );\n }\n\n /**\n * Handles the reconnection of a device. Configures the device connection and its corresponding\n * internal device upon reconnection, including updating the connection state, registering\n * callbacks for write and monitor operations, and initiating a reconnect operation.\n *\n * @param {Device} device - The ddevice object that has been reconnected. Contains device details,\n * such as the device ID.\n * @return {Promise<Either<DeviceConnectionNotFound | InternalDeviceNotFound, void>>} A promise that completes when the device reconnection has been fully\n * configured. Resolves with no value or rejects if an error occurs during\n * the reconnection process.\n */\n private async _handleDeviceReconnected(device: Device) {\n const errorOrDeviceConnection = Maybe.fromNullable(\n this._deviceConnectionsById.get(device.id),\n ).toEither(new DeviceConnectionNotFound());\n\n return EitherAsync(async ({ liftEither, throwE }) => {\n const deviceConnectionStateMachine = await liftEither(\n errorOrDeviceConnection,\n );\n\n const servicesUUIDs = (await device.services()).map((s) => s.uuid);\n\n const internalDevice = this._mapServicesUUIDsToBluetoothDeviceInfo(\n servicesUUIDs,\n ).caseOf({\n Right: (info) => {\n return {\n id: device.id,\n bleDeviceInfos: info,\n };\n },\n Left: (error) => {\n this._logger.error(\n \"Error in mapping services UUIDs to Bluetooth device info\",\n {\n data: { error },\n },\n );\n\n return throwE(error);\n },\n });\n\n deviceConnectionStateMachine.setDependencies({\n device,\n manager: this._manager,\n internalDevice,\n });\n\n await deviceConnectionStateMachine.setupConnection().catch((e) => {\n this._safeCancel(device.id);\n throw e;\n });\n\n deviceConnectionStateMachine.eventDeviceAttached();\n }).run();\n }\n\n private async _safeCancel(deviceId: DeviceId) {\n // only invoke if the BleManager under test actually has it\n if (typeof this._manager.cancelDeviceConnection === \"function\") {\n const connectedDevices = await this._manager.connectedDevices(\n this._deviceModelDataSource.getBluetoothServices(),\n );\n\n for (const device of connectedDevices) {\n if (device.id === deviceId) {\n await this._manager.cancelDeviceConnection(deviceId);\n }\n }\n }\n }\n}\n\nexport const RNBleTransportFactory: TransportFactory = ({\n deviceModelDataSource,\n loggerServiceFactory,\n apduSenderServiceFactory,\n apduReceiverServiceFactory,\n}) =>\n new RNBleTransport(\n deviceModelDataSource,\n loggerServiceFactory,\n apduSenderServiceFactory,\n apduReceiverServiceFactory,\n new BleManager(),\n );\n"],
|
|
5
|
+
"mappings": "AAAA,OAAS,sBAAAA,EAAoB,YAAAC,MAAgB,eAC7C,OAAS,YAAAC,EAAU,cAAAC,EAAyB,SAAAC,MAAa,uBACzD,OAKE,gCAAAC,EAOA,0BAAAC,EAEA,4BAAAC,EAKA,sBAAAC,MACK,kCACP,OAAS,UAAAC,EAAQ,eAAAC,EAAa,QAAAC,EAAM,SAAAC,EAAO,WAAAC,EAAS,SAAAC,MAAa,YACjE,OACE,mBAAAC,EACA,UAAAC,EACA,YAAAC,EACA,QAAAC,EACA,OAAAC,EAEA,SAAAC,EAEA,aAAAC,EACA,gBAAAC,EACA,cAAAC,MACK,OAEP,OACE,kCAAAC,EACA,8BAAAC,EACA,yBAAAC,EACA,eAAAC,MACK,mBACP,OACE,mBAAAC,EACA,4BAAAC,EACA,2BAAAC,EACA,2BAAAC,MACK,oBACP,OACE,mBAAAC,MAIK,iCAEA,MAAMC,GAA2B,SAOjC,MAAMC,CAAoC,CAa/C,YACmBC,EACAC,EAGAC,EACAC,EACAC,EACAC,EAAsBvC,EACtBwC,EAA0CzC,EAC1C0C,EAEiDC,GAChE,IAAItC,EAA6BsC,CAAI,EACtBC,EAGM,CAACD,EAAME,IAC5B,IAAIb,EAAgBW,EAAME,CAAa,EACzC,CAlBiB,4BAAAV,EACA,2BAAAC,EAGA,wBAAAC,EACA,0BAAAC,EACA,cAAAC,EACA,eAAAC,EACA,yBAAAC,EACA,0CAAAC,EAIA,8B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ACnD,MAAMO,EAA+B,MAAMY,EACzCD,CACF,EAEM1B,GAAiB,MAAMH,EAAO,SAAS,GAAG,IAAKY,GAAMA,EAAE,IAAI,EAE3DG,EAAiB,KAAK,uCAC1BZ,CACF,EAAE,OAAO,CACP,MAAQG,IACC,CACL,GAAIN,EAAO,GACX,eAAgBM,CAClB,GAEF,KAAOlB,IACL,KAAK,QAAQ,MACX,2DACA,CACE,KAAM,CAAE,MAAAA,CAAM,CAChB,CACF,EAEOuB,EAAOvB,CAAK,EAEvB,CAAC,EAED8B,EAA6B,gBAAgB,CAC3C,OAAAlB,EACA,QAAS,KAAK,SACd,eAAAe,CACF,CAAC,EAED,MAAMG,EAA6B,gBAAgB,EAAE,MAAOE,GAAM,CAChE,WAAK,YAAYpB,EAAO,EAAE,EACpBoB,CACR,CAAC,EAEDF,EAA6B,oBAAoB,CACnD,CAAC,EAAE,IAAI,CACT,CAEA,MAAc,YAAYG,EAAoB,CAE5C,GAAI,OAAO,KAAK,SAAS,wBAA2B,WAAY,CAC9D,MAAM1B,EAAmB,MAAM,KAAK,SAAS,iBAC3C,KAAK,uBAAuB,qBAAqB,CACnD,EAEA,UAAWK,KAAUL,EACfK,EAAO,KAAOqB,GAChB,MAAM,KAAK,SAAS,uBAAuBA,CAAQ,CAGzD,CACF,CACF,CAEO,MAAMU,GAA0C,CAAC,CACtD,sBAAAC,EACA,qBAAAC,EACA,yBAAAC,EACA,2BAAAC,CACF,IACE,IAAI/D,EACF4D,EACAC,EACAC,EACAC,EACA,IAAI9F,CACN",
|
|
6
|
+
"names": ["PermissionsAndroid", "Platform", "BleError", "BleManager", "State", "DeviceConnectionStateMachine", "OpeningConnectionError", "TransportConnectedDevice", "UnknownDeviceError", "Either", "EitherAsync", "Left", "Maybe", "Nothing", "Right", "BehaviorSubject", "filter", "finalize", "from", "map", "retry", "switchMap", "throttleTime", "throwError", "BLE_DISCONNECT_TIMEOUT_ANDROID", "BLE_DISCONNECT_TIMEOUT_IOS", "CONNECTION_LOST_DELAY", "DEFAULT_MTU", "BleNotSupported", "DeviceConnectionNotFound", "NoDeviceModelFoundError", "PeerRemovedPairingError", "RNBleApduSender", "rnBleTransportIdentifier", "RNBleTransport", "_deviceModelDataSource", "_loggerServiceFactory", "_apduSenderFactory", "_apduReceiverFactory", "_manager", "_platform", "_permissionsAndroid", "_deviceConnectionStateMachineFactory", "args", "_deviceApduSenderFactory", "loggerFactory", "state", "isSupported", "subject", "devicesById", "error", "rnDevice", "interval", "devices", "internalScannedDevices", "eitherConnectedDevices", "connection", "connectedDevices", "eitherScannedDevices", "timestamp", "a", "b", "device", "d", "scannedDevices", "servicesUUIDs", "serviceUUID", "bluetoothServiceInfo", "info", "model", "params", "existing", "deviceModel", "throwE", "s", "disconnectionSubscription", "bleDeviceInfos", "internalDevice", "deviceApduSender", "reconnectionTimeout", "deviceConnectionStateMachine", "sub", "e", "deviceId", "deviceConnection", "granted", "result", "reconnect$", "reconnectedDevice", "reconnectedDeviceUsable", "sm", "errorOrDeviceConnection", "liftEither", "RNBleTransportFactory", "deviceModelDataSource", "loggerServiceFactory", "apduSenderServiceFactory", "apduReceiverServiceFactory"]
|
|
7
7
|
}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{BleDeviceInfos as T,DeviceConnectionStateMachine as N,DeviceModelId as b,TransportConnectedDevice as R,TransportDeviceModel as h,UnknownDeviceError as E}from"@ledgerhq/device-management-kit";import{Left as y,Right as g}from"purify-ts";import{firstValueFrom as C}from"rxjs";import{beforeEach as I,expect as s}from"vitest";import{BleNotSupported as F}from"../model/Errors";import{RNBleTransport as v,RNBleTransportFactory as P}from"./RNBleTransport";const l={error:vi.fn(),info:vi.fn(),warn:vi.fn(),debug:vi.fn()};vi.mock("react-native",()=>({Platform:{},PermissionsAndroid:{}}));vi.mock("react-native-ble-plx",()=>({BleManager:vi.fn()}));const A=async(t,m)=>{const O={OS:"android",Version:t.version},k={request:vi.fn().mockImplementation(e=>Promise.resolve({ACCESS_FINE_LOCATION:t.accessFineLocationResult}[e])),PERMISSIONS:t.permissions,RESULTS:{GRANTED:"granted"},requestMultiple:vi.fn().mockImplementation(()=>Promise.resolve(t.requestPermissionResult))},u=new v("DeviceModelDataSource",()=>l,()=>{},()=>{},O,k);await u.requestPermission();const n=u.isSupported();m.callRequestPermission&&s(k.request).toHaveBeenCalledWith("ACCESS_FINE_LOCATION"),s(n).toBe(m.isSupported)};describe("RNBleTransportFactory",()=>{it("should return a RNBleTransport",()=>{const m=P({deviceModelDataSource:"DeviceModelDataSource",loggerServiceFactory:()=>l,apduSenderServiceFactory:()=>{},apduReceiverServiceFactory:()=>{},config:{}});s(m).toBeInstanceOf(v)})});describe("RNBleTransport",()=>{const t={OS:"ios"},m=new h({id:b.FLEX,productName:"Ledger Flex",usbProductId:112,bootloaderUsbProductId:7,usbOnly:!1,memorySize:1533*1024,masks:[858783744]}),O=vi.fn(()=>["ledgerId"]),k=vi.fn(()=>({ledgerId:new T(m,"serviceUuid","notifyUuid","writeCmdUuid","readCmdUuid")})),u={getBluetoothServices:O,getBluetoothServicesInfos:k};I(()=>{vi.clearAllMocks()}),describe("getIdentifier",()=>{it("should return rnBleTransportIdentifier",()=>{const e=new v("DeviceModelDataSource",()=>l,()=>{},()=>{}).getIdentifier();s(e).toStrictEqual("RN_BLE")})}),describe("isSupported",()=>{it("should return true if platform is ios",async()=>{const n={OS:"ios"},e=new v("DeviceModelDataSource",()=>l,()=>{},()=>{},n);await e.requestPermission();const i=e.isSupported();s(i).toBe(!0)}),it("should return true if platform is android and apiLevel < 31 with good permissions",async()=>{await A({version:30,permissions:{ACCESS_FINE_LOCATION:"ACCESS_FINE_LOCATION",BLUETOOTH_SCAN:"BLUETOOTH_SCAN",BLUETOOTH_CONNECT:"BLUETOOTH_CONNECT"},requestPermissionResult:{"android.permission.BLUETOOTH_CONNECT":"granted","android.permission.BLUETOOTH_SCAN":"granted","android.permission.ACCESS_FINE_LOCATION":"granted"}},{isSupported:!0,callRequestPermission:!0})}),it("should return true if platform is android and apiLevel >= 31 with good permissions",async()=>{await A({version:31,permissions:{ACCESS_FINE_LOCATION:"ACCESS_FINE_LOCATION",BLUETOOTH_SCAN:"BLUETOOTH_SCAN",BLUETOOTH_CONNECT:"BLUETOOTH_CONNECT"},requestPermissionResult:{"android.permission.BLUETOOTH_CONNECT":"granted","android.permission.BLUETOOTH_SCAN":"granted","android.permission.ACCESS_FINE_LOCATION":"granted"}},{isSupported:!0,callRequestPermission:!1})}),it("should return false if platform is android with bad permissions",async()=>{await A({version:31,permissions:{ACCESS_FINE_LOCATION:"",BLUETOOTH_SCAN:"",BLUETOOTH_CONNECT:"BLUETOOTH_CONNECT"},requestPermissionResult:{"android.permission.ACCESS_FINE_LOCATION":"denied","android.permission.BLUETOOTH_CONNECT":"granted","android.permission.BLUETOOTH_SCAN":"granted"}},{isSupported:!1,callRequestPermission:!1})}),it("should return false if platform is android and denied permissions",async()=>{await A({version:31,permissions:{ACCESS_FINE_LOCATION:"ACCESS_FINE_LOCATION",BLUETOOTH_SCAN:"BLUETOOTH_SCAN",BLUETOOTH_CONNECT:"BLUETOOTH_CONNECT"},requestPermissionResult:{"android.permission.BLUETOOTH_CONNECT":"denied","android.permission.BLUETOOTH_SCAN":"denied","android.permission.ACCESS_FINE_LOCATION":"denied"}},{isSupported:!1,callRequestPermission:!1})}),it("should return false if platform isn't android nor ios",async()=>{const n=new v("DeviceModelDataSource",()=>l,()=>{},()=>{},{OS:"windows"});await n.requestPermission();const e=n.isSupported();s(e).toBe(!1)})}),describe("startDiscovering",()=>{it("should throw error if transport is not supported",()=>{const n={OS:"windows"},e=new v(u,()=>l,()=>{},()=>{},n);try{e.startDiscovering()}catch(i){s(i).toBeInstanceOf(F)}}),it("should emit discovered known device",()=>new Promise(n=>{const e={connectedDevices:vi.fn().mockResolvedValueOnce([{readRSSI:vi.fn().mockResolvedValueOnce({discoverAllServicesAndCharacteristics:vi.fn().mockResolvedValueOnce({services:vi.fn().mockResolvedValue({}),serviceUUIDs:["ledgerId"],rssi:42,id:"id",localName:"name"})})}]),startDeviceScan:vi.fn(),stopDeviceScan:vi.fn(),onDeviceDisconnected:vi.fn()},c=new v(u,()=>l,()=>{},()=>{},t,{},()=>e).startDiscovering().subscribe({next:a=>{s(a).toStrictEqual({id:"id",name:"name",deviceModel:m,transport:"RN_BLE",rssi:42}),c.unsubscribe(),n(void 0)},error:a=>{throw c&&!c.closed&&c.unsubscribe(),a},complete:()=>{throw c&&!c.closed&&c.unsubscribe(),new Error("complete should not be called")}})})),it("should emit discovered new device",()=>new Promise(n=>{let e;const i=vi.fn((d,f,p)=>{e=setInterval(()=>{p(null,{id:"id",localName:"name",serviceUUIDs:["ledgerId"],rssi:42})},500),p(null,{id:"43",localName:"name43",serviceUUIDs:["notLedgerId"],rssi:43})}),r=vi.fn(()=>{clearInterval(e)}),c={connectedDevices:vi.fn().mockResolvedValueOnce([]),startDeviceScan:i,stopDeviceScan:r,onDeviceDisconnected:vi.fn()},o=new v(u,()=>l,()=>{},()=>{},t,{},()=>c).startDiscovering().subscribe({next:d=>{s(d).toStrictEqual({id:"id",name:"name",deviceModel:m,transport:"RN_BLE",rssi:42}),o.unsubscribe(),n(void 0)},error:d=>{throw o&&!o.closed&&o.unsubscribe(),d},complete:()=>{throw o&&!o.closed&&o.unsubscribe(),new Error("complete should not be called")}})})),it("should emit both known and new device",()=>new Promise(n=>{let e;const i=vi.fn((p,D,w)=>{e=setInterval(()=>{w(null,{id:"newDeviceId",localName:"newDeviceName",serviceUUIDs:["ledgerId"],rssi:42})},500),w(null,{id:"43",localName:"name43",serviceUUIDs:["notLedgerId"],rssi:43})}),r=vi.fn(()=>{clearInterval(e)}),a={connectedDevices:vi.fn().mockResolvedValueOnce([{readRSSI:vi.fn().mockResolvedValueOnce({discoverAllServicesAndCharacteristics:vi.fn().mockResolvedValueOnce({services:vi.fn().mockResolvedValueOnce({}),serviceUUIDs:["ledgerId"],rssi:64,id:"knownDeviceId",localName:"knownDeviceName"})})}]),startDeviceScan:i,stopDeviceScan:r,onDeviceDisconnected:vi.fn()},o=new v(u,()=>l,()=>{},()=>{},t,{},()=>a).startDiscovering(),d={},f=o.subscribe({next:p=>{d[p.id]=p,Object.values(d).length===2&&(f.unsubscribe(),s(Object.values(d)).toStrictEqual([{id:"knownDeviceId",name:"knownDeviceName",deviceModel:m,transport:"RN_BLE",rssi:64},{id:"newDeviceId",name:"newDeviceName",deviceModel:m,transport:"RN_BLE",rssi:42}]),n(void 0))}})}))}),describe("stopDiscovering",()=>{it("should call ble manager stop scan on stop discovering",()=>{const n=vi.fn(),e={connectedDevices:vi.fn().mockResolvedValueOnce([]),startDeviceScan:vi.fn(),stopDeviceScan:n,onDeviceDisconnected:vi.fn()};new v(u,()=>l,()=>{},()=>{},t,{},()=>e).stopDiscovering(),s(n).toHaveBeenCalled()}),it("should call ble manager stop scan when unsubscribe startDiscovering obs",()=>{let n;const e=vi.fn((a,S,o)=>{n=setInterval(()=>{o(null,{id:"id",localName:"name",serviceUUIDs:["ledgerId"],rssi:42})},500),o(null,{id:"43",localName:"name43",serviceUUIDs:["notLedgerId"],rssi:43})}),i=vi.fn(()=>{clearInterval(n),n=void 0}),r={connectedDevices:vi.fn().mockResolvedValueOnce([]),startDeviceScan:e,stopDeviceScan:i,onDeviceDisconnected:vi.fn()};new v(u,()=>l,()=>{},()=>{},t,{},()=>r).startDiscovering().subscribe().unsubscribe(),s(e).toHaveBeenCalled(),s(i).toHaveBeenCalled()})}),describe("listenToAvailableDevices",()=>{it("should call startScan and connectedDevices from ble manager",()=>new Promise(n=>{let e;const i=vi.fn((d,f,p)=>{e=setInterval(()=>{p(null,{id:"id",localName:"name",serviceUUIDs:["ledgerId"],rssi:42})},500),p(null,{id:"43",localName:"name43",serviceUUIDs:["notLedgerId"],rssi:43})}),r=vi.fn(()=>{clearInterval(e),e=void 0}),a={connectedDevices:vi.fn().mockResolvedValueOnce([{readRSSI:vi.fn().mockResolvedValueOnce({discoverAllServicesAndCharacteristics:vi.fn().mockResolvedValueOnce({services:vi.fn().mockResolvedValueOnce({}),serviceUUIDs:["ledgerId"],rssi:64,id:"knownDeviceId",localName:"knownDeviceName"})})}]),startDeviceScan:i,stopDeviceScan:r,onDeviceDisconnected:vi.fn(),isDeviceConnected:vi.fn()},o=new v(u,()=>l,()=>{},()=>{},t,{},()=>a).listenToAvailableDevices().subscribe({next:d=>{d.length===2&&(s(d).toEqual([{id:"knownDeviceId",name:"knownDeviceName",deviceModel:m,transport:"RN_BLE",rssi:64},{id:"id",name:"name",deviceModel:m,transport:"RN_BLE",rssi:42}]),o.unsubscribe(),n(void 0))}})}))}),describe("connect",()=>{let n;I(()=>{n=vi.fn().mockResolvedValueOnce([{readRSSI:vi.fn().mockResolvedValueOnce({discoverAllServicesAndCharacteristics:vi.fn().mockResolvedValueOnce({services:vi.fn().mockResolvedValueOnce({}),serviceUUIDs:["ledgerId"],rssi:64,id:"deviceId",localName:"knownDeviceName"})})}])}),it("should throw an error if device id is unknown",async()=>{const e={connectedDevices:vi.fn(),startDeviceScan:vi.fn(),stopDeviceScan:vi.fn(),onDeviceDisconnected:vi.fn(),isDeviceConnected:vi.fn()},r=await new v(u,()=>l,()=>{},()=>{},t,{},()=>e).connect({deviceId:"42",onDisconnect:vi.fn()});s(r).toEqual(y(new E("Unknown device 42")))}),it("should connect to a discovered device with correct MTU and discover services and setup apdu sender",async()=>{const e={connectedDevices:n,startDeviceScan:vi.fn(),stopDeviceScan:vi.fn(),onDeviceDisconnected:vi.fn(),isDeviceConnected:vi.fn(),monitorCharacteristicForDevice:vi.fn(),writeCharacteristicWithoutResponseForDevice:vi.fn(),connectToDevice:vi.fn().mockResolvedValueOnce({id:"deviceId",rssi:64}),discoverAllServicesAndCharacteristicsForDevice:vi.fn()},i=vi.fn(),r=vi.fn().mockReturnValue({sendApdu:vi.fn()}),c=vi.fn().mockReturnValue({setupConnection:i}),a=new v(u,()=>l,()=>{},()=>{},t,{},()=>e,r,c),S=await C(a.startDiscovering()),o=await a.connect({deviceId:S.id,onDisconnect:vi.fn()});s(o.isRight()).toBe(!0),s(e.connectToDevice).toHaveBeenCalledWith("deviceId",{requestMTU:156}),s(e.discoverAllServicesAndCharacteristicsForDevice).toHaveBeenCalledWith("deviceId"),s(i).toHaveBeenCalled()}),it("should return a connected device which calls state machine sendApdu",async()=>{const e={connectedDevices:n,startDeviceScan:vi.fn(),stopDeviceScan:vi.fn(),onDeviceDisconnected:vi.fn(),isDeviceConnected:vi.fn(),monitorCharacteristicForDevice:vi.fn(),writeCharacteristicWithoutResponseForDevice:vi.fn(),connectToDevice:vi.fn().mockResolvedValueOnce({id:"deviceId",rssi:64}),discoverAllServicesAndCharacteristicsForDevice:vi.fn()},i=vi.fn(),r=vi.fn().mockReturnValue({sendApdu:i}),c=vi.fn().mockReturnValue({setupConnection:vi.fn()}),a=new v(u,()=>l,()=>{},()=>{},t,{},()=>e,r,c),S=await C(a.startDiscovering()),o=await a.connect({deviceId:S.id,onDisconnect:vi.fn()});o.extract().sendApdu(Uint8Array.from([67,50])),s(o).toEqual(g(new R({id:"deviceId",deviceModel:m,type:"BLE",transport:"RN_BLE",sendApdu:s.any(Function)}))),s(i).toHaveBeenCalledWith(Uint8Array.from([67,50]))})}),describe("disconnect",()=>{let n;I(()=>{n=vi.fn().mockResolvedValueOnce([{readRSSI:vi.fn().mockResolvedValueOnce({discoverAllServicesAndCharacteristics:vi.fn().mockResolvedValueOnce({services:vi.fn().mockResolvedValueOnce({}),serviceUUIDs:["ledgerId"],rssi:64,id:"deviceId",localName:"knownDeviceName"})})}])}),it("should disconnect gracefully",async()=>{const e=vi.fn().mockImplementation((D,w)=>(w(null,{deviceId:"deviceId",connect:vi.fn().mockResolvedValue({services:vi.fn().mockResolvedValueOnce({}),serviceUUIDs:["ledgerId"],rssi:64,id:"deviceId",localName:"knownDeviceName"}),discoverAllServicesAndCharacteristics:vi.fn().mockResolvedValueOnce({services:vi.fn().mockResolvedValueOnce({}),serviceUUIDs:["ledgerId"],rssi:64,id:"deviceId",localName:"knownDeviceName"})}),{remove:vi.fn()})),i={connectedDevices:n,startDeviceScan:vi.fn(),stopDeviceScan:vi.fn(),onDeviceDisconnected:e,isDeviceConnected:vi.fn(),monitorCharacteristicForDevice:vi.fn(),writeCharacteristicWithoutResponseForDevice:vi.fn(),connectToDevice:vi.fn().mockResolvedValueOnce({id:"deviceId",rssi:64}),discoverAllServicesAndCharacteristicsForDevice:vi.fn()},r=vi.fn(),c=D=>new N({deviceId:"deviceId",deviceApduSender:D.deviceApduSender,timeoutDuration:1e3,onTerminated:D.onTerminated}),a=vi.fn().mockReturnValue({setupConnection:vi.fn(),closeConnection:r}),S=new v(u,()=>l,()=>{},()=>{},t,{},()=>i,c,a),o=vi.fn(),d=await C(S.startDiscovering()),f=await S.connect({deviceId:d.id,onDisconnect:o}),p=await S.disconnect({connectedDevice:f.extract()});s(p).toEqual(g(void 0)),s(o).toHaveBeenCalled(),s(r).toHaveBeenCalled()}),it("should handle error while disconnecting",async()=>{const e=vi.fn().mockImplementation((D,w)=>(w(new Error("yolo"),null),{remove:vi.fn()})),i={connectedDevices:n,startDeviceScan:vi.fn(),stopDeviceScan:vi.fn(),onDeviceDisconnected:e,isDeviceConnected:vi.fn(),monitorCharacteristicForDevice:vi.fn(),writeCharacteristicWithoutResponseForDevice:vi.fn(),connectToDevice:vi.fn().mockResolvedValueOnce({id:"deviceId",rssi:64}),discoverAllServicesAndCharacteristicsForDevice:vi.fn()},r=vi.fn(),c=D=>new N({deviceId:"deviceId",deviceApduSender:D.deviceApduSender,timeoutDuration:1e3,onTerminated:D.onTerminated}),a=vi.fn().mockReturnValue({setupConnection:vi.fn(),closeConnection:r}),S=new v(u,()=>l,()=>{},()=>{},t,{},()=>i,c,a),o=vi.fn(),d=await C(S.startDiscovering()),f=await S.connect({deviceId:d.id,onDisconnect:o}),p=await S.disconnect({connectedDevice:f.extract()});s(p).toEqual(g(void 0)),s(o).toHaveBeenCalled()})})});
|
|
1
|
+
import{BleManager as l,State as g}from"react-native-ble-plx";import{BleDeviceInfos as L,DeviceConnectionStateMachine as U,DeviceModelId as _,OpeningConnectionError as B,TransportConnectedDevice as M,TransportDeviceModel as V}from"@ledgerhq/device-management-kit";import{Left as H,Right as E}from"purify-ts";import{lastValueFrom as N,take as T}from"rxjs";import{beforeEach as F,expect as o}from"vitest";import{BleNotSupported as q}from"../model/Errors";import{RNBleTransport as d,RNBleTransportFactory as x}from"./RNBleTransport";const v={error:vi.fn(),info:vi.fn(),warn:vi.fn(),debug:vi.fn()};vi.mock("react-native",()=>({Platform:{},PermissionsAndroid:{}}));vi.mock("react-native-ble-plx",()=>({Device:vi.fn(),State:{PoweredOn:"PoweredOn",Unknown:"Unknown"},BleError:vi.fn(),BleManager:vi.fn().mockReturnValue({onStateChange:vi.fn(),startDeviceScan:vi.fn(),stopDeviceScan:vi.fn(),connectToDevice:vi.fn(),disconnectFromDevice:vi.fn(),cancelDeviceConnection:vi.fn(),connectedDevices:vi.fn(),monitorCharacteristicForDevice:vi.fn(),writeCharacteristicWithoutResponseForDevice:vi.fn(),discoverAllServicesAndCharacteristicsForDevice:vi.fn(),onDeviceDisconnected:vi.fn(),isDeviceConnected:vi.fn()})}));const h=async(r,I)=>{const b={OS:"android",Version:r.version},R={request:vi.fn().mockImplementation(i=>Promise.resolve({ACCESS_FINE_LOCATION:r.accessFineLocationResult}[i])),PERMISSIONS:r.permissions,RESULTS:{GRANTED:"granted"},requestMultiple:vi.fn().mockImplementation(()=>Promise.resolve(r.requestPermissionResult))},u=new d("DeviceModelDataSource",()=>v,()=>{},()=>{},new l,b,R);await u.requestPermission();const O=u.isSupported();I.callRequestPermission&&o(R.request).toHaveBeenCalledWith("ACCESS_FINE_LOCATION"),o(O).toBe(I.isSupported)};describe("RNBleTransportFactory",()=>{it("should return a RNBleTransport",()=>{const I=x({deviceModelDataSource:"DeviceModelDataSource",loggerServiceFactory:()=>v,apduSenderServiceFactory:()=>{},apduReceiverServiceFactory:()=>{},config:{}});o(I).toBeInstanceOf(d)})});describe("RNBleTransport",()=>{const r={OS:"ios"},I=new V({id:_.FLEX,productName:"Ledger Flex",usbProductId:112,bootloaderUsbProductId:7,usbOnly:!1,memorySize:1533*1024,blockSize:32,masks:[858783744]}),b=vi.fn(()=>["ledgerId"]),R=vi.fn(()=>({ledgerId:new L(I,"serviceUuid","notifyUuid","writeCmdUuid","readCmdUuid")})),u={getBluetoothServices:b,getBluetoothServicesInfos:R};let O;F(()=>{vi.clearAllMocks()}),afterEach(()=>{O&&O.unsubscribe()}),describe("getIdentifier",()=>{it("should return rnBleTransportIdentifier",()=>{const i=new l,e=new d("DeviceModelDataSource",()=>v,()=>{},()=>{},i).getIdentifier();o(e).toStrictEqual("RN_BLE")})}),describe("isSupported",()=>{it("should return true if platform is ios",async()=>{const i={OS:"ios"},n=new l,e=new d("DeviceModelDataSource",()=>v,()=>{},()=>{},n,i);await e.requestPermission();const s=e.isSupported();o(s).toBe(!0)}),it("should return true if platform is android and apiLevel < 31 with good permissions",async()=>{await h({version:30,permissions:{ACCESS_FINE_LOCATION:"ACCESS_FINE_LOCATION",BLUETOOTH_SCAN:"BLUETOOTH_SCAN",BLUETOOTH_CONNECT:"BLUETOOTH_CONNECT"},requestPermissionResult:{"android.permission.BLUETOOTH_CONNECT":"granted","android.permission.BLUETOOTH_SCAN":"granted","android.permission.ACCESS_FINE_LOCATION":"granted"}},{isSupported:!0,callRequestPermission:!0})}),it("should return true if platform is android and apiLevel >= 31 with good permissions",async()=>{await h({version:31,permissions:{ACCESS_FINE_LOCATION:"ACCESS_FINE_LOCATION",BLUETOOTH_SCAN:"BLUETOOTH_SCAN",BLUETOOTH_CONNECT:"BLUETOOTH_CONNECT"},requestPermissionResult:{"android.permission.BLUETOOTH_CONNECT":"granted","android.permission.BLUETOOTH_SCAN":"granted","android.permission.ACCESS_FINE_LOCATION":"granted"}},{isSupported:!0,callRequestPermission:!1})}),it("should return false if platform is android with bad permissions",async()=>{await h({version:31,permissions:{ACCESS_FINE_LOCATION:"",BLUETOOTH_SCAN:"",BLUETOOTH_CONNECT:"BLUETOOTH_CONNECT"},requestPermissionResult:{"android.permission.ACCESS_FINE_LOCATION":"denied","android.permission.BLUETOOTH_CONNECT":"granted","android.permission.BLUETOOTH_SCAN":"granted"}},{isSupported:!1,callRequestPermission:!1})}),it("should return false if platform is android and denied permissions",async()=>{await h({version:31,permissions:{ACCESS_FINE_LOCATION:"ACCESS_FINE_LOCATION",BLUETOOTH_SCAN:"BLUETOOTH_SCAN",BLUETOOTH_CONNECT:"BLUETOOTH_CONNECT"},requestPermissionResult:{"android.permission.BLUETOOTH_CONNECT":"denied","android.permission.BLUETOOTH_SCAN":"denied","android.permission.ACCESS_FINE_LOCATION":"denied"}},{isSupported:!1,callRequestPermission:!1})}),it("should return false if platform isn't android nor ios",async()=>{const i=new l,n=new d("DeviceModelDataSource",()=>v,()=>{},()=>{},i,{OS:"windows"});await n.requestPermission();const e=n.isSupported();o(e).toBe(!1)})}),describe("startDiscovering",()=>{it("should throw error if transport is not supported",()=>{const i={OS:"windows"},n=new l,e=new d(u,()=>v,()=>{},()=>{},n,i);try{e.startDiscovering()}catch(s){o(s).toBeInstanceOf(q)}}),it("should emit an empty array",()=>new Promise(i=>{const n=new l;O=new d(u,()=>v,()=>{},()=>{},n,r,{}).startDiscovering().subscribe({next:t=>{o(t).toStrictEqual([]),i(void 0)},error:t=>{throw t},complete:()=>{i(void 0)}})})),it.skip("should emit discovered new device",()=>new Promise(i=>{let n=null;const e=new l,s=vi.fn().mockImplementation((c,k,a)=>(n=setInterval(()=>{a(null,{id:"id",localName:"name",serviceUUIDs:["ledgerId"],rssi:42})},500),a(null,{id:"43",localName:"name43",serviceUUIDs:["notLedgerId"],rssi:43}),Promise.resolve())),t=vi.fn().mockImplementation(()=>(n&&(clearInterval(n),n=null),Promise.resolve()));vi.spyOn(e,"connectedDevices").mockResolvedValueOnce([]),vi.spyOn(e,"startDeviceScan").mockImplementation(s),vi.spyOn(e,"stopDeviceScan").mockImplementation(t),O=new d(u,()=>v,()=>{},()=>{},e,r,{}).startDiscovering().subscribe({next:c=>{o(c).toStrictEqual([]),i(void 0)},error:c=>{throw c},complete:()=>{throw new Error("complete should not be called")}})})),it.skip("should emit both known and new device",()=>new Promise(i=>{let n=null;const e=new l,s={readRSSI:vi.fn().mockResolvedValueOnce({discoverAllServicesAndCharacteristics:vi.fn().mockResolvedValueOnce({services:vi.fn().mockResolvedValueOnce({}),serviceUUIDs:["ledgerId"],rssi:64,id:"knownDeviceId",localName:"knownDeviceName"})})},t=vi.fn().mockImplementation((a,f,D)=>(n=setInterval(()=>{D(null,{id:"newDeviceId",localName:"newDeviceName",serviceUUIDs:["ledgerId"],rssi:42})},500),D(null,{id:"43",localName:"name43",serviceUUIDs:["notLedgerId"],rssi:43}),Promise.resolve())),p=vi.fn().mockImplementation(()=>(n&&(clearInterval(n),n=null),Promise.resolve()));vi.spyOn(e,"connectedDevices").mockResolvedValueOnce([s]),vi.spyOn(e,"startDeviceScan").mockImplementation(t),vi.spyOn(e,"stopDeviceScan").mockImplementation(p),vi.spyOn(e,"onDeviceDisconnected").mockImplementation(vi.fn());const c=new d(u,()=>v,()=>{},()=>{},e,r,{}).startDiscovering(),k={};O=c.subscribe({next:a=>{k[a.id]=a,Object.values(k).length===2&&(o(Object.values(k)).toStrictEqual([{id:"knownDeviceId",name:"knownDeviceName",deviceModel:I,transport:"RN_BLE",rssi:64},{id:"newDeviceId",name:"newDeviceName",deviceModel:I,transport:"RN_BLE",rssi:42}]),i(void 0))}})}))}),describe("stopDiscovering",()=>{it("should call ble manager stop scan on stop discovering",()=>{const i=new l,n=vi.fn();vi.spyOn(i,"connectedDevices").mockResolvedValueOnce([]),vi.spyOn(i,"stopDeviceScan").mockImplementation(n),new d(u,()=>v,()=>{},()=>{},i,r,{}).stopDiscovering(),o(n).toHaveBeenCalled()}),it.skip("should call ble manager stop scan when unsubscribe startDiscovering obs",()=>{let i=null;const n=new l,e=vi.fn().mockImplementation((p,S,c)=>(i=setInterval(()=>{c(null,{id:"id",localName:"name",serviceUUIDs:["ledgerId"],rssi:42})},500),c(null,{id:"43",localName:"name43",serviceUUIDs:["notLedgerId"],rssi:43}),Promise.resolve())),s=vi.fn().mockImplementation(()=>(i&&(clearInterval(i),i=null),Promise.resolve()));vi.spyOn(n,"connectedDevices").mockResolvedValueOnce([]),vi.spyOn(n,"startDeviceScan").mockImplementation(e),vi.spyOn(n,"stopDeviceScan").mockImplementation(s),vi.spyOn(n,"onDeviceDisconnected").mockImplementation(vi.fn()),new d(u,()=>v,()=>{},()=>{},n,r,{}).startDiscovering().subscribe().unsubscribe(),o(e).toHaveBeenCalled(),o(s).toHaveBeenCalled()})}),describe("listenToAvailableDevices",()=>{it("should call startScan and connectedDevices from ble manager",()=>new Promise(i=>{let n=null;const e=new l,s={readRSSI:vi.fn().mockResolvedValueOnce({discoverAllServicesAndCharacteristics:vi.fn().mockResolvedValueOnce({services:vi.fn().mockResolvedValueOnce({}),serviceUUIDs:["ledgerId"],rssi:64,id:"knownDeviceId",localName:"knownDeviceName"})})},t=vi.fn().mockImplementation((c,k,a)=>{n=setInterval(()=>{a(null,{id:"id",localName:"name",serviceUUIDs:["ledgerId"],rssi:42})},10),a(null,{id:"43",localName:"name43",serviceUUIDs:["notLedgerId"],rssi:43})}),p=vi.fn().mockImplementation(()=>{n&&(clearInterval(n),n=null)});vi.spyOn(e,"connectedDevices").mockResolvedValueOnce([s]),vi.spyOn(e,"startDeviceScan").mockImplementation(t),vi.spyOn(e,"stopDeviceScan").mockImplementation(p),vi.spyOn(e,"onDeviceDisconnected").mockImplementation(vi.fn()),vi.spyOn(e,"isDeviceConnected").mockImplementation(vi.fn()),vi.spyOn(e,"onStateChange").mockImplementation(c=>(c(g.PoweredOn),{remove:vi.fn()})),O=new d(u,()=>v,()=>{},()=>{},e,r,{}).listenToAvailableDevices().subscribe({next:c=>{c.length===1&&(o(c).toEqual([{id:"id",name:"name",deviceModel:I,transport:"RN_BLE",rssi:42}]),i(void 0))}})}))}),describe("connect",()=>{let i;F(()=>{i=vi.fn().mockResolvedValueOnce([{readRSSI:vi.fn().mockResolvedValueOnce({discoverAllServicesAndCharacteristics:vi.fn().mockResolvedValueOnce({services:vi.fn().mockResolvedValueOnce({}),serviceUUIDs:["ledgerId"],rssi:64,id:"deviceId",localName:"knownDeviceName"})})}])}),it("should throw an error if device id is unknown",async()=>{const n=new l;vi.spyOn(n,"connectedDevices").mockImplementation(i),vi.spyOn(n,"discoverAllServicesAndCharacteristicsForDevice").mockRejectedValueOnce(new Error("discoverAllServicesAndCharacteristicsForDevice error"));const e=vi.fn().mockReturnValue({setupConnection:vi.fn().mockResolvedValue(void 0)}),t=await new d(u,()=>v,()=>{},()=>{},n,r,{},vi.fn(),e).connect({deviceId:null,onDisconnect:vi.fn()});o(t).toEqual(H(new B("discoverAllServicesAndCharacteristicsForDevice error")))}),it("should connect to a discovered device with correct MTU and discover services and setup apdu sender",async()=>{let n=null;const e=new l,s={readRSSI:vi.fn().mockResolvedValueOnce({discoverAllServicesAndCharacteristics:vi.fn().mockResolvedValueOnce({services:vi.fn().mockResolvedValueOnce({}),serviceUUIDs:["ledgerId"],rssi:64,id:"knownDeviceId",localName:"knownDeviceName"})}),services:vi.fn().mockResolvedValueOnce([{uuid:"ledgerId"}])},t=vi.fn().mockImplementation((w,C,A)=>{n=setInterval(()=>{A(null,{id:"deviceId",localName:"name",serviceUUIDs:["ledgerId"],rssi:42})},500),A(null,{id:"43",localName:"name43",serviceUUIDs:["notLedgerId"],rssi:43})}),p=vi.fn().mockImplementation(()=>{n&&(clearInterval(n),n=null)});vi.spyOn(e,"connectedDevices").mockImplementation(i),vi.spyOn(e,"startDeviceScan").mockImplementation(t),vi.spyOn(e,"stopDeviceScan").mockImplementation(p),vi.spyOn(e,"connectToDevice").mockResolvedValueOnce(s),vi.spyOn(e,"discoverAllServicesAndCharacteristicsForDevice").mockResolvedValueOnce(s),vi.spyOn(e,"monitorCharacteristicForDevice").mockImplementation(vi.fn()),vi.spyOn(e,"writeCharacteristicWithoutResponseForDevice").mockImplementation(vi.fn()),vi.spyOn(e,"onDeviceDisconnected").mockImplementation(vi.fn()),vi.spyOn(e,"isDeviceConnected").mockImplementation(vi.fn()),vi.spyOn(e,"onStateChange").mockImplementation(w=>(w(g.PoweredOn),{remove:vi.fn()}));const S=vi.fn().mockResolvedValue(void 0),c=vi.fn().mockReturnValue({sendApdu:vi.fn()}),k=vi.fn().mockReturnValue({setupConnection:S}),a=new d(u,()=>v,()=>{},()=>{},e,r,{},c,k),[f]=await N(a.listenToAvailableDevices().pipe(T(3))),D=await a.connect({deviceId:f.id,onDisconnect:vi.fn()});o(D.isRight()).toBe(!0),o(e.connectToDevice).toHaveBeenCalledWith("deviceId",{requestMTU:156}),o(e.discoverAllServicesAndCharacteristicsForDevice).toHaveBeenCalledWith("deviceId"),o(S).toHaveBeenCalled()}),it("should return a connected device which calls state machine sendApdu",async()=>{let n=null;const e=new l,s={id:"deviceId",readRSSI:vi.fn().mockResolvedValueOnce({discoverAllServicesAndCharacteristics:vi.fn().mockResolvedValueOnce({services:vi.fn().mockResolvedValueOnce({}),serviceUUIDs:["ledgerId"],rssi:64,id:"knownDeviceId",localName:"knownDeviceName"})}),services:vi.fn().mockResolvedValueOnce([{uuid:"ledgerId"}])},t=vi.fn().mockImplementation((C,A,m)=>{n=setInterval(()=>{m(null,{id:"deviceId",localName:"name",serviceUUIDs:["ledgerId"],rssi:42})},100)}),p=vi.fn().mockImplementation(()=>{n&&(clearInterval(n),n=null)});vi.spyOn(e,"connectedDevices").mockImplementation(i),vi.spyOn(e,"startDeviceScan").mockImplementation(t),vi.spyOn(e,"stopDeviceScan").mockImplementation(p),vi.spyOn(e,"connectToDevice").mockResolvedValueOnce(s),vi.spyOn(e,"discoverAllServicesAndCharacteristicsForDevice").mockResolvedValueOnce(s),vi.spyOn(e,"monitorCharacteristicForDevice").mockImplementation(vi.fn()),vi.spyOn(e,"writeCharacteristicWithoutResponseForDevice").mockImplementation(vi.fn()),vi.spyOn(e,"onDeviceDisconnected").mockImplementation(vi.fn()),vi.spyOn(e,"isDeviceConnected").mockImplementation(vi.fn()),vi.spyOn(e,"onStateChange").mockImplementation(C=>(C(g.PoweredOn),{remove:vi.fn()}));const S=vi.fn(),c=vi.fn().mockReturnValue({sendApdu:S}),k=vi.fn().mockReturnValue({setupConnection:vi.fn().mockResolvedValue(void 0)}),a=new d(u,()=>v,()=>{},()=>{},e,r,{},c,k),[f]=await N(a.listenToAvailableDevices().pipe(T(3))),D=await a.connect({deviceId:f.id,onDisconnect:vi.fn()});D.extract().sendApdu(Uint8Array.from([67,50])),o(D).toEqual(E(new M({id:"deviceId",deviceModel:I,type:"BLE",transport:"RN_BLE",sendApdu:o.any(Function)}))),o(S).toHaveBeenCalledWith(Uint8Array.from([67,50]))})}),describe("disconnect",()=>{let i;F(()=>{i=vi.fn().mockResolvedValue([{readRSSI:vi.fn().mockResolvedValueOnce({discoverAllServicesAndCharacteristics:vi.fn().mockResolvedValueOnce({services:vi.fn().mockResolvedValueOnce({}),serviceUUIDs:["ledgerId"],rssi:64,id:"deviceId",localName:"knownDeviceName"})})}])}),it("should disconnect gracefully",async()=>{let n=null;const e=new l,s={id:"deviceId",readRSSI:vi.fn().mockResolvedValueOnce({discoverAllServicesAndCharacteristics:vi.fn().mockResolvedValueOnce({services:vi.fn().mockResolvedValueOnce({}),serviceUUIDs:["ledgerId"],rssi:64,id:"knownDeviceId",localName:"knownDeviceName"})}),services:vi.fn().mockResolvedValueOnce([{uuid:"ledgerId"}])},t=vi.fn().mockImplementation((m,y,P)=>{n=setInterval(()=>{P(null,{id:"deviceId",localName:"name",serviceUUIDs:["ledgerId"],rssi:42})},100)}),p=vi.fn().mockImplementation(()=>{n&&(clearInterval(n),n=null)}),S=vi.fn().mockImplementation((m,y)=>(y(null,{deviceId:"deviceId",connect:vi.fn().mockResolvedValue({services:vi.fn().mockResolvedValueOnce({}),serviceUUIDs:["ledgerId"],rssi:64,id:"deviceId",localName:"knownDeviceName"}),discoverAllServicesAndCharacteristics:vi.fn().mockResolvedValueOnce({services:vi.fn().mockResolvedValueOnce({}),serviceUUIDs:["ledgerId"],rssi:64,id:"deviceId",localName:"knownDeviceName"})}),{remove:vi.fn()})),c=vi.fn();vi.spyOn(e,"connectedDevices").mockImplementation(i),vi.spyOn(e,"startDeviceScan").mockImplementation(t),vi.spyOn(e,"stopDeviceScan").mockImplementation(p),vi.spyOn(e,"connectToDevice").mockResolvedValueOnce(s),vi.spyOn(e,"discoverAllServicesAndCharacteristicsForDevice").mockResolvedValueOnce(s),vi.spyOn(e,"monitorCharacteristicForDevice").mockImplementation(vi.fn()),vi.spyOn(e,"writeCharacteristicWithoutResponseForDevice").mockImplementation(vi.fn()),vi.spyOn(e,"onDeviceDisconnected").mockImplementation(vi.fn()),vi.spyOn(e,"isDeviceConnected").mockImplementation(vi.fn()),vi.spyOn(e,"onStateChange").mockImplementation(m=>(m(g.PoweredOn),{remove:vi.fn()})),vi.spyOn(e,"onDeviceDisconnected").mockImplementation(S),vi.spyOn(e,"isDeviceConnected").mockImplementation(vi.fn());const k=m=>new U({deviceId:"deviceId",deviceApduSender:m.deviceApduSender,timeoutDuration:1e3,onTerminated:m.onTerminated}),a=vi.fn().mockReturnValue({setupConnection:vi.fn().mockResolvedValue(void 0),closeConnection:c}),f=new d(u,()=>v,()=>{},()=>{},e,r,{},k,a),D=vi.fn(),[w]=await N(f.listenToAvailableDevices().pipe(T(3))),C=await f.connect({deviceId:w.id,onDisconnect:D}),A=await f.disconnect({connectedDevice:C.extract()});o(A).toEqual(E(void 0)),o(D).toHaveBeenCalled(),o(c).toHaveBeenCalled()}),it("should handle error while disconnecting",async()=>{let n=null;const e=new l,s={id:"deviceId",readRSSI:vi.fn().mockResolvedValueOnce({discoverAllServicesAndCharacteristics:vi.fn().mockResolvedValueOnce({services:vi.fn().mockResolvedValueOnce({}),serviceUUIDs:["ledgerId"],rssi:64,id:"knownDeviceId",localName:"knownDeviceName"})}),services:vi.fn().mockResolvedValueOnce([{uuid:"ledgerId"}])},t=vi.fn().mockImplementation((m,y,P)=>{n=setInterval(()=>{P(null,{id:"deviceId",localName:"name",serviceUUIDs:["ledgerId"],rssi:42})},100)}),p=vi.fn().mockImplementation(()=>{n&&(clearInterval(n),n=null)}),S=vi.fn().mockImplementation((m,y)=>(y(new Error("yolo"),null),{remove:vi.fn()})),c=vi.fn();vi.spyOn(e,"connectedDevices").mockImplementation(i),vi.spyOn(e,"startDeviceScan").mockImplementation(t),vi.spyOn(e,"stopDeviceScan").mockImplementation(p),vi.spyOn(e,"connectToDevice").mockResolvedValueOnce(s),vi.spyOn(e,"discoverAllServicesAndCharacteristicsForDevice").mockResolvedValueOnce(s),vi.spyOn(e,"monitorCharacteristicForDevice").mockImplementation(vi.fn()),vi.spyOn(e,"writeCharacteristicWithoutResponseForDevice").mockImplementation(vi.fn()),vi.spyOn(e,"onDeviceDisconnected").mockImplementation(vi.fn()),vi.spyOn(e,"isDeviceConnected").mockImplementation(vi.fn()),vi.spyOn(e,"onStateChange").mockImplementation(m=>(m(g.PoweredOn),{remove:vi.fn()})),vi.spyOn(e,"onDeviceDisconnected").mockImplementation(S),vi.spyOn(e,"isDeviceConnected").mockImplementation(vi.fn());const k=m=>new U({deviceId:"deviceId",deviceApduSender:m.deviceApduSender,timeoutDuration:1e3,onTerminated:m.onTerminated}),a=vi.fn().mockReturnValue({setupConnection:vi.fn().mockResolvedValue(void 0),closeConnection:c}),f=new d(u,()=>v,()=>{},()=>{},e,r,{},k,a),D=vi.fn(),[w]=await N(f.listenToAvailableDevices().pipe(T(3))),C=await f.connect({deviceId:w.id,onDisconnect:D}),A=await f.disconnect({connectedDevice:C.extract()});o(A).toEqual(E(void 0)),o(D).toHaveBeenCalled()})})});
|
|
2
2
|
//# sourceMappingURL=RNBleTransport.test.js.map
|