@ledgerhq/device-transport-kit-react-native-ble 0.0.0-wrong-error-when-in-experimental-provider-20251021162636 → 0.0.0-zzz-solana-20251204140055
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/lib/cjs/api/transport/RNBleTransport.js +1 -1
- package/lib/cjs/api/transport/RNBleTransport.js.map +3 -3
- package/lib/cjs/api/transport/RNBleTransport.test.js +1 -1
- package/lib/cjs/api/transport/RNBleTransport.test.js.map +2 -2
- package/lib/cjs/package.json +44 -40
- package/lib/esm/api/transport/RNBleTransport.js +1 -1
- package/lib/esm/api/transport/RNBleTransport.js.map +3 -3
- package/lib/esm/api/transport/RNBleTransport.test.js +1 -1
- package/lib/esm/api/transport/RNBleTransport.test.js.map +2 -2
- package/lib/esm/package.json +44 -40
- package/lib/types/api/transport/RNBleTransport.d.ts.map +1 -1
- package/lib/types/tsconfig.prod.tsbuildinfo +1 -1
- package/package.json +35 -31
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var b=Object.defineProperty;var I=Object.getOwnPropertyDescriptor;var w=Object.getOwnPropertyNames;var T=Object.prototype.hasOwnProperty;var C=(D,e)=>{for(var t in e)b(D,t,{get:e[t],enumerable:!0})},B=(D,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of w(e))!T.call(D,n)&&n!==t&&b(D,n,{get:()=>e[n],enumerable:!(i=I(e,n))||i.enumerable});return D};var R=D=>B(b({},"__esModule",{value:!0}),D);var A={};C(A,{RNBleTransport:()=>E,rnBleTransportIdentifier:()=>M});module.exports=R(A);var y=require("react-native"),h=require("react-native-ble-plx"),u=require("@ledgerhq/device-management-kit"),s=require("purify-ts"),r=require("rxjs"),p=require("../model/Const"),l=require("../model/Errors"),m=require("../transport/RNBleApduSender");const M="RN_BLE";class E{constructor(e,t,i,n,a,v,c,d=1e3,f=g=>new u.DeviceConnectionStateMachine(g),_=(g,S)=>new m.RNBleApduSender(g,S)){this._deviceModelDataSource=e;this._loggerServiceFactory=t;this._apduSenderFactory=i;this._apduReceiverFactory=n;this._manager=a;this._platform=v;this._permissionsService=c;this._scanThrottleDelayMs=d;this._deviceConnectionStateMachineFactory=f;this._deviceApduSenderFactory=_;this._logger=t("ReactNativeBleTransport"),this._deviceConnectionsById=new Map,this._reconnectionSubscription=s.Maybe.zero();let g=!1;this._manager.onStateChange(S=>{this._logger.debug(`[manager.onStateChange] called with state: ${S}`),this._bleStateSubject.next(S),g=S===h.State.Unknown,g&&(this._logger.debug('[manager.onStateChange] forcing state update from "Unknown"'),this._manager.state().then(o=>{g&&(this._logger.debug(`[manager.onStateChange] forcing state update to: "${o}"`),this._bleStateSubject.next(o))}))},!0)}_logger;_deviceConnectionsById;identifier="RN_BLE";_reconnectionSubscription;_bleStateSubject=new r.BehaviorSubject(h.State.Unknown);observeBleState(){return this._bleStateSubject.asObservable()}startDiscovering(){return(0,r.from)([])}async stopDiscovering(){await this._stopScanning()}_scannedDevicesSubject=new r.BehaviorSubject([]);_startedScanningSubscriber=void 0;_waitForScanningPrerequisites(){return(0,r.from)([!0]).pipe((0,r.tap)(()=>{if(!this.isSupported())throw new l.BleNotSupported("BLE not supported");this._logger.debug("[waitForScanningPrerequisites] Prerequisite: isSupported=true")}),(0,r.switchMap)(async()=>this.checkAndRequestPermissions()),(0,r.tap)(e=>{if(this._logger.debug(`[_waitForScanningPrerequisites] Prerequisite: hasPermissions=${e}`),!e)throw new l.BlePermissionsNotGranted("Permissions not granted")}),(0,r.switchMap)(()=>this.observeBleState()),(0,r.first)(e=>{const t=e===h.State.PoweredOn;if(this._logger.info(`[waitForScanningPrerequisites] Prerequisite: BLE state=${e}, canStartScanning=${t}`),e===h.State.PoweredOff)throw new l.BlePoweredOff;if(e===h.State.Unauthorized)throw new l.BlePermissionsNotGranted('Ble State is "Unauthorized"');if(e===h.State.Unsupported)throw new l.BleNotSupported;return t}))}_startScanning(){if(this._startedScanningSubscriber!=null){this._logger.info("[startScanning] !! startScanning already started");return}this._scannedDevicesSubject.next([]),this._logger.info("[startScanning] startScanning"),this._startedScanningSubscriber=(0,r.from)([!0]).pipe((0,r.switchMap)(()=>{const e=new r.BehaviorSubject([]),t=new Map;this._logger.info("[startScanning] startDeviceScan"),this._manager.startDeviceScan(this._deviceModelDataSource.getBluetoothServices(),{allowDuplicates:!0},(n,a)=>{if(n){this._logger.error("[startScanning] Error in startDeviceScan callback",{data:{error:n,rnDevice:a}}),e.error(n);return}if(!a){this._logger.warn("[startScanning] Null Device in startDeviceScan callback",{data:{rnDevice:a}}),e.error(new Error("Null device in startDeviceScan callback"));return}t.set(a.id,{device:a,timestamp:Date.now()}),e.next(Array.from(t.values()))}).catch(n=>{e.error(n),this._logger.error("[startScanning] Error while calling startDeviceScan",{data:{error:n}})}),this._logger.debug("[startScanning] after startDeviceScan");const i=setInterval(()=>{e.next(Array.from(t.values()))},1e3);return e.pipe((0,r.finalize)(()=>{this._logger.debug("[startScanning] finalize"),e.complete(),clearInterval(i),this._stopScanning()}))}),(0,r.throttleTime)(this._scanThrottleDelayMs)).subscribe({next:e=>{this._scannedDevicesSubject.next(e)},error:e=>{this._logger.error("[startScanning] Error while scanning",{data:{error:e}}),this._scannedDevicesSubject.error(e)}})}async _stopScanning(){this._logger.debug("[stopScanning] stopScanning"),await this._manager.stopDeviceScan(),this._startedScanningSubscriber?.unsubscribe(),this._startedScanningSubscriber=void 0,this._scannedDevicesSubject.complete(),this._scannedDevicesSubject=new r.BehaviorSubject([])}listenToAvailableDevices(){return this._waitForScanningPrerequisites().pipe((0,r.tap)(()=>this._startScanning()),(0,r.switchMap)(()=>this._scannedDevicesSubject),(0,r.switchMap)(async e=>{const t=e.filter(({timestamp:c})=>c>Date.now()-p.CONNECTION_LOST_DELAY).sort((c,d)=>(d.device.rssi??-1/0)-(c.device.rssi??-1/0)).map(({device:c})=>this._mapDeviceToTransportDiscoveredDevice(c,c.serviceUUIDs)).filter(c=>!!c),i=s.Either.rights(t),n=await this._manager.connectedDevices(this._deviceModelDataSource.getBluetoothServices()).catch(c=>{throw this._logger.error("[listenToAvailableDevices] Error calling manager.connectedDevices",{data:{error:c}}),c}),a=await Promise.all(n.map(async c=>{try{const f=(await c.services()).map(_=>_.uuid);return this._mapDeviceToTransportDiscoveredDevice(c,f)}catch(d){return this._logger.error("[listenToAvailableDevices] Error in mapping device to transport discovered device",{data:{e:d}}),(0,s.Left)(new l.NoDeviceModelFoundError(`Error in mapping device to transport discovered device: ${d}`))}})),v=s.Either.rights(a);return this._logger.debug("[listenToAvailableDevices]",{data:{rawConnectedDevices:n.map(c=>c.name),connectedDevices:v.map(c=>c.name),scannedDevices:i.map(c=>c.name)}}),[...v,...i]}))}_mapServicesUUIDsToBluetoothDeviceInfo(e){for(const t of e||[]){const i=this._deviceModelDataSource.getBluetoothServicesInfos()[t];if(i)return(0,s.Right)(i)}return(0,s.Left)(new l.NoDeviceModelFoundError(`No device model found for [uuids=${e}]`))}_mapServicesUUIDsToDeviceModel(e){return this._mapServicesUUIDsToBluetoothDeviceInfo(e).map(i=>i.deviceModel)}_mapDeviceToTransportDiscoveredDevice(e,t){return this._mapServicesUUIDsToDeviceModel(t).map(n=>({id:e.id,name:e.localName||e.name||"",deviceModel:n,transport:this.identifier,rssi:e.rssi||void 0}))}async connect(e){this._logger.debug("[connect] Called",{data:{deviceId:e.deviceId}});const t=this._deviceConnectionsById.get(e.deviceId);if(t){this._logger.debug("[connect] Existing device connection found",{data:{deviceId:e.deviceId}});const i=t.getDependencies().internalDevice.bleDeviceInfos.deviceModel;return(0,s.Right)(new u.TransportConnectedDevice({id:e.deviceId,deviceModel:i,type:"BLE",sendApdu:(...n)=>t.sendApdu(...n),transport:this.identifier}))}return this._logger.debug("[connect] No existing device connection found, establishing one",{data:{deviceId:e.deviceId}}),await this._stopScanning(),await this._safeCancel(e.deviceId),(0,s.EitherAsync)(async({throwE:i})=>{let n,a=[];try{await this._manager.connectToDevice(e.deviceId,{requestMTU:p.DEFAULT_MTU}),n=await this._manager.discoverAllServicesAndCharacteristicsForDevice(e.deviceId),a=(await n.services()).map(o=>o.uuid)}catch(o){return o instanceof h.BleError&&o.iosErrorCode===14?i(new l.PeerRemovedPairingError(o)):i(new u.OpeningConnectionError(o))}const v=this._listenToDeviceDisconnected(e.deviceId),c=this._mapServicesUUIDsToBluetoothDeviceInfo(a).caseOf({Right:o=>o,Left:o=>i(new u.OpeningConnectionError(o))}),d=c.deviceModel,f={id:n.id,bleDeviceInfos:c},_=this._deviceApduSenderFactory({apduSenderFactory:this._apduSenderFactory,apduReceiverFactory:this._apduReceiverFactory,dependencies:{device:n,internalDevice:f,manager:this._manager}},this._loggerServiceFactory),g=y.Platform.OS==="ios"?p.BLE_DISCONNECT_TIMEOUT_IOS:p.BLE_DISCONNECT_TIMEOUT_ANDROID,S=this._deviceConnectionStateMachineFactory({deviceId:e.deviceId,deviceApduSender:_,timeoutDuration:g,tryToReconnect:()=>this.tryToReconnect(e.deviceId),onTerminated:async()=>{this._logger.debug("[onTerminated]",{data:{deviceId:e.deviceId}});try{await this._safeCancel(e.deviceId)}catch(o){this._logger.error("[onTerminated] Error in termination of device connection",{data:{e:o}})}finally{this._deviceConnectionsById.delete(e.deviceId),this._reconnectionSubscription.ifJust(o=>{o.unsubscribe(),this._reconnectionSubscription=s.Maybe.zero()}),this._logger.debug("[onTerminated] signaling disconnection",{data:{deviceId:e.deviceId}}),e.onDisconnect(e.deviceId)}}});return await _.setupConnection().catch(o=>{throw this._safeCancel(e.deviceId),v.remove(),o}),this._deviceConnectionsById.set(e.deviceId,S),new u.TransportConnectedDevice({id:n.id,deviceModel:d,type:"BLE",sendApdu:(...o)=>S.sendApdu(...o),transport:this.identifier})}).run()}async disconnect(e){const t=e.connectedDevice.id,i=this._deviceConnectionsById.get(t);if(!i)throw new u.UnknownDeviceError(`No connected device found with id ${t}`);return i.closeConnection(),Promise.resolve((0,s.Right)(void 0))}isSupported(){return["android","ios"].includes(this._platform.OS)}getIdentifier(){return this.identifier}async checkAndRequestPermissions(){return this._logger.debug("[checkAndRequestPermissions] Called"),await this._permissionsService.checkRequiredPermissions()?!0:await this._permissionsService.requestRequiredPermissions()}_handleDeviceDisconnected(e,t){if(this._logger.debug("[_handleDeviceDisconnected]",{data:{error:e,device:t}}),!t){this._logger.debug("[_handleDeviceDisconnected] disconnected handler didn't find device");return}if(!t?.id||!this._deviceConnectionsById.has(t?.id))return;if(e){this._logger.error("device disconnected error",{data:{error:e,device:t}});return}const i=t.id;s.Maybe.fromNullable(this._deviceConnectionsById.get(i)).map(n=>n.eventDeviceDisconnected())}_listenToDeviceDisconnected(e){const t=this._manager.onDeviceDisconnected(e,(i,n)=>{this._handleDeviceDisconnected(i,n),t.remove()});return t}async tryToReconnect(e){this._logger.debug("[tryToReconnect] Called",{data:{deviceId:e}});let t=0;await this._stopScanning(),await this._safeCancel(e);const i=(0,r.defer)(async()=>{let n=null;t++;try{this._logger.debug(`[tryToReconnect](try=${t}) Reconnecting to device`,{data:{id:e}});const a=await this._manager.connectToDevice(e,{requestMTU:p.DEFAULT_MTU,timeout:2e3});this._logger.debug(`[tryToReconnect](try=${t}) Established connection to device`,{data:{id:e}});const v=await a.discoverAllServicesAndCharacteristics();return this._logger.debug(`[tryToReconnect](try=${t}) Discovered all services and characteristics`,{data:{usableReconnectedDevice:v}}),n=this._listenToDeviceDisconnected(e),await this._handleDeviceReconnected(v),v}catch(a){throw this._logger.warn(`[tryToReconnect](try=${t}) Reconnecting to device failed`,{data:{e:a}}),n?.remove(),await this._stopScanning(),await this._safeCancel(e),a}}).pipe((0,r.retry)(5));this._reconnectionSubscription=s.Maybe.of(i.subscribe({next:n=>this._logger.debug(`[tryToReconnect](try=${t}) Fully reconnected to device (id=${n.id})`),complete:()=>{this._logger.debug("[tryToReconnect] Completed"),this._reconnectionSubscription=s.Maybe.zero()},error:n=>{this._logger.error("[tryToReconnect] All reconnection attempts failed",{data:{e:n}}),this._deviceConnectionsById.get(e)?.closeConnection(),this._reconnectionSubscription=s.Maybe.zero()}}))}async _handleDeviceReconnected(e){const t=s.Maybe.fromNullable(this._deviceConnectionsById.get(e.id)).toEither(new l.DeviceConnectionNotFound);return(0,s.EitherAsync)(async({liftEither:i,throwE:n})=>{const a=await i(t),v=(await e.services()).map(d=>d.uuid),c=this._mapServicesUUIDsToBluetoothDeviceInfo(v).caseOf({Right:d=>({id:e.id,bleDeviceInfos:d}),Left:d=>(this._logger.error("[_handleDeviceReconnected] Error in mapping services UUIDs to Bluetooth device info",{data:{error:d}}),n(d))});a.setDependencies({device:e,manager:this._manager,internalDevice:c}),await a.setupConnection().catch(d=>{throw this._safeCancel(e.id),d}),a.eventDeviceConnected()}).run()}async _safeCancel(e){if(typeof this._manager.cancelDeviceConnection=="function"){const t=await this._manager.connectedDevices(this._deviceModelDataSource.getBluetoothServices());for(const i of t)if(i.id===e)try{await this._manager.cancelDeviceConnection(e)}catch(n){this._logger.error("[safeCancel] Error in cancelling device connection",{data:{e:n}})}}}}0&&(module.exports={RNBleTransport,rnBleTransportIdentifier});
|
|
1
|
+
"use strict";var b=Object.defineProperty;var I=Object.getOwnPropertyDescriptor;var w=Object.getOwnPropertyNames;var C=Object.prototype.hasOwnProperty;var T=(D,e)=>{for(var n in e)b(D,n,{get:e[n],enumerable:!0})},B=(D,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let t of w(e))!C.call(D,t)&&t!==n&&b(D,t,{get:()=>e[t],enumerable:!(i=I(e,t))||i.enumerable});return D};var R=D=>B(b({},"__esModule",{value:!0}),D);var N={};T(N,{RNBleTransport:()=>E,rnBleTransportIdentifier:()=>M});module.exports=R(N);var m=require("react-native"),u=require("react-native-ble-plx"),g=require("@ledgerhq/device-management-kit"),a=require("purify-ts"),r=require("rxjs"),p=require("../model/Const"),l=require("../model/Errors"),y=require("../transport/RNBleApduSender");const M="RN_BLE";class E{constructor(e,n,i,t,s,v,c,d=1e3,f=h=>new g.DeviceConnectionStateMachine(h),_=(h,S)=>new y.RNBleApduSender(h,S)){this._deviceModelDataSource=e;this._loggerServiceFactory=n;this._apduSenderFactory=i;this._apduReceiverFactory=t;this._manager=s;this._platform=v;this._permissionsService=c;this._scanThrottleDelayMs=d;this._deviceConnectionStateMachineFactory=f;this._deviceApduSenderFactory=_;this._logger=n("ReactNativeBleTransport"),this._deviceConnectionsById=new Map,this._reconnectionSubscription=a.Maybe.zero();let h=!1;this._manager.onStateChange(S=>{this._logger.debug(`[manager.onStateChange] called with state: ${S}`),this._bleStateSubject.next(S),h=S===u.State.Unknown,h&&(this._logger.debug('[manager.onStateChange] forcing state update from "Unknown"'),this._manager.state().then(o=>{h&&(this._logger.debug(`[manager.onStateChange] forcing state update to: "${o}"`),this._bleStateSubject.next(o))}))},!0)}_logger;_deviceConnectionsById;identifier="RN_BLE";_reconnectionSubscription;_bleStateSubject=new r.BehaviorSubject(u.State.Unknown);observeBleState(){return this._bleStateSubject.asObservable()}startDiscovering(){return(0,r.from)([])}async stopDiscovering(){await this._stopScanning()}_scannedDevicesSubject=new r.BehaviorSubject([]);_startedScanningSubscriber=void 0;_waitForScanningPrerequisites(){return(0,r.from)([!0]).pipe((0,r.tap)(()=>{if(!this.isSupported())throw new l.BleNotSupported("BLE not supported");this._logger.debug("[waitForScanningPrerequisites] Prerequisite: isSupported=true")}),(0,r.switchMap)(async()=>this.checkAndRequestPermissions()),(0,r.tap)(e=>{if(this._logger.debug(`[_waitForScanningPrerequisites] Prerequisite: hasPermissions=${e}`),!e)throw new l.BlePermissionsNotGranted("Permissions not granted")}),(0,r.switchMap)(()=>this.observeBleState()),(0,r.first)(e=>{const n=e===u.State.PoweredOn;if(this._logger.info(`[waitForScanningPrerequisites] Prerequisite: BLE state=${e}, canStartScanning=${n}`),e===u.State.PoweredOff)throw new l.BlePoweredOff;if(e===u.State.Unauthorized)throw new l.BlePermissionsNotGranted('Ble State is "Unauthorized"');if(e===u.State.Unsupported)throw new l.BleNotSupported;return n}))}_startScanning(){if(this._startedScanningSubscriber!=null){this._logger.info("[startScanning] !! startScanning already started");return}this._scannedDevicesSubject.next([]),this._logger.info("[startScanning] startScanning"),this._startedScanningSubscriber=(0,r.from)([!0]).pipe((0,r.switchMap)(()=>{const e=new r.BehaviorSubject([]),n=new Map;this._logger.info("[startScanning] startDeviceScan"),this._manager.startDeviceScan(this._deviceModelDataSource.getBluetoothServices(),{allowDuplicates:!0},(t,s)=>{if(t){this._logger.error("[startScanning] Error in startDeviceScan callback",{data:{error:t,rnDevice:s}}),e.error(t);return}if(!s){this._logger.warn("[startScanning] Null Device in startDeviceScan callback",{data:{rnDevice:s}}),e.error(new Error("Null device in startDeviceScan callback"));return}n.set(s.id,{device:s,timestamp:Date.now()}),e.next(Array.from(n.values()))}).catch(t=>{e.error(t),this._logger.error("[startScanning] Error while calling startDeviceScan",{data:{error:t}})}),this._logger.debug("[startScanning] after startDeviceScan");const i=setInterval(()=>{e.next(Array.from(n.values()))},1e3);return e.pipe((0,r.finalize)(()=>{this._logger.debug("[startScanning] finalize"),e.complete(),clearInterval(i),this._stopScanning()}))}),(0,r.throttleTime)(this._scanThrottleDelayMs)).subscribe({next:e=>{this._scannedDevicesSubject.next(e)},error:e=>{this._logger.error("[startScanning] Error while scanning",{data:{error:e}}),this._scannedDevicesSubject.error(e)}})}async _stopScanning(){this._logger.debug("[stopScanning] stopScanning"),await this._manager.stopDeviceScan(),this._startedScanningSubscriber?.unsubscribe(),this._startedScanningSubscriber=void 0,this._scannedDevicesSubject.complete(),this._scannedDevicesSubject=new r.BehaviorSubject([])}listenToAvailableDevices(){return this._waitForScanningPrerequisites().pipe((0,r.tap)(()=>this._startScanning()),(0,r.switchMap)(()=>this._scannedDevicesSubject),(0,r.switchMap)(async e=>{const n=e.filter(({timestamp:c})=>c>Date.now()-p.CONNECTION_LOST_DELAY).sort((c,d)=>(d.device.rssi??-1/0)-(c.device.rssi??-1/0)).map(({device:c})=>this._mapDeviceToTransportDiscoveredDevice(c,c.serviceUUIDs)).filter(c=>!!c),i=a.Either.rights(n),t=await this._manager.connectedDevices(this._deviceModelDataSource.getBluetoothServices()).catch(c=>{throw this._logger.error("[listenToAvailableDevices] Error calling manager.connectedDevices",{data:{error:c}}),c}),s=await Promise.all(t.map(async c=>{try{const f=(await c.services()).map(_=>_.uuid);return this._mapDeviceToTransportDiscoveredDevice(c,f)}catch(d){return this._logger.error("[listenToAvailableDevices] Error in mapping device to transport discovered device",{data:{e:d}}),(0,a.Left)(new l.NoDeviceModelFoundError(`Error in mapping device to transport discovered device: ${d}`))}})),v=a.Either.rights(s);return this._logger.debug("[listenToAvailableDevices]",{data:{rawConnectedDevices:t.map(c=>c.name),connectedDevices:v.map(c=>c.name),scannedDevices:i.map(c=>c.name)}}),[...v,...i]}))}_mapServicesUUIDsToBluetoothDeviceInfo(e){for(const n of e||[]){const i=this._deviceModelDataSource.getBluetoothServicesInfos()[n];if(i)return(0,a.Right)(i)}return(0,a.Left)(new l.NoDeviceModelFoundError(`No device model found for [uuids=${e}]`))}_mapServicesUUIDsToDeviceModel(e){return this._mapServicesUUIDsToBluetoothDeviceInfo(e).map(i=>i.deviceModel)}_mapDeviceToTransportDiscoveredDevice(e,n){return this._mapServicesUUIDsToDeviceModel(n).map(t=>({id:e.id,name:e.localName||e.name||"",deviceModel:t,transport:this.identifier,rssi:e.rssi||void 0}))}async connect(e){this._logger.debug("[connect] Called",{data:{deviceId:e.deviceId}});const n=this._deviceConnectionsById.get(e.deviceId);if(n){this._logger.debug("[connect] Existing device connection found",{data:{deviceId:e.deviceId}});const i=n.getDependencies(),t=i.internalDevice.bleDeviceInfos.deviceModel,s=i.device.localName||i.device.name||void 0;return(0,a.Right)(new g.TransportConnectedDevice({id:e.deviceId,deviceModel:t,type:"BLE",sendApdu:(...v)=>n.sendApdu(...v),transport:this.identifier,name:s}))}return this._logger.debug("[connect] No existing device connection found, establishing one",{data:{deviceId:e.deviceId}}),await this._stopScanning(),await this._safeCancel(e.deviceId),(0,a.EitherAsync)(async({throwE:i})=>{let t,s=[];try{await this._manager.connectToDevice(e.deviceId,{requestMTU:p.DEFAULT_MTU}),t=await this._manager.discoverAllServicesAndCharacteristicsForDevice(e.deviceId),s=(await t.services()).map(o=>o.uuid)}catch(o){return o instanceof u.BleError&&o.iosErrorCode===14?i(new l.PeerRemovedPairingError(o)):o instanceof u.BleError&&o.errorCode===u.BleErrorCode.OperationCancelled&&m.Platform.OS==="android"?i(new l.PeerRemovedPairingError(o)):i(new g.OpeningConnectionError(o))}const v=this._listenToDeviceDisconnected(e.deviceId),c=this._mapServicesUUIDsToBluetoothDeviceInfo(s).caseOf({Right:o=>o,Left:o=>i(new g.OpeningConnectionError(o))}),d=c.deviceModel,f={id:t.id,bleDeviceInfos:c},_=this._deviceApduSenderFactory({apduSenderFactory:this._apduSenderFactory,apduReceiverFactory:this._apduReceiverFactory,dependencies:{device:t,internalDevice:f,manager:this._manager}},this._loggerServiceFactory),h=m.Platform.OS==="ios"?p.BLE_DISCONNECT_TIMEOUT_IOS:p.BLE_DISCONNECT_TIMEOUT_ANDROID,S=this._deviceConnectionStateMachineFactory({deviceId:e.deviceId,deviceApduSender:_,timeoutDuration:h,tryToReconnect:()=>this.tryToReconnect(e.deviceId),onTerminated:async()=>{this._logger.debug("[onTerminated]",{data:{deviceId:e.deviceId}});try{await this._safeCancel(e.deviceId)}catch(o){this._logger.error("[onTerminated] Error in termination of device connection",{data:{e:o}})}finally{this._deviceConnectionsById.delete(e.deviceId),this._reconnectionSubscription.ifJust(o=>{o.unsubscribe(),this._reconnectionSubscription=a.Maybe.zero()}),this._logger.debug("[onTerminated] signaling disconnection",{data:{deviceId:e.deviceId}}),e.onDisconnect(e.deviceId)}}});return await _.setupConnection().catch(o=>{throw this._safeCancel(e.deviceId),v.remove(),o}),this._deviceConnectionsById.set(e.deviceId,S),new g.TransportConnectedDevice({id:t.id,deviceModel:d,type:"BLE",sendApdu:(...o)=>S.sendApdu(...o),transport:this.identifier,name:t.localName||t.name||void 0})}).run()}async disconnect(e){const n=e.connectedDevice.id,i=this._deviceConnectionsById.get(n);if(!i)throw new g.UnknownDeviceError(`No connected device found with id ${n}`);return i.closeConnection(),Promise.resolve((0,a.Right)(void 0))}isSupported(){return["android","ios"].includes(this._platform.OS)}getIdentifier(){return this.identifier}async checkAndRequestPermissions(){return this._logger.debug("[checkAndRequestPermissions] Called"),await this._permissionsService.checkRequiredPermissions()?!0:await this._permissionsService.requestRequiredPermissions()}_handleDeviceDisconnected(e,n){if(this._logger.debug("[_handleDeviceDisconnected]",{data:{error:e,device:n}}),!n){this._logger.debug("[_handleDeviceDisconnected] disconnected handler didn't find device");return}if(!n?.id||!this._deviceConnectionsById.has(n?.id))return;if(e){this._logger.error("device disconnected error",{data:{error:e,device:n}});return}const i=n.id;a.Maybe.fromNullable(this._deviceConnectionsById.get(i)).map(t=>t.eventDeviceDisconnected())}_listenToDeviceDisconnected(e){const n=this._manager.onDeviceDisconnected(e,(i,t)=>{this._handleDeviceDisconnected(i,t),n.remove()});return n}async tryToReconnect(e){this._logger.debug("[tryToReconnect] Called",{data:{deviceId:e}});let n=0;await this._stopScanning(),await this._safeCancel(e);const i=(0,r.defer)(async()=>{let t=null;n++;try{this._logger.debug(`[tryToReconnect](try=${n}) Reconnecting to device`,{data:{id:e}});const s=await this._manager.connectToDevice(e,{requestMTU:p.DEFAULT_MTU,timeout:2e3});this._logger.debug(`[tryToReconnect](try=${n}) Established connection to device`,{data:{id:e}});const v=await s.discoverAllServicesAndCharacteristics();return this._logger.debug(`[tryToReconnect](try=${n}) Discovered all services and characteristics`,{data:{usableReconnectedDevice:v}}),t=this._listenToDeviceDisconnected(e),await this._handleDeviceReconnected(v),v}catch(s){throw this._logger.warn(`[tryToReconnect](try=${n}) Reconnecting to device failed`,{data:{e:s}}),t?.remove(),await this._stopScanning(),await this._safeCancel(e),s}}).pipe((0,r.retry)(5));this._reconnectionSubscription=a.Maybe.of(i.subscribe({next:t=>this._logger.debug(`[tryToReconnect](try=${n}) Fully reconnected to device (id=${t.id})`),complete:()=>{this._logger.debug("[tryToReconnect] Completed"),this._reconnectionSubscription=a.Maybe.zero()},error:t=>{this._logger.error("[tryToReconnect] All reconnection attempts failed",{data:{e:t}}),this._deviceConnectionsById.get(e)?.closeConnection(),this._reconnectionSubscription=a.Maybe.zero()}}))}async _handleDeviceReconnected(e){const n=a.Maybe.fromNullable(this._deviceConnectionsById.get(e.id)).toEither(new l.DeviceConnectionNotFound);return(0,a.EitherAsync)(async({liftEither:i,throwE:t})=>{const s=await i(n),v=(await e.services()).map(d=>d.uuid),c=this._mapServicesUUIDsToBluetoothDeviceInfo(v).caseOf({Right:d=>({id:e.id,bleDeviceInfos:d}),Left:d=>(this._logger.error("[_handleDeviceReconnected] Error in mapping services UUIDs to Bluetooth device info",{data:{error:d}}),t(d))});s.setDependencies({device:e,manager:this._manager,internalDevice:c}),await s.setupConnection().catch(d=>{throw this._safeCancel(e.id),d}),s.eventDeviceConnected()}).run()}async _safeCancel(e){if(typeof this._manager.cancelDeviceConnection=="function"){const n=await this._manager.connectedDevices(this._deviceModelDataSource.getBluetoothServices());for(const i of n)if(i.id===e)try{await this._manager.cancelDeviceConnection(e)}catch(t){this._logger.error("[safeCancel] Error in cancelling device connection",{data:{e:t}})}}}}0&&(module.exports={RNBleTransport,rnBleTransportIdentifier});
|
|
2
2
|
//# sourceMappingURL=RNBleTransport.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/api/transport/RNBleTransport.ts"],
|
|
4
|
-
"sourcesContent": ["import { Platform } from \"react-native\";\nimport {\n BleError,\n type BleManager,\n type Device,\n State,\n type Subscription as BleSubscription,\n} 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 TransportIdentifier,\n UnknownDeviceError,\n} from \"@ledgerhq/device-management-kit\";\nimport { Either, EitherAsync, Left, Maybe, Right } from \"purify-ts\";\nimport {\n BehaviorSubject,\n defer,\n finalize,\n first,\n from,\n type Observable,\n retry,\n type Subscription,\n switchMap,\n tap,\n throttleTime,\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 BlePermissionsNotGranted,\n BlePoweredOff,\n DeviceConnectionNotFound,\n NoDeviceModelFoundError,\n PeerRemovedPairingError,\n} from \"@api/model/Errors\";\nimport { type PermissionsService } from \"@api/permissions/PermissionsService\";\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 _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,\n private readonly _permissionsService: PermissionsService,\n private readonly _scanThrottleDelayMs: number = 1000,\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._deviceConnectionsById = new Map();\n this._reconnectionSubscription = Maybe.zero();\n // FIXME: we should have a destroy method to unregister the onStateChange listener\n let lastBleStateIsUnknown = false;\n this._manager.onStateChange((state) => {\n this._logger.debug(`[manager.onStateChange] called with state: ${state}`);\n this._bleStateSubject.next(state);\n lastBleStateIsUnknown = state === State.Unknown;\n if (lastBleStateIsUnknown) {\n // There seems to be a bug in the library where the state is not updated after going in an Unknown state...\n this._logger.debug(\n `[manager.onStateChange] forcing state update from \"Unknown\"`,\n );\n this._manager.state().then((s) => {\n if (lastBleStateIsUnknown) {\n this._logger.debug(\n `[manager.onStateChange] forcing state update to: \"${s}\"`,\n );\n this._bleStateSubject.next(s);\n }\n });\n }\n }, true);\n }\n\n /** Exposed for testing purposes */\n observeBleState(): Observable<State> {\n return this._bleStateSubject.asObservable();\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 _scannedDevicesSubject: BehaviorSubject<InternalScannedDevice[]> =\n new BehaviorSubject<InternalScannedDevice[]>([]);\n private _startedScanningSubscriber: Subscription | undefined = undefined;\n\n /**\n * Returns an observable that emits a value when the prerequisites for scanning are met.\n * The prerequisites are:\n * - BLE should be supported. If not, it will throw an error.\n * - Permissions should be granted. If not, it request them, if it fails, it will throw an error.\n * - BLE state should be PoweredOn.\n * - If BLE state is undetermined (Unknown or Resetting), it will wait for the state to be updated.\n * - For other states, it will throw an error.\n */\n private _waitForScanningPrerequisites() {\n return from([true]).pipe(\n tap(() => {\n if (!this.isSupported()) {\n throw new BleNotSupported(\"BLE not supported\");\n }\n this._logger.debug(\n \"[waitForScanningPrerequisites] Prerequisite: isSupported=true\",\n );\n }),\n switchMap(async () => this.checkAndRequestPermissions()),\n tap((hasPermissions) => {\n this._logger.debug(\n `[_waitForScanningPrerequisites] Prerequisite: hasPermissions=${hasPermissions}`,\n );\n if (!hasPermissions) {\n throw new BlePermissionsNotGranted(\"Permissions not granted\");\n }\n }),\n switchMap(() => this.observeBleState()),\n first((state) => {\n /**\n * We wait for the BLE state to be PoweredOn, in case the current state is one of those:\n * - Unknown: temporary undetermined state which will quickly be updated\n * - Resetting: temporary undetermined state which will quickly be updated\n */\n const canStartScanning = state === State.PoweredOn;\n this._logger.info(\n `[waitForScanningPrerequisites] Prerequisite: BLE state=${state}, canStartScanning=${canStartScanning}`,\n );\n if (state === State.PoweredOff) {\n throw new BlePoweredOff();\n } else if (state === State.Unauthorized) {\n throw new BlePermissionsNotGranted('Ble State is \"Unauthorized\"');\n } else if (state === State.Unsupported) {\n throw new BleNotSupported();\n }\n return canStartScanning;\n }),\n );\n }\n\n private _startScanning() {\n if (this._startedScanningSubscriber != undefined) {\n this._logger.info(\"[startScanning] !! startScanning already started\");\n return;\n }\n\n //Reset the scanned devices list as new scan will start\n this._scannedDevicesSubject.next([]);\n\n this._logger.info(\"[startScanning] startScanning\");\n\n this._startedScanningSubscriber = from([true])\n .pipe(\n switchMap(() => {\n const subject = new BehaviorSubject<InternalScannedDevice[]>([]);\n const devicesById = new Map<string, InternalScannedDevice>();\n\n this._logger.info(\"[startScanning] startDeviceScan\");\n this._manager\n .startDeviceScan(\n this._deviceModelDataSource.getBluetoothServices(),\n { allowDuplicates: true },\n (error, rnDevice) => {\n if (error) {\n this._logger.error(\n \"[startScanning] Error in startDeviceScan callback\",\n {\n data: { error, rnDevice },\n },\n );\n subject.error(error);\n return;\n }\n if (!rnDevice) {\n this._logger.warn(\n \"[startScanning] Null Device in startDeviceScan callback\",\n {\n data: { rnDevice },\n },\n );\n subject.error(\n new Error(\"Null device in startDeviceScan callback\"),\n );\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 .catch((e) => {\n subject.error(e);\n this._logger.error(\n \"[startScanning] Error while calling startDeviceScan\",\n {\n data: { error: e },\n },\n );\n });\n\n this._logger.debug(\"[startScanning] after startDeviceScan\");\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.pipe(\n finalize(() => {\n this._logger.debug(\"[startScanning] finalize\");\n subject.complete();\n clearInterval(interval);\n this._stopScanning();\n }),\n );\n }),\n throttleTime(this._scanThrottleDelayMs),\n )\n .subscribe({\n next: (devices) => {\n this._scannedDevicesSubject.next(devices);\n },\n error: (error) => {\n this._logger.error(\"[startScanning] Error while scanning\", {\n data: { error },\n });\n this._scannedDevicesSubject.error(error);\n },\n });\n }\n\n private async _stopScanning(): Promise<void> {\n this._logger.debug(\"[stopScanning] stopScanning\");\n await this._manager.stopDeviceScan();\n //Stop listening the observable from this._startScanning()\n this._startedScanningSubscriber?.unsubscribe();\n this._startedScanningSubscriber = undefined;\n this._scannedDevicesSubject.complete();\n this._scannedDevicesSubject = new BehaviorSubject<InternalScannedDevice[]>(\n [],\n );\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 return this._waitForScanningPrerequisites().pipe(\n tap(() => this._startScanning()),\n switchMap(() => this._scannedDevicesSubject),\n switchMap(async (internalScannedDevices) => {\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 const rawConnectedDevices = await this._manager\n .connectedDevices(this._deviceModelDataSource.getBluetoothServices())\n .catch((e) => {\n this._logger.error(\n \"[listenToAvailableDevices] Error calling manager.connectedDevices\",\n {\n data: { error: e },\n },\n );\n throw e;\n });\n\n const eitherConnectedDevices = await Promise.all(\n rawConnectedDevices.map(async (device) => {\n try {\n const services = await device.services();\n const servicesUUIDs = services.map((s) => s.uuid);\n return this._mapDeviceToTransportDiscoveredDevice(\n device,\n servicesUUIDs,\n );\n } catch (e) {\n this._logger.error(\n \"[listenToAvailableDevices] Error in mapping device to transport discovered device\",\n {\n data: { e },\n },\n );\n return Left(\n new NoDeviceModelFoundError(\n `Error in mapping device to transport discovered device: ${e}`,\n ),\n );\n }\n }),\n );\n\n const connectedDevices = Either.rights(eitherConnectedDevices);\n\n this._logger.debug(\"[listenToAvailableDevices]\", {\n data: {\n rawConnectedDevices: rawConnectedDevices.map((d) => d.name),\n connectedDevices: connectedDevices.map((d) => d.name),\n scannedDevices: scannedDevices.map((d) => d.name),\n },\n });\n\n /** We return both connected and scanned devices, as scanned devices don't include connected devices */\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 this._logger.debug(\"[connect] Called\", {\n data: { deviceId: params.deviceId },\n });\n const existing = this._deviceConnectionsById.get(params.deviceId);\n if (existing) {\n this._logger.debug(\"[connect] Existing device connection found\", {\n data: { deviceId: params.deviceId },\n });\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 this._logger.debug(\n \"[connect] No existing device connection found, establishing one\",\n {\n data: { deviceId: params.deviceId },\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._listenToDeviceDisconnected(\n params.deviceId,\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: () => this.tryToReconnect(params.deviceId),\n onTerminated: async () => {\n this._logger.debug(\"[onTerminated]\", {\n data: { deviceId: params.deviceId },\n });\n try {\n await this._safeCancel(params.deviceId);\n } catch (e) {\n this._logger.error(\n \"[onTerminated] Error in termination of device connection\",\n { data: { e } },\n );\n } finally {\n this._deviceConnectionsById.delete(params.deviceId);\n this._reconnectionSubscription.ifJust((sub) => {\n sub.unsubscribe();\n this._reconnectionSubscription = Maybe.zero();\n });\n this._logger.debug(\"[onTerminated] signaling disconnection\", {\n data: { deviceId: params.deviceId },\n });\n params.onDisconnect(params.deviceId);\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 [\"android\", \"ios\"].includes(this._platform.OS);\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 * Checks if the necessary permissions are granted and requests them if not.\n */\n async checkAndRequestPermissions(): Promise<boolean> {\n this._logger.debug(\"[checkAndRequestPermissions] Called\");\n\n const checkResult =\n await this._permissionsService.checkRequiredPermissions();\n if (checkResult) return true;\n\n const requestResult =\n await this._permissionsService.requestRequiredPermissions();\n return requestResult;\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(\"[_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\n Maybe.fromNullable(this._deviceConnectionsById.get(deviceId)).map(\n (deviceConnection) => deviceConnection.eventDeviceDisconnected(),\n );\n }\n\n private _listenToDeviceDisconnected(deviceId: DeviceId): BleSubscription {\n const disconnectionSubscription = this._manager.onDeviceDisconnected(\n deviceId,\n (error, d) => {\n this._handleDeviceDisconnected(error, d);\n disconnectionSubscription.remove();\n },\n );\n return disconnectionSubscription;\n }\n\n private async tryToReconnect(deviceId: DeviceId) {\n this._logger.debug(\"[tryToReconnect] Called\", {\n data: { deviceId },\n });\n let reconnectionTryCount = 0;\n\n await this._stopScanning();\n await this._safeCancel(deviceId);\n\n const reconnect$ = defer(async () => {\n let disconnectionSubscription: BleSubscription | null = null;\n reconnectionTryCount++;\n try {\n this._logger.debug(\n `[tryToReconnect](try=${reconnectionTryCount}) Reconnecting to device`,\n {\n data: { id: deviceId },\n },\n );\n const reconnectedDevice = await this._manager.connectToDevice(\n deviceId,\n { requestMTU: DEFAULT_MTU, timeout: 2000 },\n );\n this._logger.debug(\n `[tryToReconnect](try=${reconnectionTryCount}) Established connection to device`,\n {\n data: { id: deviceId },\n },\n );\n const usableReconnectedDevice =\n await reconnectedDevice.discoverAllServicesAndCharacteristics();\n this._logger.debug(\n `[tryToReconnect](try=${reconnectionTryCount}) Discovered all services and characteristics`,\n { data: { usableReconnectedDevice } },\n );\n disconnectionSubscription = this._listenToDeviceDisconnected(deviceId);\n await this._handleDeviceReconnected(usableReconnectedDevice);\n return usableReconnectedDevice;\n } catch (e) {\n this._logger.warn(\n `[tryToReconnect](try=${reconnectionTryCount}) Reconnecting to device failed`,\n {\n data: { e },\n },\n );\n disconnectionSubscription?.remove();\n await this._stopScanning();\n await this._safeCancel(deviceId);\n throw e;\n }\n }).pipe(retry(5));\n\n this._reconnectionSubscription = Maybe.of(\n reconnect$.subscribe({\n next: (d) =>\n this._logger.debug(\n `[tryToReconnect](try=${reconnectionTryCount}) Fully reconnected to device (id=${d.id})`,\n ),\n complete: () => {\n this._logger.debug(\"[tryToReconnect] Completed\");\n this._reconnectionSubscription = Maybe.zero();\n },\n error: (e) => {\n this._logger.error(\n `[tryToReconnect] All reconnection attempts failed`,\n { data: { e } },\n );\n this._deviceConnectionsById.get(deviceId)?.closeConnection();\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 \"[_handleDeviceReconnected] 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 try {\n await this._manager.cancelDeviceConnection(deviceId);\n } catch (e) {\n this._logger.error(\n \"[safeCancel] Error in cancelling device connection\",\n {\n data: { e },\n },\n );\n }\n }\n }\n }\n }\n}\n"],
|
|
5
|
-
"mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,oBAAAE,EAAA,6BAAAC,IAAA,eAAAC,EAAAJ,GAAA,IAAAK,EAAyB,wBACzBC,EAMO,gCACPC,EAmBO,2CACPC,EAAwD,qBACxDC,EAYO,gBAEPC,EAKO,4BACPC,EAOO,6BAEPC,EAKO,0CAEA,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AAO5B,GAAM,CAChE,WAAK,YAAYQ,EAAO,EAAE,EACpBR,CACR,CAAC,EAED4B,EAA6B,qBAAqB,CACpD,CAAC,EAAE,IAAI,CACT,CAEA,MAAc,YAAYE,EAAoB,CAE5C,GAAI,OAAO,KAAK,SAAS,wBAA2B,WAAY,CAC9D,MAAMhB,EAAmB,MAAM,KAAK,SAAS,iBAC3C,KAAK,uBAAuB,qBAAqB,CACnD,EAEA,UAAWN,KAAUM,EACnB,GAAIN,EAAO,KAAOsB,EAChB,GAAI,CACF,MAAM,KAAK,SAAS,uBAAuBA,CAAQ,CACrD,OAAS9B,EAAG,CACV,KAAK,QAAQ,MACX,qDACA,CACE,KAAM,CAAE,EAAAA,CAAE,CACZ,CACF,CACF,CAGN,CACF,CACF",
|
|
6
|
-
"names": ["RNBleTransport_exports", "__export", "RNBleTransport", "rnBleTransportIdentifier", "__toCommonJS", "import_react_native", "import_react_native_ble_plx", "import_device_management_kit", "import_purify_ts", "import_rxjs", "import_Const", "import_Errors", "import_RNBleApduSender", "_deviceModelDataSource", "_loggerServiceFactory", "_apduSenderFactory", "_apduReceiverFactory", "_manager", "_platform", "_permissionsService", "_scanThrottleDelayMs", "_deviceConnectionStateMachineFactory", "args", "_deviceApduSenderFactory", "loggerFactory", "lastBleStateIsUnknown", "state", "s", "hasPermissions", "canStartScanning", "subject", "devicesById", "error", "rnDevice", "e", "interval", "devices", "internalScannedDevices", "eitherScannedDevices", "timestamp", "a", "b", "device", "d", "scannedDevices", "rawConnectedDevices", "eitherConnectedDevices", "servicesUUIDs", "connectedDevices", "serviceUUID", "bluetoothServiceInfo", "info", "model", "params", "existing", "deviceModel", "throwE", "disconnectionSubscription", "bleDeviceInfos", "internalDevice", "deviceApduSender", "reconnectionTimeout", "deviceConnectionStateMachine", "sub", "deviceId", "deviceConnection", "reconnectionTryCount", "reconnect$", "reconnectedDevice", "usableReconnectedDevice", "errorOrDeviceConnection", "liftEither"]
|
|
4
|
+
"sourcesContent": ["import { Platform } from \"react-native\";\nimport {\n BleError,\n BleErrorCode,\n type BleManager,\n type Device,\n State,\n type Subscription as BleSubscription,\n} 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 TransportIdentifier,\n UnknownDeviceError,\n} from \"@ledgerhq/device-management-kit\";\nimport { Either, EitherAsync, Left, Maybe, Right } from \"purify-ts\";\nimport {\n BehaviorSubject,\n defer,\n finalize,\n first,\n from,\n type Observable,\n retry,\n type Subscription,\n switchMap,\n tap,\n throttleTime,\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 BlePermissionsNotGranted,\n BlePoweredOff,\n DeviceConnectionNotFound,\n NoDeviceModelFoundError,\n PeerRemovedPairingError,\n} from \"@api/model/Errors\";\nimport { type PermissionsService } from \"@api/permissions/PermissionsService\";\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 _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,\n private readonly _permissionsService: PermissionsService,\n private readonly _scanThrottleDelayMs: number = 1000,\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._deviceConnectionsById = new Map();\n this._reconnectionSubscription = Maybe.zero();\n // FIXME: we should have a destroy method to unregister the onStateChange listener\n let lastBleStateIsUnknown = false;\n this._manager.onStateChange((state) => {\n this._logger.debug(`[manager.onStateChange] called with state: ${state}`);\n this._bleStateSubject.next(state);\n lastBleStateIsUnknown = state === State.Unknown;\n if (lastBleStateIsUnknown) {\n // There seems to be a bug in the library where the state is not updated after going in an Unknown state...\n this._logger.debug(\n `[manager.onStateChange] forcing state update from \"Unknown\"`,\n );\n this._manager.state().then((s) => {\n if (lastBleStateIsUnknown) {\n this._logger.debug(\n `[manager.onStateChange] forcing state update to: \"${s}\"`,\n );\n this._bleStateSubject.next(s);\n }\n });\n }\n }, true);\n }\n\n /** Exposed for testing purposes */\n observeBleState(): Observable<State> {\n return this._bleStateSubject.asObservable();\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 _scannedDevicesSubject: BehaviorSubject<InternalScannedDevice[]> =\n new BehaviorSubject<InternalScannedDevice[]>([]);\n private _startedScanningSubscriber: Subscription | undefined = undefined;\n\n /**\n * Returns an observable that emits a value when the prerequisites for scanning are met.\n * The prerequisites are:\n * - BLE should be supported. If not, it will throw an error.\n * - Permissions should be granted. If not, it request them, if it fails, it will throw an error.\n * - BLE state should be PoweredOn.\n * - If BLE state is undetermined (Unknown or Resetting), it will wait for the state to be updated.\n * - For other states, it will throw an error.\n */\n private _waitForScanningPrerequisites() {\n return from([true]).pipe(\n tap(() => {\n if (!this.isSupported()) {\n throw new BleNotSupported(\"BLE not supported\");\n }\n this._logger.debug(\n \"[waitForScanningPrerequisites] Prerequisite: isSupported=true\",\n );\n }),\n switchMap(async () => this.checkAndRequestPermissions()),\n tap((hasPermissions) => {\n this._logger.debug(\n `[_waitForScanningPrerequisites] Prerequisite: hasPermissions=${hasPermissions}`,\n );\n if (!hasPermissions) {\n throw new BlePermissionsNotGranted(\"Permissions not granted\");\n }\n }),\n switchMap(() => this.observeBleState()),\n first((state) => {\n /**\n * We wait for the BLE state to be PoweredOn, in case the current state is one of those:\n * - Unknown: temporary undetermined state which will quickly be updated\n * - Resetting: temporary undetermined state which will quickly be updated\n */\n const canStartScanning = state === State.PoweredOn;\n this._logger.info(\n `[waitForScanningPrerequisites] Prerequisite: BLE state=${state}, canStartScanning=${canStartScanning}`,\n );\n if (state === State.PoweredOff) {\n throw new BlePoweredOff();\n } else if (state === State.Unauthorized) {\n throw new BlePermissionsNotGranted('Ble State is \"Unauthorized\"');\n } else if (state === State.Unsupported) {\n throw new BleNotSupported();\n }\n return canStartScanning;\n }),\n );\n }\n\n private _startScanning() {\n if (this._startedScanningSubscriber != undefined) {\n this._logger.info(\"[startScanning] !! startScanning already started\");\n return;\n }\n\n //Reset the scanned devices list as new scan will start\n this._scannedDevicesSubject.next([]);\n\n this._logger.info(\"[startScanning] startScanning\");\n\n this._startedScanningSubscriber = from([true])\n .pipe(\n switchMap(() => {\n const subject = new BehaviorSubject<InternalScannedDevice[]>([]);\n const devicesById = new Map<string, InternalScannedDevice>();\n\n this._logger.info(\"[startScanning] startDeviceScan\");\n this._manager\n .startDeviceScan(\n this._deviceModelDataSource.getBluetoothServices(),\n { allowDuplicates: true },\n (error, rnDevice) => {\n if (error) {\n this._logger.error(\n \"[startScanning] Error in startDeviceScan callback\",\n {\n data: { error, rnDevice },\n },\n );\n subject.error(error);\n return;\n }\n if (!rnDevice) {\n this._logger.warn(\n \"[startScanning] Null Device in startDeviceScan callback\",\n {\n data: { rnDevice },\n },\n );\n subject.error(\n new Error(\"Null device in startDeviceScan callback\"),\n );\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 .catch((e) => {\n subject.error(e);\n this._logger.error(\n \"[startScanning] Error while calling startDeviceScan\",\n {\n data: { error: e },\n },\n );\n });\n\n this._logger.debug(\"[startScanning] after startDeviceScan\");\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.pipe(\n finalize(() => {\n this._logger.debug(\"[startScanning] finalize\");\n subject.complete();\n clearInterval(interval);\n this._stopScanning();\n }),\n );\n }),\n throttleTime(this._scanThrottleDelayMs),\n )\n .subscribe({\n next: (devices) => {\n this._scannedDevicesSubject.next(devices);\n },\n error: (error) => {\n this._logger.error(\"[startScanning] Error while scanning\", {\n data: { error },\n });\n this._scannedDevicesSubject.error(error);\n },\n });\n }\n\n private async _stopScanning(): Promise<void> {\n this._logger.debug(\"[stopScanning] stopScanning\");\n await this._manager.stopDeviceScan();\n //Stop listening the observable from this._startScanning()\n this._startedScanningSubscriber?.unsubscribe();\n this._startedScanningSubscriber = undefined;\n this._scannedDevicesSubject.complete();\n this._scannedDevicesSubject = new BehaviorSubject<InternalScannedDevice[]>(\n [],\n );\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 return this._waitForScanningPrerequisites().pipe(\n tap(() => this._startScanning()),\n switchMap(() => this._scannedDevicesSubject),\n switchMap(async (internalScannedDevices) => {\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 const rawConnectedDevices = await this._manager\n .connectedDevices(this._deviceModelDataSource.getBluetoothServices())\n .catch((e) => {\n this._logger.error(\n \"[listenToAvailableDevices] Error calling manager.connectedDevices\",\n {\n data: { error: e },\n },\n );\n throw e;\n });\n\n const eitherConnectedDevices = await Promise.all(\n rawConnectedDevices.map(async (device) => {\n try {\n const services = await device.services();\n const servicesUUIDs = services.map((s) => s.uuid);\n return this._mapDeviceToTransportDiscoveredDevice(\n device,\n servicesUUIDs,\n );\n } catch (e) {\n this._logger.error(\n \"[listenToAvailableDevices] Error in mapping device to transport discovered device\",\n {\n data: { e },\n },\n );\n return Left(\n new NoDeviceModelFoundError(\n `Error in mapping device to transport discovered device: ${e}`,\n ),\n );\n }\n }),\n );\n\n const connectedDevices = Either.rights(eitherConnectedDevices);\n\n this._logger.debug(\"[listenToAvailableDevices]\", {\n data: {\n rawConnectedDevices: rawConnectedDevices.map((d) => d.name),\n connectedDevices: connectedDevices.map((d) => d.name),\n scannedDevices: scannedDevices.map((d) => d.name),\n },\n });\n\n /** We return both connected and scanned devices, as scanned devices don't include connected devices */\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 this._logger.debug(\"[connect] Called\", {\n data: { deviceId: params.deviceId },\n });\n const existing = this._deviceConnectionsById.get(params.deviceId);\n if (existing) {\n this._logger.debug(\"[connect] Existing device connection found\", {\n data: { deviceId: params.deviceId },\n });\n const dependencies = existing.getDependencies();\n const deviceModel =\n dependencies.internalDevice.bleDeviceInfos.deviceModel;\n const deviceName =\n dependencies.device.localName || dependencies.device.name || undefined;\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 name: deviceName,\n }),\n );\n }\n\n this._logger.debug(\n \"[connect] No existing device connection found, establishing one\",\n {\n data: { deviceId: params.deviceId },\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 if (\n error instanceof BleError &&\n error.errorCode === BleErrorCode.OperationCancelled &&\n Platform.OS === \"android\"\n ) {\n return throwE(new PeerRemovedPairingError(error));\n }\n return throwE(new OpeningConnectionError(error));\n }\n\n const disconnectionSubscription = this._listenToDeviceDisconnected(\n params.deviceId,\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: () => this.tryToReconnect(params.deviceId),\n onTerminated: async () => {\n this._logger.debug(\"[onTerminated]\", {\n data: { deviceId: params.deviceId },\n });\n try {\n await this._safeCancel(params.deviceId);\n } catch (e) {\n this._logger.error(\n \"[onTerminated] Error in termination of device connection\",\n { data: { e } },\n );\n } finally {\n this._deviceConnectionsById.delete(params.deviceId);\n this._reconnectionSubscription.ifJust((sub) => {\n sub.unsubscribe();\n this._reconnectionSubscription = Maybe.zero();\n });\n this._logger.debug(\"[onTerminated] signaling disconnection\", {\n data: { deviceId: params.deviceId },\n });\n params.onDisconnect(params.deviceId);\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 name: device.localName || device.name || undefined,\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 [\"android\", \"ios\"].includes(this._platform.OS);\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 * Checks if the necessary permissions are granted and requests them if not.\n */\n async checkAndRequestPermissions(): Promise<boolean> {\n this._logger.debug(\"[checkAndRequestPermissions] Called\");\n\n const checkResult =\n await this._permissionsService.checkRequiredPermissions();\n if (checkResult) return true;\n\n const requestResult =\n await this._permissionsService.requestRequiredPermissions();\n return requestResult;\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(\"[_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\n Maybe.fromNullable(this._deviceConnectionsById.get(deviceId)).map(\n (deviceConnection) => deviceConnection.eventDeviceDisconnected(),\n );\n }\n\n private _listenToDeviceDisconnected(deviceId: DeviceId): BleSubscription {\n const disconnectionSubscription = this._manager.onDeviceDisconnected(\n deviceId,\n (error, d) => {\n this._handleDeviceDisconnected(error, d);\n disconnectionSubscription.remove();\n },\n );\n return disconnectionSubscription;\n }\n\n private async tryToReconnect(deviceId: DeviceId) {\n this._logger.debug(\"[tryToReconnect] Called\", {\n data: { deviceId },\n });\n let reconnectionTryCount = 0;\n\n await this._stopScanning();\n await this._safeCancel(deviceId);\n\n const reconnect$ = defer(async () => {\n let disconnectionSubscription: BleSubscription | null = null;\n reconnectionTryCount++;\n try {\n this._logger.debug(\n `[tryToReconnect](try=${reconnectionTryCount}) Reconnecting to device`,\n {\n data: { id: deviceId },\n },\n );\n const reconnectedDevice = await this._manager.connectToDevice(\n deviceId,\n { requestMTU: DEFAULT_MTU, timeout: 2000 },\n );\n this._logger.debug(\n `[tryToReconnect](try=${reconnectionTryCount}) Established connection to device`,\n {\n data: { id: deviceId },\n },\n );\n const usableReconnectedDevice =\n await reconnectedDevice.discoverAllServicesAndCharacteristics();\n this._logger.debug(\n `[tryToReconnect](try=${reconnectionTryCount}) Discovered all services and characteristics`,\n { data: { usableReconnectedDevice } },\n );\n disconnectionSubscription = this._listenToDeviceDisconnected(deviceId);\n await this._handleDeviceReconnected(usableReconnectedDevice);\n return usableReconnectedDevice;\n } catch (e) {\n this._logger.warn(\n `[tryToReconnect](try=${reconnectionTryCount}) Reconnecting to device failed`,\n {\n data: { e },\n },\n );\n disconnectionSubscription?.remove();\n await this._stopScanning();\n await this._safeCancel(deviceId);\n throw e;\n }\n }).pipe(retry(5));\n\n this._reconnectionSubscription = Maybe.of(\n reconnect$.subscribe({\n next: (d) =>\n this._logger.debug(\n `[tryToReconnect](try=${reconnectionTryCount}) Fully reconnected to device (id=${d.id})`,\n ),\n complete: () => {\n this._logger.debug(\"[tryToReconnect] Completed\");\n this._reconnectionSubscription = Maybe.zero();\n },\n error: (e) => {\n this._logger.error(\n `[tryToReconnect] All reconnection attempts failed`,\n { data: { e } },\n );\n this._deviceConnectionsById.get(deviceId)?.closeConnection();\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 \"[_handleDeviceReconnected] 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 try {\n await this._manager.cancelDeviceConnection(deviceId);\n } catch (e) {\n this._logger.error(\n \"[safeCancel] Error in cancelling device connection\",\n {\n data: { e },\n },\n );\n }\n }\n }\n }\n }\n}\n"],
|
|
5
|
+
"mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,oBAAAE,EAAA,6BAAAC,IAAA,eAAAC,EAAAJ,GAAA,IAAAK,EAAyB,wBACzBC,EAOO,gCACPC,EAmBO,2CACPC,EAAwD,qBACxDC,EAYO,gBAEPC,EAKO,4BACPC,EAOO,6BAEPC,EAKO,0CAEA,MAAMT,EAA2B,SAOjC,MAAMD,CAAoC,CAY/C,YACmBW,EACAC,EAGAC,EACAC,EACAC,EACAC,EACAC,EACAC,EAA+B,IAC/BC,EAEiDC,GAChE,IAAI,+BAA6BA,CAAI,EACtBC,EAGM,CAACD,EAAME,IAC5B,IAAI,kBAAgBF,EAAME,CAAa,EACzC,CAnBiB,4BAAAX,EACA,2BAAAC,EAGA,wBAAAC,EACA,0BAAAC,EACA,cAAAC,EACA,eAAAC,EACA,yBAAAC,EACA,0BAAAC,EACA,0CAAAC,EAIA,8BAAAE,EAMjB,KAAK,QAAUT,EAAsB,yBAAyB,EAC9D,KAAK,uBAAyB,IAAI,IAClC,KAAK,0BAA4B,QAAM,KAAK,EAE5C,IAAIW,EAAwB,GAC5B,KAAK,SAAS,cAAeC,GAAU,CACrC,KAAK,QAAQ,MAAM,8CAA8CA,CAAK,EAAE,EACxE,KAAK,iBAAiB,KAAKA,CAAK,EAChCD,EAAwBC,IAAU,QAAM,QACpCD,IAEF,KAAK,QAAQ,MACX,6DACF,EACA,KAAK,SAAS,MAAM,EAAE,KAAME,GAAM,CAC5BF,IACF,KAAK,QAAQ,MACX,qDAAqDE,CAAC,GACxD,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__export", "RNBleTransport", "rnBleTransportIdentifier", "__toCommonJS", "import_react_native", "import_react_native_ble_plx", "import_device_management_kit", "import_purify_ts", "import_rxjs", "import_Const", "import_Errors", "import_RNBleApduSender", "_deviceModelDataSource", "_loggerServiceFactory", "_apduSenderFactory", "_apduReceiverFactory", "_manager", "_platform", "_permissionsService", "_scanThrottleDelayMs", "_deviceConnectionStateMachineFactory", "args", "_deviceApduSenderFactory", "loggerFactory", "lastBleStateIsUnknown", "state", "s", "hasPermissions", "canStartScanning", "subject", "devicesById", "error", "rnDevice", "e", "interval", "devices", "internalScannedDevices", "eitherScannedDevices", "timestamp", "a", "b", "device", "d", "scannedDevices", "rawConnectedDevices", "eitherConnectedDevices", "servicesUUIDs", "connectedDevices", "serviceUUID", "bluetoothServiceInfo", "info", "model", "params", "existing", "dependencies", "deviceModel", "deviceName", "throwE", "disconnectionSubscription", "bleDeviceInfos", "internalDevice", "deviceApduSender", "reconnectionTimeout", "deviceConnectionStateMachine", "sub", "deviceId", "deviceConnection", "reconnectionTryCount", "reconnect$", "reconnectedDevice", "usableReconnectedDevice", "errorOrDeviceConnection", "liftEither"]
|
|
7
7
|
}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var d=require("react-native-ble-plx"),S=require("@ledgerhq/device-management-kit"),P=require("purify-ts"),l=require("rxjs"),t=require("vitest"),k=require("../model/Errors"),T=require("../permissions/DefaultPermissionsService"),F=require("./RNBleTransport"),O=require("./RNBleTransportFactory");const E={error:vi.fn(),info:vi.fn(),warn:vi.fn(),debug:vi.fn(),subscribers:[]},V={error:console.error,info:console.info,warn:console.warn,debug:console.debug,subscribers:[]};vi.mock("react-native",()=>({Platform:{},PermissionsAndroid:{}}));vi.mock("react-native-ble-plx",()=>({Device:vi.fn(),State:{PoweredOn:"PoweredOn",Unknown:"Unknown",PoweredOff:"PoweredOff",Resetting:"Resetting",Unsupported:"Unsupported",Unauthorized:"Unauthorized"},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 C=new S.TransportDeviceModel({id:S.DeviceModelId.FLEX,productName:"Ledger Flex",usbProductId:112,bootloaderUsbProductId:7,usbOnly:!1,memorySize:1533*1024,blockSize:32,masks:[858783744]}),h={OS:"ios"},U={OS:"android"},I={OS:"windows"};class s{deviceModelDataSource=g();loggerServiceFactory=()=>E;apduSenderServiceFactory=()=>{};apduReceiverServiceFactory=()=>{};bleManager=new d.BleManager;platform=h;permissionsService=new T.DefaultPermissionsService;deviceConnectionStateMachineFactory;deviceApduSenderFactory;scanThrottleDelayMs=1e3;withDeviceModelDataSource(e){return this.deviceModelDataSource=e,this}withPlatform(e){return this.platform=e,this}withPermissionsService(e){return this.permissionsService=e,this}withBleManager(e){return this.bleManager=e,this}withDeviceConnectionStateMachineFactory(e){return this.deviceConnectionStateMachineFactory=e,this}withDeviceApduSenderFactory(e){return this.deviceApduSenderFactory=e,this}withLogger(e=V){return this.loggerServiceFactory=()=>e,this}withScanThrottleDelayMs(e){return this.scanThrottleDelayMs=e,this}build(){return new F.RNBleTransport(this.deviceModelDataSource,this.loggerServiceFactory,this.apduSenderServiceFactory,this.apduReceiverServiceFactory,this.bleManager,this.platform,this.permissionsService,this.scanThrottleDelayMs,this.deviceConnectionStateMachineFactory,this.deviceApduSenderFactory)}}function g(){const p=vi.fn(()=>["ledgerId"]),e=vi.fn(()=>({ledgerId:new S.BleDeviceInfos(C,"serviceUuid","notifyUuid","writeCmdUuid","readCmdUuid")}));return{getBluetoothServices:p,getBluetoothServicesInfos:e,getAllDeviceModels:vi.fn(),getDeviceModel:vi.fn(),filterDeviceModels:vi.fn()}}function A(p={}){return{id:"deviceId",localName:"deviceName",serviceUUIDs:["ledgerId"],services:vi.fn().mockResolvedValue([{uuid:"ledgerId"}]),...p}}function f(p={},e=d.State.PoweredOn){return{onStateChange:vi.fn().mockImplementation((o,c)=>(c&&o(e),{remove:vi.fn()})),startDeviceScan:vi.fn(),stopDeviceScan:vi.fn(),connectToDevice:vi.fn(),disconnectFromDevice:vi.fn(),cancelDeviceConnection:vi.fn(),connectedDevices:vi.fn().mockResolvedValue([]),monitorCharacteristicForDevice:vi.fn(),writeCharacteristicWithoutResponseForDevice:vi.fn(),discoverAllServicesAndCharacteristicsForDevice:vi.fn(),onDeviceDisconnected:vi.fn(),isDeviceConnected:vi.fn(),state:vi.fn(),...p}}describe("RNBleTransportFactory",()=>{it("should return a RNBleTransport",()=>{const p={deviceModelDataSource:g(),loggerServiceFactory:()=>E,apduSenderServiceFactory:()=>{},apduReceiverServiceFactory:()=>{},config:{}},e=(0,O.RNBleTransportFactory)(p);(0,t.expect)(e).toBeInstanceOf(F.RNBleTransport)})});describe("RNBleTransport",()=>{let p;(0,t.beforeEach)(()=>{vi.clearAllMocks(),vi.useRealTimers()}),afterEach(()=>{p&&p.unsubscribe()}),describe("BLE state monitoring",()=>{test("the constructor should call BleManager.onStateChange with a parameter requesting the initial state",()=>{const e=vi.fn();new s().withBleManager(f({onStateChange:e})).build(),(0,t.expect)(e).toHaveBeenCalledWith(t.expect.any(Function),!0)}),describe("observeBleState",()=>{it("should emit the initial BLE state",async()=>{const e=vi.fn().mockImplementation((i,r)=>(r&&i(d.State.PoweredOn),{remove:vi.fn()})),o=new s().withBleManager(f({onStateChange:e})).build().observeBleState(),c=await(0,l.firstValueFrom)(o);(0,t.expect)(c).toBe(d.State.PoweredOn)}),it("should emit the new BLE state values",async()=>{const e=new l.Subject,o=new s().withBleManager(f({onStateChange:r=>(r(d.State.PoweredOn),e.subscribe(a=>r(a)),{remove:vi.fn()})})).build().observeBleState();e.next(d.State.PoweredOff);const c=await(0,l.firstValueFrom)(o);(0,t.expect)(c).toBe(d.State.PoweredOff),e.next(d.State.Resetting);const i=await(0,l.firstValueFrom)(o);(0,t.expect)(i).toBe(d.State.Resetting)}),it("should recover from an Unknown state by calling BleManager.state() method and emitting the new state",async()=>{vi.useFakeTimers();const e=new l.Subject,n=vi.fn().mockImplementation(()=>new Promise(a=>{setTimeout(()=>{a(d.State.PoweredOn)},10)})),c=new s().withBleManager(f({state:n,onStateChange:a=>(e.subscribe(v=>a(v)),{remove:vi.fn()})})).build().observeBleState();e.next(d.State.PoweredOff),(0,t.expect)(n).not.toHaveBeenCalled(),e.next(d.State.Unknown);const i=await(0,l.firstValueFrom)(c);(0,t.expect)(i).toBe(d.State.Unknown),(0,t.expect)(n).toHaveBeenCalled(),vi.advanceTimersByTime(11),await Promise.resolve();const r=await(0,l.firstValueFrom)(c);(0,t.expect)(r).toBe(d.State.PoweredOn)})})}),describe("getIdentifier",()=>{it("should return rnBleTransportIdentifier",()=>{const n=new s().build().getIdentifier();(0,t.expect)(n).toStrictEqual("RN_BLE")})}),describe("isSupported",()=>{it("should return true if platform is ios",()=>{const n=new s().withPlatform(h).build().isSupported();(0,t.expect)(n).toBe(!0)}),it("should return true if platform is android",()=>{const n=new s().withPlatform(U).build().isSupported();(0,t.expect)(n).toBe(!0)}),it("should return false if platform is not android nor ios",()=>{const n=new s().withPlatform(I).build().isSupported();(0,t.expect)(n).toBe(!1)})}),describe("startDiscovering",()=>{it("should emit an empty array",()=>new Promise((e,n)=>{p=new s().withPlatform(h).withDeviceModelDataSource(g()).build().startDiscovering().subscribe({next:i=>{try{(0,t.expect)(i).toStrictEqual([])}catch(r){n(r)}},error:i=>{throw n(i),i},complete:()=>{e(void 0)}})}))}),describe("stopDiscovering",()=>{it("should call ble manager stop scan on stop discovering",()=>{const e=vi.fn(),n=f({stopDeviceScan:e,connectedDevices:vi.fn().mockResolvedValueOnce([])});new s().withBleManager(n).withPlatform(h).withDeviceModelDataSource(g()).build().stopDiscovering(),(0,t.expect)(e).toHaveBeenCalled()})}),describe("listenToAvailableDevices",()=>{it("should emit an error if platform is not android nor ios",async()=>{const e=new s().withBleManager(f()).withPlatform(I).build();return new Promise((n,o)=>{e.listenToAvailableDevices().subscribe({error:c=>{try{(0,t.expect)(c).toBeInstanceOf(k.BleNotSupported)}catch(i){o(i)}n(void 0)},complete:()=>{o(new Error("Should not complete"))}})})}),it("should emit an error if BLE state is PoweredOff",async()=>{const n=new s().withBleManager(f({},d.State.PoweredOff)).build().listenToAvailableDevices();let o;await(0,l.firstValueFrom)(n).catch(c=>{o=c}),(0,t.expect)(o).toBeInstanceOf(k.BlePoweredOff)}),describe("permissions check",()=>{const e=vi.fn(),n=vi.fn(),o={checkRequiredPermissions:e,requestRequiredPermissions:n},c=vi.fn().mockImplementation(async()=>{}),i=f({startDeviceScan:c,stopDeviceScan:vi.fn(),connectedDevices:vi.fn().mockResolvedValue([]),onDeviceDisconnected:vi.fn(),isDeviceConnected:vi.fn(),onStateChange:r=>(r(d.State.PoweredOn),{remove:vi.fn()})});it("should call checkPermissions",async()=>{const a=new s().withBleManager(i).withPlatform(h).withPermissionsService(o).build().listenToAvailableDevices();await(0,l.firstValueFrom)(a).catch(v=>{(0,t.expect)(v).toBeInstanceOf(k.BlePermissionsNotGranted)}),(0,t.expect)(e).toHaveBeenCalled()}),it("should call BleManager.startDeviceScan if checkPermissions resolves to true",async()=>{e.mockResolvedValue(!0);const a=new s().withBleManager(i).withPlatform(h).withPermissionsService(o).build().listenToAvailableDevices();await(0,l.firstValueFrom)(a).catch(v=>{(0,t.expect)(v).toBeInstanceOf(k.BlePermissionsNotGranted)}),(0,t.expect)(c).toHaveBeenCalled()}),it("should call requestPermissions if checkPermissions resolves to false",async()=>{e.mockResolvedValue(!1);const a=new s().withBleManager(i).withPlatform(h).withPermissionsService(o).build().listenToAvailableDevices();await(0,l.firstValueFrom)(a).catch(()=>{}),(0,t.expect)(n).toHaveBeenCalled()}),it("should call BleManager.startDeviceScan if requestPermissions resolves to true",async()=>{e.mockResolvedValue(!1),n.mockResolvedValue(!0);const r=new s().withBleManager(i).withPlatform(h).withPermissionsService(o).build(),a=r.listenToAvailableDevices();await(0,l.firstValueFrom)(r.observeBleState()),await(0,l.firstValueFrom)(a),(0,t.expect)(c).toHaveBeenCalled()}),it("should emit an error if checkPermissions and requestPermissions resolve to false",async()=>{e.mockResolvedValue(!1),n.mockResolvedValue(!1);const a=new s().withBleManager(i).withPlatform(h).withPermissionsService(o).build().listenToAvailableDevices();return new Promise((v,u)=>{a.subscribe({error:m=>{try{(0,t.expect)(m).toBeInstanceOf(k.BlePermissionsNotGranted)}catch(w){u(w)}v(void 0)},complete:()=>{u(new Error("Should not complete"))}})})})}),it("should return already connected devices and scanned devices",()=>new Promise((e,n)=>{let o=null;const c=A({id:"aConnectedDeviceId",localName:"aConnectedDeviceName"}),i=vi.fn().mockImplementation(async(m,w,b)=>{o=setInterval(()=>{b(null,{id:"aScannedDeviceId",localName:"aScannedDeviceName",serviceUUIDs:["ledgerId"],rssi:1})},10),b(null,{id:"aNonLedgerScannedDeviceId",localName:"aNonLedgerScannedDeviceName",serviceUUIDs:["notLedgerId"],rssi:2})}),r=vi.fn().mockImplementation(()=>{o&&(clearInterval(o),o=null)}),a=f({connectedDevices:vi.fn().mockResolvedValue([c]),startDeviceScan:i,stopDeviceScan:r,onDeviceDisconnected:vi.fn(),isDeviceConnected:vi.fn(),onStateChange:m=>(m(d.State.PoweredOn),{remove:vi.fn()})}),v=new s().withBleManager(a).withPlatform(h).withDeviceModelDataSource(g()).withScanThrottleDelayMs(1).build(),u=[];p=v.listenToAvailableDevices().subscribe({next:m=>{if(u.push(m),u.length===2)try{(0,t.expect)(u).toEqual([[{id:"aConnectedDeviceId",name:"aConnectedDeviceName",deviceModel:C,transport:"RN_BLE",rssi:void 0}],[{id:"aConnectedDeviceId",name:"aConnectedDeviceName",deviceModel:C,transport:"RN_BLE",rssi:void 0},{id:"aScannedDeviceId",name:"aScannedDeviceName",deviceModel:C,transport:"RN_BLE",rssi:1}]]),e(void 0)}catch(w){n(w)}}})})),it("should propagate the error if startDeviceScan throws an error",()=>{const e=new Error("startDeviceScan error"),n=vi.fn().mockRejectedValueOnce(e),c=new s().withBleManager(f({startDeviceScan:n})).build().listenToAvailableDevices();return new Promise((i,r)=>{c.subscribe({error:a=>{try{(0,t.expect)(a).toBe(e),i(void 0)}catch(v){r(v)}},complete:()=>r(new Error("Should not complete"))})})}),it("should propagate the error if startDeviceScan emits an error",()=>{const e=new Error("startDeviceScan error"),n=vi.fn().mockImplementation(async(i,r,a)=>{a(e,{})}),c=new s().withBleManager(f({startDeviceScan:n})).build().listenToAvailableDevices();return new Promise((i,r)=>{c.subscribe({error:a=>{try{(0,t.expect)(a).toBe(e),i(void 0)}catch(v){r(v)}i(void 0)},complete:()=>r(new Error("Should not complete"))})})}),it("should propagate an error if startDeviceScan emits a null device",()=>{const e=vi.fn().mockImplementation(async(c,i,r)=>{r(null,null)}),o=new s().withBleManager(f({startDeviceScan:e})).build().listenToAvailableDevices();return new Promise((c,i)=>{o.subscribe({error:r=>{try{(0,t.expect)(r).toEqual(new Error("Null device in startDeviceScan callback")),c(void 0)}catch(a){i(a)}}})})}),it("should recover from a scanning error, allowing next calls of listenToAvailableDevices to succeed and emit the devices",async()=>{vi.useFakeTimers();const e=new Error("A Scan Error"),n=vi.fn().mockRejectedValueOnce(e),o=new s().withBleManager(f({startDeviceScan:n})).build(),c=o.listenToAvailableDevices();let i;await(0,l.firstValueFrom)(c).catch(v=>{i=v}),(0,t.expect)(i).toBe(e),n.mockImplementation(async(v,u,m)=>{m(null,{id:"aScannedDeviceId",localName:"aScannedDeviceName",serviceUUIDs:["ledgerId"],rssi:1})});const r=o.listenToAvailableDevices();vi.advanceTimersByTime(2e3);const a=await(0,l.firstValueFrom)(r).catch(()=>{throw new Error("Caught error in second observable, this should not happen if listenToAvailableDevices recovers from the scanning error")});(0,t.expect)(a).toEqual([{id:"aScannedDeviceId",name:"aScannedDeviceName",deviceModel:C,transport:"RN_BLE",rssi:1}])})}),describe("connect",()=>{it("should throw an error if device id is unknown",async()=>{const e=f({connectedDevices:vi.fn().mockResolvedValue([]),discoverAllServicesAndCharacteristicsForDevice:vi.fn().mockRejectedValueOnce(new Error("discoverAllServicesAndCharacteristicsForDevice error"))}),n=vi.fn().mockReturnValue({setupConnection:vi.fn().mockResolvedValue(void 0)}),c=await new s().withBleManager(e).withPlatform(h).withDeviceModelDataSource(g()).withDeviceApduSenderFactory(n).build().connect({deviceId:null,onDisconnect:vi.fn()});(0,t.expect)(c).toEqual((0,P.Left)(new S.OpeningConnectionError("discoverAllServicesAndCharacteristicsForDevice error")))}),it("should connect to a discovered device with correct MTU and discover services and setup apdu sender",async()=>{const e=A({id:"deviceId",localName:"name"}),n=vi.fn().mockImplementation(async(y,M,B)=>{B(null,{id:"deviceId",localName:"name",serviceUUIDs:["ledgerId"],rssi:42})}),o=vi.fn(),c=f({connectedDevices:vi.fn().mockResolvedValue([]),startDeviceScan:n,stopDeviceScan:o,connectToDevice:vi.fn().mockResolvedValueOnce(e),discoverAllServicesAndCharacteristicsForDevice:vi.fn().mockResolvedValueOnce(e),monitorCharacteristicForDevice:vi.fn(),writeCharacteristicWithoutResponseForDevice:vi.fn(),onDeviceDisconnected:vi.fn(),isDeviceConnected:vi.fn(),onStateChange:y=>(y(d.State.PoweredOn),{remove:vi.fn()})}),i=vi.fn().mockResolvedValue(void 0),r=vi.fn().mockReturnValue({sendApdu:vi.fn()}),a=vi.fn().mockReturnValue({setupConnection:i}),v=new s().withBleManager(c).withPlatform(h).withDeviceModelDataSource(g()).withDeviceConnectionStateMachineFactory(r).withDeviceApduSenderFactory(a).withScanThrottleDelayMs(1).build(),u=v.listenToAvailableDevices(),m=await(0,l.firstValueFrom)(u),[w]=m,b=await v.connect({deviceId:w.id,onDisconnect:vi.fn()});(0,t.expect)(b.isRight()).toBe(!0),(0,t.expect)(c.connectToDevice).toHaveBeenCalledWith("deviceId",{requestMTU:156}),(0,t.expect)(c.discoverAllServicesAndCharacteristicsForDevice).toHaveBeenCalledWith("deviceId"),(0,t.expect)(i).toHaveBeenCalled()}),it("should return a connected device which calls state machine sendApdu",async()=>{vi.useFakeTimers();const e=A({id:"deviceId",localName:"name"}),n=vi.fn().mockImplementation(async(M,B,D)=>{D(null,{id:"deviceId",localName:"name",serviceUUIDs:["ledgerId"],rssi:42})}),o=vi.fn(),c=f({connectedDevices:vi.fn().mockResolvedValue([]),startDeviceScan:n,stopDeviceScan:o,connectToDevice:vi.fn().mockResolvedValueOnce(e),discoverAllServicesAndCharacteristicsForDevice:vi.fn().mockResolvedValueOnce(e),monitorCharacteristicForDevice:vi.fn(),writeCharacteristicWithoutResponseForDevice:vi.fn(),onDeviceDisconnected:vi.fn(),isDeviceConnected:vi.fn(),onStateChange:M=>(M(d.State.PoweredOn),{remove:vi.fn()})}),i=vi.fn(),r=vi.fn().mockReturnValue({sendApdu:i}),a=vi.fn().mockReturnValue({setupConnection:vi.fn().mockResolvedValue(void 0)}),v=new s().withBleManager(c).withPlatform(h).withDeviceModelDataSource(g()).withDeviceConnectionStateMachineFactory(r).withDeviceApduSenderFactory(a).build(),u=v.listenToAvailableDevices();vi.advanceTimersByTime(2e3);const m=await(0,l.firstValueFrom)(u),[w]=m,b=await v.connect({deviceId:w.id,onDisconnect:vi.fn()});b.extract().sendApdu(Uint8Array.from([67,50])),(0,t.expect)(b).toEqual((0,P.Right)(new S.TransportConnectedDevice({id:"deviceId",deviceModel:C,type:"BLE",transport:"RN_BLE",sendApdu:t.expect.any(Function)}))),(0,t.expect)(i).toHaveBeenCalledWith(Uint8Array.from([67,50]))})}),describe("disconnect",()=>{it("should disconnect gracefully",async()=>{vi.useFakeTimers();const e=A({id:"deviceId",localName:"name"}),n=vi.fn().mockImplementation(async(D,N,R)=>{R(null,{id:"deviceId",localName:"name",serviceUUIDs:["ledgerId"],rssi:42})}),o=vi.fn(),c=vi.fn().mockImplementation(()=>({remove:vi.fn()})),i=vi.fn(),r=f({connectedDevices:vi.fn().mockResolvedValue([]),startDeviceScan:n,stopDeviceScan:o,connectToDevice:vi.fn().mockResolvedValueOnce(e),discoverAllServicesAndCharacteristicsForDevice:vi.fn().mockResolvedValueOnce(e),monitorCharacteristicForDevice:vi.fn(),writeCharacteristicWithoutResponseForDevice:vi.fn(),onStateChange:D=>(D(d.State.PoweredOn),{remove:vi.fn()}),onDeviceDisconnected:c,isDeviceConnected:vi.fn()}),a=D=>new S.DeviceConnectionStateMachine({deviceId:"deviceId",deviceApduSender:D.deviceApduSender,timeoutDuration:1e3,onTerminated:D.onTerminated,tryToReconnect:D.tryToReconnect}),v=vi.fn().mockReturnValue({setupConnection:vi.fn().mockResolvedValue(void 0),closeConnection:i}),u=new s().withBleManager(r).withPlatform(h).withDeviceModelDataSource(g()).withDeviceConnectionStateMachineFactory(a).withDeviceApduSenderFactory(v).build(),m=vi.fn(),w=u.listenToAvailableDevices();vi.advanceTimersByTime(2e3);const b=await(0,l.firstValueFrom)(w),[y]=b,M=await u.connect({deviceId:y.id,onDisconnect:m}),B=await u.disconnect({connectedDevice:M.extract()});(0,t.expect)(B).toEqual((0,P.Right)(void 0)),(0,t.expect)(m).toHaveBeenCalled(),(0,t.expect)(i).toHaveBeenCalled()}),it("should handle error while disconnecting",async()=>{vi.useFakeTimers();const e=A({id:"deviceId",localName:"name"}),n=vi.fn().mockImplementation(async(D,N,R)=>{R(null,{id:"deviceId",localName:"name",serviceUUIDs:["ledgerId"],rssi:42})}),o=vi.fn(),c=vi.fn().mockImplementation(()=>({remove:vi.fn()})),i=vi.fn(),r=f({connectedDevices:vi.fn().mockResolvedValue([]),startDeviceScan:n,stopDeviceScan:o,connectToDevice:vi.fn().mockResolvedValueOnce(e),discoverAllServicesAndCharacteristicsForDevice:vi.fn().mockResolvedValueOnce(e),monitorCharacteristicForDevice:vi.fn(),writeCharacteristicWithoutResponseForDevice:vi.fn(),onDeviceDisconnected:c,isDeviceConnected:vi.fn(),onStateChange:D=>(D(d.State.PoweredOn),{remove:vi.fn()})}),a=D=>new S.DeviceConnectionStateMachine({deviceId:"deviceId",deviceApduSender:D.deviceApduSender,timeoutDuration:1e3,onTerminated:D.onTerminated,tryToReconnect:D.tryToReconnect}),v=vi.fn().mockReturnValue({setupConnection:vi.fn().mockResolvedValue(void 0),closeConnection:i}),u=new s().withBleManager(r).withPlatform(h).withDeviceModelDataSource(g()).withDeviceConnectionStateMachineFactory(a).withDeviceApduSenderFactory(v).build(),m=vi.fn(),w=u.listenToAvailableDevices();vi.advanceTimersByTime(2e3);const b=await(0,l.firstValueFrom)(w),[y]=b,M=await u.connect({deviceId:y.id,onDisconnect:m}),B=await u.disconnect({connectedDevice:M.extract()});(0,t.expect)(B).toEqual((0,P.Right)(void 0)),(0,t.expect)(m).toHaveBeenCalled()})})});
|
|
1
|
+
"use strict";var d=require("react-native-ble-plx"),S=require("@ledgerhq/device-management-kit"),P=require("purify-ts"),l=require("rxjs"),t=require("vitest"),k=require("../model/Errors"),T=require("../permissions/DefaultPermissionsService"),F=require("./RNBleTransport"),O=require("./RNBleTransportFactory");const E={error:vi.fn(),info:vi.fn(),warn:vi.fn(),debug:vi.fn(),subscribers:[]},V={error:console.error,info:console.info,warn:console.warn,debug:console.debug,subscribers:[]};vi.mock("react-native",()=>({Platform:{},PermissionsAndroid:{}}));vi.mock("react-native-ble-plx",()=>({Device:vi.fn(),State:{PoweredOn:"PoweredOn",Unknown:"Unknown",PoweredOff:"PoweredOff",Resetting:"Resetting",Unsupported:"Unsupported",Unauthorized:"Unauthorized"},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 C=new S.TransportDeviceModel({id:S.DeviceModelId.FLEX,productName:"Ledger Flex",usbProductId:112,bootloaderUsbProductId:7,usbOnly:!1,memorySize:1533*1024,blockSize:32,masks:[858783744]}),h={OS:"ios"},U={OS:"android"},I={OS:"windows"};class s{deviceModelDataSource=g();loggerServiceFactory=()=>E;apduSenderServiceFactory=()=>{};apduReceiverServiceFactory=()=>{};bleManager=new d.BleManager;platform=h;permissionsService=new T.DefaultPermissionsService;deviceConnectionStateMachineFactory;deviceApduSenderFactory;scanThrottleDelayMs=1e3;withDeviceModelDataSource(e){return this.deviceModelDataSource=e,this}withPlatform(e){return this.platform=e,this}withPermissionsService(e){return this.permissionsService=e,this}withBleManager(e){return this.bleManager=e,this}withDeviceConnectionStateMachineFactory(e){return this.deviceConnectionStateMachineFactory=e,this}withDeviceApduSenderFactory(e){return this.deviceApduSenderFactory=e,this}withLogger(e=V){return this.loggerServiceFactory=()=>e,this}withScanThrottleDelayMs(e){return this.scanThrottleDelayMs=e,this}build(){return new F.RNBleTransport(this.deviceModelDataSource,this.loggerServiceFactory,this.apduSenderServiceFactory,this.apduReceiverServiceFactory,this.bleManager,this.platform,this.permissionsService,this.scanThrottleDelayMs,this.deviceConnectionStateMachineFactory,this.deviceApduSenderFactory)}}function g(){const p=vi.fn(()=>["ledgerId"]),e=vi.fn(()=>({ledgerId:new S.BleDeviceInfos(C,"serviceUuid","notifyUuid","writeCmdUuid","readCmdUuid")}));return{getBluetoothServices:p,getBluetoothServicesInfos:e,getAllDeviceModels:vi.fn(),getDeviceModel:vi.fn(),filterDeviceModels:vi.fn()}}function A(p={}){return{id:"deviceId",localName:"deviceName",serviceUUIDs:["ledgerId"],services:vi.fn().mockResolvedValue([{uuid:"ledgerId"}]),...p}}function f(p={},e=d.State.PoweredOn){return{onStateChange:vi.fn().mockImplementation((o,c)=>(c&&o(e),{remove:vi.fn()})),startDeviceScan:vi.fn(),stopDeviceScan:vi.fn(),connectToDevice:vi.fn(),disconnectFromDevice:vi.fn(),cancelDeviceConnection:vi.fn(),connectedDevices:vi.fn().mockResolvedValue([]),monitorCharacteristicForDevice:vi.fn(),writeCharacteristicWithoutResponseForDevice:vi.fn(),discoverAllServicesAndCharacteristicsForDevice:vi.fn(),onDeviceDisconnected:vi.fn(),isDeviceConnected:vi.fn(),state:vi.fn(),...p}}describe("RNBleTransportFactory",()=>{it("should return a RNBleTransport",()=>{const p={deviceModelDataSource:g(),loggerServiceFactory:()=>E,apduSenderServiceFactory:()=>{},apduReceiverServiceFactory:()=>{},config:{}},e=(0,O.RNBleTransportFactory)(p);(0,t.expect)(e).toBeInstanceOf(F.RNBleTransport)})});describe("RNBleTransport",()=>{let p;(0,t.beforeEach)(()=>{vi.clearAllMocks(),vi.useRealTimers()}),afterEach(()=>{p&&p.unsubscribe()}),describe("BLE state monitoring",()=>{test("the constructor should call BleManager.onStateChange with a parameter requesting the initial state",()=>{const e=vi.fn();new s().withBleManager(f({onStateChange:e})).build(),(0,t.expect)(e).toHaveBeenCalledWith(t.expect.any(Function),!0)}),describe("observeBleState",()=>{it("should emit the initial BLE state",async()=>{const e=vi.fn().mockImplementation((i,r)=>(r&&i(d.State.PoweredOn),{remove:vi.fn()})),o=new s().withBleManager(f({onStateChange:e})).build().observeBleState(),c=await(0,l.firstValueFrom)(o);(0,t.expect)(c).toBe(d.State.PoweredOn)}),it("should emit the new BLE state values",async()=>{const e=new l.Subject,o=new s().withBleManager(f({onStateChange:r=>(r(d.State.PoweredOn),e.subscribe(a=>r(a)),{remove:vi.fn()})})).build().observeBleState();e.next(d.State.PoweredOff);const c=await(0,l.firstValueFrom)(o);(0,t.expect)(c).toBe(d.State.PoweredOff),e.next(d.State.Resetting);const i=await(0,l.firstValueFrom)(o);(0,t.expect)(i).toBe(d.State.Resetting)}),it("should recover from an Unknown state by calling BleManager.state() method and emitting the new state",async()=>{vi.useFakeTimers();const e=new l.Subject,n=vi.fn().mockImplementation(()=>new Promise(a=>{setTimeout(()=>{a(d.State.PoweredOn)},10)})),c=new s().withBleManager(f({state:n,onStateChange:a=>(e.subscribe(v=>a(v)),{remove:vi.fn()})})).build().observeBleState();e.next(d.State.PoweredOff),(0,t.expect)(n).not.toHaveBeenCalled(),e.next(d.State.Unknown);const i=await(0,l.firstValueFrom)(c);(0,t.expect)(i).toBe(d.State.Unknown),(0,t.expect)(n).toHaveBeenCalled(),vi.advanceTimersByTime(11),await Promise.resolve();const r=await(0,l.firstValueFrom)(c);(0,t.expect)(r).toBe(d.State.PoweredOn)})})}),describe("getIdentifier",()=>{it("should return rnBleTransportIdentifier",()=>{const n=new s().build().getIdentifier();(0,t.expect)(n).toStrictEqual("RN_BLE")})}),describe("isSupported",()=>{it("should return true if platform is ios",()=>{const n=new s().withPlatform(h).build().isSupported();(0,t.expect)(n).toBe(!0)}),it("should return true if platform is android",()=>{const n=new s().withPlatform(U).build().isSupported();(0,t.expect)(n).toBe(!0)}),it("should return false if platform is not android nor ios",()=>{const n=new s().withPlatform(I).build().isSupported();(0,t.expect)(n).toBe(!1)})}),describe("startDiscovering",()=>{it("should emit an empty array",()=>new Promise((e,n)=>{p=new s().withPlatform(h).withDeviceModelDataSource(g()).build().startDiscovering().subscribe({next:i=>{try{(0,t.expect)(i).toStrictEqual([])}catch(r){n(r)}},error:i=>{throw n(i),i},complete:()=>{e(void 0)}})}))}),describe("stopDiscovering",()=>{it("should call ble manager stop scan on stop discovering",()=>{const e=vi.fn(),n=f({stopDeviceScan:e,connectedDevices:vi.fn().mockResolvedValueOnce([])});new s().withBleManager(n).withPlatform(h).withDeviceModelDataSource(g()).build().stopDiscovering(),(0,t.expect)(e).toHaveBeenCalled()})}),describe("listenToAvailableDevices",()=>{it("should emit an error if platform is not android nor ios",async()=>{const e=new s().withBleManager(f()).withPlatform(I).build();return new Promise((n,o)=>{e.listenToAvailableDevices().subscribe({error:c=>{try{(0,t.expect)(c).toBeInstanceOf(k.BleNotSupported)}catch(i){o(i)}n(void 0)},complete:()=>{o(new Error("Should not complete"))}})})}),it("should emit an error if BLE state is PoweredOff",async()=>{const n=new s().withBleManager(f({},d.State.PoweredOff)).build().listenToAvailableDevices();let o;await(0,l.firstValueFrom)(n).catch(c=>{o=c}),(0,t.expect)(o).toBeInstanceOf(k.BlePoweredOff)}),describe("permissions check",()=>{const e=vi.fn(),n=vi.fn(),o={checkRequiredPermissions:e,requestRequiredPermissions:n},c=vi.fn().mockImplementation(async()=>{}),i=f({startDeviceScan:c,stopDeviceScan:vi.fn(),connectedDevices:vi.fn().mockResolvedValue([]),onDeviceDisconnected:vi.fn(),isDeviceConnected:vi.fn(),onStateChange:r=>(r(d.State.PoweredOn),{remove:vi.fn()})});it("should call checkPermissions",async()=>{const a=new s().withBleManager(i).withPlatform(h).withPermissionsService(o).build().listenToAvailableDevices();await(0,l.firstValueFrom)(a).catch(v=>{(0,t.expect)(v).toBeInstanceOf(k.BlePermissionsNotGranted)}),(0,t.expect)(e).toHaveBeenCalled()}),it("should call BleManager.startDeviceScan if checkPermissions resolves to true",async()=>{e.mockResolvedValue(!0);const a=new s().withBleManager(i).withPlatform(h).withPermissionsService(o).build().listenToAvailableDevices();await(0,l.firstValueFrom)(a).catch(v=>{(0,t.expect)(v).toBeInstanceOf(k.BlePermissionsNotGranted)}),(0,t.expect)(c).toHaveBeenCalled()}),it("should call requestPermissions if checkPermissions resolves to false",async()=>{e.mockResolvedValue(!1);const a=new s().withBleManager(i).withPlatform(h).withPermissionsService(o).build().listenToAvailableDevices();await(0,l.firstValueFrom)(a).catch(()=>{}),(0,t.expect)(n).toHaveBeenCalled()}),it("should call BleManager.startDeviceScan if requestPermissions resolves to true",async()=>{e.mockResolvedValue(!1),n.mockResolvedValue(!0);const r=new s().withBleManager(i).withPlatform(h).withPermissionsService(o).build(),a=r.listenToAvailableDevices();await(0,l.firstValueFrom)(r.observeBleState()),await(0,l.firstValueFrom)(a),(0,t.expect)(c).toHaveBeenCalled()}),it("should emit an error if checkPermissions and requestPermissions resolve to false",async()=>{e.mockResolvedValue(!1),n.mockResolvedValue(!1);const a=new s().withBleManager(i).withPlatform(h).withPermissionsService(o).build().listenToAvailableDevices();return new Promise((v,u)=>{a.subscribe({error:m=>{try{(0,t.expect)(m).toBeInstanceOf(k.BlePermissionsNotGranted)}catch(w){u(w)}v(void 0)},complete:()=>{u(new Error("Should not complete"))}})})})}),it("should return already connected devices and scanned devices",()=>new Promise((e,n)=>{let o=null;const c=A({id:"aConnectedDeviceId",localName:"aConnectedDeviceName"}),i=vi.fn().mockImplementation(async(m,w,b)=>{o=setInterval(()=>{b(null,{id:"aScannedDeviceId",localName:"aScannedDeviceName",serviceUUIDs:["ledgerId"],rssi:1})},10),b(null,{id:"aNonLedgerScannedDeviceId",localName:"aNonLedgerScannedDeviceName",serviceUUIDs:["notLedgerId"],rssi:2})}),r=vi.fn().mockImplementation(()=>{o&&(clearInterval(o),o=null)}),a=f({connectedDevices:vi.fn().mockResolvedValue([c]),startDeviceScan:i,stopDeviceScan:r,onDeviceDisconnected:vi.fn(),isDeviceConnected:vi.fn(),onStateChange:m=>(m(d.State.PoweredOn),{remove:vi.fn()})}),v=new s().withBleManager(a).withPlatform(h).withDeviceModelDataSource(g()).withScanThrottleDelayMs(1).build(),u=[];p=v.listenToAvailableDevices().subscribe({next:m=>{if(u.push(m),u.length===2)try{(0,t.expect)(u).toEqual([[{id:"aConnectedDeviceId",name:"aConnectedDeviceName",deviceModel:C,transport:"RN_BLE",rssi:void 0}],[{id:"aConnectedDeviceId",name:"aConnectedDeviceName",deviceModel:C,transport:"RN_BLE",rssi:void 0},{id:"aScannedDeviceId",name:"aScannedDeviceName",deviceModel:C,transport:"RN_BLE",rssi:1}]]),e(void 0)}catch(w){n(w)}}})})),it("should propagate the error if startDeviceScan throws an error",()=>{const e=new Error("startDeviceScan error"),n=vi.fn().mockRejectedValueOnce(e),c=new s().withBleManager(f({startDeviceScan:n})).build().listenToAvailableDevices();return new Promise((i,r)=>{c.subscribe({error:a=>{try{(0,t.expect)(a).toBe(e),i(void 0)}catch(v){r(v)}},complete:()=>r(new Error("Should not complete"))})})}),it("should propagate the error if startDeviceScan emits an error",()=>{const e=new Error("startDeviceScan error"),n=vi.fn().mockImplementation(async(i,r,a)=>{a(e,{})}),c=new s().withBleManager(f({startDeviceScan:n})).build().listenToAvailableDevices();return new Promise((i,r)=>{c.subscribe({error:a=>{try{(0,t.expect)(a).toBe(e),i(void 0)}catch(v){r(v)}i(void 0)},complete:()=>r(new Error("Should not complete"))})})}),it("should propagate an error if startDeviceScan emits a null device",()=>{const e=vi.fn().mockImplementation(async(c,i,r)=>{r(null,null)}),o=new s().withBleManager(f({startDeviceScan:e})).build().listenToAvailableDevices();return new Promise((c,i)=>{o.subscribe({error:r=>{try{(0,t.expect)(r).toEqual(new Error("Null device in startDeviceScan callback")),c(void 0)}catch(a){i(a)}}})})}),it("should recover from a scanning error, allowing next calls of listenToAvailableDevices to succeed and emit the devices",async()=>{vi.useFakeTimers();const e=new Error("A Scan Error"),n=vi.fn().mockRejectedValueOnce(e),o=new s().withBleManager(f({startDeviceScan:n})).build(),c=o.listenToAvailableDevices();let i;await(0,l.firstValueFrom)(c).catch(v=>{i=v}),(0,t.expect)(i).toBe(e),n.mockImplementation(async(v,u,m)=>{m(null,{id:"aScannedDeviceId",localName:"aScannedDeviceName",serviceUUIDs:["ledgerId"],rssi:1})});const r=o.listenToAvailableDevices();vi.advanceTimersByTime(2e3);const a=await(0,l.firstValueFrom)(r).catch(()=>{throw new Error("Caught error in second observable, this should not happen if listenToAvailableDevices recovers from the scanning error")});(0,t.expect)(a).toEqual([{id:"aScannedDeviceId",name:"aScannedDeviceName",deviceModel:C,transport:"RN_BLE",rssi:1}])})}),describe("connect",()=>{it("should throw an error if device id is unknown",async()=>{const e=f({connectedDevices:vi.fn().mockResolvedValue([]),discoverAllServicesAndCharacteristicsForDevice:vi.fn().mockRejectedValueOnce(new Error("discoverAllServicesAndCharacteristicsForDevice error"))}),n=vi.fn().mockReturnValue({setupConnection:vi.fn().mockResolvedValue(void 0)}),c=await new s().withBleManager(e).withPlatform(h).withDeviceModelDataSource(g()).withDeviceApduSenderFactory(n).build().connect({deviceId:null,onDisconnect:vi.fn()});(0,t.expect)(c).toEqual((0,P.Left)(new S.OpeningConnectionError("discoverAllServicesAndCharacteristicsForDevice error")))}),it("should connect to a discovered device with correct MTU and discover services and setup apdu sender",async()=>{const e=A({id:"deviceId",localName:"name"}),n=vi.fn().mockImplementation(async(y,M,B)=>{B(null,{id:"deviceId",localName:"name",serviceUUIDs:["ledgerId"],rssi:42})}),o=vi.fn(),c=f({connectedDevices:vi.fn().mockResolvedValue([]),startDeviceScan:n,stopDeviceScan:o,connectToDevice:vi.fn().mockResolvedValueOnce(e),discoverAllServicesAndCharacteristicsForDevice:vi.fn().mockResolvedValueOnce(e),monitorCharacteristicForDevice:vi.fn(),writeCharacteristicWithoutResponseForDevice:vi.fn(),onDeviceDisconnected:vi.fn(),isDeviceConnected:vi.fn(),onStateChange:y=>(y(d.State.PoweredOn),{remove:vi.fn()})}),i=vi.fn().mockResolvedValue(void 0),r=vi.fn().mockReturnValue({sendApdu:vi.fn()}),a=vi.fn().mockReturnValue({setupConnection:i}),v=new s().withBleManager(c).withPlatform(h).withDeviceModelDataSource(g()).withDeviceConnectionStateMachineFactory(r).withDeviceApduSenderFactory(a).withScanThrottleDelayMs(1).build(),u=v.listenToAvailableDevices(),m=await(0,l.firstValueFrom)(u),[w]=m,b=await v.connect({deviceId:w.id,onDisconnect:vi.fn()});(0,t.expect)(b.isRight()).toBe(!0),(0,t.expect)(c.connectToDevice).toHaveBeenCalledWith("deviceId",{requestMTU:156}),(0,t.expect)(c.discoverAllServicesAndCharacteristicsForDevice).toHaveBeenCalledWith("deviceId"),(0,t.expect)(i).toHaveBeenCalled()}),it("should return a connected device which calls state machine sendApdu",async()=>{vi.useFakeTimers();const e=A({id:"deviceId",localName:"name"}),n=vi.fn().mockImplementation(async(M,B,D)=>{D(null,{id:"deviceId",localName:"name",serviceUUIDs:["ledgerId"],rssi:42})}),o=vi.fn(),c=f({connectedDevices:vi.fn().mockResolvedValue([]),startDeviceScan:n,stopDeviceScan:o,connectToDevice:vi.fn().mockResolvedValueOnce(e),discoverAllServicesAndCharacteristicsForDevice:vi.fn().mockResolvedValueOnce(e),monitorCharacteristicForDevice:vi.fn(),writeCharacteristicWithoutResponseForDevice:vi.fn(),onDeviceDisconnected:vi.fn(),isDeviceConnected:vi.fn(),onStateChange:M=>(M(d.State.PoweredOn),{remove:vi.fn()})}),i=vi.fn(),r=vi.fn().mockReturnValue({sendApdu:i}),a=vi.fn().mockReturnValue({setupConnection:vi.fn().mockResolvedValue(void 0)}),v=new s().withBleManager(c).withPlatform(h).withDeviceModelDataSource(g()).withDeviceConnectionStateMachineFactory(r).withDeviceApduSenderFactory(a).build(),u=v.listenToAvailableDevices();vi.advanceTimersByTime(2e3);const m=await(0,l.firstValueFrom)(u),[w]=m,b=await v.connect({deviceId:w.id,onDisconnect:vi.fn()});b.extract().sendApdu(Uint8Array.from([67,50])),(0,t.expect)(b).toEqual((0,P.Right)(new S.TransportConnectedDevice({id:"deviceId",deviceModel:C,type:"BLE",transport:"RN_BLE",sendApdu:t.expect.any(Function),name:"name"}))),(0,t.expect)(i).toHaveBeenCalledWith(Uint8Array.from([67,50]))})}),describe("disconnect",()=>{it("should disconnect gracefully",async()=>{vi.useFakeTimers();const e=A({id:"deviceId",localName:"name"}),n=vi.fn().mockImplementation(async(D,N,R)=>{R(null,{id:"deviceId",localName:"name",serviceUUIDs:["ledgerId"],rssi:42})}),o=vi.fn(),c=vi.fn().mockImplementation(()=>({remove:vi.fn()})),i=vi.fn(),r=f({connectedDevices:vi.fn().mockResolvedValue([]),startDeviceScan:n,stopDeviceScan:o,connectToDevice:vi.fn().mockResolvedValueOnce(e),discoverAllServicesAndCharacteristicsForDevice:vi.fn().mockResolvedValueOnce(e),monitorCharacteristicForDevice:vi.fn(),writeCharacteristicWithoutResponseForDevice:vi.fn(),onStateChange:D=>(D(d.State.PoweredOn),{remove:vi.fn()}),onDeviceDisconnected:c,isDeviceConnected:vi.fn()}),a=D=>new S.DeviceConnectionStateMachine({deviceId:"deviceId",deviceApduSender:D.deviceApduSender,timeoutDuration:1e3,onTerminated:D.onTerminated,tryToReconnect:D.tryToReconnect}),v=vi.fn().mockReturnValue({setupConnection:vi.fn().mockResolvedValue(void 0),closeConnection:i}),u=new s().withBleManager(r).withPlatform(h).withDeviceModelDataSource(g()).withDeviceConnectionStateMachineFactory(a).withDeviceApduSenderFactory(v).build(),m=vi.fn(),w=u.listenToAvailableDevices();vi.advanceTimersByTime(2e3);const b=await(0,l.firstValueFrom)(w),[y]=b,M=await u.connect({deviceId:y.id,onDisconnect:m}),B=await u.disconnect({connectedDevice:M.extract()});(0,t.expect)(B).toEqual((0,P.Right)(void 0)),(0,t.expect)(m).toHaveBeenCalled(),(0,t.expect)(i).toHaveBeenCalled()}),it("should handle error while disconnecting",async()=>{vi.useFakeTimers();const e=A({id:"deviceId",localName:"name"}),n=vi.fn().mockImplementation(async(D,N,R)=>{R(null,{id:"deviceId",localName:"name",serviceUUIDs:["ledgerId"],rssi:42})}),o=vi.fn(),c=vi.fn().mockImplementation(()=>({remove:vi.fn()})),i=vi.fn(),r=f({connectedDevices:vi.fn().mockResolvedValue([]),startDeviceScan:n,stopDeviceScan:o,connectToDevice:vi.fn().mockResolvedValueOnce(e),discoverAllServicesAndCharacteristicsForDevice:vi.fn().mockResolvedValueOnce(e),monitorCharacteristicForDevice:vi.fn(),writeCharacteristicWithoutResponseForDevice:vi.fn(),onDeviceDisconnected:c,isDeviceConnected:vi.fn(),onStateChange:D=>(D(d.State.PoweredOn),{remove:vi.fn()})}),a=D=>new S.DeviceConnectionStateMachine({deviceId:"deviceId",deviceApduSender:D.deviceApduSender,timeoutDuration:1e3,onTerminated:D.onTerminated,tryToReconnect:D.tryToReconnect}),v=vi.fn().mockReturnValue({setupConnection:vi.fn().mockResolvedValue(void 0),closeConnection:i}),u=new s().withBleManager(r).withPlatform(h).withDeviceModelDataSource(g()).withDeviceConnectionStateMachineFactory(a).withDeviceApduSenderFactory(v).build(),m=vi.fn(),w=u.listenToAvailableDevices();vi.advanceTimersByTime(2e3);const b=await(0,l.firstValueFrom)(w),[y]=b,M=await u.connect({deviceId:y.id,onDisconnect:m}),B=await u.disconnect({connectedDevice:M.extract()});(0,t.expect)(B).toEqual((0,P.Right)(void 0)),(0,t.expect)(m).toHaveBeenCalled()})})});
|
|
2
2
|
//# sourceMappingURL=RNBleTransport.test.js.map
|