@ledgerhq/device-transport-kit-react-native-ble 0.0.0-wip-20250214170223 → 1.1.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 +89 -0
- 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 +2 -0
- package/lib/cjs/api/transport/RNBleApduSender.test.js.map +7 -0
- 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 +2 -0
- package/lib/cjs/api/transport/RNBleTransport.test.js.map +7 -0
- package/lib/cjs/index.js.map +1 -1
- package/lib/cjs/package.json +22 -20
- 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 +2 -0
- package/lib/esm/api/transport/RNBleApduSender.test.js.map +7 -0
- 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 +2 -0
- package/lib/esm/api/transport/RNBleTransport.test.js.map +7 -0
- package/lib/esm/package.json +22 -20
- package/lib/types/api/model/Const.d.ts +3 -2
- package/lib/types/api/model/Const.d.ts.map +1 -1
- package/lib/types/api/model/Errors.d.ts +26 -1
- package/lib/types/api/model/Errors.d.ts.map +1 -1
- package/lib/types/api/transport/RNBleApduSender.d.ts +7 -9
- package/lib/types/api/transport/RNBleApduSender.d.ts.map +1 -1
- package/lib/types/api/transport/RNBleApduSender.test.d.ts +2 -0
- package/lib/types/api/transport/RNBleApduSender.test.d.ts.map +1 -0
- package/lib/types/api/transport/RNBleTransport.d.ts +33 -64
- package/lib/types/api/transport/RNBleTransport.d.ts.map +1 -1
- package/lib/types/api/transport/RNBleTransport.test.d.ts +2 -0
- package/lib/types/api/transport/RNBleTransport.test.d.ts.map +1 -0
- package/lib/types/tsconfig.prod.tsbuildinfo +1 -1
- package/package.json +23 -21
|
@@ -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 DeviceId,\n type DeviceModelDataSource,\n type DisconnectHandler,\n type DmkError,\n type LoggerPublisherService,\n OpeningConnectionError,\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 from,\n merge,\n Observable,\n retry,\n type Subscriber,\n switchMap,\n} from \"rxjs\";\n\nimport {\n BLE_DISCONNECT_TIMEOUT,\n CONNECTION_LOST_DELAY,\n DEFAULT_MTU,\n} from \"@api/model/Const\";\nimport {\n DeviceConnectionNotFound,\n InternalDeviceNotFound,\n} from \"@api/model/Errors\";\nimport {\n RNBleApduSender,\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\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 ) {\n this._logger = _loggerServiceFactory(\"ReactNativeBleTransport\");\n this._manager = new BleManager();\n this._isSupported = Maybe.zero();\n this._internalDevicesById = new Map();\n this._deviceConnectionsById = new Map();\n this.requestPermission();\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 const ledgerUuids = this._deviceModelDataSource.getBluetoothServices();\n this._internalDevicesById.clear();\n return from(this.requestPermission()).pipe(\n switchMap((isSupported) => {\n if (!isSupported) {\n throw new Error(\"BLE not supported\");\n }\n return merge(\n this._discoverKnownDevices(ledgerUuids),\n this._discoverNewDevices(ledgerUuids),\n );\n }),\n );\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 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 let device: Device;\n\n try {\n device = await this._manager.connectToDevice(params.deviceId, {\n requestMTU: DEFAULT_MTU,\n });\n await this._manager.discoverAllServicesAndCharacteristicsForDevice(\n params.deviceId,\n );\n } catch (error) {\n return throwE(new OpeningConnectionError(error));\n }\n\n const deviceApduSender = new RNBleApduSender(\n {\n apduSenderFactory: this._apduSenderFactory,\n apduReceiverFactory: this._apduReceiverFactory,\n dependencies: {\n device,\n internalDevice,\n manager: this._manager,\n },\n },\n this._loggerServiceFactory,\n );\n\n const deviceConnectionStateMachine =\n new DeviceConnectionStateMachine<RNBleApduSenderDependencies>({\n deviceId: params.deviceId,\n deviceApduSender,\n timeoutDuration: BLE_DISCONNECT_TIMEOUT,\n onTerminated: () => {\n params.onDisconnect(params.deviceId);\n this._deviceConnectionsById.delete(params.deviceId);\n const iDevice = this._internalDevicesById.get(params.deviceId);\n\n if (iDevice) {\n iDevice.disconnectionSubscription.remove();\n }\n\n this._internalDevicesById.delete(params.deviceId);\n },\n });\n\n await deviceApduSender.setupConnection();\n\n this._deviceConnectionsById.set(\n internalDevice.id,\n deviceConnectionStateMachine,\n );\n\n internalDevice.disconnectionSubscription =\n this._manager.onDeviceDisconnected(internalDevice.id, (...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 deviceConnection = Maybe.fromNullable(\n this._deviceConnectionsById.get(params.connectedDevice.id),\n );\n\n deviceConnection.map((d) => {\n d.closeConnection();\n });\n\n return Promise.resolve(Right(undefined));\n }\n\n private _isDiscoveredDeviceLost(internalDevice: RNBleInternalDevice) {\n return internalDevice.lastDiscoveredTimeStamp.caseOf({\n Just: (lastDiscoveredTimeStamp) =>\n Date.now() > lastDiscoveredTimeStamp + CONNECTION_LOST_DELAY,\n Nothing: () => {\n internalDevice.lastDiscoveredTimeStamp = Maybe.of(Date.now());\n return true;\n },\n });\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 listenToKnownDevices(): Observable<TransportDiscoveredDevice[]> {\n return from([]);\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 (Platform.OS === \"ios\") {\n this._isSupported = Maybe.of(true);\n return true;\n }\n\n if (\n Platform.OS === \"android\" &&\n PermissionsAndroid.PERMISSIONS[\"ACCESS_FINE_LOCATION\"]\n ) {\n const apiLevel = parseInt(Platform.Version.toString(), 10);\n\n if (apiLevel < 31) {\n const granted = await PermissionsAndroid.request(\n PermissionsAndroid.PERMISSIONS[\"ACCESS_FINE_LOCATION\"],\n );\n this._isSupported = Maybe.of(\n granted === PermissionsAndroid.RESULTS[\"GRANTED\"],\n );\n }\n if (\n PermissionsAndroid.PERMISSIONS[\"BLUETOOTH_SCAN\"] &&\n PermissionsAndroid.PERMISSIONS[\"BLUETOOTH_CONNECT\"]\n ) {\n const result = await PermissionsAndroid.requestMultiple([\n PermissionsAndroid.PERMISSIONS[\"BLUETOOTH_SCAN\"],\n PermissionsAndroid.PERMISSIONS[\"BLUETOOTH_CONNECT\"],\n PermissionsAndroid.PERMISSIONS[\"ACCESS_FINE_LOCATION\"],\n ]);\n\n this._isSupported = Maybe.of(\n result[\"android.permission.BLUETOOTH_CONNECT\"] ===\n PermissionsAndroid.RESULTS[\"GRANTED\"] &&\n result[\"android.permission.BLUETOOTH_SCAN\"] ===\n PermissionsAndroid.RESULTS[\"GRANTED\"] &&\n result[\"android.permission.ACCESS_FINE_LOCATION\"] ===\n 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() },\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 rnDevice?.serviceUUIDs?.find((uuid) => ledgerUuids.includes(uuid)),\n );\n\n const existingInternalDevice = Maybe.fromNullable(\n this._internalDevicesById.get(rnDevice.id),\n );\n\n if (existingInternalDevice.isJust()) {\n return Nothing;\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 };\n\n return {\n discoveredDevice,\n bleDeviceInfos,\n };\n });\n }, Nothing);\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 _handleLostDiscoveredDevices(\n subscriber: Subscriber<TransportDiscoveredDevice>,\n ) {\n this._internalDevicesById.forEach((internalDevice) => {\n if (this._isDiscoveredDeviceLost(internalDevice)) {\n this._internalDevicesById.delete(internalDevice.id);\n subscriber.next({\n ...internalDevice.discoveredDevice,\n available: false,\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} Does*/\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 available: true,\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 // this._internalDevicesById.delete(discoveredDevice.id);\n subscriber.next({ ...discoveredDevice, available: false });\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 return new Observable<TransportDiscoveredDevice>((subscriber) => {\n this._manager.startDeviceScan(null, null, (error, device) => {\n this._handleLostDiscoveredDevices(subscriber);\n\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 });\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 devices.forEach((device) => {\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 /**\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 * @param {DisconnectHandler} onDisconnect - A callback function to be called if the reconnection attempts fail completely.\n * @return {void}\n */\n private _handleDeviceDisconnected(\n error: BleError | null,\n device: Device | null,\n ) {\n if (error) {\n this._logger.error(\"device disconnected error\", {\n data: { error, device },\n });\n }\n\n if (!device) {\n this._logger.info(\"disconnected handler didn't found device\");\n return;\n }\n\n const errorOrDeviceConnection = Maybe.fromNullable(\n this._deviceConnectionsById.get(device.id),\n );\n\n errorOrDeviceConnection.map((deviceConnection) => {\n deviceConnection.eventDeviceDetached();\n });\n\n let reconnectedDevice: Device;\n\n from([0])\n .pipe(\n switchMap(async () => {\n try {\n reconnectedDevice = await device.connect({\n requestMTU: DEFAULT_MTU,\n });\n reconnectedDevice =\n await device.discoverAllServicesAndCharacteristics();\n await this._handleDeviceReconnected(reconnectedDevice);\n } catch (e) {\n this._logger.error(\n \"[_handleDeviceDisconnected] Reconnecting failed\",\n { data: { e } },\n );\n\n Maybe.fromNullable(this._deviceConnectionsById.get(device.id)).map(\n (deviceConnection) => {\n deviceConnection.closeConnection();\n },\n );\n\n throw e;\n }\n\n return device;\n }),\n retry({\n count: 5,\n delay: BLE_DISCONNECT_TIMEOUT / 5,\n }),\n )\n .subscribe({\n next: (value) =>\n this._logger.info(\n \"[_handleDeviceDisconnected] Got new device after reconnection\",\n { data: { value } },\n ),\n error: (e) => {\n this._logger.error(\n \"[_handleDeviceDisconnected] Reconnection failed after all retries\",\n { data: { e } },\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\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", "DeviceConnectionStateMachine", "OpeningConnectionError", "TransportConnectedDevice", "UnknownDeviceError", "EitherAsync", "Maybe", "Nothing", "Right", "
|
|
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 tryToReconnect: () => {\n this.tryToReconnect(params.deviceId);\n },\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.eventDeviceDisconnected(),\n );\n }\n\n private tryToReconnect(deviceId: DeviceId) {\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: deviceId } },\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: deviceId } },\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.eventDeviceConnected();\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,OAK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,CAAC,EAED,MAAMG,EAA6B,gBAAgB,EAAE,MAAOE,GAAM,CAChE,WAAK,YAAYpB,EAAO,EAAE,EACpBoB,CACR,CAAC,EAEDF,EAA6B,qBAAqB,CACpD,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
|
}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{BleManager as u,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 i}from"vitest";import{BleNotSupported as q}from"../model/Errors";import{RNBleTransport as v,RNBleTransportFactory as x}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",()=>({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(o=>Promise.resolve({ACCESS_FINE_LOCATION:r.accessFineLocationResult}[o])),PERMISSIONS:r.permissions,RESULTS:{GRANTED:"granted"},requestMultiple:vi.fn().mockImplementation(()=>Promise.resolve(r.requestPermissionResult))},m=new v("DeviceModelDataSource",()=>l,()=>{},()=>{},new u,b,R);await m.requestPermission();const O=m.isSupported();I.callRequestPermission&&i(R.request).toHaveBeenCalledWith("ACCESS_FINE_LOCATION"),i(O).toBe(I.isSupported)};describe("RNBleTransportFactory",()=>{it("should return a RNBleTransport",()=>{const I=x({deviceModelDataSource:"DeviceModelDataSource",loggerServiceFactory:()=>l,apduSenderServiceFactory:()=>{},apduReceiverServiceFactory:()=>{},config:{}});i(I).toBeInstanceOf(v)})});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")})),m={getBluetoothServices:b,getBluetoothServicesInfos:R};let O;F(()=>{vi.clearAllMocks()}),afterEach(()=>{O&&O.unsubscribe()}),describe("getIdentifier",()=>{it("should return rnBleTransportIdentifier",()=>{const o=new u,e=new v("DeviceModelDataSource",()=>l,()=>{},()=>{},o).getIdentifier();i(e).toStrictEqual("RN_BLE")})}),describe("isSupported",()=>{it("should return true if platform is ios",async()=>{const o={OS:"ios"},n=new u,e=new v("DeviceModelDataSource",()=>l,()=>{},()=>{},n,o);await e.requestPermission();const s=e.isSupported();i(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 o=new u,n=new v("DeviceModelDataSource",()=>l,()=>{},()=>{},o,{OS:"windows"});await n.requestPermission();const e=n.isSupported();i(e).toBe(!1)})}),describe("startDiscovering",()=>{it("should throw error if transport is not supported",()=>{const o={OS:"windows"},n=new u,e=new v(m,()=>l,()=>{},()=>{},n,o);try{e.startDiscovering()}catch(s){i(s).toBeInstanceOf(q)}}),it("should emit an empty array",()=>new Promise(o=>{const n=new u;O=new v(m,()=>l,()=>{},()=>{},n,r,{}).startDiscovering().subscribe({next:t=>{i(t).toStrictEqual([]),o(void 0)},error:t=>{throw t},complete:()=>{o(void 0)}})})),it.skip("should emit discovered new device",()=>new Promise(o=>{let n=null;const e=new u,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 v(m,()=>l,()=>{},()=>{},e,r,{}).startDiscovering().subscribe({next:c=>{i(c).toStrictEqual([]),o(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(o=>{let n=null;const e=new u,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 v(m,()=>l,()=>{},()=>{},e,r,{}).startDiscovering(),k={};O=c.subscribe({next:a=>{k[a.id]=a,Object.values(k).length===2&&(i(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}]),o(void 0))}})}))}),describe("stopDiscovering",()=>{it("should call ble manager stop scan on stop discovering",()=>{const o=new u,n=vi.fn();vi.spyOn(o,"connectedDevices").mockResolvedValueOnce([]),vi.spyOn(o,"stopDeviceScan").mockImplementation(n),new v(m,()=>l,()=>{},()=>{},o,r,{}).stopDiscovering(),i(n).toHaveBeenCalled()}),it.skip("should call ble manager stop scan when unsubscribe startDiscovering obs",()=>{let o=null;const n=new u,e=vi.fn().mockImplementation((p,S,c)=>(o=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(()=>(o&&(clearInterval(o),o=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 v(m,()=>l,()=>{},()=>{},n,r,{}).startDiscovering().subscribe().unsubscribe(),i(e).toHaveBeenCalled(),i(s).toHaveBeenCalled()})}),describe("listenToAvailableDevices",()=>{it("should call startScan and connectedDevices from ble manager",()=>new Promise(o=>{let n=null;const e=new u,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 v(m,()=>l,()=>{},()=>{},e,r,{}).listenToAvailableDevices().subscribe({next:c=>{c.length===1&&(i(c).toEqual([{id:"id",name:"name",deviceModel:I,transport:"RN_BLE",rssi:42}]),o(void 0))}})}))}),describe("connect",()=>{let o;F(()=>{o=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 u;vi.spyOn(n,"connectedDevices").mockImplementation(o),vi.spyOn(n,"discoverAllServicesAndCharacteristicsForDevice").mockRejectedValueOnce(new Error("discoverAllServicesAndCharacteristicsForDevice error"));const e=vi.fn().mockReturnValue({setupConnection:vi.fn().mockResolvedValue(void 0)}),t=await new v(m,()=>l,()=>{},()=>{},n,r,{},vi.fn(),e).connect({deviceId:null,onDisconnect:vi.fn()});i(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 u,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(o),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 v(m,()=>l,()=>{},()=>{},e,r,{},c,k),[f]=await N(a.listenToAvailableDevices().pipe(T(3))),D=await a.connect({deviceId:f.id,onDisconnect:vi.fn()});i(D.isRight()).toBe(!0),i(e.connectToDevice).toHaveBeenCalledWith("deviceId",{requestMTU:156}),i(e.discoverAllServicesAndCharacteristicsForDevice).toHaveBeenCalledWith("deviceId"),i(S).toHaveBeenCalled()}),it("should return a connected device which calls state machine sendApdu",async()=>{let n=null;const e=new u,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,d)=>{n=setInterval(()=>{d(null,{id:"deviceId",localName:"name",serviceUUIDs:["ledgerId"],rssi:42})},100)}),p=vi.fn().mockImplementation(()=>{n&&(clearInterval(n),n=null)});vi.spyOn(e,"connectedDevices").mockImplementation(o),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 v(m,()=>l,()=>{},()=>{},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])),i(D).toEqual(E(new M({id:"deviceId",deviceModel:I,type:"BLE",transport:"RN_BLE",sendApdu:i.any(Function)}))),i(S).toHaveBeenCalledWith(Uint8Array.from([67,50]))})}),describe("disconnect",()=>{let o;F(()=>{o=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 u,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((d,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((d,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(o),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(d=>(d(g.PoweredOn),{remove:vi.fn()})),vi.spyOn(e,"onDeviceDisconnected").mockImplementation(S),vi.spyOn(e,"isDeviceConnected").mockImplementation(vi.fn());const k=d=>new U({deviceId:"deviceId",deviceApduSender:d.deviceApduSender,timeoutDuration:1e3,onTerminated:d.onTerminated,tryToReconnect:d.tryToReconnect}),a=vi.fn().mockReturnValue({setupConnection:vi.fn().mockResolvedValue(void 0),closeConnection:c}),f=new v(m,()=>l,()=>{},()=>{},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()});i(A).toEqual(E(void 0)),i(D).toHaveBeenCalled(),i(c).toHaveBeenCalled()}),it("should handle error while disconnecting",async()=>{let n=null;const e=new u,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((d,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((d,y)=>(y(new Error("yolo"),null),{remove:vi.fn()})),c=vi.fn();vi.spyOn(e,"connectedDevices").mockImplementation(o),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(d=>(d(g.PoweredOn),{remove:vi.fn()})),vi.spyOn(e,"onDeviceDisconnected").mockImplementation(S),vi.spyOn(e,"isDeviceConnected").mockImplementation(vi.fn());const k=d=>new U({deviceId:"deviceId",deviceApduSender:d.deviceApduSender,timeoutDuration:1e3,onTerminated:d.onTerminated,tryToReconnect:d.tryToReconnect}),a=vi.fn().mockReturnValue({setupConnection:vi.fn().mockResolvedValue(void 0),closeConnection:c}),f=new v(m,()=>l,()=>{},()=>{},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()});i(A).toEqual(E(void 0)),i(D).toHaveBeenCalled()})})});
|
|
2
|
+
//# sourceMappingURL=RNBleTransport.test.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../../src/api/transport/RNBleTransport.test.ts"],
|
|
4
|
+
"sourcesContent": ["/* eslint @typescript-eslint/consistent-type-imports: off */\nimport { type PermissionsAndroid, type Platform } from \"react-native\";\nimport { type PermissionStatus } from \"react-native/Libraries/PermissionsAndroid/PermissionsAndroid\";\nimport { BleManager, type Device, State } from \"react-native-ble-plx\";\nimport {\n type ApduReceiverServiceFactory,\n type ApduSenderServiceFactory,\n BleDeviceInfos,\n DeviceConnectionStateMachine,\n type DeviceConnectionStateMachineParams,\n type DeviceModelDataSource,\n DeviceModelId,\n type DmkConfig,\n type LoggerPublisherService,\n OpeningConnectionError,\n TransportConnectedDevice,\n TransportDeviceModel,\n type TransportDiscoveredDevice,\n} from \"@ledgerhq/device-management-kit\";\nimport { Left, Right } from \"purify-ts\";\nimport { lastValueFrom, Subscription, take } from \"rxjs\";\nimport { beforeEach, expect, type Mock } from \"vitest\";\n\nimport { BleNotSupported } from \"@api/model/Errors\";\n\nimport { type RNBleApduSenderDependencies } from \"./RNBleApduSender\";\nimport { RNBleTransport, RNBleTransportFactory } from \"./RNBleTransport\";\n\nconst fakeLogger = {\n error: vi.fn(),\n info: vi.fn(),\n warn: vi.fn(),\n debug: vi.fn(),\n};\n\nvi.mock(\"react-native\", () => ({\n Platform: {},\n PermissionsAndroid: {},\n}));\n\nvi.mock(\"react-native-ble-plx\", () => ({\n Device: vi.fn(),\n State: {\n PoweredOn: \"PoweredOn\",\n Unknown: \"Unknown\",\n },\n BleError: vi.fn(),\n BleManager: vi.fn().mockReturnValue({\n onStateChange: vi.fn(),\n startDeviceScan: vi.fn(),\n stopDeviceScan: vi.fn(),\n connectToDevice: vi.fn(),\n disconnectFromDevice: vi.fn(),\n cancelDeviceConnection: vi.fn(),\n connectedDevices: vi.fn(),\n monitorCharacteristicForDevice: vi.fn(),\n writeCharacteristicWithoutResponseForDevice: vi.fn(),\n discoverAllServicesAndCharacteristicsForDevice: vi.fn(),\n onDeviceDisconnected: vi.fn(),\n isDeviceConnected: vi.fn(),\n }),\n}));\n\nconst expectAndroidSupportedResult = async (\n params: {\n version: number;\n permissions: Record<string, string>;\n requestPermissionResult: {\n \"android.permission.BLUETOOTH_CONNECT\": PermissionStatus;\n \"android.permission.BLUETOOTH_SCAN\": PermissionStatus;\n \"android.permission.ACCESS_FINE_LOCATION\": PermissionStatus;\n };\n accessFineLocationResult?: PermissionStatus;\n },\n expects: {\n isSupported: boolean;\n callRequestPermission: boolean;\n },\n) => {\n // given\n const platform = { OS: \"android\", Version: params.version };\n const permissionsAndroid = {\n request: vi.fn().mockImplementation((key: string) =>\n Promise.resolve(\n {\n ACCESS_FINE_LOCATION: params.accessFineLocationResult,\n }[key],\n ),\n ),\n PERMISSIONS: params.permissions,\n RESULTS: {\n GRANTED: \"granted\",\n },\n requestMultiple: vi\n .fn()\n .mockImplementation(() =>\n Promise.resolve(params.requestPermissionResult),\n ),\n };\n const transport = new RNBleTransport(\n \"DeviceModelDataSource\" as unknown as DeviceModelDataSource,\n () => fakeLogger as unknown as LoggerPublisherService,\n (() => {}) as unknown as ApduSenderServiceFactory,\n (() => {}) as unknown as ApduReceiverServiceFactory,\n new BleManager(),\n platform as Platform,\n permissionsAndroid as unknown as PermissionsAndroid,\n );\n // when\n await transport.requestPermission();\n const isSupported = transport.isSupported();\n // then\n if (expects.callRequestPermission) {\n expect(permissionsAndroid.request).toHaveBeenCalledWith(\n \"ACCESS_FINE_LOCATION\",\n );\n }\n expect(isSupported).toBe(expects.isSupported);\n};\n\ndescribe(\"RNBleTransportFactory\", () => {\n it(\"should return a RNBleTransport\", () => {\n const fakeArgs = {\n deviceModelDataSource:\n \"DeviceModelDataSource\" as unknown as DeviceModelDataSource,\n loggerServiceFactory: () =>\n fakeLogger as unknown as LoggerPublisherService,\n apduSenderServiceFactory:\n (() => {}) as unknown as ApduSenderServiceFactory,\n apduReceiverServiceFactory:\n (() => {}) as unknown as ApduReceiverServiceFactory,\n config: {} as DmkConfig,\n };\n // when\n const transport = RNBleTransportFactory(fakeArgs);\n // then\n expect(transport).toBeInstanceOf(RNBleTransport);\n });\n});\n\ndescribe(\"RNBleTransport\", () => {\n const fakePlaftorm = { OS: \"ios\" };\n const fakeDeviceModel = new TransportDeviceModel({\n id: DeviceModelId.FLEX,\n productName: \"Ledger Flex\",\n usbProductId: 0x70,\n bootloaderUsbProductId: 0x0007,\n usbOnly: false,\n memorySize: 1533 * 1024,\n blockSize: 32,\n masks: [0x33300000],\n });\n const getBluetoothServicesMock = vi.fn(() => [\"ledgerId\"]);\n const getBluetoothServicesInfosMock = vi.fn(() => ({\n ledgerId: new BleDeviceInfos(\n fakeDeviceModel,\n \"serviceUuid\",\n \"notifyUuid\",\n \"writeCmdUuid\",\n \"readCmdUuid\",\n ),\n }));\n const fakeDataSource = {\n getBluetoothServices: getBluetoothServicesMock,\n getBluetoothServicesInfos: getBluetoothServicesInfosMock,\n };\n\n let subscription: Subscription | undefined;\n\n beforeEach(() => {\n vi.clearAllMocks();\n });\n\n afterEach(() => {\n if (subscription) {\n subscription.unsubscribe();\n }\n });\n\n describe(\"getIdentifier\", () => {\n it(\"should return rnBleTransportIdentifier\", () => {\n // given\n const bleManager = new BleManager();\n const transport = new RNBleTransport(\n \"DeviceModelDataSource\" as unknown as DeviceModelDataSource,\n () => fakeLogger as unknown as LoggerPublisherService,\n (() => {}) as unknown as ApduSenderServiceFactory,\n (() => {}) as unknown as ApduReceiverServiceFactory,\n bleManager,\n );\n\n // when\n const identifier = transport.getIdentifier();\n\n // then\n expect(identifier).toStrictEqual(\"RN_BLE\");\n });\n });\n\n describe(\"isSupported\", () => {\n it(\"should return true if platform is ios\", async () => {\n // given\n const platform = { OS: \"ios\" };\n const bleManager = new BleManager();\n const transport = new RNBleTransport(\n \"DeviceModelDataSource\" as unknown as DeviceModelDataSource,\n () => fakeLogger as unknown as LoggerPublisherService,\n (() => {}) as unknown as ApduSenderServiceFactory,\n (() => {}) as unknown as ApduReceiverServiceFactory,\n bleManager,\n platform as Platform,\n );\n\n // when\n await transport.requestPermission();\n const isSupported = transport.isSupported();\n\n // then\n expect(isSupported).toBe(true);\n });\n\n it(\"should return true if platform is android and apiLevel < 31 with good permissions\", async () => {\n await expectAndroidSupportedResult(\n {\n version: 30,\n permissions: {\n ACCESS_FINE_LOCATION: \"ACCESS_FINE_LOCATION\",\n BLUETOOTH_SCAN: \"BLUETOOTH_SCAN\",\n BLUETOOTH_CONNECT: \"BLUETOOTH_CONNECT\",\n },\n requestPermissionResult: {\n \"android.permission.BLUETOOTH_CONNECT\": \"granted\",\n \"android.permission.BLUETOOTH_SCAN\": \"granted\",\n \"android.permission.ACCESS_FINE_LOCATION\": \"granted\",\n },\n },\n {\n isSupported: true,\n callRequestPermission: true,\n },\n );\n });\n\n it(\"should return true if platform is android and apiLevel >= 31 with good permissions\", async () => {\n await expectAndroidSupportedResult(\n {\n version: 31,\n permissions: {\n ACCESS_FINE_LOCATION: \"ACCESS_FINE_LOCATION\",\n BLUETOOTH_SCAN: \"BLUETOOTH_SCAN\",\n BLUETOOTH_CONNECT: \"BLUETOOTH_CONNECT\",\n },\n requestPermissionResult: {\n \"android.permission.BLUETOOTH_CONNECT\": \"granted\",\n \"android.permission.BLUETOOTH_SCAN\": \"granted\",\n \"android.permission.ACCESS_FINE_LOCATION\": \"granted\",\n },\n },\n {\n isSupported: true,\n callRequestPermission: false,\n },\n );\n });\n\n it(\"should return false if platform is android with bad permissions\", async () => {\n await expectAndroidSupportedResult(\n {\n version: 31,\n permissions: {\n ACCESS_FINE_LOCATION: \"\",\n BLUETOOTH_SCAN: \"\",\n BLUETOOTH_CONNECT: \"BLUETOOTH_CONNECT\",\n },\n requestPermissionResult: {\n \"android.permission.ACCESS_FINE_LOCATION\": \"denied\",\n \"android.permission.BLUETOOTH_CONNECT\": \"granted\",\n \"android.permission.BLUETOOTH_SCAN\": \"granted\",\n },\n },\n {\n isSupported: false,\n callRequestPermission: false,\n },\n );\n });\n\n it(\"should return false if platform is android and denied permissions\", async () => {\n await expectAndroidSupportedResult(\n {\n version: 31,\n permissions: {\n ACCESS_FINE_LOCATION: \"ACCESS_FINE_LOCATION\",\n BLUETOOTH_SCAN: \"BLUETOOTH_SCAN\",\n BLUETOOTH_CONNECT: \"BLUETOOTH_CONNECT\",\n },\n requestPermissionResult: {\n \"android.permission.BLUETOOTH_CONNECT\": \"denied\",\n \"android.permission.BLUETOOTH_SCAN\": \"denied\",\n \"android.permission.ACCESS_FINE_LOCATION\": \"denied\",\n },\n },\n {\n isSupported: false,\n callRequestPermission: false,\n },\n );\n });\n\n it(\"should return false if platform isn't android nor ios\", async () => {\n // given\n const bleManager = new BleManager();\n const transport = new RNBleTransport(\n \"DeviceModelDataSource\" as unknown as DeviceModelDataSource,\n () => fakeLogger as unknown as LoggerPublisherService,\n (() => {}) as unknown as ApduSenderServiceFactory,\n (() => {}) as unknown as ApduReceiverServiceFactory,\n bleManager,\n { OS: \"windows\" } as Platform,\n );\n\n // when\n await transport.requestPermission();\n const isSupported = transport.isSupported();\n\n // then\n expect(isSupported).toBe(false);\n });\n });\n\n // startDiscovering is not used / implemented anymore and just returns a from([])\n describe(\"startDiscovering\", () => {\n it(\"should throw error if transport is not supported\", () => {\n // given\n const platform = { OS: \"windows\" };\n const bleManager = new BleManager();\n\n const transport = new RNBleTransport(\n fakeDataSource as unknown as DeviceModelDataSource,\n () => fakeLogger as unknown as LoggerPublisherService,\n (() => {}) as unknown as ApduSenderServiceFactory,\n (() => {}) as unknown as ApduReceiverServiceFactory,\n bleManager,\n platform as Platform,\n );\n\n try {\n // when\n transport.startDiscovering();\n } catch (e) {\n // then\n expect(e).toBeInstanceOf(BleNotSupported);\n }\n });\n\n it(\"should emit an empty array\", () =>\n new Promise((done) => {\n // given\n const bleManager = new BleManager();\n\n const transport = new RNBleTransport(\n fakeDataSource as unknown as DeviceModelDataSource,\n () => fakeLogger as unknown as LoggerPublisherService,\n (() => {}) as unknown as ApduSenderServiceFactory,\n (() => {}) as unknown as ApduReceiverServiceFactory,\n bleManager,\n fakePlaftorm as Platform,\n {} as unknown as PermissionsAndroid,\n );\n\n // when\n const observable = transport.startDiscovering();\n\n // then\n subscription = observable.subscribe({\n next: (discoveredDevice) => {\n expect(discoveredDevice).toStrictEqual([]);\n done(undefined);\n },\n error: (e) => {\n throw e;\n },\n complete: () => {\n // Will complete as we use from([])\n done(undefined);\n },\n });\n }));\n\n it.skip(\"should emit discovered new device\", () =>\n new Promise((done) => {\n // given\n let scanInterval: NodeJS.Timeout | null = null;\n\n const bleManager = new BleManager();\n const startScan = vi\n .fn()\n .mockImplementation((_uuids, _options, listener) => {\n scanInterval = setInterval(() => {\n listener(null, {\n id: \"id\",\n localName: \"name\",\n serviceUUIDs: [\"ledgerId\"],\n rssi: 42,\n });\n }, 500);\n\n listener(null, {\n id: \"43\",\n localName: \"name43\",\n serviceUUIDs: [\"notLedgerId\"],\n rssi: 43,\n });\n\n return Promise.resolve();\n });\n\n const stopScan = vi.fn().mockImplementation(() => {\n if (scanInterval) {\n clearInterval(scanInterval);\n scanInterval = null;\n }\n return Promise.resolve();\n });\n\n vi.spyOn(bleManager, \"connectedDevices\").mockResolvedValueOnce([]);\n vi.spyOn(bleManager, \"startDeviceScan\").mockImplementation(startScan);\n vi.spyOn(bleManager, \"stopDeviceScan\").mockImplementation(stopScan);\n\n const transport = new RNBleTransport(\n fakeDataSource as unknown as DeviceModelDataSource,\n () => fakeLogger as unknown as LoggerPublisherService,\n (() => {}) as unknown as ApduSenderServiceFactory,\n (() => {}) as unknown as ApduReceiverServiceFactory,\n bleManager,\n fakePlaftorm as Platform,\n {} as unknown as PermissionsAndroid,\n );\n\n // when\n const observable = transport.startDiscovering();\n\n // then\n subscription = observable.subscribe({\n next: (discoveredDevice) => {\n expect(discoveredDevice).toStrictEqual([]);\n done(undefined);\n },\n error: (e) => {\n throw e;\n },\n complete: () => {\n throw new Error(\"complete should not be called\");\n },\n });\n }));\n\n it.skip(\"should emit both known and new device\", () =>\n new Promise((done) => {\n // given\n let scanInterval: NodeJS.Timeout | null = null;\n\n const bleManager = new BleManager();\n const mockDevice = {\n readRSSI: vi.fn().mockResolvedValueOnce({\n discoverAllServicesAndCharacteristics: vi\n .fn()\n .mockResolvedValueOnce({\n services: vi.fn().mockResolvedValueOnce({}),\n serviceUUIDs: [\"ledgerId\"],\n rssi: 64,\n id: \"knownDeviceId\",\n localName: \"knownDeviceName\",\n }),\n }),\n } as unknown as Device;\n\n const startScan = vi\n .fn()\n .mockImplementation((_uuids, _options, listener) => {\n scanInterval = setInterval(() => {\n listener(null, {\n id: \"newDeviceId\",\n localName: \"newDeviceName\",\n serviceUUIDs: [\"ledgerId\"],\n rssi: 42,\n } as unknown as Device);\n }, 500);\n\n listener(null, {\n id: \"43\",\n localName: \"name43\",\n serviceUUIDs: [\"notLedgerId\"],\n rssi: 43,\n } as unknown as Device);\n\n return Promise.resolve();\n });\n\n const stopScan = vi.fn().mockImplementation(() => {\n if (scanInterval) {\n clearInterval(scanInterval);\n scanInterval = null;\n }\n return Promise.resolve();\n });\n\n vi.spyOn(bleManager, \"connectedDevices\").mockResolvedValueOnce([\n mockDevice,\n ]);\n vi.spyOn(bleManager, \"startDeviceScan\").mockImplementation(startScan);\n vi.spyOn(bleManager, \"stopDeviceScan\").mockImplementation(stopScan);\n vi.spyOn(bleManager, \"onDeviceDisconnected\").mockImplementation(\n vi.fn(),\n );\n\n const transport = new RNBleTransport(\n fakeDataSource as unknown as DeviceModelDataSource,\n () => fakeLogger as unknown as LoggerPublisherService,\n (() => {}) as unknown as ApduSenderServiceFactory,\n (() => {}) as unknown as ApduReceiverServiceFactory,\n bleManager,\n fakePlaftorm as Platform,\n {} as unknown as PermissionsAndroid,\n );\n\n // when\n const obs = transport.startDiscovering();\n const discoveredDevices: Record<string, TransportDiscoveredDevice> = {};\n\n // then\n subscription = obs.subscribe({\n next: (device) => {\n discoveredDevices[device.id] = device;\n if (Object.values(discoveredDevices).length === 2) {\n expect(Object.values(discoveredDevices)).toStrictEqual([\n {\n id: \"knownDeviceId\",\n name: \"knownDeviceName\",\n deviceModel: fakeDeviceModel,\n transport: \"RN_BLE\",\n rssi: 64,\n },\n {\n id: \"newDeviceId\",\n name: \"newDeviceName\",\n deviceModel: fakeDeviceModel,\n transport: \"RN_BLE\",\n rssi: 42,\n },\n ]);\n done(undefined);\n }\n },\n });\n }));\n });\n\n describe(\"stopDiscovering\", () => {\n it(\"should call ble manager stop scan on stop discovering\", () => {\n // given\n const bleManager = new BleManager();\n const stopDeviceScan = vi.fn();\n vi.spyOn(bleManager, \"connectedDevices\").mockResolvedValueOnce([]);\n vi.spyOn(bleManager, \"stopDeviceScan\").mockImplementation(stopDeviceScan);\n\n const transport = new RNBleTransport(\n fakeDataSource as unknown as DeviceModelDataSource,\n () => fakeLogger as unknown as LoggerPublisherService,\n (() => {}) as unknown as ApduSenderServiceFactory,\n (() => {}) as unknown as ApduReceiverServiceFactory,\n bleManager,\n fakePlaftorm as Platform,\n {} as unknown as PermissionsAndroid,\n );\n\n // when\n transport.stopDiscovering();\n\n // then\n expect(stopDeviceScan).toHaveBeenCalled();\n });\n\n it.skip(\"should call ble manager stop scan when unsubscribe startDiscovering obs\", () => {\n // given\n let scanInterval: NodeJS.Timeout | null = null;\n\n const bleManager = new BleManager();\n const startScan = vi\n .fn()\n .mockImplementation((_uuids, _options, listener) => {\n scanInterval = setInterval(() => {\n listener(null, {\n id: \"id\",\n localName: \"name\",\n serviceUUIDs: [\"ledgerId\"],\n rssi: 42,\n });\n }, 500);\n listener(null, {\n id: \"43\",\n localName: \"name43\",\n serviceUUIDs: [\"notLedgerId\"],\n rssi: 43,\n });\n\n return Promise.resolve();\n });\n\n const stopScan = vi.fn().mockImplementation(() => {\n if (scanInterval) {\n clearInterval(scanInterval);\n scanInterval = null;\n }\n return Promise.resolve();\n });\n\n vi.spyOn(bleManager, \"connectedDevices\").mockResolvedValueOnce([]);\n vi.spyOn(bleManager, \"startDeviceScan\").mockImplementation(startScan);\n vi.spyOn(bleManager, \"stopDeviceScan\").mockImplementation(stopScan);\n vi.spyOn(bleManager, \"onDeviceDisconnected\").mockImplementation(vi.fn());\n\n const transport = new RNBleTransport(\n fakeDataSource as unknown as DeviceModelDataSource,\n () => fakeLogger as unknown as LoggerPublisherService,\n (() => {}) as unknown as ApduSenderServiceFactory,\n (() => {}) as unknown as ApduReceiverServiceFactory,\n bleManager,\n fakePlaftorm as Platform,\n {} as unknown as PermissionsAndroid,\n );\n\n // when\n transport.startDiscovering().subscribe().unsubscribe();\n\n // then\n expect(startScan).toHaveBeenCalled();\n expect(stopScan).toHaveBeenCalled();\n });\n });\n\n describe(\"listenToAvailableDevices\", () => {\n it(\"should call startScan and connectedDevices from ble manager\", () =>\n new Promise((done) => {\n // given\n let scanInterval: NodeJS.Timeout | null = null;\n\n const bleManager = new BleManager();\n const mockDevice = {\n readRSSI: vi.fn().mockResolvedValueOnce({\n discoverAllServicesAndCharacteristics: vi\n .fn()\n .mockResolvedValueOnce({\n services: vi.fn().mockResolvedValueOnce({}),\n serviceUUIDs: [\"ledgerId\"],\n rssi: 64,\n id: \"knownDeviceId\",\n localName: \"knownDeviceName\",\n }),\n }),\n } as unknown as Device;\n\n const startScan = vi\n .fn()\n .mockImplementation((_uuids, _options, listener) => {\n scanInterval = setInterval(() => {\n listener(null, {\n id: \"id\",\n localName: \"name\",\n serviceUUIDs: [\"ledgerId\"],\n rssi: 42,\n });\n }, 10);\n\n listener(null, {\n id: \"43\",\n localName: \"name43\",\n serviceUUIDs: [\"notLedgerId\"],\n rssi: 43,\n });\n });\n\n const stopScan = vi.fn().mockImplementation(() => {\n if (scanInterval) {\n clearInterval(scanInterval);\n scanInterval = null;\n }\n });\n\n vi.spyOn(bleManager, \"connectedDevices\").mockResolvedValueOnce([\n mockDevice,\n ]);\n vi.spyOn(bleManager, \"startDeviceScan\").mockImplementation(startScan);\n vi.spyOn(bleManager, \"stopDeviceScan\").mockImplementation(stopScan);\n vi.spyOn(bleManager, \"onDeviceDisconnected\").mockImplementation(\n vi.fn(),\n );\n vi.spyOn(bleManager, \"isDeviceConnected\").mockImplementation(vi.fn());\n vi.spyOn(bleManager, \"onStateChange\").mockImplementation(\n (listener: (state: State) => void) => {\n listener(State.PoweredOn);\n return {\n remove: vi.fn(),\n };\n },\n );\n\n const transport = new RNBleTransport(\n fakeDataSource as unknown as DeviceModelDataSource,\n () => fakeLogger as unknown as LoggerPublisherService,\n (() => {}) as unknown as ApduSenderServiceFactory,\n (() => {}) as unknown as ApduReceiverServiceFactory,\n bleManager,\n fakePlaftorm as Platform,\n {} as unknown as PermissionsAndroid,\n );\n\n // when\n subscription = transport.listenToAvailableDevices().subscribe({\n next: (devices) => {\n if (devices.length === 1) {\n // then\n expect(devices).toEqual([\n {\n id: \"id\",\n name: \"name\",\n deviceModel: fakeDeviceModel,\n transport: \"RN_BLE\",\n rssi: 42,\n },\n ]);\n done(undefined);\n }\n },\n });\n }));\n });\n\n describe(\"connect\", () => {\n let fakeConnectedDevices: Mock;\n\n beforeEach(() => {\n fakeConnectedDevices = vi.fn().mockResolvedValueOnce([\n {\n readRSSI: vi.fn().mockResolvedValueOnce({\n discoverAllServicesAndCharacteristics: vi\n .fn()\n .mockResolvedValueOnce({\n services: vi.fn().mockResolvedValueOnce({}),\n serviceUUIDs: [\"ledgerId\"],\n rssi: 64,\n id: \"deviceId\",\n localName: \"knownDeviceName\",\n }),\n }),\n },\n ]);\n });\n\n it(\"should throw an error if device id is unknown\", async () => {\n // given\n const bleManager = new BleManager();\n\n vi.spyOn(bleManager, \"connectedDevices\").mockImplementation(\n fakeConnectedDevices,\n );\n\n vi.spyOn(\n bleManager,\n \"discoverAllServicesAndCharacteristicsForDevice\",\n ).mockRejectedValueOnce(\n new Error(\"discoverAllServicesAndCharacteristicsForDevice error\"),\n );\n\n const deviceApduSenderFactory = vi.fn().mockReturnValue({\n setupConnection: vi.fn().mockResolvedValue(undefined),\n });\n\n const transport = new RNBleTransport(\n fakeDataSource as unknown as DeviceModelDataSource,\n () => fakeLogger as unknown as LoggerPublisherService,\n (() => {}) as unknown as ApduSenderServiceFactory,\n (() => {}) as unknown as ApduReceiverServiceFactory,\n bleManager,\n fakePlaftorm as Platform,\n {} as unknown as PermissionsAndroid,\n vi.fn(),\n deviceApduSenderFactory,\n );\n\n // when\n const result = await transport.connect({\n // @ts-expect-error test case\n deviceId: null,\n onDisconnect: vi.fn(),\n });\n\n // then\n expect(result).toEqual(\n Left(\n new OpeningConnectionError(\n `discoverAllServicesAndCharacteristicsForDevice error`,\n ),\n ),\n );\n });\n\n it(\"should connect to a discovered device with correct MTU and discover services and setup apdu sender\", async () => {\n // given\n let scanInterval: NodeJS.Timeout | null = null;\n const bleManager = new BleManager();\n const mockDevice = {\n readRSSI: vi.fn().mockResolvedValueOnce({\n discoverAllServicesAndCharacteristics: vi.fn().mockResolvedValueOnce({\n services: vi.fn().mockResolvedValueOnce({}),\n serviceUUIDs: [\"ledgerId\"],\n rssi: 64,\n id: \"knownDeviceId\",\n localName: \"knownDeviceName\",\n }),\n }),\n services: vi.fn().mockResolvedValueOnce([\n {\n uuid: \"ledgerId\",\n },\n ]),\n } as unknown as Device;\n\n const startScan = vi\n .fn()\n .mockImplementation((_uuids, _options, listener) => {\n scanInterval = setInterval(() => {\n listener(null, {\n id: \"deviceId\",\n localName: \"name\",\n serviceUUIDs: [\"ledgerId\"],\n rssi: 42,\n });\n }, 500);\n\n listener(null, {\n id: \"43\",\n localName: \"name43\",\n serviceUUIDs: [\"notLedgerId\"],\n rssi: 43,\n });\n });\n\n const stopScan = vi.fn().mockImplementation(() => {\n if (scanInterval) {\n clearInterval(scanInterval);\n scanInterval = null;\n }\n });\n\n vi.spyOn(bleManager, \"connectedDevices\").mockImplementation(\n fakeConnectedDevices,\n );\n vi.spyOn(bleManager, \"startDeviceScan\").mockImplementation(startScan);\n vi.spyOn(bleManager, \"stopDeviceScan\").mockImplementation(stopScan);\n vi.spyOn(bleManager, \"connectToDevice\").mockResolvedValueOnce(mockDevice);\n vi.spyOn(\n bleManager,\n \"discoverAllServicesAndCharacteristicsForDevice\",\n ).mockResolvedValueOnce(mockDevice);\n vi.spyOn(bleManager, \"monitorCharacteristicForDevice\").mockImplementation(\n vi.fn(),\n );\n vi.spyOn(\n bleManager,\n \"writeCharacteristicWithoutResponseForDevice\",\n ).mockImplementation(vi.fn());\n vi.spyOn(bleManager, \"onDeviceDisconnected\").mockImplementation(vi.fn());\n vi.spyOn(bleManager, \"isDeviceConnected\").mockImplementation(vi.fn());\n vi.spyOn(bleManager, \"onStateChange\").mockImplementation(\n (listener: (state: State) => void) => {\n listener(State.PoweredOn);\n return {\n remove: vi.fn(),\n };\n },\n );\n\n const fakeSetupConnection = vi.fn().mockResolvedValue(undefined);\n const deviceConnectionStateMachineFactory = vi.fn().mockReturnValue({\n sendApdu: vi.fn(),\n });\n const deviceApduSenderFactory = vi.fn().mockReturnValue({\n setupConnection: fakeSetupConnection,\n });\n\n const transport = new RNBleTransport(\n fakeDataSource as unknown as DeviceModelDataSource,\n () => fakeLogger as unknown as LoggerPublisherService,\n (() => {}) as unknown as ApduSenderServiceFactory,\n (() => {}) as unknown as ApduReceiverServiceFactory,\n bleManager,\n fakePlaftorm as Platform,\n {} as unknown as PermissionsAndroid,\n deviceConnectionStateMachineFactory,\n deviceApduSenderFactory,\n );\n\n // when\n const [device] = await lastValueFrom(\n transport.listenToAvailableDevices().pipe(take(3)),\n );\n\n const result = await transport.connect({\n deviceId: device!.id,\n onDisconnect: vi.fn(),\n });\n\n // then\n expect(result.isRight()).toBe(true);\n expect(bleManager.connectToDevice).toHaveBeenCalledWith(\"deviceId\", {\n requestMTU: 156,\n });\n expect(\n bleManager.discoverAllServicesAndCharacteristicsForDevice,\n ).toHaveBeenCalledWith(\"deviceId\");\n expect(fakeSetupConnection).toHaveBeenCalled();\n });\n\n it(\"should return a connected device which calls state machine sendApdu\", async () => {\n // given\n let scanInterval: NodeJS.Timeout | null = null;\n const bleManager = new BleManager();\n const mockDevice = {\n id: \"deviceId\",\n readRSSI: vi.fn().mockResolvedValueOnce({\n discoverAllServicesAndCharacteristics: vi.fn().mockResolvedValueOnce({\n services: vi.fn().mockResolvedValueOnce({}),\n serviceUUIDs: [\"ledgerId\"],\n rssi: 64,\n id: \"knownDeviceId\",\n localName: \"knownDeviceName\",\n }),\n }),\n services: vi.fn().mockResolvedValueOnce([\n {\n uuid: \"ledgerId\",\n },\n ]),\n } as unknown as Device;\n\n const startScan = vi\n .fn()\n .mockImplementation((_uuids, _options, listener) => {\n scanInterval = setInterval(() => {\n listener(null, {\n id: \"deviceId\",\n localName: \"name\",\n serviceUUIDs: [\"ledgerId\"],\n rssi: 42,\n });\n }, 100);\n });\n\n const stopScan = vi.fn().mockImplementation(() => {\n if (scanInterval) {\n clearInterval(scanInterval);\n scanInterval = null;\n }\n });\n\n vi.spyOn(bleManager, \"connectedDevices\").mockImplementation(\n fakeConnectedDevices,\n );\n vi.spyOn(bleManager, \"startDeviceScan\").mockImplementation(startScan);\n vi.spyOn(bleManager, \"stopDeviceScan\").mockImplementation(stopScan);\n vi.spyOn(bleManager, \"connectToDevice\").mockResolvedValueOnce(mockDevice);\n vi.spyOn(\n bleManager,\n \"discoverAllServicesAndCharacteristicsForDevice\",\n ).mockResolvedValueOnce(mockDevice);\n vi.spyOn(bleManager, \"monitorCharacteristicForDevice\").mockImplementation(\n vi.fn(),\n );\n vi.spyOn(\n bleManager,\n \"writeCharacteristicWithoutResponseForDevice\",\n ).mockImplementation(vi.fn());\n vi.spyOn(bleManager, \"onDeviceDisconnected\").mockImplementation(vi.fn());\n vi.spyOn(bleManager, \"isDeviceConnected\").mockImplementation(vi.fn());\n vi.spyOn(bleManager, \"onStateChange\").mockImplementation(\n (listener: (state: State) => void) => {\n listener(State.PoweredOn);\n return {\n remove: vi.fn(),\n };\n },\n );\n\n const fakeSendApdu = vi.fn();\n const deviceConnectionStateMachineFactory = vi.fn().mockReturnValue({\n sendApdu: fakeSendApdu,\n });\n const deviceApduSenderFactory = vi.fn().mockReturnValue({\n setupConnection: vi.fn().mockResolvedValue(undefined),\n });\n\n const transport = new RNBleTransport(\n fakeDataSource as unknown as DeviceModelDataSource,\n () => fakeLogger as unknown as LoggerPublisherService,\n (() => {}) as unknown as ApduSenderServiceFactory,\n (() => {}) as unknown as ApduReceiverServiceFactory,\n bleManager,\n fakePlaftorm as Platform,\n {} as unknown as PermissionsAndroid,\n deviceConnectionStateMachineFactory,\n deviceApduSenderFactory,\n );\n\n // when\n const [device] = await lastValueFrom(\n transport.listenToAvailableDevices().pipe(take(3)),\n );\n\n const result = await transport.connect({\n deviceId: device!.id,\n onDisconnect: vi.fn(),\n });\n\n const connectedDevice = result.extract() as TransportConnectedDevice;\n connectedDevice.sendApdu(Uint8Array.from([0x43, 0x32]));\n // then\n expect(result).toEqual(\n Right(\n new TransportConnectedDevice({\n id: \"deviceId\",\n deviceModel: fakeDeviceModel,\n type: \"BLE\",\n transport: \"RN_BLE\",\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n sendApdu: expect.any(Function),\n }),\n ),\n );\n expect(fakeSendApdu).toHaveBeenCalledWith(Uint8Array.from([0x43, 0x32]));\n });\n });\n\n describe(\"disconnect\", () => {\n let fakeConnectedDevices: Mock;\n\n beforeEach(() => {\n fakeConnectedDevices = vi.fn().mockResolvedValue([\n {\n readRSSI: vi.fn().mockResolvedValueOnce({\n discoverAllServicesAndCharacteristics: vi\n .fn()\n .mockResolvedValueOnce({\n services: vi.fn().mockResolvedValueOnce({}),\n serviceUUIDs: [\"ledgerId\"],\n rssi: 64,\n id: \"deviceId\",\n localName: \"knownDeviceName\",\n }),\n }),\n },\n ]);\n });\n\n it(\"should disconnect gracefully\", async () => {\n let scanInterval: NodeJS.Timeout | null = null;\n const bleManager = new BleManager();\n const mockDevice = {\n id: \"deviceId\",\n readRSSI: vi.fn().mockResolvedValueOnce({\n discoverAllServicesAndCharacteristics: vi.fn().mockResolvedValueOnce({\n services: vi.fn().mockResolvedValueOnce({}),\n serviceUUIDs: [\"ledgerId\"],\n rssi: 64,\n id: \"knownDeviceId\",\n localName: \"knownDeviceName\",\n }),\n }),\n services: vi.fn().mockResolvedValueOnce([\n {\n uuid: \"ledgerId\",\n },\n ]),\n } as unknown as Device;\n\n const startScan = vi\n .fn()\n .mockImplementation((_uuids, _options, listener) => {\n scanInterval = setInterval(() => {\n listener(null, {\n id: \"deviceId\",\n localName: \"name\",\n serviceUUIDs: [\"ledgerId\"],\n rssi: 42,\n });\n }, 100);\n });\n\n const stopScan = vi.fn().mockImplementation(() => {\n if (scanInterval) {\n clearInterval(scanInterval);\n scanInterval = null;\n }\n });\n\n const onDeviceDisconnected = vi\n .fn()\n .mockImplementation((_id, callback) => {\n callback(null, {\n deviceId: \"deviceId\",\n connect: vi.fn().mockResolvedValue({\n services: vi.fn().mockResolvedValueOnce({}),\n serviceUUIDs: [\"ledgerId\"],\n rssi: 64,\n id: \"deviceId\",\n localName: \"knownDeviceName\",\n }),\n discoverAllServicesAndCharacteristics: vi\n .fn()\n .mockResolvedValueOnce({\n services: vi.fn().mockResolvedValueOnce({}),\n serviceUUIDs: [\"ledgerId\"],\n rssi: 64,\n id: \"deviceId\",\n localName: \"knownDeviceName\",\n }),\n });\n return { remove: vi.fn() };\n });\n\n const fakeCloseConnection = vi.fn();\n\n vi.spyOn(bleManager, \"connectedDevices\").mockImplementation(\n fakeConnectedDevices,\n );\n vi.spyOn(bleManager, \"startDeviceScan\").mockImplementation(startScan);\n vi.spyOn(bleManager, \"stopDeviceScan\").mockImplementation(stopScan);\n vi.spyOn(bleManager, \"connectToDevice\").mockResolvedValueOnce(mockDevice);\n vi.spyOn(\n bleManager,\n \"discoverAllServicesAndCharacteristicsForDevice\",\n ).mockResolvedValueOnce(mockDevice);\n vi.spyOn(bleManager, \"monitorCharacteristicForDevice\").mockImplementation(\n vi.fn(),\n );\n vi.spyOn(\n bleManager,\n \"writeCharacteristicWithoutResponseForDevice\",\n ).mockImplementation(vi.fn());\n vi.spyOn(bleManager, \"onDeviceDisconnected\").mockImplementation(vi.fn());\n vi.spyOn(bleManager, \"isDeviceConnected\").mockImplementation(vi.fn());\n vi.spyOn(bleManager, \"onStateChange\").mockImplementation(\n (listener: (state: State) => void) => {\n listener(State.PoweredOn);\n return {\n remove: vi.fn(),\n };\n },\n );\n\n vi.spyOn(bleManager, \"onDeviceDisconnected\").mockImplementation(\n onDeviceDisconnected,\n );\n vi.spyOn(bleManager, \"isDeviceConnected\").mockImplementation(vi.fn());\n\n const deviceConnectionStateMachineFactory = (\n _args: DeviceConnectionStateMachineParams<RNBleApduSenderDependencies>,\n ) => {\n return new DeviceConnectionStateMachine({\n deviceId: \"deviceId\",\n deviceApduSender: _args.deviceApduSender,\n timeoutDuration: 1000,\n onTerminated: _args.onTerminated,\n tryToReconnect: _args.tryToReconnect,\n });\n };\n\n const deviceApduSenderFactory = vi.fn().mockReturnValue({\n setupConnection: vi.fn().mockResolvedValue(undefined),\n closeConnection: fakeCloseConnection,\n });\n\n const transport = new RNBleTransport(\n fakeDataSource as unknown as DeviceModelDataSource,\n () => fakeLogger as unknown as LoggerPublisherService,\n (() => {}) as unknown as ApduSenderServiceFactory,\n (() => {}) as unknown as ApduReceiverServiceFactory,\n bleManager,\n fakePlaftorm as Platform,\n {} as unknown as PermissionsAndroid,\n deviceConnectionStateMachineFactory,\n deviceApduSenderFactory,\n );\n\n const fakeOnDisconnect = vi.fn();\n\n // when\n const [device] = await lastValueFrom(\n transport.listenToAvailableDevices().pipe(take(3)),\n );\n\n const result = await transport.connect({\n deviceId: device!.id,\n onDisconnect: fakeOnDisconnect,\n });\n\n const res = await transport.disconnect({\n connectedDevice: result.extract() as TransportConnectedDevice,\n });\n\n // then\n expect(res).toEqual(Right(undefined));\n expect(fakeOnDisconnect).toHaveBeenCalled();\n expect(fakeCloseConnection).toHaveBeenCalled();\n });\n\n it(\"should handle error while disconnecting\", async () => {\n let scanInterval: NodeJS.Timeout | null = null;\n const bleManager = new BleManager();\n const mockDevice = {\n id: \"deviceId\",\n readRSSI: vi.fn().mockResolvedValueOnce({\n discoverAllServicesAndCharacteristics: vi.fn().mockResolvedValueOnce({\n services: vi.fn().mockResolvedValueOnce({}),\n serviceUUIDs: [\"ledgerId\"],\n rssi: 64,\n id: \"knownDeviceId\",\n localName: \"knownDeviceName\",\n }),\n }),\n services: vi.fn().mockResolvedValueOnce([\n {\n uuid: \"ledgerId\",\n },\n ]),\n } as unknown as Device;\n\n const startScan = vi\n .fn()\n .mockImplementation((_uuids, _options, listener) => {\n scanInterval = setInterval(() => {\n listener(null, {\n id: \"deviceId\",\n localName: \"name\",\n serviceUUIDs: [\"ledgerId\"],\n rssi: 42,\n });\n }, 100);\n });\n\n const stopScan = vi.fn().mockImplementation(() => {\n if (scanInterval) {\n clearInterval(scanInterval);\n scanInterval = null;\n }\n });\n\n const onDeviceDisconnected = vi\n .fn()\n .mockImplementation((_id, callback) => {\n callback(new Error(\"yolo\"), null);\n return { remove: vi.fn() };\n });\n\n const fakeCloseConnection = vi.fn();\n\n vi.spyOn(bleManager, \"connectedDevices\").mockImplementation(\n fakeConnectedDevices,\n );\n vi.spyOn(bleManager, \"startDeviceScan\").mockImplementation(startScan);\n vi.spyOn(bleManager, \"stopDeviceScan\").mockImplementation(stopScan);\n vi.spyOn(bleManager, \"connectToDevice\").mockResolvedValueOnce(mockDevice);\n vi.spyOn(\n bleManager,\n \"discoverAllServicesAndCharacteristicsForDevice\",\n ).mockResolvedValueOnce(mockDevice);\n vi.spyOn(bleManager, \"monitorCharacteristicForDevice\").mockImplementation(\n vi.fn(),\n );\n vi.spyOn(\n bleManager,\n \"writeCharacteristicWithoutResponseForDevice\",\n ).mockImplementation(vi.fn());\n vi.spyOn(bleManager, \"onDeviceDisconnected\").mockImplementation(vi.fn());\n vi.spyOn(bleManager, \"isDeviceConnected\").mockImplementation(vi.fn());\n vi.spyOn(bleManager, \"onStateChange\").mockImplementation(\n (listener: (state: State) => void) => {\n listener(State.PoweredOn);\n return {\n remove: vi.fn(),\n };\n },\n );\n\n vi.spyOn(bleManager, \"onDeviceDisconnected\").mockImplementation(\n onDeviceDisconnected,\n );\n vi.spyOn(bleManager, \"isDeviceConnected\").mockImplementation(vi.fn());\n\n const deviceConnectionStateMachineFactory = (\n _args: DeviceConnectionStateMachineParams<RNBleApduSenderDependencies>,\n ) => {\n return new DeviceConnectionStateMachine({\n deviceId: \"deviceId\",\n deviceApduSender: _args.deviceApduSender,\n timeoutDuration: 1000,\n onTerminated: _args.onTerminated,\n tryToReconnect: _args.tryToReconnect,\n });\n };\n\n const deviceApduSenderFactory = vi.fn().mockReturnValue({\n setupConnection: vi.fn().mockResolvedValue(undefined),\n closeConnection: fakeCloseConnection,\n });\n\n const transport = new RNBleTransport(\n fakeDataSource as unknown as DeviceModelDataSource,\n () => fakeLogger as unknown as LoggerPublisherService,\n (() => {}) as unknown as ApduSenderServiceFactory,\n (() => {}) as unknown as ApduReceiverServiceFactory,\n bleManager,\n fakePlaftorm as Platform,\n {} as unknown as PermissionsAndroid,\n deviceConnectionStateMachineFactory,\n deviceApduSenderFactory,\n );\n\n const fakeOnDisconnect = vi.fn();\n\n // when\n const [device] = await lastValueFrom(\n transport.listenToAvailableDevices().pipe(take(3)),\n );\n const result = await transport.connect({\n deviceId: device!.id,\n onDisconnect: fakeOnDisconnect,\n });\n\n const res = await transport.disconnect({\n connectedDevice: result.extract() as TransportConnectedDevice,\n });\n\n // then\n expect(res).toEqual(Right(undefined));\n expect(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AUsB,EAAQ,GAClB,aAAcc,CAChB,CAAC,EAEKC,EAAM,MAAMrC,EAAU,WAAW,CACrC,gBAAiB2B,EAAO,QAAQ,CAClC,CAAC,EAGDtC,EAAOgD,CAAG,EAAE,QAAQpD,EAAM,MAAS,CAAC,EACpCI,EAAO+C,CAAgB,EAAE,iBAAiB,CAC5C,CAAC,CACH,CAAC,CACH,CAAC",
|
|
6
|
+
"names": ["BleManager", "State", "BleDeviceInfos", "DeviceConnectionStateMachine", "DeviceModelId", "OpeningConnectionError", "TransportConnectedDevice", "TransportDeviceModel", "Left", "Right", "lastValueFrom", "take", "beforeEach", "expect", "BleNotSupported", "RNBleTransport", "RNBleTransportFactory", "fakeLogger", "expectAndroidSupportedResult", "params", "expects", "platform", "permissionsAndroid", "key", "transport", "isSupported", "fakePlaftorm", "fakeDeviceModel", "getBluetoothServicesMock", "getBluetoothServicesInfosMock", "fakeDataSource", "subscription", "bleManager", "identifier", "e", "done", "discoveredDevice", "scanInterval", "startScan", "_uuids", "_options", "listener", "stopScan", "mockDevice", "obs", "discoveredDevices", "device", "stopDeviceScan", "devices", "fakeConnectedDevices", "deviceApduSenderFactory", "result", "fakeSetupConnection", "deviceConnectionStateMachineFactory", "fakeSendApdu", "onDeviceDisconnected", "_id", "callback", "fakeCloseConnection", "_args", "fakeOnDisconnect", "res"]
|
|
7
|
+
}
|
package/lib/esm/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ledgerhq/device-transport-kit-react-native-ble",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "1.1.0",
|
|
4
4
|
"license": "Apache-2.0",
|
|
5
5
|
"private": false,
|
|
6
6
|
"exports": {
|
|
@@ -20,9 +20,9 @@
|
|
|
20
20
|
],
|
|
21
21
|
"scripts": {
|
|
22
22
|
"prebuild": "rimraf lib",
|
|
23
|
-
"build": "pnpm
|
|
23
|
+
"build": "pnpm ldmk-tool build --entryPoints src/index.ts,src/**/*.ts --tsconfig tsconfig.prod.json",
|
|
24
24
|
"dev": "concurrently \"pnpm watch:builds\" \"pnpm watch:types\"",
|
|
25
|
-
"watch:builds": "pnpm
|
|
25
|
+
"watch:builds": "pnpm ldmk-tool watch --entryPoints src/index.ts,src/**/*.ts --tsconfig tsconfig.prod.json",
|
|
26
26
|
"watch:types": "concurrently \"tsc --watch -p tsconfig.prod.json\" \"tsc-alias --watch -p tsconfig.prod.json\"",
|
|
27
27
|
"lint": "eslint",
|
|
28
28
|
"lint:fix": "pnpm lint --fix",
|
|
@@ -30,33 +30,35 @@
|
|
|
30
30
|
"prettier": "prettier . --check",
|
|
31
31
|
"prettier:fix": "prettier . --write",
|
|
32
32
|
"typecheck": "tsc --noEmit",
|
|
33
|
-
"test": "vitest run
|
|
34
|
-
"test:watch": "vitest
|
|
35
|
-
"test:coverage": "vitest run --coverage
|
|
33
|
+
"test": "vitest run",
|
|
34
|
+
"test:watch": "vitest",
|
|
35
|
+
"test:coverage": "vitest run --coverage"
|
|
36
36
|
},
|
|
37
37
|
"dependencies": {
|
|
38
|
-
"@sentry/minimal": "
|
|
39
|
-
"js-base64": "
|
|
40
|
-
"purify-ts": "
|
|
41
|
-
"uuid": "
|
|
38
|
+
"@sentry/minimal": "catalog:",
|
|
39
|
+
"js-base64": "catalog:",
|
|
40
|
+
"purify-ts": "catalog:",
|
|
41
|
+
"uuid": "catalog:"
|
|
42
42
|
},
|
|
43
43
|
"devDependencies": {
|
|
44
44
|
"@ledgerhq/device-management-kit": "workspace:*",
|
|
45
|
-
"@ledgerhq/esbuild-tools": "workspace:*",
|
|
46
45
|
"@ledgerhq/eslint-config-dsdk": "workspace:*",
|
|
47
|
-
"@ledgerhq/
|
|
46
|
+
"@ledgerhq/ldmk-tool": "workspace:*",
|
|
48
47
|
"@ledgerhq/prettier-config-dsdk": "workspace:*",
|
|
49
48
|
"@ledgerhq/tsconfig-dsdk": "workspace:*",
|
|
50
|
-
"@
|
|
51
|
-
"
|
|
52
|
-
"react
|
|
53
|
-
"
|
|
54
|
-
"
|
|
49
|
+
"@ledgerhq/vitest-config-dmk": "workspace:*",
|
|
50
|
+
"@types/uuid": "catalog:",
|
|
51
|
+
"@vitejs/plugin-react": "catalog:",
|
|
52
|
+
"react-native": "catalog:",
|
|
53
|
+
"react-native-ble-plx": "catalog:",
|
|
54
|
+
"rxjs": "catalog:",
|
|
55
|
+
"ts-node": "catalog:",
|
|
56
|
+
"vitest-react-native": "catalog:"
|
|
55
57
|
},
|
|
56
58
|
"peerDependencies": {
|
|
57
59
|
"@ledgerhq/device-management-kit": "workspace:*",
|
|
58
|
-
"react-native
|
|
59
|
-
"react-native": "
|
|
60
|
-
"rxjs": "
|
|
60
|
+
"react-native": ">0.74.1",
|
|
61
|
+
"react-native-ble-plx": "3.4.0",
|
|
62
|
+
"rxjs": "catalog:"
|
|
61
63
|
}
|
|
62
64
|
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
export declare const DEFAULT_MTU = 156;
|
|
2
|
-
export declare const CONNECTION_LOST_DELAY =
|
|
3
|
-
export declare const
|
|
2
|
+
export declare const CONNECTION_LOST_DELAY = 2000;
|
|
3
|
+
export declare const BLE_DISCONNECT_TIMEOUT_ANDROID = 15000;
|
|
4
|
+
export declare const BLE_DISCONNECT_TIMEOUT_IOS = 10000;
|
|
4
5
|
//# sourceMappingURL=Const.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Const.d.ts","sourceRoot":"","sources":["../../../../src/api/model/Const.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,WAAW,MAAM,CAAC;AAC/B,eAAO,MAAM,qBAAqB,OAAM,CAAC;AACzC,eAAO,MAAM,
|
|
1
|
+
{"version":3,"file":"Const.d.ts","sourceRoot":"","sources":["../../../../src/api/model/Const.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,WAAW,MAAM,CAAC;AAC/B,eAAO,MAAM,qBAAqB,OAAM,CAAC;AACzC,eAAO,MAAM,8BAA8B,QAAO,CAAC;AACnD,eAAO,MAAM,0BAA0B,QAAO,CAAC"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { GeneralDmkError } from "@ledgerhq/device-management-kit";
|
|
1
|
+
import { GeneralDmkError, OpeningConnectionError } from "@ledgerhq/device-management-kit";
|
|
2
2
|
export declare class BleTransportNotSupportedError extends GeneralDmkError {
|
|
3
3
|
readonly err?: unknown | undefined;
|
|
4
4
|
readonly _tag = "BleTransportNotSupportedError";
|
|
@@ -19,4 +19,29 @@ export declare class InternalDeviceNotFound extends GeneralDmkError {
|
|
|
19
19
|
readonly _tag = "InternalDeviceNotFound";
|
|
20
20
|
constructor(err?: unknown | undefined);
|
|
21
21
|
}
|
|
22
|
+
export declare class BleNotSupported extends GeneralDmkError {
|
|
23
|
+
readonly err?: unknown | undefined;
|
|
24
|
+
readonly _tag = "BleNotSupported";
|
|
25
|
+
constructor(err?: unknown | undefined);
|
|
26
|
+
}
|
|
27
|
+
export declare class NoDeviceModelFoundError extends GeneralDmkError {
|
|
28
|
+
readonly err?: unknown | undefined;
|
|
29
|
+
readonly _tag = "NoDeviceModelFoundError";
|
|
30
|
+
constructor(err?: unknown | undefined);
|
|
31
|
+
}
|
|
32
|
+
export declare class PairingRefusedError extends OpeningConnectionError {
|
|
33
|
+
readonly err?: unknown | undefined;
|
|
34
|
+
readonly _tag = "PairingRefusedError";
|
|
35
|
+
constructor(err?: unknown | undefined);
|
|
36
|
+
}
|
|
37
|
+
export declare class UnknownBleError extends GeneralDmkError {
|
|
38
|
+
readonly err?: unknown | undefined;
|
|
39
|
+
readonly _tag = "UnknownBleError";
|
|
40
|
+
constructor(err?: unknown | undefined);
|
|
41
|
+
}
|
|
42
|
+
export declare class PeerRemovedPairingError extends OpeningConnectionError {
|
|
43
|
+
readonly err?: unknown | undefined;
|
|
44
|
+
readonly _tag = "PeerRemovedPairingError";
|
|
45
|
+
constructor(err?: unknown | undefined);
|
|
46
|
+
}
|
|
22
47
|
//# sourceMappingURL=Errors.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Errors.d.ts","sourceRoot":"","sources":["../../../../src/api/model/Errors.ts"],"names":[],"mappings":"AAAA,OAAO,
|
|
1
|
+
{"version":3,"file":"Errors.d.ts","sourceRoot":"","sources":["../../../../src/api/model/Errors.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,eAAe,EACf,sBAAsB,EACvB,MAAM,iCAAiC,CAAC;AAEzC,qBAAa,6BAA8B,SAAQ,eAAe;IAEpD,QAAQ,CAAC,GAAG,CAAC,EAAE,OAAO;IADlC,SAAkB,IAAI,mCAAmC;gBACpC,GAAG,CAAC,EAAE,OAAO,YAAA;CAGnC;AACD,qBAAa,wBAAyB,SAAQ,eAAe;IAE/C,QAAQ,CAAC,GAAG,CAAC,EAAE,OAAO;IADlC,SAAkB,IAAI,8BAA8B;gBAC/B,GAAG,CAAC,EAAE,OAAO,YAAA;CAGnC;AACD,qBAAa,wBAAyB,SAAQ,eAAe;IAE/C,QAAQ,CAAC,GAAG,CAAC,EAAE,OAAO;IADlC,SAAkB,IAAI,8BAA8B;gBAC/B,GAAG,CAAC,EAAE,OAAO,YAAA;CAGnC;AACD,qBAAa,sBAAuB,SAAQ,eAAe;IAE7C,QAAQ,CAAC,GAAG,CAAC,EAAE,OAAO;IADlC,SAAkB,IAAI,4BAA4B;gBAC7B,GAAG,CAAC,EAAE,OAAO,YAAA;CAGnC;AAED,qBAAa,eAAgB,SAAQ,eAAe;IAEtC,QAAQ,CAAC,GAAG,CAAC,EAAE,OAAO;IADlC,SAAkB,IAAI,qBAAqB;gBACtB,GAAG,CAAC,EAAE,OAAO,YAAA;CAGnC;AAED,qBAAa,uBAAwB,SAAQ,eAAe;IAE9C,QAAQ,CAAC,GAAG,CAAC,EAAE,OAAO;IADlC,SAAkB,IAAI,6BAA6B;gBAC9B,GAAG,CAAC,EAAE,OAAO,YAAA;CAGnC;AAED,qBAAa,mBAAoB,SAAQ,sBAAsB;IAEjD,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