@ledgerhq/device-transport-kit-react-native-ble 0.0.0-rnble-transport-20250307123452 → 0.0.0-rnble-transport-20250317160347

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.
@@ -1,2 +1,2 @@
1
- "use strict";var o=Object.defineProperty;var u=Object.getOwnPropertyDescriptor;var v=Object.getOwnPropertyNames;var l=Object.prototype.hasOwnProperty;var h=(s,i)=>{for(var r in i)o(s,r,{get:i[r],enumerable:!0})},y=(s,i,r,t)=>{if(i&&typeof i=="object"||typeof i=="function")for(let e of v(i))!l.call(s,e)&&e!==r&&o(s,e,{get:()=>i[e],enumerable:!(t=u(i,e))||t.enumerable});return s};var m=s=>y(o({},"__esModule",{value:!0}),s);var R={};h(R,{RNBleApduSender:()=>S});module.exports=m(R);var p=require("@ledgerhq/device-management-kit"),c=require("js-base64"),n=require("purify-ts"),a=require("rxjs");const D=3;class S{_dependencies;_isDeviceReady;_logger;_apduSender;_apduSenderFactory;_apduReceiver;_sendApduPromiseResolver;constructor({apduSenderFactory:i,apduReceiverFactory:r,dependencies:t},e){this._dependencies=t,this._isDeviceReady=new a.BehaviorSubject(!1),this._logger=e("RNBleApduSender"),this._apduSenderFactory=i,this._apduSender=n.Nothing,this._apduReceiver=r(),this._sendApduPromiseResolver=n.Nothing}onReceiveSetupApduResponse(i){const r=new Uint8Array(i),{device:t}=this._dependencies,[e]=r.slice(5);let d=t.mtu-D;e&&e!==d&&(d=e),this._apduSender=n.Maybe.of(this._apduSenderFactory({frameSize:d})),this._isDeviceReady.next(!0)}receiveApdu(i){this._apduReceiver.handleFrame(i).map(t=>{t.map(e=>{this._logger.debug("Received APDU Response",{data:{response:e}}),this._sendApduPromiseResolver.map(d=>d((0,n.Right)(e)))})}).mapLeft(t=>{this._sendApduPromiseResolver.map(e=>e((0,n.Left)(t)))})}onMonitor(i){if(!i.value)return;const r=c.Base64.toUint8Array(i.value);this._isDeviceReady.value?this.receiveApdu(r):this.onReceiveSetupApduResponse(r)}write(i){return this._dependencies.manager.writeCharacteristicWithoutResponseForDevice(this._dependencies.device.id,this._dependencies.internalDevice.bleDeviceInfos.serviceUuid,this._dependencies.internalDevice.bleDeviceInfos.writeCmdUuid,i)}getDependencies(){return this._dependencies}setDependencies(i){this._dependencies=i}async setupConnection(){this._dependencies.manager.monitorCharacteristicForDevice(this._dependencies.device.id,this._dependencies.internalDevice.bleDeviceInfos.serviceUuid,this._dependencies.internalDevice.bleDeviceInfos.notifyUuid,(t,e)=>{!t&&e&&this.onMonitor(e)}),this._isDeviceReady.next(!1);const i=Uint8Array.from([8,0,0,0,0]);await this.write(c.Base64.fromUint8Array(i));let r;await new Promise(t=>{r=this._isDeviceReady.subscribe(e=>{e&&(t(),r.unsubscribe())})})}async sendApdu(i){if(!this._isDeviceReady.value)return Promise.resolve((0,n.Left)(new p.DeviceNotInitializedError("Unknown MTU")));const r=new Promise(e=>{this._sendApduPromiseResolver=n.Maybe.of(e)}),t=this._apduSender.caseOf({Just:e=>e.getFrames(i),Nothing:()=>[]});for(const e of t)try{await this.write(c.Base64.fromUint8Array(e.getRawData()))}catch(d){this._logger.info("Error sending frame",{data:{error:d}})}return r}closeConnection(){this._dependencies.device.cancelConnection()}}0&&(module.exports={RNBleApduSender});
1
+ "use strict";var o=Object.defineProperty;var v=Object.getOwnPropertyDescriptor;var u=Object.getOwnPropertyNames;var l=Object.prototype.hasOwnProperty;var h=(s,e)=>{for(var r in e)o(s,r,{get:e[r],enumerable:!0})},y=(s,e,r,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of u(e))!l.call(s,i)&&i!==r&&o(s,i,{get:()=>e[i],enumerable:!(t=v(e,i))||t.enumerable});return s};var m=s=>y(o({},"__esModule",{value:!0}),s);var A={};h(A,{RNBleApduSender:()=>R});module.exports=m(A);var p=require("@ledgerhq/device-management-kit"),c=require("js-base64"),n=require("purify-ts"),a=require("rxjs");const D=3;class R{_dependencies;_isDeviceReady;_logger;_apduSender;_apduSenderFactory;_apduReceiver;_sendApduPromiseResolver;constructor({apduSenderFactory:e,apduReceiverFactory:r,dependencies:t},i){this._dependencies=t,this._isDeviceReady=new a.BehaviorSubject(!1),this._logger=i("RNBleApduSender"),this._apduSenderFactory=e,this._apduSender=n.Nothing,this._apduReceiver=r(),this._sendApduPromiseResolver=n.Nothing}onReceiveSetupApduResponse(e){const r=new Uint8Array(e),{device:t}=this._dependencies,[i]=r.slice(5);let d=t.mtu-D;i&&i!==d&&(d=i),this._apduSender=n.Maybe.of(this._apduSenderFactory({frameSize:d})),this._isDeviceReady.next(!0)}receiveApdu(e){this._apduReceiver.handleFrame(e).map(t=>{t.map(i=>{this._logger.debug("Received APDU Response",{data:{response:i}}),this._sendApduPromiseResolver.map(d=>d((0,n.Right)(i)))})}).mapLeft(t=>{this._sendApduPromiseResolver.map(i=>i((0,n.Left)(t)))})}onMonitor(e){if(!e.value)return;const r=c.Base64.toUint8Array(e.value);this._isDeviceReady.value?this.receiveApdu(r):this.onReceiveSetupApduResponse(r)}write(e){return this._dependencies.manager.writeCharacteristicWithoutResponseForDevice(this._dependencies.device.id,this._dependencies.internalDevice.bleDeviceInfos.serviceUuid,this._dependencies.internalDevice.bleDeviceInfos.writeCmdUuid,e)}getDependencies(){return this._dependencies}setDependencies(e){this._dependencies=e}async setupConnection(){this._dependencies.manager.monitorCharacteristicForDevice(this._dependencies.device.id,this._dependencies.internalDevice.bleDeviceInfos.serviceUuid,this._dependencies.internalDevice.bleDeviceInfos.notifyUuid,(r,t)=>{!r&&t&&this.onMonitor(t)}),this._isDeviceReady.next(!1);const e=Uint8Array.from([8,0,0,0,0]);await this.write(c.Base64.fromUint8Array(e)),await new Promise(r=>{const t=this._isDeviceReady.subscribe(i=>{i&&(r(),t.unsubscribe())})})}async sendApdu(e){if(!this._isDeviceReady.value)return Promise.resolve((0,n.Left)(new p.DeviceNotInitializedError("Unknown MTU")));const r=new Promise(i=>{this._sendApduPromiseResolver=n.Maybe.of(i)}),t=this._apduSender.caseOf({Just:i=>i.getFrames(e),Nothing:()=>[]});for(const i of t)try{await this.write(c.Base64.fromUint8Array(i.getRawData()))}catch(d){this._logger.info("Error sending frame",{data:{error:d}})}return r}closeConnection(){this._dependencies.device.cancelConnection()}}0&&(module.exports={RNBleApduSender});
2
2
  //# sourceMappingURL=RNBleApduSender.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/api/transport/RNBleApduSender.ts"],
4
- "sourcesContent": ["import {\n type BleManager,\n type Characteristic,\n type Device,\n type Subscription as RNBleSubscription,\n} from \"react-native-ble-plx\";\nimport {\n type ApduReceiverService,\n type ApduReceiverServiceFactory,\n type ApduResponse,\n type ApduSenderService,\n type ApduSenderServiceFactory,\n type BleDeviceInfos,\n type DeviceApduSender,\n type DeviceId,\n DeviceNotInitializedError,\n type DmkError,\n type LoggerPublisherService,\n type TransportDiscoveredDevice,\n} from \"@ledgerhq/device-management-kit\";\nimport { Base64 } from \"js-base64\";\nimport { type Either, Left, Maybe, Nothing, Right } from \"purify-ts\";\nimport { BehaviorSubject, type Subscription } from \"rxjs\";\n\nconst FRAME_HEADER_SIZE = 3;\n\nexport type RNBleInternalDevice = {\n id: DeviceId;\n bleDeviceInfos: BleDeviceInfos;\n discoveredDevice: TransportDiscoveredDevice;\n disconnectionSubscription: RNBleSubscription;\n lastDiscoveredTimeStamp: Maybe<number>;\n};\n\ntype RNBleApduSenderConstructorArgs = {\n dependencies: RNBleApduSenderDependencies;\n apduSenderFactory: ApduSenderServiceFactory;\n apduReceiverFactory: ApduReceiverServiceFactory;\n};\n\nexport type RNBleApduSenderDependencies = {\n device: Device;\n internalDevice: RNBleInternalDevice;\n manager: BleManager;\n};\n\nexport class RNBleApduSender\n implements DeviceApduSender<RNBleApduSenderDependencies>\n{\n private _dependencies: RNBleApduSenderDependencies;\n private _isDeviceReady: BehaviorSubject<boolean>;\n private _logger: LoggerPublisherService;\n private _apduSender: Maybe<ApduSenderService>;\n private readonly _apduSenderFactory: ApduSenderServiceFactory;\n private readonly _apduReceiver: ApduReceiverService;\n private _sendApduPromiseResolver: Maybe<\n (value: Either<DmkError, ApduResponse>) => void\n >;\n\n constructor(\n {\n apduSenderFactory,\n apduReceiverFactory,\n dependencies,\n }: RNBleApduSenderConstructorArgs,\n loggerServiceFactory: (tag: string) => LoggerPublisherService,\n ) {\n this._dependencies = dependencies;\n this._isDeviceReady = new BehaviorSubject<boolean>(false);\n this._logger = loggerServiceFactory(\"RNBleApduSender\");\n this._apduSenderFactory = apduSenderFactory;\n this._apduSender = Nothing;\n this._apduReceiver = apduReceiverFactory();\n this._sendApduPromiseResolver = Nothing;\n }\n\n private onReceiveSetupApduResponse(value: Uint8Array) {\n const mtuResponse = new Uint8Array(value);\n const { device } = this._dependencies;\n // ledger mtu is the 5th byte of the response\n const [ledgerMtu] = mtuResponse.slice(5);\n let frameSize = device.mtu - FRAME_HEADER_SIZE;\n\n if (ledgerMtu && ledgerMtu !== frameSize) {\n // should never happen since ble mtu is negotiated on device connect with 156 bytes and ledger should return mtu size minus header size\n frameSize = ledgerMtu;\n }\n this._apduSender = Maybe.of(this._apduSenderFactory({ frameSize }));\n this._isDeviceReady.next(true);\n }\n\n private receiveApdu(apdu: Uint8Array) {\n const response = this._apduReceiver.handleFrame(apdu);\n\n response\n .map((maybeApduResponse) => {\n maybeApduResponse.map((apduResponse) => {\n this._logger.debug(\"Received APDU Response\", {\n data: { response: apduResponse },\n });\n this._sendApduPromiseResolver.map((resolve) =>\n resolve(Right(apduResponse)),\n );\n });\n })\n .mapLeft((error) => {\n this._sendApduPromiseResolver.map((resolve) => resolve(Left(error)));\n });\n }\n\n private onMonitor(characteristic: Characteristic) {\n if (!characteristic.value) {\n return;\n }\n\n const apdu = Base64.toUint8Array(characteristic.value);\n if (!this._isDeviceReady.value) {\n this.onReceiveSetupApduResponse(apdu);\n } else {\n this.receiveApdu(apdu);\n }\n }\n\n private write(value: string) {\n return this._dependencies.manager.writeCharacteristicWithoutResponseForDevice(\n this._dependencies.device.id,\n this._dependencies.internalDevice.bleDeviceInfos.serviceUuid,\n this._dependencies.internalDevice.bleDeviceInfos.writeCmdUuid,\n value,\n );\n }\n\n public getDependencies() {\n return this._dependencies;\n }\n\n public setDependencies(dependencies: RNBleApduSenderDependencies) {\n this._dependencies = dependencies;\n }\n\n public async setupConnection() {\n this._dependencies.manager.monitorCharacteristicForDevice(\n this._dependencies.device.id,\n this._dependencies.internalDevice.bleDeviceInfos.serviceUuid,\n this._dependencies.internalDevice.bleDeviceInfos.notifyUuid,\n (error, characteristic) => {\n if (!error && characteristic) {\n this.onMonitor(characteristic);\n }\n },\n );\n this._isDeviceReady.next(false);\n const requestMtuFrame = Uint8Array.from([0x08, 0x00, 0x00, 0x00, 0x00]);\n await this.write(Base64.fromUint8Array(requestMtuFrame));\n let sub: Subscription;\n await new Promise<void>((resolve) => {\n sub = this._isDeviceReady.subscribe((isReady) => {\n if (isReady) {\n resolve();\n sub.unsubscribe();\n }\n });\n });\n }\n\n async sendApdu(apdu: Uint8Array): Promise<Either<DmkError, ApduResponse>> {\n if (!this._isDeviceReady.value) {\n return Promise.resolve(\n Left(new DeviceNotInitializedError(\"Unknown MTU\")),\n );\n }\n\n const resultPromise = new Promise<Either<DmkError, ApduResponse>>(\n (resolve) => {\n this._sendApduPromiseResolver = Maybe.of(resolve);\n },\n );\n\n const frames = this._apduSender.caseOf({\n Just: (apduSender) => apduSender.getFrames(apdu),\n Nothing: () => [],\n });\n\n for (const frame of frames) {\n try {\n await this.write(Base64.fromUint8Array(frame.getRawData()));\n } catch (error) {\n this._logger.info(\"Error sending frame\", { data: { error } });\n }\n }\n\n return resultPromise;\n }\n\n public closeConnection() {\n this._dependencies.device.cancelConnection();\n }\n}\n"],
5
- "mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,qBAAAE,IAAA,eAAAC,EAAAH,GAMA,IAAAI,EAaO,2CACPC,EAAuB,qBACvBC,EAAyD,qBACzDC,EAAmD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M,CAAE,CAAC,CAC9D,CAGF,OAAOK,CACT,CAEO,iBAAkB,CACvB,KAAK,cAAc,OAAO,iBAAiB,CAC7C,CACF",
4
+ "sourcesContent": ["import {\n type BleManager,\n type Characteristic,\n type Device,\n type Subscription as RNBleSubscription,\n} from \"react-native-ble-plx\";\nimport {\n type ApduReceiverService,\n type ApduReceiverServiceFactory,\n type ApduResponse,\n type ApduSenderService,\n type ApduSenderServiceFactory,\n type BleDeviceInfos,\n type DeviceApduSender,\n type DeviceId,\n DeviceNotInitializedError,\n type DmkError,\n type LoggerPublisherService,\n type TransportDiscoveredDevice,\n} from \"@ledgerhq/device-management-kit\";\nimport { Base64 } from \"js-base64\";\nimport { type Either, Left, Maybe, Nothing, Right } from \"purify-ts\";\nimport { BehaviorSubject } from \"rxjs\";\n\nconst FRAME_HEADER_SIZE = 3;\n\nexport type RNBleInternalDevice = {\n id: DeviceId;\n bleDeviceInfos: BleDeviceInfos;\n discoveredDevice: TransportDiscoveredDevice;\n disconnectionSubscription: RNBleSubscription;\n lastDiscoveredTimeStamp: Maybe<number>;\n};\n\ntype RNBleApduSenderConstructorArgs = {\n dependencies: RNBleApduSenderDependencies;\n apduSenderFactory: ApduSenderServiceFactory;\n apduReceiverFactory: ApduReceiverServiceFactory;\n};\n\nexport type RNBleApduSenderDependencies = {\n device: Device;\n internalDevice: RNBleInternalDevice;\n manager: BleManager;\n};\n\nexport class RNBleApduSender\n implements DeviceApduSender<RNBleApduSenderDependencies>\n{\n private _dependencies: RNBleApduSenderDependencies;\n private _isDeviceReady: BehaviorSubject<boolean>;\n private _logger: LoggerPublisherService;\n private _apduSender: Maybe<ApduSenderService>;\n private readonly _apduSenderFactory: ApduSenderServiceFactory;\n private readonly _apduReceiver: ApduReceiverService;\n private _sendApduPromiseResolver: Maybe<\n (value: Either<DmkError, ApduResponse>) => void\n >;\n\n constructor(\n {\n apduSenderFactory,\n apduReceiverFactory,\n dependencies,\n }: RNBleApduSenderConstructorArgs,\n loggerServiceFactory: (tag: string) => LoggerPublisherService,\n ) {\n this._dependencies = dependencies;\n this._isDeviceReady = new BehaviorSubject<boolean>(false);\n this._logger = loggerServiceFactory(\"RNBleApduSender\");\n this._apduSenderFactory = apduSenderFactory;\n this._apduSender = Nothing;\n this._apduReceiver = apduReceiverFactory();\n this._sendApduPromiseResolver = Nothing;\n }\n\n private onReceiveSetupApduResponse(value: Uint8Array) {\n const mtuResponse = new Uint8Array(value);\n const { device } = this._dependencies;\n // ledger mtu is the 5th byte of the response\n const [ledgerMtu] = mtuResponse.slice(5);\n let frameSize = device.mtu - FRAME_HEADER_SIZE;\n\n if (ledgerMtu && ledgerMtu !== frameSize) {\n // should never happen since ble mtu is negotiated on device connect with 156 bytes and ledger should return mtu size minus header size\n frameSize = ledgerMtu;\n }\n this._apduSender = Maybe.of(this._apduSenderFactory({ frameSize }));\n this._isDeviceReady.next(true);\n }\n\n private receiveApdu(apdu: Uint8Array) {\n const response = this._apduReceiver.handleFrame(apdu);\n\n response\n .map((maybeApduResponse) => {\n maybeApduResponse.map((apduResponse) => {\n this._logger.debug(\"Received APDU Response\", {\n data: { response: apduResponse },\n });\n this._sendApduPromiseResolver.map((resolve) =>\n resolve(Right(apduResponse)),\n );\n });\n })\n .mapLeft((error) => {\n this._sendApduPromiseResolver.map((resolve) => resolve(Left(error)));\n });\n }\n\n private onMonitor(characteristic: Characteristic) {\n if (!characteristic.value) {\n return;\n }\n\n const apdu = Base64.toUint8Array(characteristic.value);\n if (!this._isDeviceReady.value) {\n this.onReceiveSetupApduResponse(apdu);\n } else {\n this.receiveApdu(apdu);\n }\n }\n\n private write(value: string) {\n return this._dependencies.manager.writeCharacteristicWithoutResponseForDevice(\n this._dependencies.device.id,\n this._dependencies.internalDevice.bleDeviceInfos.serviceUuid,\n this._dependencies.internalDevice.bleDeviceInfos.writeCmdUuid,\n value,\n );\n }\n\n public getDependencies() {\n return this._dependencies;\n }\n\n public setDependencies(dependencies: RNBleApduSenderDependencies) {\n this._dependencies = dependencies;\n }\n\n public async setupConnection() {\n this._dependencies.manager.monitorCharacteristicForDevice(\n this._dependencies.device.id,\n this._dependencies.internalDevice.bleDeviceInfos.serviceUuid,\n this._dependencies.internalDevice.bleDeviceInfos.notifyUuid,\n (error, characteristic) => {\n if (!error && characteristic) {\n this.onMonitor(characteristic);\n }\n },\n );\n this._isDeviceReady.next(false);\n const requestMtuFrame = Uint8Array.from([0x08, 0x00, 0x00, 0x00, 0x00]);\n await this.write(Base64.fromUint8Array(requestMtuFrame));\n await new Promise<void>((resolve) => {\n const sub = this._isDeviceReady.subscribe((isReady) => {\n if (isReady) {\n resolve();\n sub.unsubscribe();\n }\n });\n });\n }\n\n async sendApdu(apdu: Uint8Array): Promise<Either<DmkError, ApduResponse>> {\n if (!this._isDeviceReady.value) {\n return Promise.resolve(\n Left(new DeviceNotInitializedError(\"Unknown MTU\")),\n );\n }\n\n const resultPromise = new Promise<Either<DmkError, ApduResponse>>(\n (resolve) => {\n this._sendApduPromiseResolver = Maybe.of(resolve);\n },\n );\n\n const frames = this._apduSender.caseOf({\n Just: (apduSender) => apduSender.getFrames(apdu),\n Nothing: () => [],\n });\n\n for (const frame of frames) {\n try {\n await this.write(Base64.fromUint8Array(frame.getRawData()));\n } catch (error) {\n this._logger.info(\"Error sending frame\", { data: { error } });\n }\n }\n\n return resultPromise;\n }\n\n public closeConnection() {\n this._dependencies.device.cancelConnection();\n }\n}\n"],
5
+ "mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,qBAAAE,IAAA,eAAAC,EAAAH,GAMA,IAAAI,EAaO,2CACPC,EAAuB,qBACvBC,EAAyD,qBACzDC,EAAgC,gBAEhC,MAAMC,EAAoB,EAsBnB,MAAMN,CAEb,CACU,cACA,eACA,QACA,YACS,mBACA,cACT,yBAIR,YACE,CACE,kBAAAO,EACA,oBAAAC,EACA,aAAAC,CACF,EACAC,EACA,CACA,KAAK,cAAgBD,EACrB,KAAK,eAAiB,IAAI,kBAAyB,EAAK,EACxD,K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gBA,CACvB,CAEA,MAAa,iBAAkB,CAC7B,KAAK,cAAc,QAAQ,+BACzB,KAAK,cAAc,OAAO,GAC1B,KAAK,cAAc,eAAe,eAAe,YACjD,KAAK,cAAc,eAAe,eAAe,WACjD,CAACW,EAAOC,IAAmB,CACrB,CAACD,GAASC,GACZ,KAAK,UAAUA,CAAc,CAEjC,CACF,EACA,KAAK,eAAe,KAAK,EAAK,EAC9B,MAAMC,EAAkB,WAAW,KAAK,CAAC,EAAM,EAAM,EAAM,EAAM,CAAI,CAAC,EACtE,MAAM,KAAK,MAAM,SAAO,eAAeA,CAAe,CAAC,EACvD,MAAM,IAAI,QAAeH,GAAY,CACnC,MAAMI,EAAM,KAAK,eAAe,UAAWC,GAAY,CACjDA,IACFL,EAAQ,EACRI,EAAI,YAAY,EAEpB,CAAC,CACH,CAAC,CACH,CAEA,MAAM,SAASP,EAA2D,CACxE,GAAI,CAAC,KAAK,eAAe,MACvB,OAAO,QAAQ,WACb,QAAK,IAAI,4BAA0B,aAAa,CAAC,CACnD,EAGF,MAAMS,EAAgB,IAAI,QACvBN,GAAY,CACX,KAAK,yBAA2B,QAAM,GAAGA,CAAO,CAClD,CACF,EAEMO,EAAS,KAAK,YAAY,OAAO,CACrC,KAAOC,GAAeA,EAAW,UAAUX,CAAI,EAC/C,QAAS,IAAM,CAAC,CAClB,CAAC,EAED,UAAWY,KAASF,EAClB,GAAI,CACF,MAAM,KAAK,MAAM,SAAO,eAAeE,EAAM,WAAW,CAAC,CAAC,CAC5D,OAASR,EAAO,CACd,KAAK,QAAQ,KAAK,sBAAuB,CAAE,KAAM,CAAE,MAAAA,CAAM,CAAE,CAAC,CAC9D,CAGF,OAAOK,CACT,CAEO,iBAAkB,CACvB,KAAK,cAAc,OAAO,iBAAiB,CAC7C,CACF",
6
6
  "names": ["RNBleApduSender_exports", "__export", "RNBleApduSender", "__toCommonJS", "import_device_management_kit", "import_js_base64", "import_purify_ts", "import_rxjs", "FRAME_HEADER_SIZE", "apduSenderFactory", "apduReceiverFactory", "dependencies", "loggerServiceFactory", "value", "mtuResponse", "device", "ledgerMtu", "frameSize", "apdu", "maybeApduResponse", "apduResponse", "resolve", "error", "characteristic", "requestMtuFrame", "sub", "isReady", "resultPromise", "frames", "apduSender", "frame"]
7
7
  }
@@ -1,2 +1,2 @@
1
- "use strict";var h=Object.defineProperty;var y=Object.getOwnPropertyDescriptor;var I=Object.getOwnPropertyNames;var g=Object.prototype.hasOwnProperty;var f=(v,e)=>{for(var i in e)h(v,i,{get:e[i],enumerable:!0})},T=(v,e,i,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let t of I(e))!g.call(v,t)&&t!==i&&h(v,t,{get:()=>e[t],enumerable:!(r=y(e,t))||r.enumerable});return v};var N=v=>T(h({},"__esModule",{value:!0}),v);var b={};f(b,{RNBleTransport:()=>m,RNBleTransportFactory:()=>C,rnBleTransportIdentifier:()=>E});module.exports=N(b);var s=require("react-native"),S=require("react-native-ble-plx"),l=require("@ledgerhq/device-management-kit"),n=require("purify-ts"),c=require("rxjs"),p=require("../model/Const"),u=require("../model/Errors"),_=require("../transport/RNBleApduSender");const E="RN_BLE";class m{constructor(e,i,r,t){this._deviceModelDataSource=e;this._loggerServiceFactory=i;this._apduSenderFactory=r;this._apduReceiverFactory=t;this._logger=i("ReactNativeBleTransport"),this._manager=new S.BleManager,this._isSupported=n.Maybe.zero(),this._internalDevicesById=new Map,this._deviceConnectionsById=new Map,this.requestPermission(),this._reconnectionSubscription=n.Maybe.zero()}_logger;_isSupported;_internalDevicesById;_deviceConnectionsById;_manager;identifier="RN_BLE";_reconnectionSubscription;_startDiscovering(){const e=this._deviceModelDataSource.getBluetoothServices();return(0,c.from)(this.requestPermission()).pipe((0,c.switchMap)(i=>{if(!i)throw new Error("BLE not supported");return this._discoverKnownDevices(e)}),(0,c.mergeWith)(this._discoverNewDevices(e)))}startDiscovering(){return this._startDiscovering()}async stopDiscovering(){await this._manager.stopDeviceScan()}async connect(e){return(0,n.EitherAsync)(async({liftEither:i,throwE:r})=>{const t=await i(n.Maybe.fromNullable(this._internalDevicesById.get(e.deviceId)).toEither(new l.UnknownDeviceError(`Unknown device ${e.deviceId}`)));let o;try{o=await this._manager.connectToDevice(e.deviceId,{requestMTU:p.DEFAULT_MTU}),await this._manager.discoverAllServicesAndCharacteristicsForDevice(e.deviceId)}catch(d){return r(new l.OpeningConnectionError(d))}const a=new _.RNBleApduSender({apduSenderFactory:this._apduSenderFactory,apduReceiverFactory:this._apduReceiverFactory,dependencies:{device:o,internalDevice:t,manager:this._manager}},this._loggerServiceFactory),D=new l.DeviceConnectionStateMachine({deviceId:e.deviceId,deviceApduSender:a,timeoutDuration:p.BLE_DISCONNECT_TIMEOUT,onTerminated:()=>{e.onDisconnect(e.deviceId),this._deviceConnectionsById.delete(e.deviceId);const d=this._internalDevicesById.get(e.deviceId);d&&d.disconnectionSubscription.remove(),this._internalDevicesById.delete(e.deviceId)}});return await a.setupConnection(),this._deviceConnectionsById.set(t.id,D),t.disconnectionSubscription=this._manager.onDeviceDisconnected(t.id,(...d)=>{this._handleDeviceDisconnected(...d)}),t.lastDiscoveredTimeStamp=n.Maybe.zero(),new l.TransportConnectedDevice({id:t.id,deviceModel:t.discoveredDevice.deviceModel,type:"BLE",sendApdu:(...d)=>D.sendApdu(...d),transport:this.identifier})}).run()}async disconnect(e){return n.Maybe.fromNullable(this._deviceConnectionsById.get(e.connectedDevice.id)).map(r=>{r.closeConnection()}),Promise.resolve((0,n.Right)(void 0))}listenToAvailableDevices(){const e={};return this._startDiscovering().pipe((0,c.map)(i=>(e[i.id]=i,Object.values(e).filter(r=>r.rssi!==null))))}isSupported(){return this._isSupported.caseOf({Just:e=>e,Nothing:()=>{throw new Error("Should initialize permission")}})}getIdentifier(){return this.identifier}async requestPermission(){if(s.Platform.OS==="ios")return this._isSupported=n.Maybe.of(!0),!0;if(s.Platform.OS==="android"&&s.PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION){if(parseInt(s.Platform.Version.toString(),10)<31){const i=await s.PermissionsAndroid.request(s.PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION);this._isSupported=n.Maybe.of(i===s.PermissionsAndroid.RESULTS.GRANTED)}if(s.PermissionsAndroid.PERMISSIONS.BLUETOOTH_SCAN&&s.PermissionsAndroid.PERMISSIONS.BLUETOOTH_CONNECT){const i=await s.PermissionsAndroid.requestMultiple([s.PermissionsAndroid.PERMISSIONS.BLUETOOTH_SCAN,s.PermissionsAndroid.PERMISSIONS.BLUETOOTH_CONNECT,s.PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION]);return this._isSupported=n.Maybe.of(i["android.permission.BLUETOOTH_CONNECT"]===s.PermissionsAndroid.RESULTS.GRANTED&&i["android.permission.BLUETOOTH_SCAN"]===s.PermissionsAndroid.RESULTS.GRANTED&&i["android.permission.ACCESS_FINE_LOCATION"]===s.PermissionsAndroid.RESULTS.GRANTED),!0}}return this._logger.error("Permission have not been granted",{data:{isSupported:this.isSupported()}}),this._isSupported=n.Maybe.of(!1),!1}_getDiscoveredDeviceFrom(e,i){const r=n.Maybe.fromNullable(e?.serviceUUIDs?.find(o=>i.includes(o))),t=n.Maybe.fromNullable(this._internalDevicesById.get(e.id));return t.isJust()?t.map(o=>({bleDeviceInfos:o.bleDeviceInfos,discoveredDevice:{...o.discoveredDevice,rssi:e.rssi||void 0}})):r.mapOrDefault(o=>{const a=this._deviceModelDataSource.getBluetoothServicesInfos();return n.Maybe.fromNullable(a[o]).map(d=>({discoveredDevice:{id:e.id,name:e.localName||d.deviceModel.productName,deviceModel:d.deviceModel,transport:this.identifier,rssi:e.rssi||void 0},bleDeviceInfos:d}))},n.Nothing)}_isDiscoveredDeviceDelayOver(e){return e.lastDiscoveredTimeStamp.caseOf({Just:i=>Date.now()>i+p.CONNECTION_LOST_DELAY,Nothing:()=>!1})}async _handleLostDiscoveredDevices(e){const i=this._internalDevicesById.values().map(r=>async()=>{this._isDiscoveredDeviceDelayOver(r)&&!await this._manager.isDeviceConnected(r.id)&&(this._internalDevicesById.delete(r.id),e.next({...r.discoveredDevice,rssi:null}))});await Promise.all(i)}_emitDiscoveredDevice(e,i,r){e.next(r);const t={id:r.id,bleDeviceInfos:i,discoveredDevice:r,lastDiscoveredTimeStamp:n.Maybe.of(Date.now())};this._internalDevicesById.set(r.id,{...t,disconnectionSubscription:this._manager.onDeviceDisconnected(r.id,()=>{e.next({...r,rssi:null})})})}_discoverNewDevices(e){return new c.Observable(i=>(this._manager.startDeviceScan(null,null,(r,t)=>{if(r||!t){i.error(r);return}this._getDiscoveredDeviceFrom(t,e).map(({discoveredDevice:o,bleDeviceInfos:a})=>{this._emitDiscoveredDevice(i,a,o)}),this._handleLostDiscoveredDevices(i)}),{unsubscribe:async()=>{await this._manager.stopDeviceScan(),i.unsubscribe()}}))}_discoverKnownDevices(e){return(0,c.from)(this._manager.connectedDevices(e)).pipe((0,c.switchMap)(i=>new c.Observable(r=>{for(const t of i)t.readRSSI().then(o=>{this._getDiscoveredDeviceFrom(o,e).map(({bleDeviceInfos:a,discoveredDevice:D})=>{this._emitDiscoveredDevice(r,a,D)})})})),(0,c.repeat)({delay:p.BLE_DISCONNECT_TIMEOUT/5}))}_handleDeviceDisconnected(e,i){if(e){this._logger.error("device disconnected error",{data:{error:e,device:i}});return}if(!i){this._logger.debug("disconnected handler didn't found device");return}if(this._reconnectionSubscription.isJust())return;const r=n.Maybe.fromNullable(this._deviceConnectionsById.get(i.id));r.map(o=>{o.eventDeviceDetached()});let t;this._reconnectionSubscription=n.Maybe.of((0,c.from)([0]).pipe((0,c.switchMap)(async()=>{try{t=await i.connect({requestMTU:p.DEFAULT_MTU}),t=await i.discoverAllServicesAndCharacteristics(),await this._handleDeviceReconnected(t)}catch(o){this._logger.error("[_handleDeviceDisconnected] Reconnecting failed",{data:{e:o}}),(0,c.throwError)(()=>o);return}return t}),(0,c.retry)({count:5,delay:p.BLE_DISCONNECT_TIMEOUT/5})).subscribe({next:o=>this._logger.debug("[_handleDeviceDisconnected] Got new device after reconnection",{data:{value:o}}),complete:()=>{this._reconnectionSubscription=n.Maybe.zero()},error:o=>{this._logger.error("[_handleDeviceDisconnected] Reconnection failed after all retries",{data:{e:o}}),this._reconnectionSubscription=n.Maybe.zero(),r.map(a=>{a.closeConnection()})}}))}async _handleDeviceReconnected(e){const i=n.Maybe.fromNullable(this._deviceConnectionsById.get(e.id)).toEither(new u.DeviceConnectionNotFound),r=n.Maybe.fromNullable(this._internalDevicesById.get(e.id)).toEither(new u.InternalDeviceNotFound);return(0,n.EitherAsync)(async({liftEither:t})=>{const o=await t(i),a=await t(r);o.setDependencies({device:e,manager:this._manager,internalDevice:a}),await o.setupConnection(),o.eventDeviceAttached()}).run()}}const C=({deviceModelDataSource:v,loggerServiceFactory:e,apduSenderServiceFactory:i,apduReceiverServiceFactory:r})=>new m(v,e,i,r);0&&(module.exports={RNBleTransport,RNBleTransportFactory,rnBleTransportIdentifier});
1
+ "use strict";var h=Object.defineProperty;var y=Object.getOwnPropertyDescriptor;var I=Object.getOwnPropertyNames;var g=Object.prototype.hasOwnProperty;var f=(v,e)=>{for(var i in e)h(v,i,{get:e[i],enumerable:!0})},T=(v,e,i,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let t of I(e))!g.call(v,t)&&t!==i&&h(v,t,{get:()=>e[t],enumerable:!(r=y(e,t))||r.enumerable});return v};var N=v=>T(h({},"__esModule",{value:!0}),v);var O={};f(O,{RNBleTransport:()=>m,RNBleTransportFactory:()=>C,rnBleTransportIdentifier:()=>E});module.exports=N(O);var s=require("react-native"),S=require("react-native-ble-plx"),p=require("@ledgerhq/device-management-kit"),n=require("purify-ts"),c=require("rxjs"),l=require("../model/Const"),u=require("../model/Errors"),_=require("../transport/RNBleApduSender");const E="RN_BLE";class m{constructor(e,i,r,t){this._deviceModelDataSource=e;this._loggerServiceFactory=i;this._apduSenderFactory=r;this._apduReceiverFactory=t;this._logger=i("ReactNativeBleTransport"),this._manager=new S.BleManager,this._isSupported=n.Maybe.zero(),this._internalDevicesById=new Map,this._deviceConnectionsById=new Map,this.requestPermission(),this._reconnectionSubscription=n.Maybe.zero()}_logger;_isSupported;_internalDevicesById;_deviceConnectionsById;_manager;identifier="RN_BLE";_reconnectionSubscription;_startDiscovering(){const e=this._deviceModelDataSource.getBluetoothServices();return(0,c.from)(this.requestPermission()).pipe((0,c.switchMap)(i=>{if(!i)throw new Error("BLE not supported");return this._discoverKnownDevices(e)}),(0,c.mergeWith)(this._discoverNewDevices(e)))}startDiscovering(){return this._startDiscovering()}async stopDiscovering(){await this._manager.stopDeviceScan()}async connect(e){return(0,n.EitherAsync)(async({liftEither:i,throwE:r})=>{const t=await i(n.Maybe.fromNullable(this._internalDevicesById.get(e.deviceId)).toEither(new p.UnknownDeviceError(`Unknown device ${e.deviceId}`)));let o;try{o=await this._manager.connectToDevice(e.deviceId,{requestMTU:l.DEFAULT_MTU}),await this._manager.discoverAllServicesAndCharacteristicsForDevice(e.deviceId)}catch(d){return r(new p.OpeningConnectionError(d))}const a=new _.RNBleApduSender({apduSenderFactory:this._apduSenderFactory,apduReceiverFactory:this._apduReceiverFactory,dependencies:{device:o,internalDevice:t,manager:this._manager}},this._loggerServiceFactory),D=new p.DeviceConnectionStateMachine({deviceId:e.deviceId,deviceApduSender:a,timeoutDuration:l.BLE_DISCONNECT_TIMEOUT,onTerminated:()=>{e.onDisconnect(e.deviceId),this._deviceConnectionsById.delete(e.deviceId);const d=this._internalDevicesById.get(e.deviceId);d&&d.disconnectionSubscription.remove(),this._internalDevicesById.delete(e.deviceId)}});return await a.setupConnection(),this._deviceConnectionsById.set(t.id,D),t.disconnectionSubscription=this._manager.onDeviceDisconnected(t.id,(...d)=>{this._handleDeviceDisconnected(...d)}),t.lastDiscoveredTimeStamp=n.Maybe.zero(),new p.TransportConnectedDevice({id:t.id,deviceModel:t.discoveredDevice.deviceModel,type:"BLE",sendApdu:(...d)=>D.sendApdu(...d),transport:this.identifier})}).run()}async disconnect(e){return n.Maybe.fromNullable(this._deviceConnectionsById.get(e.connectedDevice.id)).map(r=>{r.closeConnection()}),Promise.resolve((0,n.Right)(void 0))}listenToAvailableDevices(){const e={};return this._startDiscovering().pipe((0,c.map)(i=>(e[i.id]=i,Object.values(e).filter(r=>r.rssi!==null))))}isSupported(){return this._isSupported.caseOf({Just:e=>e,Nothing:()=>{throw new Error("Should initialize permission")}})}getIdentifier(){return this.identifier}async requestPermission(){if(s.Platform.OS==="ios")return this._isSupported=n.Maybe.of(!0),!0;if(s.Platform.OS==="android"&&s.PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION){if(parseInt(s.Platform.Version.toString(),10)<31){const i=await s.PermissionsAndroid.request(s.PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION);this._isSupported=n.Maybe.of(i===s.PermissionsAndroid.RESULTS.GRANTED)}if(s.PermissionsAndroid.PERMISSIONS.BLUETOOTH_SCAN&&s.PermissionsAndroid.PERMISSIONS.BLUETOOTH_CONNECT){const i=await s.PermissionsAndroid.requestMultiple([s.PermissionsAndroid.PERMISSIONS.BLUETOOTH_SCAN,s.PermissionsAndroid.PERMISSIONS.BLUETOOTH_CONNECT,s.PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION]);return this._isSupported=n.Maybe.of(i["android.permission.BLUETOOTH_CONNECT"]===s.PermissionsAndroid.RESULTS.GRANTED&&i["android.permission.BLUETOOTH_SCAN"]===s.PermissionsAndroid.RESULTS.GRANTED&&i["android.permission.ACCESS_FINE_LOCATION"]===s.PermissionsAndroid.RESULTS.GRANTED),!0}}return this._logger.error("Permission have not been granted",{data:{isSupported:this.isSupported()}}),this._isSupported=n.Maybe.of(!1),!1}_getDiscoveredDeviceFrom(e,i){const r=n.Maybe.fromNullable(e?.serviceUUIDs?.find(o=>i.includes(o))),t=n.Maybe.fromNullable(this._internalDevicesById.get(e.id));return t.isJust()?t.map(o=>({bleDeviceInfos:o.bleDeviceInfos,discoveredDevice:{...o.discoveredDevice,rssi:e.rssi||void 0}})):r.mapOrDefault(o=>{const a=this._deviceModelDataSource.getBluetoothServicesInfos();return n.Maybe.fromNullable(a[o]).map(d=>({discoveredDevice:{id:e.id,name:e.localName||d.deviceModel.productName,deviceModel:d.deviceModel,transport:this.identifier,rssi:e.rssi||void 0},bleDeviceInfos:d}))},n.Nothing)}_isDiscoveredDeviceDelayOver(e){return e.lastDiscoveredTimeStamp.caseOf({Just:i=>Date.now()>i+l.CONNECTION_LOST_DELAY,Nothing:()=>!1})}async _handleLostDiscoveredDevices(e){for(const i of this._internalDevicesById.values())this._isDiscoveredDeviceDelayOver(i)&&!await this._manager.isDeviceConnected(i.id)&&(this._internalDevicesById.delete(i.id),e.next({...i.discoveredDevice,rssi:null}))}_emitDiscoveredDevice(e,i,r){e.next(r);const t={id:r.id,bleDeviceInfos:i,discoveredDevice:r,lastDiscoveredTimeStamp:n.Maybe.of(Date.now())};this._internalDevicesById.set(r.id,{...t,disconnectionSubscription:this._manager.onDeviceDisconnected(r.id,()=>{e.next({...r,rssi:null})})})}_discoverNewDevices(e){return new c.Observable(i=>(this._manager.startDeviceScan(null,null,(r,t)=>{if(r||!t){i.error(r);return}this._getDiscoveredDeviceFrom(t,e).map(({discoveredDevice:o,bleDeviceInfos:a})=>{this._emitDiscoveredDevice(i,a,o)}),this._handleLostDiscoveredDevices(i)}),{unsubscribe:async()=>{await this._manager.stopDeviceScan(),i.unsubscribe()}}))}_discoverKnownDevices(e){return(0,c.from)(this._manager.connectedDevices(e)).pipe((0,c.switchMap)(i=>new c.Observable(r=>{for(const t of i)t.readRSSI().then(o=>{this._getDiscoveredDeviceFrom(o,e).map(({bleDeviceInfos:a,discoveredDevice:D})=>{this._emitDiscoveredDevice(r,a,D)})});this._handleLostDiscoveredDevices(r)})),(0,c.repeat)({delay:l.BLE_DISCONNECT_TIMEOUT/5}))}_handleDeviceDisconnected(e,i){if(e){this._logger.error("device disconnected error",{data:{error:e,device:i}});return}if(!i){this._logger.debug("disconnected handler didn't found device");return}if(this._reconnectionSubscription.isJust())return;const r=n.Maybe.fromNullable(this._deviceConnectionsById.get(i.id));r.map(o=>{o.eventDeviceDetached()});let t;this._reconnectionSubscription=n.Maybe.of((0,c.from)([0]).pipe((0,c.switchMap)(async()=>{try{t=await i.connect({requestMTU:l.DEFAULT_MTU}),t=await i.discoverAllServicesAndCharacteristics(),await this._handleDeviceReconnected(t)}catch(o){this._logger.error("[_handleDeviceDisconnected] Reconnecting failed",{data:{e:o}}),(0,c.throwError)(()=>o);return}return t}),(0,c.retry)({count:5,delay:l.BLE_DISCONNECT_TIMEOUT/5})).subscribe({next:o=>this._logger.debug("[_handleDeviceDisconnected] Got new device after reconnection",{data:{value:o}}),complete:()=>{this._reconnectionSubscription=n.Maybe.zero()},error:o=>{this._logger.error("[_handleDeviceDisconnected] Reconnection failed after all retries",{data:{e:o}}),this._reconnectionSubscription=n.Maybe.zero(),r.map(a=>{a.closeConnection()})}}))}async _handleDeviceReconnected(e){const i=n.Maybe.fromNullable(this._deviceConnectionsById.get(e.id)).toEither(new u.DeviceConnectionNotFound),r=n.Maybe.fromNullable(this._internalDevicesById.get(e.id)).toEither(new u.InternalDeviceNotFound);return(0,n.EitherAsync)(async({liftEither:t})=>{const o=await t(i),a=await t(r);o.setDependencies({device:e,manager:this._manager,internalDevice:a}),await o.setupConnection(),o.eventDeviceAttached()}).run()}}const C=({deviceModelDataSource:v,loggerServiceFactory:e,apduSenderServiceFactory:i,apduReceiverServiceFactory:r})=>new m(v,e,i,r);0&&(module.exports={RNBleTransport,RNBleTransportFactory,rnBleTransportIdentifier});
2
2
  //# sourceMappingURL=RNBleTransport.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/api/transport/RNBleTransport.ts"],
4
- "sourcesContent": ["import { PermissionsAndroid, Platform } from \"react-native\";\nimport { type BleError, BleManager, type Device } from \"react-native-ble-plx\";\nimport {\n type ApduReceiverServiceFactory,\n type ApduSenderServiceFactory,\n type BleDeviceInfos,\n type ConnectError,\n DeviceConnectionStateMachine,\n type DeviceId,\n type DeviceModelDataSource,\n type DisconnectHandler,\n type DmkError,\n type LoggerPublisherService,\n OpeningConnectionError,\n type Transport,\n TransportConnectedDevice,\n type TransportDiscoveredDevice,\n type TransportFactory,\n type TransportIdentifier,\n UnknownDeviceError,\n} from \"@ledgerhq/device-management-kit\";\nimport { type Either, EitherAsync, Maybe, Nothing, Right } from \"purify-ts\";\nimport {\n from,\n map,\n mergeWith,\n Observable,\n repeat,\n retry,\n type Subscriber,\n type Subscription,\n switchMap,\n throwError,\n} from \"rxjs\";\n\nimport {\n BLE_DISCONNECT_TIMEOUT,\n CONNECTION_LOST_DELAY,\n DEFAULT_MTU,\n} from \"@api/model/Const\";\nimport {\n DeviceConnectionNotFound,\n InternalDeviceNotFound,\n} from \"@api/model/Errors\";\nimport {\n RNBleApduSender,\n type RNBleApduSenderDependencies,\n type RNBleInternalDevice,\n} from \"@api/transport/RNBleApduSender\";\n\nexport const rnBleTransportIdentifier = \"RN_BLE\";\n\nexport class RNBleTransport implements Transport {\n private _logger: LoggerPublisherService;\n private _isSupported: Maybe<boolean>;\n private _internalDevicesById: Map<DeviceId, RNBleInternalDevice>;\n private _deviceConnectionsById: Map<\n DeviceId,\n DeviceConnectionStateMachine<RNBleApduSenderDependencies>\n >;\n private readonly _manager: BleManager;\n private readonly identifier: TransportIdentifier = \"RN_BLE\";\n private _reconnectionSubscription: Maybe<Subscription>;\n\n constructor(\n private readonly _deviceModelDataSource: DeviceModelDataSource,\n private readonly _loggerServiceFactory: (\n tag: string,\n ) => LoggerPublisherService,\n private readonly _apduSenderFactory: ApduSenderServiceFactory,\n private readonly _apduReceiverFactory: ApduReceiverServiceFactory,\n ) {\n this._logger = _loggerServiceFactory(\"ReactNativeBleTransport\");\n this._manager = new BleManager();\n this._isSupported = Maybe.zero();\n this._internalDevicesById = new Map();\n this._deviceConnectionsById = new Map();\n this.requestPermission();\n this._reconnectionSubscription = Maybe.zero();\n }\n\n private _startDiscovering() {\n const ledgerUuids = this._deviceModelDataSource.getBluetoothServices();\n return from(this.requestPermission()).pipe(\n switchMap((isSupported) => {\n if (!isSupported) {\n throw new Error(\"BLE not supported\");\n }\n return this._discoverKnownDevices(ledgerUuids);\n }),\n mergeWith(this._discoverNewDevices(ledgerUuids)),\n );\n }\n\n /**\n * Starts the discovery process to find Bluetooth devices that match specific criteria.\n *\n * This method clears the internal device cache and requests necessary permissions\n * before initiating the discovery of both known and new devices. If the Bluetooth\n * Low Energy (BLE) feature is not supported, an error is thrown.\n *\n * @return {Observable<TransportDiscoveredDevice>} An observable emitting discovered devices\n * that match the specified Bluetooth services.\n */\n startDiscovering(): Observable<TransportDiscoveredDevice> {\n return this._startDiscovering();\n }\n\n /**\n * Stops the device scanning operation currently in progress.\n *\n * @return {Promise<void>} A promise that resolves once the device scanning has been successfully stopped.\n */\n async stopDiscovering(): Promise<void> {\n await this._manager.stopDeviceScan();\n }\n\n /**\n * Establishes a connection to a device and configures the necessary parameters for communication.\n *\n * @param {Object} params - An object containing parameters required for the connection.\n * @param {DeviceId} params.deviceId - The unique identifier of the device to connect to.\n * @param {DisconnectHandler} params.onDisconnect - A callback function to handle device disconnection.\n * @returns {Promise<Either<ConnectError, TransportConnectedDevice>>} A promise resolving to either a connection error or a successfully connected device.\n */\n async connect(params: {\n deviceId: DeviceId;\n onDisconnect: DisconnectHandler;\n }): Promise<Either<ConnectError, TransportConnectedDevice>> {\n return EitherAsync<ConnectError, TransportConnectedDevice>(\n async ({ liftEither, throwE }) => {\n const internalDevice = await liftEither(\n Maybe.fromNullable(\n this._internalDevicesById.get(params.deviceId),\n ).toEither(\n new UnknownDeviceError(`Unknown device ${params.deviceId}`),\n ),\n );\n\n let device: Device;\n\n try {\n device = await this._manager.connectToDevice(params.deviceId, {\n requestMTU: DEFAULT_MTU,\n });\n await this._manager.discoverAllServicesAndCharacteristicsForDevice(\n params.deviceId,\n );\n } catch (error) {\n return throwE(new OpeningConnectionError(error));\n }\n\n const deviceApduSender = new RNBleApduSender(\n {\n apduSenderFactory: this._apduSenderFactory,\n apduReceiverFactory: this._apduReceiverFactory,\n dependencies: {\n device,\n internalDevice,\n manager: this._manager,\n },\n },\n this._loggerServiceFactory,\n );\n\n const deviceConnectionStateMachine =\n new DeviceConnectionStateMachine<RNBleApduSenderDependencies>({\n deviceId: params.deviceId,\n deviceApduSender,\n timeoutDuration: BLE_DISCONNECT_TIMEOUT,\n onTerminated: () => {\n params.onDisconnect(params.deviceId);\n this._deviceConnectionsById.delete(params.deviceId);\n const iDevice = this._internalDevicesById.get(params.deviceId);\n\n if (iDevice) {\n iDevice.disconnectionSubscription.remove();\n }\n\n this._internalDevicesById.delete(params.deviceId);\n },\n });\n\n await deviceApduSender.setupConnection();\n\n this._deviceConnectionsById.set(\n internalDevice.id,\n deviceConnectionStateMachine,\n );\n\n internalDevice.disconnectionSubscription =\n this._manager.onDeviceDisconnected(internalDevice.id, (...args) => {\n this._handleDeviceDisconnected(...args);\n });\n\n internalDevice.lastDiscoveredTimeStamp = Maybe.zero();\n\n return new TransportConnectedDevice({\n id: internalDevice.id,\n deviceModel: internalDevice.discoveredDevice.deviceModel,\n type: \"BLE\",\n sendApdu: (...args) => deviceConnectionStateMachine.sendApdu(...args),\n transport: this.identifier,\n });\n },\n ).run();\n }\n\n /**\n * Terminates the connection with the connected device and cleans up related resources.\n *\n * @param {TransportConnectedDevice} params.connectedDevice - The connected device to be disconnected.\n * @return {Promise<Either<DmkError, void>>} A promise resolving to either a success (void) or a failure (DmkError) value.\n */\n async disconnect(params: {\n connectedDevice: TransportConnectedDevice;\n }): Promise<Either<DmkError, void>> {\n const deviceConnection = Maybe.fromNullable(\n this._deviceConnectionsById.get(params.connectedDevice.id),\n );\n\n deviceConnection.map((d) => {\n d.closeConnection();\n });\n\n return Promise.resolve(Right(undefined));\n }\n\n /**\n * Listens to known devices and emits updates when new devices are discovered or when properties of existing devices are updated.\n *\n * @return {Observable<TransportDiscoveredDevice[]>} An observable stream of discovered devices, containing device information as an array of TransportDiscoveredDevice objects.\n */\n listenToAvailableDevices(): Observable<TransportDiscoveredDevice[]> {\n const scannedDeviceMap: Record<DeviceId, TransportDiscoveredDevice> = {};\n return this._startDiscovering().pipe(\n map((discoveredDevice) => {\n scannedDeviceMap[discoveredDevice.id] = discoveredDevice;\n return Object.values(scannedDeviceMap).filter(\n (device) => device.rssi !== null,\n );\n }),\n );\n }\n\n /**\n * Determines if the feature or permission is supported.\n *\n * This method evaluates the current state of the `_isSupported` property to determine\n * whether the relevant feature is supported or throws an error if its state has\n * not been initialized properly.\n *\n * @return {boolean} Returns `true` if the feature is supported, otherwise `false`.\n * Throws an error if the `_isSupported` property has not been initialized.\n */\n isSupported(): boolean {\n return this._isSupported.caseOf({\n Just: (isSupported) => isSupported,\n Nothing: () => {\n throw new Error(\"Should initialize permission\");\n },\n });\n }\n\n /**\n * Retrieves the transport identifier associated with the object.\n *\n * @return {TransportIdentifier} The transport identifier.\n */\n getIdentifier(): TransportIdentifier {\n return this.identifier;\n }\n\n /**\n * Requests the necessary permissions based on the operating system.\n * For iOS, it automatically sets the permissions as granted.\n * For Android, it checks and requests location, Bluetooth scan, and Bluetooth connect permissions, depending on the API level.\n * If permissions are granted, updates the internal support state and logs the result.\n *\n * @return {Promise<boolean>} A promise that resolves to true if the required permissions are granted, otherwise false.\n */\n async requestPermission(): Promise<boolean> {\n if (Platform.OS === \"ios\") {\n this._isSupported = Maybe.of(true);\n return true;\n }\n\n if (\n Platform.OS === \"android\" &&\n PermissionsAndroid.PERMISSIONS[\"ACCESS_FINE_LOCATION\"]\n ) {\n const apiLevel = parseInt(Platform.Version.toString(), 10);\n\n if (apiLevel < 31) {\n const granted = await PermissionsAndroid.request(\n PermissionsAndroid.PERMISSIONS[\"ACCESS_FINE_LOCATION\"],\n );\n this._isSupported = Maybe.of(\n granted === PermissionsAndroid.RESULTS[\"GRANTED\"],\n );\n }\n if (\n PermissionsAndroid.PERMISSIONS[\"BLUETOOTH_SCAN\"] &&\n PermissionsAndroid.PERMISSIONS[\"BLUETOOTH_CONNECT\"]\n ) {\n const result = await PermissionsAndroid.requestMultiple([\n PermissionsAndroid.PERMISSIONS[\"BLUETOOTH_SCAN\"],\n PermissionsAndroid.PERMISSIONS[\"BLUETOOTH_CONNECT\"],\n PermissionsAndroid.PERMISSIONS[\"ACCESS_FINE_LOCATION\"],\n ]);\n\n this._isSupported = Maybe.of(\n result[\"android.permission.BLUETOOTH_CONNECT\"] ===\n PermissionsAndroid.RESULTS[\"GRANTED\"] &&\n result[\"android.permission.BLUETOOTH_SCAN\"] ===\n PermissionsAndroid.RESULTS[\"GRANTED\"] &&\n result[\"android.permission.ACCESS_FINE_LOCATION\"] ===\n PermissionsAndroid.RESULTS[\"GRANTED\"],\n );\n\n return true;\n }\n }\n\n this._logger.error(\"Permission have not been granted\", {\n data: { isSupported: this.isSupported() },\n });\n\n this._isSupported = Maybe.of(false);\n return false;\n }\n\n /**\n * Retrieves a discovered device and its BLE device information, if available, from the provided input.\n *\n * @param {Device} rnDevice - The Bluetooth device to analyze for discovery.\n * @param {string[]} ledgerUuids - A list of UUIDs associated with the target Ledger devices.\n * @return {Maybe<{ bleDeviceInfos: BleDeviceInfos; discoveredDevice: TransportDiscoveredDevice }>} A Maybe object containing the discovered device and its BLE information, or Nothing if the device or information cannot be determined.\n */\n private _getDiscoveredDeviceFrom(\n rnDevice: Device,\n ledgerUuids: string[],\n ): Maybe<{\n bleDeviceInfos: BleDeviceInfos;\n discoveredDevice: TransportDiscoveredDevice;\n }> {\n const maybeUuid = Maybe.fromNullable(\n rnDevice?.serviceUUIDs?.find((uuid) => ledgerUuids.includes(uuid)),\n );\n\n const existingInternalDevice = Maybe.fromNullable(\n this._internalDevicesById.get(rnDevice.id),\n );\n\n if (existingInternalDevice.isJust()) {\n return existingInternalDevice.map((internalDevice) => ({\n bleDeviceInfos: internalDevice.bleDeviceInfos,\n discoveredDevice: {\n ...internalDevice.discoveredDevice,\n rssi: rnDevice.rssi || undefined,\n },\n }));\n }\n\n return maybeUuid.mapOrDefault((uuid) => {\n const serviceToBleInfos =\n this._deviceModelDataSource.getBluetoothServicesInfos();\n const maybeBleDeviceInfos = Maybe.fromNullable(serviceToBleInfos[uuid]);\n\n return maybeBleDeviceInfos.map((bleDeviceInfos) => {\n const discoveredDevice: TransportDiscoveredDevice = {\n id: rnDevice.id,\n name: rnDevice.localName || bleDeviceInfos.deviceModel.productName,\n deviceModel: bleDeviceInfos.deviceModel,\n transport: this.identifier,\n rssi: rnDevice.rssi || undefined,\n };\n\n return {\n discoveredDevice,\n bleDeviceInfos,\n };\n });\n }, Nothing);\n }\n\n /**\n * Determines whether the delay since the device was last discovered has exceeded a predefined threshold.\n *\n * @param {RNBleInternalDevice} internalDevice - The internal device object containing the last discovered timestamp.\n * @return {boolean} - Returns true if the delay is over, otherwise false.\n */\n private _isDiscoveredDeviceDelayOver(internalDevice: RNBleInternalDevice) {\n return internalDevice.lastDiscoveredTimeStamp.caseOf({\n Just: (lastDiscoveredTimeStamp) =>\n Date.now() > lastDiscoveredTimeStamp + CONNECTION_LOST_DELAY,\n Nothing: () => {\n return false;\n },\n });\n }\n\n /**\n * Handles the processing of devices that have been determined to be \"lost\" by iterating\n * through a collection of internal devices, identifying lost devices, updating their status,\n * and notifying a subscriber about the change.\n *\n * @param {Subscriber<TransportDiscoveredDevice>} subscriber - The observer that will be notified\n * when a device is marked as lost, including updated device information with its availability set to false.\n * @return {void} This method does not return a value.\n */\n private async _handleLostDiscoveredDevices(\n subscriber: Subscriber<TransportDiscoveredDevice>,\n ) {\n const promises = this._internalDevicesById\n .values()\n .map((internalDevice) => async () => {\n if (\n this._isDiscoveredDeviceDelayOver(internalDevice) &&\n !(await this._manager.isDeviceConnected(internalDevice.id))\n ) {\n this._internalDevicesById.delete(internalDevice.id);\n subscriber.next({\n ...internalDevice.discoveredDevice,\n rssi: null,\n });\n }\n });\n await Promise.all(promises);\n }\n\n /**\n * Emits a discovered device to the provided subscriber and manages internal state\n * for the discovered device, including handling its availability status and disconnection events.\n *\n * @param {Subscriber<TransportDiscoveredDevice>} subscriber The subscriber to emit the discovered device to.\n * @param {BleDeviceInfos} bleDeviceInfos The BLE device information associated with the discovered device.\n * @param {TransportDiscoveredDevice} discoveredDevice The newly discovered device to be emitted.\n * @return {void} */\n private _emitDiscoveredDevice(\n subscriber: Subscriber<TransportDiscoveredDevice>,\n bleDeviceInfos: BleDeviceInfos,\n discoveredDevice: TransportDiscoveredDevice,\n ) {\n subscriber.next(discoveredDevice);\n const internalDevice = {\n id: discoveredDevice.id,\n bleDeviceInfos,\n discoveredDevice,\n lastDiscoveredTimeStamp: Maybe.of(Date.now()),\n };\n this._internalDevicesById.set(discoveredDevice.id, {\n ...internalDevice,\n disconnectionSubscription: this._manager.onDeviceDisconnected(\n discoveredDevice.id,\n () => {\n subscriber.next({\n ...discoveredDevice,\n rssi: null,\n });\n },\n ),\n });\n }\n\n /**\n * Discovers new devices by scanning for BLE devices and filtering them based on the provided ledger UUIDs.\n *\n * @param {string[]} ledgerUuids - An array of UUIDs used to identify relevant ledger devices.\n * @return {Observable<TransportDiscoveredDevice>} An observable that emits discovered devices matching the provided UUIDs.\n */\n private _discoverNewDevices(\n ledgerUuids: string[],\n ): Observable<TransportDiscoveredDevice> {\n return new Observable<TransportDiscoveredDevice>((subscriber) => {\n this._manager.startDeviceScan(null, null, (error, device) => {\n if (error || !device) {\n subscriber.error(error);\n return;\n }\n\n this._getDiscoveredDeviceFrom(device, ledgerUuids).map(\n ({ discoveredDevice, bleDeviceInfos }) => {\n this._emitDiscoveredDevice(\n subscriber,\n bleDeviceInfos,\n discoveredDevice,\n );\n },\n );\n this._handleLostDiscoveredDevices(subscriber);\n });\n return {\n unsubscribe: async () => {\n await this._manager.stopDeviceScan();\n subscriber.unsubscribe();\n },\n };\n });\n }\n\n /**\n * Discovers and emits known ledger devices based on the provided UUIDs.\n *\n * @param {string[]} ledgerUuids - An array of UUIDs representing the target ledger devices to discover.\n * @return {Observable<TransportDiscoveredDevice>} An Observable that emits discovered devices matching the provided UUIDs.\n */\n private _discoverKnownDevices(\n ledgerUuids: string[],\n ): Observable<TransportDiscoveredDevice> {\n return from(this._manager.connectedDevices(ledgerUuids)).pipe(\n switchMap(\n (devices) =>\n new Observable<TransportDiscoveredDevice>((subscriber) => {\n for (const fromDevice of devices) {\n fromDevice.readRSSI().then((device) => {\n this._getDiscoveredDeviceFrom(device, ledgerUuids).map(\n ({ bleDeviceInfos, discoveredDevice }) => {\n this._emitDiscoveredDevice(\n subscriber,\n bleDeviceInfos,\n discoveredDevice,\n );\n },\n );\n });\n }\n }),\n ),\n repeat({ delay: BLE_DISCONNECT_TIMEOUT / 5 }),\n );\n }\n\n /**\n * Handles the event when a Bluetooth device gets disconnected. This method attempts\n * to reconnect to the device, retries a certain number of times on failure, and\n * invokes a callback if the reconnection does not succeed.\n *\n * @param {BleError | null} error - The error object representing the reason for the disconnection, or null if no error occurred.\n * @param {Device | null} device - The Bluetooth device that was disconnected, or null if no device is provided.\n * @return {void}\n */\n private _handleDeviceDisconnected(\n error: BleError | null,\n device: Device | null,\n ) {\n if (error) {\n this._logger.error(\"device disconnected error\", {\n data: { error, device },\n });\n return;\n }\n\n if (!device) {\n this._logger.debug(\"disconnected handler didn't found device\");\n return;\n }\n\n if (this._reconnectionSubscription.isJust()) {\n return;\n }\n\n const errorOrDeviceConnection = Maybe.fromNullable(\n this._deviceConnectionsById.get(device.id),\n );\n\n errorOrDeviceConnection.map((deviceConnection) => {\n deviceConnection.eventDeviceDetached();\n });\n\n let reconnectedDevice: Device;\n\n this._reconnectionSubscription = Maybe.of(\n from([0])\n .pipe(\n switchMap(async () => {\n try {\n reconnectedDevice = await device.connect({\n requestMTU: DEFAULT_MTU,\n });\n reconnectedDevice =\n await device.discoverAllServicesAndCharacteristics();\n await this._handleDeviceReconnected(reconnectedDevice);\n } catch (e) {\n this._logger.error(\n \"[_handleDeviceDisconnected] Reconnecting failed\",\n { data: { e } },\n );\n\n throwError(() => e);\n return;\n }\n return reconnectedDevice;\n }),\n retry({\n count: 5,\n delay: BLE_DISCONNECT_TIMEOUT / 5,\n }),\n )\n .subscribe({\n next: (value) =>\n this._logger.debug(\n \"[_handleDeviceDisconnected] Got new device after reconnection\",\n { data: { value } },\n ),\n complete: () => {\n this._reconnectionSubscription = Maybe.zero();\n },\n error: (e) => {\n this._logger.error(\n \"[_handleDeviceDisconnected] Reconnection failed after all retries\",\n { data: { e } },\n );\n this._reconnectionSubscription = Maybe.zero();\n errorOrDeviceConnection.map((deviceConnection) => {\n deviceConnection.closeConnection();\n });\n },\n }),\n );\n }\n\n /**\n * Handles the reconnection of a device. Configures the device connection and its corresponding\n * internal device upon reconnection, including updating the connection state, registering\n * callbacks for write and monitor operations, and initiating a reconnect operation.\n *\n * @param {Device} device - The device object that has been reconnected. Contains device details,\n * such as the device ID.\n * @return {Promise<Either<DeviceConnectionNotFound | InternalDeviceNotFound, void>>} A promise that completes when the device reconnection has been fully\n * configured. Resolves with no value or rejects if an error occurs during\n * the reconnection process.\n */\n private async _handleDeviceReconnected(device: Device) {\n const errorOrDeviceConnection = Maybe.fromNullable(\n this._deviceConnectionsById.get(device.id),\n ).toEither(new DeviceConnectionNotFound());\n\n const errorOrInternalDevice = Maybe.fromNullable(\n this._internalDevicesById.get(device.id),\n ).toEither(new InternalDeviceNotFound());\n\n return EitherAsync(async ({ liftEither }) => {\n const deviceConnectionStateMachine = await liftEither(\n errorOrDeviceConnection,\n );\n\n const internalDevice = await liftEither(errorOrInternalDevice);\n\n deviceConnectionStateMachine.setDependencies({\n device,\n manager: this._manager,\n internalDevice,\n });\n\n await deviceConnectionStateMachine.setupConnection();\n\n deviceConnectionStateMachine.eventDeviceAttached();\n }).run();\n }\n}\n\nexport const RNBleTransportFactory: TransportFactory = ({\n deviceModelDataSource,\n loggerServiceFactory,\n apduSenderServiceFactory,\n apduReceiverServiceFactory,\n}) =>\n new RNBleTransport(\n deviceModelDataSource,\n loggerServiceFactory,\n apduSenderServiceFactory,\n apduRecei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AAE,CAC3C,EAAE,SAAS,IAAI,0BAA0B,EAEnC2B,EAAwB,QAAM,aAClC,KAAK,qBAAqB,IAAI3B,EAAO,EAAE,CACzC,EAAE,SAAS,IAAI,wBAAwB,EAEvC,SAAO,eAAY,MAAO,CAAE,WAAAH,CAAW,IAAM,CAC3C,MAAMM,EAA+B,MAAMN,EACzCyB,CACF,EAEMvB,EAAiB,MAAMF,EAAW8B,CAAqB,EAE7DxB,EAA6B,gBAAgB,CAC3C,OAAAH,EACA,QAAS,KAAK,SACd,eAAAD,CACF,CAAC,EAED,MAAMI,EAA6B,gBAAgB,EAEnDA,EAA6B,oBAAoB,CACnD,CAAC,EAAE,IAAI,CACT,CACF,CAEO,MAAMxB,EAA0C,CAAC,CACtD,sBAAAiD,EACA,qBAAAC,EACA,yBAAAC,EACA,2BAAAC,CACF,IACE,IAAIrD,EACFkD,EACAC,EACAC,EACAC,CACF",
6
- "names": ["RNBleTransport_exports", "__export", "RNBleTransport", "RNBleTransportFactory", "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", "ledgerUuids", "isSupported", "params", "liftEither", "throwE", "internalDevice", "device", "error", "deviceApduSender", "deviceConnectionStateMachine", "iDevice", "args", "d", "scannedDeviceMap", "discoveredDevice", "granted", "result", "rnDevice", "maybeUuid", "uuid", "existingInternalDevice", "serviceToBleInfos", "bleDeviceInfos", "lastDiscoveredTimeStamp", "subscriber", "promises", "devices", "fromDevice", "errorOrDeviceConnection", "deviceConnection", "reconnectedDevice", "e", "value", "errorOrInternalDevice", "deviceModelDataSource", "loggerServiceFactory", "apduSenderServiceFactory", "apduReceiverServiceFactory"]
4
+ "sourcesContent": ["import { PermissionsAndroid, Platform } from \"react-native\";\nimport { type BleError, BleManager, type Device } from \"react-native-ble-plx\";\nimport {\n type ApduReceiverServiceFactory,\n type ApduSenderServiceFactory,\n type BleDeviceInfos,\n type ConnectError,\n DeviceConnectionStateMachine,\n type DeviceId,\n type DeviceModelDataSource,\n type DisconnectHandler,\n type DmkError,\n type LoggerPublisherService,\n OpeningConnectionError,\n type Transport,\n TransportConnectedDevice,\n type TransportDiscoveredDevice,\n type TransportFactory,\n type TransportIdentifier,\n UnknownDeviceError,\n} from \"@ledgerhq/device-management-kit\";\nimport { type Either, EitherAsync, Maybe, Nothing, Right } from \"purify-ts\";\nimport {\n from,\n map,\n mergeWith,\n Observable,\n repeat,\n retry,\n type Subscriber,\n type Subscription,\n switchMap,\n throwError,\n} from \"rxjs\";\n\nimport {\n BLE_DISCONNECT_TIMEOUT,\n CONNECTION_LOST_DELAY,\n DEFAULT_MTU,\n} from \"@api/model/Const\";\nimport {\n DeviceConnectionNotFound,\n InternalDeviceNotFound,\n} from \"@api/model/Errors\";\nimport {\n RNBleApduSender,\n type RNBleApduSenderDependencies,\n type RNBleInternalDevice,\n} from \"@api/transport/RNBleApduSender\";\n\nexport const rnBleTransportIdentifier = \"RN_BLE\";\n\nexport class RNBleTransport implements Transport {\n private _logger: LoggerPublisherService;\n private _isSupported: Maybe<boolean>;\n private _internalDevicesById: Map<DeviceId, RNBleInternalDevice>;\n private _deviceConnectionsById: Map<\n DeviceId,\n DeviceConnectionStateMachine<RNBleApduSenderDependencies>\n >;\n private readonly _manager: BleManager;\n private readonly identifier: TransportIdentifier = \"RN_BLE\";\n private _reconnectionSubscription: Maybe<Subscription>;\n\n constructor(\n private readonly _deviceModelDataSource: DeviceModelDataSource,\n private readonly _loggerServiceFactory: (\n tag: string,\n ) => LoggerPublisherService,\n private readonly _apduSenderFactory: ApduSenderServiceFactory,\n private readonly _apduReceiverFactory: ApduReceiverServiceFactory,\n ) {\n this._logger = _loggerServiceFactory(\"ReactNativeBleTransport\");\n this._manager = new BleManager();\n this._isSupported = Maybe.zero();\n this._internalDevicesById = new Map();\n this._deviceConnectionsById = new Map();\n this.requestPermission();\n this._reconnectionSubscription = Maybe.zero();\n }\n\n private _startDiscovering() {\n const ledgerUuids = this._deviceModelDataSource.getBluetoothServices();\n return from(this.requestPermission()).pipe(\n switchMap((isSupported) => {\n if (!isSupported) {\n throw new Error(\"BLE not supported\");\n }\n return this._discoverKnownDevices(ledgerUuids);\n }),\n mergeWith(this._discoverNewDevices(ledgerUuids)),\n );\n }\n\n /**\n * Starts the discovery process to find Bluetooth devices that match specific criteria.\n *\n * This method clears the internal device cache and requests necessary permissions\n * before initiating the discovery of both known and new devices. If the Bluetooth\n * Low Energy (BLE) feature is not supported, an error is thrown.\n *\n * @return {Observable<TransportDiscoveredDevice>} An observable emitting discovered devices\n * that match the specified Bluetooth services.\n */\n startDiscovering(): Observable<TransportDiscoveredDevice> {\n return this._startDiscovering();\n }\n\n /**\n * Stops the device scanning operation currently in progress.\n *\n * @return {Promise<void>} A promise that resolves once the device scanning has been successfully stopped.\n */\n async stopDiscovering(): Promise<void> {\n await this._manager.stopDeviceScan();\n }\n\n /**\n * Establishes a connection to a device and configures the necessary parameters for communication.\n *\n * @param {Object} params - An object containing parameters required for the connection.\n * @param {DeviceId} params.deviceId - The unique identifier of the device to connect to.\n * @param {DisconnectHandler} params.onDisconnect - A callback function to handle device disconnection.\n * @returns {Promise<Either<ConnectError, TransportConnectedDevice>>} A promise resolving to either a connection error or a successfully connected device.\n */\n async connect(params: {\n deviceId: DeviceId;\n onDisconnect: DisconnectHandler;\n }): Promise<Either<ConnectError, TransportConnectedDevice>> {\n return EitherAsync<ConnectError, TransportConnectedDevice>(\n async ({ liftEither, throwE }) => {\n const internalDevice = await liftEither(\n Maybe.fromNullable(\n this._internalDevicesById.get(params.deviceId),\n ).toEither(\n new UnknownDeviceError(`Unknown device ${params.deviceId}`),\n ),\n );\n\n let device: Device;\n\n try {\n device = await this._manager.connectToDevice(params.deviceId, {\n requestMTU: DEFAULT_MTU,\n });\n await this._manager.discoverAllServicesAndCharacteristicsForDevice(\n params.deviceId,\n );\n } catch (error) {\n return throwE(new OpeningConnectionError(error));\n }\n\n const deviceApduSender = new RNBleApduSender(\n {\n apduSenderFactory: this._apduSenderFactory,\n apduReceiverFactory: this._apduReceiverFactory,\n dependencies: {\n device,\n internalDevice,\n manager: this._manager,\n },\n },\n this._loggerServiceFactory,\n );\n\n const deviceConnectionStateMachine =\n new DeviceConnectionStateMachine<RNBleApduSenderDependencies>({\n deviceId: params.deviceId,\n deviceApduSender,\n timeoutDuration: BLE_DISCONNECT_TIMEOUT,\n onTerminated: () => {\n params.onDisconnect(params.deviceId);\n this._deviceConnectionsById.delete(params.deviceId);\n const iDevice = this._internalDevicesById.get(params.deviceId);\n\n if (iDevice) {\n iDevice.disconnectionSubscription.remove();\n }\n\n this._internalDevicesById.delete(params.deviceId);\n },\n });\n\n await deviceApduSender.setupConnection();\n\n this._deviceConnectionsById.set(\n internalDevice.id,\n deviceConnectionStateMachine,\n );\n\n internalDevice.disconnectionSubscription =\n this._manager.onDeviceDisconnected(internalDevice.id, (...args) => {\n this._handleDeviceDisconnected(...args);\n });\n\n internalDevice.lastDiscoveredTimeStamp = Maybe.zero();\n\n return new TransportConnectedDevice({\n id: internalDevice.id,\n deviceModel: internalDevice.discoveredDevice.deviceModel,\n type: \"BLE\",\n sendApdu: (...args) => deviceConnectionStateMachine.sendApdu(...args),\n transport: this.identifier,\n });\n },\n ).run();\n }\n\n /**\n * Terminates the connection with the connected device and cleans up related resources.\n *\n * @param {TransportConnectedDevice} params.connectedDevice - The connected device to be disconnected.\n * @return {Promise<Either<DmkError, void>>} A promise resolving to either a success (void) or a failure (DmkError) value.\n */\n async disconnect(params: {\n connectedDevice: TransportConnectedDevice;\n }): Promise<Either<DmkError, void>> {\n const deviceConnection = Maybe.fromNullable(\n this._deviceConnectionsById.get(params.connectedDevice.id),\n );\n\n deviceConnection.map((d) => {\n d.closeConnection();\n });\n\n return Promise.resolve(Right(undefined));\n }\n\n /**\n * Listens to known devices and emits updates when new devices are discovered or when properties of existing devices are updated.\n *\n * @return {Observable<TransportDiscoveredDevice[]>} An observable stream of discovered devices, containing device information as an array of TransportDiscoveredDevice objects.\n */\n listenToAvailableDevices(): Observable<TransportDiscoveredDevice[]> {\n const scannedDeviceMap: Record<DeviceId, TransportDiscoveredDevice> = {};\n return this._startDiscovering().pipe(\n map((discoveredDevice) => {\n scannedDeviceMap[discoveredDevice.id] = discoveredDevice;\n return Object.values(scannedDeviceMap).filter(\n (device) => device.rssi !== null,\n );\n }),\n );\n }\n\n /**\n * Determines if the feature or permission is supported.\n *\n * This method evaluates the current state of the `_isSupported` property to determine\n * whether the relevant feature is supported or throws an error if its state has\n * not been initialized properly.\n *\n * @return {boolean} Returns `true` if the feature is supported, otherwise `false`.\n * Throws an error if the `_isSupported` property has not been initialized.\n */\n isSupported(): boolean {\n return this._isSupported.caseOf({\n Just: (isSupported) => isSupported,\n Nothing: () => {\n throw new Error(\"Should initialize permission\");\n },\n });\n }\n\n /**\n * Retrieves the transport identifier associated with the object.\n *\n * @return {TransportIdentifier} The transport identifier.\n */\n getIdentifier(): TransportIdentifier {\n return this.identifier;\n }\n\n /**\n * Requests the necessary permissions based on the operating system.\n * For iOS, it automatically sets the permissions as granted.\n * For Android, it checks and requests location, Bluetooth scan, and Bluetooth connect permissions, depending on the API level.\n * If permissions are granted, updates the internal support state and logs the result.\n *\n * @return {Promise<boolean>} A promise that resolves to true if the required permissions are granted, otherwise false.\n */\n async requestPermission(): Promise<boolean> {\n if (Platform.OS === \"ios\") {\n this._isSupported = Maybe.of(true);\n return true;\n }\n\n if (\n Platform.OS === \"android\" &&\n PermissionsAndroid.PERMISSIONS[\"ACCESS_FINE_LOCATION\"]\n ) {\n const apiLevel = parseInt(Platform.Version.toString(), 10);\n\n if (apiLevel < 31) {\n const granted = await PermissionsAndroid.request(\n PermissionsAndroid.PERMISSIONS[\"ACCESS_FINE_LOCATION\"],\n );\n this._isSupported = Maybe.of(\n granted === PermissionsAndroid.RESULTS[\"GRANTED\"],\n );\n }\n if (\n PermissionsAndroid.PERMISSIONS[\"BLUETOOTH_SCAN\"] &&\n PermissionsAndroid.PERMISSIONS[\"BLUETOOTH_CONNECT\"]\n ) {\n const result = await PermissionsAndroid.requestMultiple([\n PermissionsAndroid.PERMISSIONS[\"BLUETOOTH_SCAN\"],\n PermissionsAndroid.PERMISSIONS[\"BLUETOOTH_CONNECT\"],\n PermissionsAndroid.PERMISSIONS[\"ACCESS_FINE_LOCATION\"],\n ]);\n\n this._isSupported = Maybe.of(\n result[\"android.permission.BLUETOOTH_CONNECT\"] ===\n PermissionsAndroid.RESULTS[\"GRANTED\"] &&\n result[\"android.permission.BLUETOOTH_SCAN\"] ===\n PermissionsAndroid.RESULTS[\"GRANTED\"] &&\n result[\"android.permission.ACCESS_FINE_LOCATION\"] ===\n PermissionsAndroid.RESULTS[\"GRANTED\"],\n );\n\n return true;\n }\n }\n\n this._logger.error(\"Permission have not been granted\", {\n data: { isSupported: this.isSupported() },\n });\n\n this._isSupported = Maybe.of(false);\n return false;\n }\n\n /**\n * Retrieves a discovered device and its BLE device information, if available, from the provided input.\n *\n * @param {Device} rnDevice - The Bluetooth device to analyze for discovery.\n * @param {string[]} ledgerUuids - A list of UUIDs associated with the target Ledger devices.\n * @return {Maybe<{ bleDeviceInfos: BleDeviceInfos; discoveredDevice: TransportDiscoveredDevice }>} A Maybe object containing the discovered device and its BLE information, or Nothing if the device or information cannot be determined.\n */\n private _getDiscoveredDeviceFrom(\n rnDevice: Device,\n ledgerUuids: string[],\n ): Maybe<{\n bleDeviceInfos: BleDeviceInfos;\n discoveredDevice: TransportDiscoveredDevice;\n }> {\n const maybeUuid = Maybe.fromNullable(\n rnDevice?.serviceUUIDs?.find((uuid) => ledgerUuids.includes(uuid)),\n );\n\n const existingInternalDevice = Maybe.fromNullable(\n this._internalDevicesById.get(rnDevice.id),\n );\n\n if (existingInternalDevice.isJust()) {\n return existingInternalDevice.map((internalDevice) => ({\n bleDeviceInfos: internalDevice.bleDeviceInfos,\n discoveredDevice: {\n ...internalDevice.discoveredDevice,\n rssi: rnDevice.rssi || undefined,\n },\n }));\n }\n\n return maybeUuid.mapOrDefault((uuid) => {\n const serviceToBleInfos =\n this._deviceModelDataSource.getBluetoothServicesInfos();\n const maybeBleDeviceInfos = Maybe.fromNullable(serviceToBleInfos[uuid]);\n\n return maybeBleDeviceInfos.map((bleDeviceInfos) => {\n const discoveredDevice: TransportDiscoveredDevice = {\n id: rnDevice.id,\n name: rnDevice.localName || bleDeviceInfos.deviceModel.productName,\n deviceModel: bleDeviceInfos.deviceModel,\n transport: this.identifier,\n rssi: rnDevice.rssi || undefined,\n };\n\n return {\n discoveredDevice,\n bleDeviceInfos,\n };\n });\n }, Nothing);\n }\n\n /**\n * Determines whether the delay since the device was last discovered has exceeded a predefined threshold.\n *\n * @param {RNBleInternalDevice} internalDevice - The internal device object containing the last discovered timestamp.\n * @return {boolean} - Returns true if the delay is over, otherwise false.\n */\n private _isDiscoveredDeviceDelayOver(internalDevice: RNBleInternalDevice) {\n return internalDevice.lastDiscoveredTimeStamp.caseOf({\n Just: (lastDiscoveredTimeStamp) =>\n Date.now() > lastDiscoveredTimeStamp + CONNECTION_LOST_DELAY,\n Nothing: () => {\n return false;\n },\n });\n }\n\n /**\n * Handles the processing of devices that have been determined to be \"lost\" by iterating\n * through a collection of internal devices, identifying lost devices, updating their status,\n * and notifying a subscriber about the change.\n *\n * @param {Subscriber<TransportDiscoveredDevice>} subscriber - The observer that will be notified\n * when a device is marked as lost, including updated device information with its availability set to false.\n * @return {void} This method does not return a value.\n */\n private async _handleLostDiscoveredDevices(\n subscriber: Subscriber<TransportDiscoveredDevice>,\n ) {\n for (const internalDevice of this._internalDevicesById.values()) {\n if (\n this._isDiscoveredDeviceDelayOver(internalDevice) &&\n !(await this._manager.isDeviceConnected(internalDevice.id))\n ) {\n this._internalDevicesById.delete(internalDevice.id);\n subscriber.next({\n ...internalDevice.discoveredDevice,\n rssi: null,\n });\n }\n }\n }\n\n /**\n * Emits a discovered device to the provided subscriber and manages internal state\n * for the discovered device, including handling its availability status and disconnection events.\n *\n * @param {Subscriber<TransportDiscoveredDevice>} subscriber The subscriber to emit the discovered device to.\n * @param {BleDeviceInfos} bleDeviceInfos The BLE device information associated with the discovered device.\n * @param {TransportDiscoveredDevice} discoveredDevice The newly discovered device to be emitted.\n * @return {void} */\n private _emitDiscoveredDevice(\n subscriber: Subscriber<TransportDiscoveredDevice>,\n bleDeviceInfos: BleDeviceInfos,\n discoveredDevice: TransportDiscoveredDevice,\n ) {\n subscriber.next(discoveredDevice);\n const internalDevice = {\n id: discoveredDevice.id,\n bleDeviceInfos,\n discoveredDevice,\n lastDiscoveredTimeStamp: Maybe.of(Date.now()),\n };\n this._internalDevicesById.set(discoveredDevice.id, {\n ...internalDevice,\n disconnectionSubscription: this._manager.onDeviceDisconnected(\n discoveredDevice.id,\n () => {\n subscriber.next({\n ...discoveredDevice,\n rssi: null,\n });\n },\n ),\n });\n }\n\n /**\n * Discovers new devices by scanning for BLE devices and filtering them based on the provided ledger UUIDs.\n *\n * @param {string[]} ledgerUuids - An array of UUIDs used to identify relevant ledger devices.\n * @return {Observable<TransportDiscoveredDevice>} An observable that emits discovered devices matching the provided UUIDs.\n */\n private _discoverNewDevices(\n ledgerUuids: string[],\n ): Observable<TransportDiscoveredDevice> {\n return new Observable<TransportDiscoveredDevice>((subscriber) => {\n this._manager.startDeviceScan(null, null, (error, device) => {\n if (error || !device) {\n subscriber.error(error);\n return;\n }\n\n this._getDiscoveredDeviceFrom(device, ledgerUuids).map(\n ({ discoveredDevice, bleDeviceInfos }) => {\n this._emitDiscoveredDevice(\n subscriber,\n bleDeviceInfos,\n discoveredDevice,\n );\n },\n );\n this._handleLostDiscoveredDevices(subscriber);\n });\n return {\n unsubscribe: async () => {\n await this._manager.stopDeviceScan();\n subscriber.unsubscribe();\n },\n };\n });\n }\n\n /**\n * Discovers and emits known ledger devices based on the provided UUIDs.\n *\n * @param {string[]} ledgerUuids - An array of UUIDs representing the target ledger devices to discover.\n * @return {Observable<TransportDiscoveredDevice>} An Observable that emits discovered devices matching the provided UUIDs.\n */\n private _discoverKnownDevices(\n ledgerUuids: string[],\n ): Observable<TransportDiscoveredDevice> {\n return from(this._manager.connectedDevices(ledgerUuids)).pipe(\n switchMap(\n (devices) =>\n new Observable<TransportDiscoveredDevice>((subscriber) => {\n for (const fromDevice of devices) {\n fromDevice.readRSSI().then((device) => {\n this._getDiscoveredDeviceFrom(device, ledgerUuids).map(\n ({ bleDeviceInfos, discoveredDevice }) => {\n this._emitDiscoveredDevice(\n subscriber,\n bleDeviceInfos,\n discoveredDevice,\n );\n },\n );\n });\n }\n this._handleLostDiscoveredDevices(subscriber);\n }),\n ),\n repeat({ delay: BLE_DISCONNECT_TIMEOUT / 5 }),\n );\n }\n\n /**\n * Handles the event when a Bluetooth device gets disconnected. This method attempts\n * to reconnect to the device, retries a certain number of times on failure, and\n * invokes a callback if the reconnection does not succeed.\n *\n * @param {BleError | null} error - The error object representing the reason for the disconnection, or null if no error occurred.\n * @param {Device | null} device - The Bluetooth device that was disconnected, or null if no device is provided.\n * @return {void}\n */\n private _handleDeviceDisconnected(\n error: BleError | null,\n device: Device | null,\n ) {\n if (error) {\n this._logger.error(\"device disconnected error\", {\n data: { error, device },\n });\n return;\n }\n\n if (!device) {\n this._logger.debug(\"disconnected handler didn't found device\");\n return;\n }\n\n if (this._reconnectionSubscription.isJust()) {\n return;\n }\n\n const errorOrDeviceConnection = Maybe.fromNullable(\n this._deviceConnectionsById.get(device.id),\n );\n\n errorOrDeviceConnection.map((deviceConnection) => {\n deviceConnection.eventDeviceDetached();\n });\n\n let reconnectedDevice: Device;\n\n this._reconnectionSubscription = Maybe.of(\n from([0])\n .pipe(\n switchMap(async () => {\n try {\n reconnectedDevice = await device.connect({\n requestMTU: DEFAULT_MTU,\n });\n reconnectedDevice =\n await device.discoverAllServicesAndCharacteristics();\n await this._handleDeviceReconnected(reconnectedDevice);\n } catch (e) {\n this._logger.error(\n \"[_handleDeviceDisconnected] Reconnecting failed\",\n { data: { e } },\n );\n\n throwError(() => e);\n return;\n }\n return reconnectedDevice;\n }),\n retry({\n count: 5,\n delay: BLE_DISCONNECT_TIMEOUT / 5,\n }),\n )\n .subscribe({\n next: (value) =>\n this._logger.debug(\n \"[_handleDeviceDisconnected] Got new device after reconnection\",\n { data: { value } },\n ),\n complete: () => {\n this._reconnectionSubscription = Maybe.zero();\n },\n error: (e) => {\n this._logger.error(\n \"[_handleDeviceDisconnected] Reconnection failed after all retries\",\n { data: { e } },\n );\n this._reconnectionSubscription = Maybe.zero();\n errorOrDeviceConnection.map((deviceConnection) => {\n deviceConnection.closeConnection();\n });\n },\n }),\n );\n }\n\n /**\n * Handles the reconnection of a device. Configures the device connection and its corresponding\n * internal device upon reconnection, including updating the connection state, registering\n * callbacks for write and monitor operations, and initiating a reconnect operation.\n *\n * @param {Device} device - The device object that has been reconnected. Contains device details,\n * such as the device ID.\n * @return {Promise<Either<DeviceConnectionNotFound | InternalDeviceNotFound, void>>} A promise that completes when the device reconnection has been fully\n * configured. Resolves with no value or rejects if an error occurs during\n * the reconnection process.\n */\n private async _handleDeviceReconnected(device: Device) {\n const errorOrDeviceConnection = Maybe.fromNullable(\n this._deviceConnectionsById.get(device.id),\n ).toEither(new DeviceConnectionNotFound());\n\n const errorOrInternalDevice = Maybe.fromNullable(\n this._internalDevicesById.get(device.id),\n ).toEither(new InternalDeviceNotFound());\n\n return EitherAsync(async ({ liftEither }) => {\n const deviceConnectionStateMachine = await liftEither(\n errorOrDeviceConnection,\n );\n\n const internalDevice = await liftEither(errorOrInternalDevice);\n\n deviceConnectionStateMachine.setDependencies({\n device,\n manager: this._manager,\n internalDevice,\n });\n\n await deviceConnectionStateMachine.setupConnection();\n\n deviceConnectionStateMachine.eventDeviceAttached();\n }).run();\n }\n}\n\nexport const RNBleTransportFactory: TransportFactory = ({\n deviceModelDataSource,\n loggerServiceFactory,\n apduSenderServiceFactory,\n apduReceiverServiceFactory,\n}) =>\n new RNBleTransport(\n deviceModelDataSource,\n loggerServiceFactory,\n apduSenderServiceFactory,\n apduReceiverServiceFactory,\n );\n"],
5
+ "mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,oBAAAE,EAAA,0BAAAC,EAAA,6BAAAC,IAAA,eAAAC,EAAAL,GAAA,IAAAM,EAA6C,wBAC7CC,EAAuD,gCACvDC,EAkBO,2CACPC,EAAgE,qBAChEC,EAWO,gBAEPC,EAIO,4BACPC,EAGO,6BACPC,EAIO,0CAEA,MAAMT,EAA2B,SAEjC,MAAMF,CAAoC,CAY/C,YACmBY,EACAC,EAGAC,EACAC,EACjB,CANiB,4BAAAH,EACA,2BAAAC,EAGA,wBAAAC,EACA,0BAAAC,EAEjB,KAAK,QAAUF,EAAsB,yBAAyB,EAC9D,KAAK,SAAW,IAAI,aACpB,KAAK,aAAe,QAAM,KAAK,EAC/B,KAAK,qBAAuB,IAAI,IAChC,KAAK,uBAAyB,IAAI,IAClC,KAAK,kBAAkB,EACvB,KAAK,0BAA4B,QAAM,KAAK,CAC9C,CA1BQ,QACA,aACA,qBACA,uBAIS,SACA,WAAkC,SAC3C,0BAmBA,mBAAoB,CAC1B,MAAMG,EAAc,KAAK,uBAAuB,qBAAqB,EACrE,SAAO,QAAK,KAAK,kBAAkB,CAAC,EAAE,QACpC,aAAWC,GAAgB,CACzB,GAAI,CAACA,EACH,MAAM,IAAI,MAAM,mBAAmB,EAErC,OAAO,KAAK,sBAAsBD,CAAW,CAC/C,CAAC,KACD,aAAU,KAAK,oBAAoBA,CAAW,CAAC,CACjD,CACF,CAYA,kBAA0D,CACxD,OAAO,KAAK,kBAAkB,CAChC,CAOA,MAAM,iBAAiC,CACrC,MAAM,KAAK,SAAS,eAAe,CACrC,CAUA,MAAM,QAAQE,EAG8C,CAC1D,SAAO,eACL,MAAO,CAAE,WAAAC,EAAY,OAAAC,CAAO,IAAM,CAChC,MAAMC,EAAiB,MAAMF,EAC3B,QAAM,aACJ,KAAK,qBAAqB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AK,uBAAuB,IAAIrB,EAAO,EAAE,CAC3C,EAAE,SAAS,IAAI,0BAA0B,EAEnC0B,EAAwB,QAAM,aAClC,KAAK,qBAAqB,IAAI1B,EAAO,EAAE,CACzC,EAAE,SAAS,IAAI,wBAAwB,EAEvC,SAAO,eAAY,MAAO,CAAE,WAAAH,CAAW,IAAM,CAC3C,MAAMM,EAA+B,MAAMN,EACzCwB,CACF,EAEMtB,EAAiB,MAAMF,EAAW6B,CAAqB,EAE7DvB,EAA6B,gBAAgB,CAC3C,OAAAH,EACA,QAAS,KAAK,SACd,eAAAD,CACF,CAAC,EAED,MAAMI,EAA6B,gBAAgB,EAEnDA,EAA6B,oBAAoB,CACnD,CAAC,EAAE,IAAI,CACT,CACF,CAEO,MAAMxB,EAA0C,CAAC,CACtD,sBAAAgD,EACA,qBAAAC,EACA,yBAAAC,EACA,2BAAAC,CACF,IACE,IAAIpD,EACFiD,EACAC,EACAC,EACAC,CACF",
6
+ "names": ["RNBleTransport_exports", "__export", "RNBleTransport", "RNBleTransportFactory", "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", "ledgerUuids", "isSupported", "params", "liftEither", "throwE", "internalDevice", "device", "error", "deviceApduSender", "deviceConnectionStateMachine", "iDevice", "args", "d", "scannedDeviceMap", "discoveredDevice", "granted", "result", "rnDevice", "maybeUuid", "uuid", "existingInternalDevice", "serviceToBleInfos", "bleDeviceInfos", "lastDiscoveredTimeStamp", "subscriber", "devices", "fromDevice", "errorOrDeviceConnection", "deviceConnection", "reconnectedDevice", "e", "value", "errorOrInternalDevice", "deviceModelDataSource", "loggerServiceFactory", "apduSenderServiceFactory", "apduReceiverServiceFactory"]
7
7
  }
@@ -1,2 +1,2 @@
1
- import{DeviceNotInitializedError as p}from"@ledgerhq/device-management-kit";import{Base64 as s}from"js-base64";import{Left as d,Maybe as c,Nothing as o,Right as a}from"purify-ts";import{BehaviorSubject as u}from"rxjs";const v=3;class S{_dependencies;_isDeviceReady;_logger;_apduSender;_apduSenderFactory;_apduReceiver;_sendApduPromiseResolver;constructor({apduSenderFactory:i,apduReceiverFactory:t,dependencies:r},e){this._dependencies=r,this._isDeviceReady=new u(!1),this._logger=e("RNBleApduSender"),this._apduSenderFactory=i,this._apduSender=o,this._apduReceiver=t(),this._sendApduPromiseResolver=o}onReceiveSetupApduResponse(i){const t=new Uint8Array(i),{device:r}=this._dependencies,[e]=t.slice(5);let n=r.mtu-v;e&&e!==n&&(n=e),this._apduSender=c.of(this._apduSenderFactory({frameSize:n})),this._isDeviceReady.next(!0)}receiveApdu(i){this._apduReceiver.handleFrame(i).map(r=>{r.map(e=>{this._logger.debug("Received APDU Response",{data:{response:e}}),this._sendApduPromiseResolver.map(n=>n(a(e)))})}).mapLeft(r=>{this._sendApduPromiseResolver.map(e=>e(d(r)))})}onMonitor(i){if(!i.value)return;const t=s.toUint8Array(i.value);this._isDeviceReady.value?this.receiveApdu(t):this.onReceiveSetupApduResponse(t)}write(i){return this._dependencies.manager.writeCharacteristicWithoutResponseForDevice(this._dependencies.device.id,this._dependencies.internalDevice.bleDeviceInfos.serviceUuid,this._dependencies.internalDevice.bleDeviceInfos.writeCmdUuid,i)}getDependencies(){return this._dependencies}setDependencies(i){this._dependencies=i}async setupConnection(){this._dependencies.manager.monitorCharacteristicForDevice(this._dependencies.device.id,this._dependencies.internalDevice.bleDeviceInfos.serviceUuid,this._dependencies.internalDevice.bleDeviceInfos.notifyUuid,(r,e)=>{!r&&e&&this.onMonitor(e)}),this._isDeviceReady.next(!1);const i=Uint8Array.from([8,0,0,0,0]);await this.write(s.fromUint8Array(i));let t;await new Promise(r=>{t=this._isDeviceReady.subscribe(e=>{e&&(r(),t.unsubscribe())})})}async sendApdu(i){if(!this._isDeviceReady.value)return Promise.resolve(d(new p("Unknown MTU")));const t=new Promise(e=>{this._sendApduPromiseResolver=c.of(e)}),r=this._apduSender.caseOf({Just:e=>e.getFrames(i),Nothing:()=>[]});for(const e of r)try{await this.write(s.fromUint8Array(e.getRawData()))}catch(n){this._logger.info("Error sending frame",{data:{error:n}})}return t}closeConnection(){this._dependencies.device.cancelConnection()}}export{S as RNBleApduSender};
1
+ import{DeviceNotInitializedError as p}from"@ledgerhq/device-management-kit";import{Base64 as s}from"js-base64";import{Left as d,Maybe as c,Nothing as o,Right as a}from"purify-ts";import{BehaviorSubject as v}from"rxjs";const u=3;class R{_dependencies;_isDeviceReady;_logger;_apduSender;_apduSenderFactory;_apduReceiver;_sendApduPromiseResolver;constructor({apduSenderFactory:i,apduReceiverFactory:t,dependencies:r},e){this._dependencies=r,this._isDeviceReady=new v(!1),this._logger=e("RNBleApduSender"),this._apduSenderFactory=i,this._apduSender=o,this._apduReceiver=t(),this._sendApduPromiseResolver=o}onReceiveSetupApduResponse(i){const t=new Uint8Array(i),{device:r}=this._dependencies,[e]=t.slice(5);let n=r.mtu-u;e&&e!==n&&(n=e),this._apduSender=c.of(this._apduSenderFactory({frameSize:n})),this._isDeviceReady.next(!0)}receiveApdu(i){this._apduReceiver.handleFrame(i).map(r=>{r.map(e=>{this._logger.debug("Received APDU Response",{data:{response:e}}),this._sendApduPromiseResolver.map(n=>n(a(e)))})}).mapLeft(r=>{this._sendApduPromiseResolver.map(e=>e(d(r)))})}onMonitor(i){if(!i.value)return;const t=s.toUint8Array(i.value);this._isDeviceReady.value?this.receiveApdu(t):this.onReceiveSetupApduResponse(t)}write(i){return this._dependencies.manager.writeCharacteristicWithoutResponseForDevice(this._dependencies.device.id,this._dependencies.internalDevice.bleDeviceInfos.serviceUuid,this._dependencies.internalDevice.bleDeviceInfos.writeCmdUuid,i)}getDependencies(){return this._dependencies}setDependencies(i){this._dependencies=i}async setupConnection(){this._dependencies.manager.monitorCharacteristicForDevice(this._dependencies.device.id,this._dependencies.internalDevice.bleDeviceInfos.serviceUuid,this._dependencies.internalDevice.bleDeviceInfos.notifyUuid,(t,r)=>{!t&&r&&this.onMonitor(r)}),this._isDeviceReady.next(!1);const i=Uint8Array.from([8,0,0,0,0]);await this.write(s.fromUint8Array(i)),await new Promise(t=>{const r=this._isDeviceReady.subscribe(e=>{e&&(t(),r.unsubscribe())})})}async sendApdu(i){if(!this._isDeviceReady.value)return Promise.resolve(d(new p("Unknown MTU")));const t=new Promise(e=>{this._sendApduPromiseResolver=c.of(e)}),r=this._apduSender.caseOf({Just:e=>e.getFrames(i),Nothing:()=>[]});for(const e of r)try{await this.write(s.fromUint8Array(e.getRawData()))}catch(n){this._logger.info("Error sending frame",{data:{error:n}})}return t}closeConnection(){this._dependencies.device.cancelConnection()}}export{R as RNBleApduSender};
2
2
  //# sourceMappingURL=RNBleApduSender.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/api/transport/RNBleApduSender.ts"],
4
- "sourcesContent": ["import {\n type BleManager,\n type Characteristic,\n type Device,\n type Subscription as RNBleSubscription,\n} from \"react-native-ble-plx\";\nimport {\n type ApduReceiverService,\n type ApduReceiverServiceFactory,\n type ApduResponse,\n type ApduSenderService,\n type ApduSenderServiceFactory,\n type BleDeviceInfos,\n type DeviceApduSender,\n type DeviceId,\n DeviceNotInitializedError,\n type DmkError,\n type LoggerPublisherService,\n type TransportDiscoveredDevice,\n} from \"@ledgerhq/device-management-kit\";\nimport { Base64 } from \"js-base64\";\nimport { type Either, Left, Maybe, Nothing, Right } from \"purify-ts\";\nimport { BehaviorSubject, type Subscription } from \"rxjs\";\n\nconst FRAME_HEADER_SIZE = 3;\n\nexport type RNBleInternalDevice = {\n id: DeviceId;\n bleDeviceInfos: BleDeviceInfos;\n discoveredDevice: TransportDiscoveredDevice;\n disconnectionSubscription: RNBleSubscription;\n lastDiscoveredTimeStamp: Maybe<number>;\n};\n\ntype RNBleApduSenderConstructorArgs = {\n dependencies: RNBleApduSenderDependencies;\n apduSenderFactory: ApduSenderServiceFactory;\n apduReceiverFactory: ApduReceiverServiceFactory;\n};\n\nexport type RNBleApduSenderDependencies = {\n device: Device;\n internalDevice: RNBleInternalDevice;\n manager: BleManager;\n};\n\nexport class RNBleApduSender\n implements DeviceApduSender<RNBleApduSenderDependencies>\n{\n private _dependencies: RNBleApduSenderDependencies;\n private _isDeviceReady: BehaviorSubject<boolean>;\n private _logger: LoggerPublisherService;\n private _apduSender: Maybe<ApduSenderService>;\n private readonly _apduSenderFactory: ApduSenderServiceFactory;\n private readonly _apduReceiver: ApduReceiverService;\n private _sendApduPromiseResolver: Maybe<\n (value: Either<DmkError, ApduResponse>) => void\n >;\n\n constructor(\n {\n apduSenderFactory,\n apduReceiverFactory,\n dependencies,\n }: RNBleApduSenderConstructorArgs,\n loggerServiceFactory: (tag: string) => LoggerPublisherService,\n ) {\n this._dependencies = dependencies;\n this._isDeviceReady = new BehaviorSubject<boolean>(false);\n this._logger = loggerServiceFactory(\"RNBleApduSender\");\n this._apduSenderFactory = apduSenderFactory;\n this._apduSender = Nothing;\n this._apduReceiver = apduReceiverFactory();\n this._sendApduPromiseResolver = Nothing;\n }\n\n private onReceiveSetupApduResponse(value: Uint8Array) {\n const mtuResponse = new Uint8Array(value);\n const { device } = this._dependencies;\n // ledger mtu is the 5th byte of the response\n const [ledgerMtu] = mtuResponse.slice(5);\n let frameSize = device.mtu - FRAME_HEADER_SIZE;\n\n if (ledgerMtu && ledgerMtu !== frameSize) {\n // should never happen since ble mtu is negotiated on device connect with 156 bytes and ledger should return mtu size minus header size\n frameSize = ledgerMtu;\n }\n this._apduSender = Maybe.of(this._apduSenderFactory({ frameSize }));\n this._isDeviceReady.next(true);\n }\n\n private receiveApdu(apdu: Uint8Array) {\n const response = this._apduReceiver.handleFrame(apdu);\n\n response\n .map((maybeApduResponse) => {\n maybeApduResponse.map((apduResponse) => {\n this._logger.debug(\"Received APDU Response\", {\n data: { response: apduResponse },\n });\n this._sendApduPromiseResolver.map((resolve) =>\n resolve(Right(apduResponse)),\n );\n });\n })\n .mapLeft((error) => {\n this._sendApduPromiseResolver.map((resolve) => resolve(Left(error)));\n });\n }\n\n private onMonitor(characteristic: Characteristic) {\n if (!characteristic.value) {\n return;\n }\n\n const apdu = Base64.toUint8Array(characteristic.value);\n if (!this._isDeviceReady.value) {\n this.onReceiveSetupApduResponse(apdu);\n } else {\n this.receiveApdu(apdu);\n }\n }\n\n private write(value: string) {\n return this._dependencies.manager.writeCharacteristicWithoutResponseForDevice(\n this._dependencies.device.id,\n this._dependencies.internalDevice.bleDeviceInfos.serviceUuid,\n this._dependencies.internalDevice.bleDeviceInfos.writeCmdUuid,\n value,\n );\n }\n\n public getDependencies() {\n return this._dependencies;\n }\n\n public setDependencies(dependencies: RNBleApduSenderDependencies) {\n this._dependencies = dependencies;\n }\n\n public async setupConnection() {\n this._dependencies.manager.monitorCharacteristicForDevice(\n this._dependencies.device.id,\n this._dependencies.internalDevice.bleDeviceInfos.serviceUuid,\n this._dependencies.internalDevice.bleDeviceInfos.notifyUuid,\n (error, characteristic) => {\n if (!error && characteristic) {\n this.onMonitor(characteristic);\n }\n },\n );\n this._isDeviceReady.next(false);\n const requestMtuFrame = Uint8Array.from([0x08, 0x00, 0x00, 0x00, 0x00]);\n await this.write(Base64.fromUint8Array(requestMtuFrame));\n let sub: Subscription;\n await new Promise<void>((resolve) => {\n sub = this._isDeviceReady.subscribe((isReady) => {\n if (isReady) {\n resolve();\n sub.unsubscribe();\n }\n });\n });\n }\n\n async sendApdu(apdu: Uint8Array): Promise<Either<DmkError, ApduResponse>> {\n if (!this._isDeviceReady.value) {\n return Promise.resolve(\n Left(new DeviceNotInitializedError(\"Unknown MTU\")),\n );\n }\n\n const resultPromise = new Promise<Either<DmkError, ApduResponse>>(\n (resolve) => {\n this._sendApduPromiseResolver = Maybe.of(resolve);\n },\n );\n\n const frames = this._apduSender.caseOf({\n Just: (apduSender) => apduSender.getFrames(apdu),\n Nothing: () => [],\n });\n\n for (const frame of frames) {\n try {\n await this.write(Base64.fromUint8Array(frame.getRawData()));\n } catch (error) {\n this._logger.info(\"Error sending frame\", { data: { error } });\n }\n }\n\n return resultPromise;\n }\n\n public closeConnection() {\n this._dependencies.device.cancelConnection();\n }\n}\n"],
5
- "mappings": "AAMA,OASE,6BAAAA,MAIK,kCACP,OAAS,UAAAC,MAAc,YACvB,OAAsB,QAAAC,EAAM,SAAAC,EAAO,WAAAC,EAAS,SAAAC,MAAa,YACzD,OAAS,mBAAAC,MAA0C,OAEnD,MAAMC,EAAoB,EAsBnB,MAAMC,CAEb,CACU,cACA,eACA,QACA,YACS,mBACA,cACT,yBAIR,YACE,CACE,kBAAAC,EACA,oBAAAC,EACA,aAAAC,CACF,EACAC,EACA,CACA,KAAK,cAAgBD,EACrB,KAAK,eAAiB,IAAIL,EAAyB,EAAK,EACxD,KAAK,QAAUM,EAAqB,iBAAiB,EACrD,KAAK,mBAAqBH,EAC1B,KAAK,YAAcL,EACnB,KAAK,cAAgBM,EAAoB,EACzC,KAAK,yBAA2BN,CAClC,CAEQ,2BAA2BS,EAAmB,CACpD,MAAMC,EAAc,IAAI,WAAWD,CAAK,EAClC,CAAE,OAAAE,CAAO,EAAI,KAAK,cAElB,CAACC,CAAS,EAAIF,EAAY,MAAM,CAAC,EACvC,IAAIG,EAAYF,EAAO,IAAMR,EAEzBS,GAAaA,IAAcC,IAE7BA,EAAYD,GAEd,KAAK,YAAcb,EAAM,GAAG,KAAK,mBAAmB,CAAE,UAAAc,CAAU,CAAC,CAAC,EAClE,KAAK,eAAe,KAAK,EAAI,CAC/B,CAEQ,YAAYC,EAAkB,CACnB,KAAK,cAAc,YAAYA,CAAI,EAGjD,IAAKC,GAAsB,CAC1BA,EAAkB,IAAKC,GAAiB,CACtC,KAAK,QAAQ,MAAM,yBAA0B,CAC3C,KAAM,CAAE,SAAUA,CAAa,CACjC,CAAC,EACD,KAAK,yBAAyB,IAAKC,GACjCA,EAAQhB,EAAMe,CAAY,CAAC,CAC7B,CACF,CAAC,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yBAA2BlB,EAAM,GAAGkB,CAAO,CAClD,CACF,EAEMO,EAAS,KAAK,YAAY,OAAO,CACrC,KAAOC,GAAeA,EAAW,UAAUX,CAAI,EAC/C,QAAS,IAAM,CAAC,CAClB,CAAC,EAED,UAAWY,KAASF,EAClB,GAAI,CACF,MAAM,KAAK,MAAM3B,EAAO,eAAe6B,EAAM,WAAW,CAAC,CAAC,CAC5D,OAASR,EAAO,CACd,KAAK,QAAQ,KAAK,sBAAuB,CAAE,KAAM,CAAE,MAAAA,CAAM,CAAE,CAAC,CAC9D,CAGF,OAAOK,CACT,CAEO,iBAAkB,CACvB,KAAK,cAAc,OAAO,iBAAiB,CAC7C,CACF",
4
+ "sourcesContent": ["import {\n type BleManager,\n type Characteristic,\n type Device,\n type Subscription as RNBleSubscription,\n} from \"react-native-ble-plx\";\nimport {\n type ApduReceiverService,\n type ApduReceiverServiceFactory,\n type ApduResponse,\n type ApduSenderService,\n type ApduSenderServiceFactory,\n type BleDeviceInfos,\n type DeviceApduSender,\n type DeviceId,\n DeviceNotInitializedError,\n type DmkError,\n type LoggerPublisherService,\n type TransportDiscoveredDevice,\n} from \"@ledgerhq/device-management-kit\";\nimport { Base64 } from \"js-base64\";\nimport { type Either, Left, Maybe, Nothing, Right } from \"purify-ts\";\nimport { BehaviorSubject } from \"rxjs\";\n\nconst FRAME_HEADER_SIZE = 3;\n\nexport type RNBleInternalDevice = {\n id: DeviceId;\n bleDeviceInfos: BleDeviceInfos;\n discoveredDevice: TransportDiscoveredDevice;\n disconnectionSubscription: RNBleSubscription;\n lastDiscoveredTimeStamp: Maybe<number>;\n};\n\ntype RNBleApduSenderConstructorArgs = {\n dependencies: RNBleApduSenderDependencies;\n apduSenderFactory: ApduSenderServiceFactory;\n apduReceiverFactory: ApduReceiverServiceFactory;\n};\n\nexport type RNBleApduSenderDependencies = {\n device: Device;\n internalDevice: RNBleInternalDevice;\n manager: BleManager;\n};\n\nexport class RNBleApduSender\n implements DeviceApduSender<RNBleApduSenderDependencies>\n{\n private _dependencies: RNBleApduSenderDependencies;\n private _isDeviceReady: BehaviorSubject<boolean>;\n private _logger: LoggerPublisherService;\n private _apduSender: Maybe<ApduSenderService>;\n private readonly _apduSenderFactory: ApduSenderServiceFactory;\n private readonly _apduReceiver: ApduReceiverService;\n private _sendApduPromiseResolver: Maybe<\n (value: Either<DmkError, ApduResponse>) => void\n >;\n\n constructor(\n {\n apduSenderFactory,\n apduReceiverFactory,\n dependencies,\n }: RNBleApduSenderConstructorArgs,\n loggerServiceFactory: (tag: string) => LoggerPublisherService,\n ) {\n this._dependencies = dependencies;\n this._isDeviceReady = new BehaviorSubject<boolean>(false);\n this._logger = loggerServiceFactory(\"RNBleApduSender\");\n this._apduSenderFactory = apduSenderFactory;\n this._apduSender = Nothing;\n this._apduReceiver = apduReceiverFactory();\n this._sendApduPromiseResolver = Nothing;\n }\n\n private onReceiveSetupApduResponse(value: Uint8Array) {\n const mtuResponse = new Uint8Array(value);\n const { device } = this._dependencies;\n // ledger mtu is the 5th byte of the response\n const [ledgerMtu] = mtuResponse.slice(5);\n let frameSize = device.mtu - FRAME_HEADER_SIZE;\n\n if (ledgerMtu && ledgerMtu !== frameSize) {\n // should never happen since ble mtu is negotiated on device connect with 156 bytes and ledger should return mtu size minus header size\n frameSize = ledgerMtu;\n }\n this._apduSender = Maybe.of(this._apduSenderFactory({ frameSize }));\n this._isDeviceReady.next(true);\n }\n\n private receiveApdu(apdu: Uint8Array) {\n const response = this._apduReceiver.handleFrame(apdu);\n\n response\n .map((maybeApduResponse) => {\n maybeApduResponse.map((apduResponse) => {\n this._logger.debug(\"Received APDU Response\", {\n data: { response: apduResponse },\n });\n this._sendApduPromiseResolver.map((resolve) =>\n resolve(Right(apduResponse)),\n );\n });\n })\n .mapLeft((error) => {\n this._sendApduPromiseResolver.map((resolve) => resolve(Left(error)));\n });\n }\n\n private onMonitor(characteristic: Characteristic) {\n if (!characteristic.value) {\n return;\n }\n\n const apdu = Base64.toUint8Array(characteristic.value);\n if (!this._isDeviceReady.value) {\n this.onReceiveSetupApduResponse(apdu);\n } else {\n this.receiveApdu(apdu);\n }\n }\n\n private write(value: string) {\n return this._dependencies.manager.writeCharacteristicWithoutResponseForDevice(\n this._dependencies.device.id,\n this._dependencies.internalDevice.bleDeviceInfos.serviceUuid,\n this._dependencies.internalDevice.bleDeviceInfos.writeCmdUuid,\n value,\n );\n }\n\n public getDependencies() {\n return this._dependencies;\n }\n\n public setDependencies(dependencies: RNBleApduSenderDependencies) {\n this._dependencies = dependencies;\n }\n\n public async setupConnection() {\n this._dependencies.manager.monitorCharacteristicForDevice(\n this._dependencies.device.id,\n this._dependencies.internalDevice.bleDeviceInfos.serviceUuid,\n this._dependencies.internalDevice.bleDeviceInfos.notifyUuid,\n (error, characteristic) => {\n if (!error && characteristic) {\n this.onMonitor(characteristic);\n }\n },\n );\n this._isDeviceReady.next(false);\n const requestMtuFrame = Uint8Array.from([0x08, 0x00, 0x00, 0x00, 0x00]);\n await this.write(Base64.fromUint8Array(requestMtuFrame));\n await new Promise<void>((resolve) => {\n const sub = this._isDeviceReady.subscribe((isReady) => {\n if (isReady) {\n resolve();\n sub.unsubscribe();\n }\n });\n });\n }\n\n async sendApdu(apdu: Uint8Array): Promise<Either<DmkError, ApduResponse>> {\n if (!this._isDeviceReady.value) {\n return Promise.resolve(\n Left(new DeviceNotInitializedError(\"Unknown MTU\")),\n );\n }\n\n const resultPromise = new Promise<Either<DmkError, ApduResponse>>(\n (resolve) => {\n this._sendApduPromiseResolver = Maybe.of(resolve);\n },\n );\n\n const frames = this._apduSender.caseOf({\n Just: (apduSender) => apduSender.getFrames(apdu),\n Nothing: () => [],\n });\n\n for (const frame of frames) {\n try {\n await this.write(Base64.fromUint8Array(frame.getRawData()));\n } catch (error) {\n this._logger.info(\"Error sending frame\", { data: { error } });\n }\n }\n\n return resultPromise;\n }\n\n public closeConnection() {\n this._dependencies.device.cancelConnection();\n }\n}\n"],
5
+ "mappings": "AAMA,OASE,6BAAAA,MA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KAAK,MAAM3B,EAAO,eAAe6B,EAAM,WAAW,CAAC,CAAC,CAC5D,OAASR,EAAO,CACd,KAAK,QAAQ,KAAK,sBAAuB,CAAE,KAAM,CAAE,MAAAA,CAAM,CAAE,CAAC,CAC9D,CAGF,OAAOK,CACT,CAEO,iBAAkB,CACvB,KAAK,cAAc,OAAO,iBAAiB,CAC7C,CACF",
6
6
  "names": ["DeviceNotInitializedError", "Base64", "Left", "Maybe", "Nothing", "Right", "BehaviorSubject", "FRAME_HEADER_SIZE", "RNBleApduSender", "apduSenderFactory", "apduReceiverFactory", "dependencies", "loggerServiceFactory", "value", "mtuResponse", "device", "ledgerMtu", "frameSize", "apdu", "maybeApduResponse", "apduResponse", "resolve", "error", "characteristic", "requestMtuFrame", "sub", "isReady", "resultPromise", "frames", "apduSender", "frame"]
7
7
  }
@@ -1,2 +1,2 @@
1
- import{PermissionsAndroid as c,Platform as v}from"react-native";import{BleManager as m}from"react-native-ble-plx";import{DeviceConnectionStateMachine as y,OpeningConnectionError as I,TransportConnectedDevice as g,UnknownDeviceError as f}from"@ledgerhq/device-management-kit";import{EitherAsync as h,Maybe as o,Nothing as T,Right as N}from"purify-ts";import{from as p,map as E,mergeWith as C,Observable as S,repeat as b,retry as O,switchMap as l,throwError as B}from"rxjs";import{BLE_DISCONNECT_TIMEOUT as D,CONNECTION_LOST_DELAY as w,DEFAULT_MTU as _}from"../model/Const";import{DeviceConnectionNotFound as R,InternalDeviceNotFound as M}from"../model/Errors";import{RNBleApduSender as A}from"../transport/RNBleApduSender";const J="RN_BLE";class L{constructor(e,i,r,t){this._deviceModelDataSource=e;this._loggerServiceFactory=i;this._apduSenderFactory=r;this._apduReceiverFactory=t;this._logger=i("ReactNativeBleTransport"),this._manager=new m,this._isSupported=o.zero(),this._internalDevicesById=new Map,this._deviceConnectionsById=new Map,this.requestPermission(),this._reconnectionSubscription=o.zero()}_logger;_isSupported;_internalDevicesById;_deviceConnectionsById;_manager;identifier="RN_BLE";_reconnectionSubscription;_startDiscovering(){const e=this._deviceModelDataSource.getBluetoothServices();return p(this.requestPermission()).pipe(l(i=>{if(!i)throw new Error("BLE not supported");return this._discoverKnownDevices(e)}),C(this._discoverNewDevices(e)))}startDiscovering(){return this._startDiscovering()}async stopDiscovering(){await this._manager.stopDeviceScan()}async connect(e){return h(async({liftEither:i,throwE:r})=>{const t=await i(o.fromNullable(this._internalDevicesById.get(e.deviceId)).toEither(new f(`Unknown device ${e.deviceId}`)));let n;try{n=await this._manager.connectToDevice(e.deviceId,{requestMTU:_}),await this._manager.discoverAllServicesAndCharacteristicsForDevice(e.deviceId)}catch(a){return r(new I(a))}const s=new A({apduSenderFactory:this._apduSenderFactory,apduReceiverFactory:this._apduReceiverFactory,dependencies:{device:n,internalDevice:t,manager:this._manager}},this._loggerServiceFactory),d=new y({deviceId:e.deviceId,deviceApduSender:s,timeoutDuration:D,onTerminated:()=>{e.onDisconnect(e.deviceId),this._deviceConnectionsById.delete(e.deviceId);const a=this._internalDevicesById.get(e.deviceId);a&&a.disconnectionSubscription.remove(),this._internalDevicesById.delete(e.deviceId)}});return await s.setupConnection(),this._deviceConnectionsById.set(t.id,d),t.disconnectionSubscription=this._manager.onDeviceDisconnected(t.id,(...a)=>{this._handleDeviceDisconnected(...a)}),t.lastDiscoveredTimeStamp=o.zero(),new g({id:t.id,deviceModel:t.discoveredDevice.deviceModel,type:"BLE",sendApdu:(...a)=>d.sendApdu(...a),transport:this.identifier})}).run()}async disconnect(e){return o.fromNullable(this._deviceConnectionsById.get(e.connectedDevice.id)).map(r=>{r.closeConnection()}),Promise.resolve(N(void 0))}listenToAvailableDevices(){const e={};return this._startDiscovering().pipe(E(i=>(e[i.id]=i,Object.values(e).filter(r=>r.rssi!==null))))}isSupported(){return this._isSupported.caseOf({Just:e=>e,Nothing:()=>{throw new Error("Should initialize permission")}})}getIdentifier(){return this.identifier}async requestPermission(){if(v.OS==="ios")return this._isSupported=o.of(!0),!0;if(v.OS==="android"&&c.PERMISSIONS.ACCESS_FINE_LOCATION){if(parseInt(v.Version.toString(),10)<31){const i=await c.request(c.PERMISSIONS.ACCESS_FINE_LOCATION);this._isSupported=o.of(i===c.RESULTS.GRANTED)}if(c.PERMISSIONS.BLUETOOTH_SCAN&&c.PERMISSIONS.BLUETOOTH_CONNECT){const i=await c.requestMultiple([c.PERMISSIONS.BLUETOOTH_SCAN,c.PERMISSIONS.BLUETOOTH_CONNECT,c.PERMISSIONS.ACCESS_FINE_LOCATION]);return this._isSupported=o.of(i["android.permission.BLUETOOTH_CONNECT"]===c.RESULTS.GRANTED&&i["android.permission.BLUETOOTH_SCAN"]===c.RESULTS.GRANTED&&i["android.permission.ACCESS_FINE_LOCATION"]===c.RESULTS.GRANTED),!0}}return this._logger.error("Permission have not been granted",{data:{isSupported:this.isSupported()}}),this._isSupported=o.of(!1),!1}_getDiscoveredDeviceFrom(e,i){const r=o.fromNullable(e?.serviceUUIDs?.find(n=>i.includes(n))),t=o.fromNullable(this._internalDevicesById.get(e.id));return t.isJust()?t.map(n=>({bleDeviceInfos:n.bleDeviceInfos,discoveredDevice:{...n.discoveredDevice,rssi:e.rssi||void 0}})):r.mapOrDefault(n=>{const s=this._deviceModelDataSource.getBluetoothServicesInfos();return o.fromNullable(s[n]).map(a=>({discoveredDevice:{id:e.id,name:e.localName||a.deviceModel.productName,deviceModel:a.deviceModel,transport:this.identifier,rssi:e.rssi||void 0},bleDeviceInfos:a}))},T)}_isDiscoveredDeviceDelayOver(e){return e.lastDiscoveredTimeStamp.caseOf({Just:i=>Date.now()>i+w,Nothing:()=>!1})}async _handleLostDiscoveredDevices(e){const i=this._internalDevicesById.values().map(r=>async()=>{this._isDiscoveredDeviceDelayOver(r)&&!await this._manager.isDeviceConnected(r.id)&&(this._internalDevicesById.delete(r.id),e.next({...r.discoveredDevice,rssi:null}))});await Promise.all(i)}_emitDiscoveredDevice(e,i,r){e.next(r);const t={id:r.id,bleDeviceInfos:i,discoveredDevice:r,lastDiscoveredTimeStamp:o.of(Date.now())};this._internalDevicesById.set(r.id,{...t,disconnectionSubscription:this._manager.onDeviceDisconnected(r.id,()=>{e.next({...r,rssi:null})})})}_discoverNewDevices(e){return new S(i=>(this._manager.startDeviceScan(null,null,(r,t)=>{if(r||!t){i.error(r);return}this._getDiscoveredDeviceFrom(t,e).map(({discoveredDevice:n,bleDeviceInfos:s})=>{this._emitDiscoveredDevice(i,s,n)}),this._handleLostDiscoveredDevices(i)}),{unsubscribe:async()=>{await this._manager.stopDeviceScan(),i.unsubscribe()}}))}_discoverKnownDevices(e){return p(this._manager.connectedDevices(e)).pipe(l(i=>new S(r=>{for(const t of i)t.readRSSI().then(n=>{this._getDiscoveredDeviceFrom(n,e).map(({bleDeviceInfos:s,discoveredDevice:d})=>{this._emitDiscoveredDevice(r,s,d)})})})),b({delay:D/5}))}_handleDeviceDisconnected(e,i){if(e){this._logger.error("device disconnected error",{data:{error:e,device:i}});return}if(!i){this._logger.debug("disconnected handler didn't found device");return}if(this._reconnectionSubscription.isJust())return;const r=o.fromNullable(this._deviceConnectionsById.get(i.id));r.map(n=>{n.eventDeviceDetached()});let t;this._reconnectionSubscription=o.of(p([0]).pipe(l(async()=>{try{t=await i.connect({requestMTU:_}),t=await i.discoverAllServicesAndCharacteristics(),await this._handleDeviceReconnected(t)}catch(n){this._logger.error("[_handleDeviceDisconnected] Reconnecting failed",{data:{e:n}}),B(()=>n);return}return t}),O({count:5,delay:D/5})).subscribe({next:n=>this._logger.debug("[_handleDeviceDisconnected] Got new device after reconnection",{data:{value:n}}),complete:()=>{this._reconnectionSubscription=o.zero()},error:n=>{this._logger.error("[_handleDeviceDisconnected] Reconnection failed after all retries",{data:{e:n}}),this._reconnectionSubscription=o.zero(),r.map(s=>{s.closeConnection()})}}))}async _handleDeviceReconnected(e){const i=o.fromNullable(this._deviceConnectionsById.get(e.id)).toEither(new R),r=o.fromNullable(this._internalDevicesById.get(e.id)).toEither(new M);return h(async({liftEither:t})=>{const n=await t(i),s=await t(r);n.setDependencies({device:e,manager:this._manager,internalDevice:s}),await n.setupConnection(),n.eventDeviceAttached()}).run()}}const K=({deviceModelDataSource:u,loggerServiceFactory:e,apduSenderServiceFactory:i,apduReceiverServiceFactory:r})=>new L(u,e,i,r);export{L as RNBleTransport,K as RNBleTransportFactory,J as rnBleTransportIdentifier};
1
+ import{PermissionsAndroid as c,Platform as v}from"react-native";import{BleManager as m}from"react-native-ble-plx";import{DeviceConnectionStateMachine as y,OpeningConnectionError as I,TransportConnectedDevice as g,UnknownDeviceError as f}from"@ledgerhq/device-management-kit";import{EitherAsync as h,Maybe as o,Nothing as T,Right as N}from"purify-ts";import{from as l,map as E,mergeWith as C,Observable as S,repeat as O,retry as B,switchMap as p,throwError as b}from"rxjs";import{BLE_DISCONNECT_TIMEOUT as D,CONNECTION_LOST_DELAY as w,DEFAULT_MTU as _}from"../model/Const";import{DeviceConnectionNotFound as R,InternalDeviceNotFound as M}from"../model/Errors";import{RNBleApduSender as A}from"../transport/RNBleApduSender";const J="RN_BLE";class L{constructor(e,i,t,r){this._deviceModelDataSource=e;this._loggerServiceFactory=i;this._apduSenderFactory=t;this._apduReceiverFactory=r;this._logger=i("ReactNativeBleTransport"),this._manager=new m,this._isSupported=o.zero(),this._internalDevicesById=new Map,this._deviceConnectionsById=new Map,this.requestPermission(),this._reconnectionSubscription=o.zero()}_logger;_isSupported;_internalDevicesById;_deviceConnectionsById;_manager;identifier="RN_BLE";_reconnectionSubscription;_startDiscovering(){const e=this._deviceModelDataSource.getBluetoothServices();return l(this.requestPermission()).pipe(p(i=>{if(!i)throw new Error("BLE not supported");return this._discoverKnownDevices(e)}),C(this._discoverNewDevices(e)))}startDiscovering(){return this._startDiscovering()}async stopDiscovering(){await this._manager.stopDeviceScan()}async connect(e){return h(async({liftEither:i,throwE:t})=>{const r=await i(o.fromNullable(this._internalDevicesById.get(e.deviceId)).toEither(new f(`Unknown device ${e.deviceId}`)));let n;try{n=await this._manager.connectToDevice(e.deviceId,{requestMTU:_}),await this._manager.discoverAllServicesAndCharacteristicsForDevice(e.deviceId)}catch(a){return t(new I(a))}const s=new A({apduSenderFactory:this._apduSenderFactory,apduReceiverFactory:this._apduReceiverFactory,dependencies:{device:n,internalDevice:r,manager:this._manager}},this._loggerServiceFactory),d=new y({deviceId:e.deviceId,deviceApduSender:s,timeoutDuration:D,onTerminated:()=>{e.onDisconnect(e.deviceId),this._deviceConnectionsById.delete(e.deviceId);const a=this._internalDevicesById.get(e.deviceId);a&&a.disconnectionSubscription.remove(),this._internalDevicesById.delete(e.deviceId)}});return await s.setupConnection(),this._deviceConnectionsById.set(r.id,d),r.disconnectionSubscription=this._manager.onDeviceDisconnected(r.id,(...a)=>{this._handleDeviceDisconnected(...a)}),r.lastDiscoveredTimeStamp=o.zero(),new g({id:r.id,deviceModel:r.discoveredDevice.deviceModel,type:"BLE",sendApdu:(...a)=>d.sendApdu(...a),transport:this.identifier})}).run()}async disconnect(e){return o.fromNullable(this._deviceConnectionsById.get(e.connectedDevice.id)).map(t=>{t.closeConnection()}),Promise.resolve(N(void 0))}listenToAvailableDevices(){const e={};return this._startDiscovering().pipe(E(i=>(e[i.id]=i,Object.values(e).filter(t=>t.rssi!==null))))}isSupported(){return this._isSupported.caseOf({Just:e=>e,Nothing:()=>{throw new Error("Should initialize permission")}})}getIdentifier(){return this.identifier}async requestPermission(){if(v.OS==="ios")return this._isSupported=o.of(!0),!0;if(v.OS==="android"&&c.PERMISSIONS.ACCESS_FINE_LOCATION){if(parseInt(v.Version.toString(),10)<31){const i=await c.request(c.PERMISSIONS.ACCESS_FINE_LOCATION);this._isSupported=o.of(i===c.RESULTS.GRANTED)}if(c.PERMISSIONS.BLUETOOTH_SCAN&&c.PERMISSIONS.BLUETOOTH_CONNECT){const i=await c.requestMultiple([c.PERMISSIONS.BLUETOOTH_SCAN,c.PERMISSIONS.BLUETOOTH_CONNECT,c.PERMISSIONS.ACCESS_FINE_LOCATION]);return this._isSupported=o.of(i["android.permission.BLUETOOTH_CONNECT"]===c.RESULTS.GRANTED&&i["android.permission.BLUETOOTH_SCAN"]===c.RESULTS.GRANTED&&i["android.permission.ACCESS_FINE_LOCATION"]===c.RESULTS.GRANTED),!0}}return this._logger.error("Permission have not been granted",{data:{isSupported:this.isSupported()}}),this._isSupported=o.of(!1),!1}_getDiscoveredDeviceFrom(e,i){const t=o.fromNullable(e?.serviceUUIDs?.find(n=>i.includes(n))),r=o.fromNullable(this._internalDevicesById.get(e.id));return r.isJust()?r.map(n=>({bleDeviceInfos:n.bleDeviceInfos,discoveredDevice:{...n.discoveredDevice,rssi:e.rssi||void 0}})):t.mapOrDefault(n=>{const s=this._deviceModelDataSource.getBluetoothServicesInfos();return o.fromNullable(s[n]).map(a=>({discoveredDevice:{id:e.id,name:e.localName||a.deviceModel.productName,deviceModel:a.deviceModel,transport:this.identifier,rssi:e.rssi||void 0},bleDeviceInfos:a}))},T)}_isDiscoveredDeviceDelayOver(e){return e.lastDiscoveredTimeStamp.caseOf({Just:i=>Date.now()>i+w,Nothing:()=>!1})}async _handleLostDiscoveredDevices(e){for(const i of this._internalDevicesById.values())this._isDiscoveredDeviceDelayOver(i)&&!await this._manager.isDeviceConnected(i.id)&&(this._internalDevicesById.delete(i.id),e.next({...i.discoveredDevice,rssi:null}))}_emitDiscoveredDevice(e,i,t){e.next(t);const r={id:t.id,bleDeviceInfos:i,discoveredDevice:t,lastDiscoveredTimeStamp:o.of(Date.now())};this._internalDevicesById.set(t.id,{...r,disconnectionSubscription:this._manager.onDeviceDisconnected(t.id,()=>{e.next({...t,rssi:null})})})}_discoverNewDevices(e){return new S(i=>(this._manager.startDeviceScan(null,null,(t,r)=>{if(t||!r){i.error(t);return}this._getDiscoveredDeviceFrom(r,e).map(({discoveredDevice:n,bleDeviceInfos:s})=>{this._emitDiscoveredDevice(i,s,n)}),this._handleLostDiscoveredDevices(i)}),{unsubscribe:async()=>{await this._manager.stopDeviceScan(),i.unsubscribe()}}))}_discoverKnownDevices(e){return l(this._manager.connectedDevices(e)).pipe(p(i=>new S(t=>{for(const r of i)r.readRSSI().then(n=>{this._getDiscoveredDeviceFrom(n,e).map(({bleDeviceInfos:s,discoveredDevice:d})=>{this._emitDiscoveredDevice(t,s,d)})});this._handleLostDiscoveredDevices(t)})),O({delay:D/5}))}_handleDeviceDisconnected(e,i){if(e){this._logger.error("device disconnected error",{data:{error:e,device:i}});return}if(!i){this._logger.debug("disconnected handler didn't found device");return}if(this._reconnectionSubscription.isJust())return;const t=o.fromNullable(this._deviceConnectionsById.get(i.id));t.map(n=>{n.eventDeviceDetached()});let r;this._reconnectionSubscription=o.of(l([0]).pipe(p(async()=>{try{r=await i.connect({requestMTU:_}),r=await i.discoverAllServicesAndCharacteristics(),await this._handleDeviceReconnected(r)}catch(n){this._logger.error("[_handleDeviceDisconnected] Reconnecting failed",{data:{e:n}}),b(()=>n);return}return r}),B({count:5,delay:D/5})).subscribe({next:n=>this._logger.debug("[_handleDeviceDisconnected] Got new device after reconnection",{data:{value:n}}),complete:()=>{this._reconnectionSubscription=o.zero()},error:n=>{this._logger.error("[_handleDeviceDisconnected] Reconnection failed after all retries",{data:{e:n}}),this._reconnectionSubscription=o.zero(),t.map(s=>{s.closeConnection()})}}))}async _handleDeviceReconnected(e){const i=o.fromNullable(this._deviceConnectionsById.get(e.id)).toEither(new R),t=o.fromNullable(this._internalDevicesById.get(e.id)).toEither(new M);return h(async({liftEither:r})=>{const n=await r(i),s=await r(t);n.setDependencies({device:e,manager:this._manager,internalDevice:s}),await n.setupConnection(),n.eventDeviceAttached()}).run()}}const K=({deviceModelDataSource:u,loggerServiceFactory:e,apduSenderServiceFactory:i,apduReceiverServiceFactory:t})=>new L(u,e,i,t);export{L as RNBleTransport,K as RNBleTransportFactory,J as rnBleTransportIdentifier};
2
2
  //# sourceMappingURL=RNBleTransport.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/api/transport/RNBleTransport.ts"],
4
- "sourcesContent": ["import { PermissionsAndroid, Platform } from \"react-native\";\nimport { type BleError, BleManager, type Device } from \"react-native-ble-plx\";\nimport {\n type ApduReceiverServiceFactory,\n type ApduSenderServiceFactory,\n type BleDeviceInfos,\n type ConnectError,\n DeviceConnectionStateMachine,\n type DeviceId,\n type DeviceModelDataSource,\n type DisconnectHandler,\n type DmkError,\n type LoggerPublisherService,\n OpeningConnectionError,\n type Transport,\n TransportConnectedDevice,\n type TransportDiscoveredDevice,\n type TransportFactory,\n type TransportIdentifier,\n UnknownDeviceError,\n} from \"@ledgerhq/device-management-kit\";\nimport { type Either, EitherAsync, Maybe, Nothing, Right } from \"purify-ts\";\nimport {\n from,\n map,\n mergeWith,\n Observable,\n repeat,\n retry,\n type Subscriber,\n type Subscription,\n switchMap,\n throwError,\n} from \"rxjs\";\n\nimport {\n BLE_DISCONNECT_TIMEOUT,\n CONNECTION_LOST_DELAY,\n DEFAULT_MTU,\n} from \"@api/model/Const\";\nimport {\n DeviceConnectionNotFound,\n InternalDeviceNotFound,\n} from \"@api/model/Errors\";\nimport {\n RNBleApduSender,\n type RNBleApduSenderDependencies,\n type RNBleInternalDevice,\n} from \"@api/transport/RNBleApduSender\";\n\nexport const rnBleTransportIdentifier = \"RN_BLE\";\n\nexport class RNBleTransport implements Transport {\n private _logger: LoggerPublisherService;\n private _isSupported: Maybe<boolean>;\n private _internalDevicesById: Map<DeviceId, RNBleInternalDevice>;\n private _deviceConnectionsById: Map<\n DeviceId,\n DeviceConnectionStateMachine<RNBleApduSenderDependencies>\n >;\n private readonly _manager: BleManager;\n private readonly identifier: TransportIdentifier = \"RN_BLE\";\n private _reconnectionSubscription: Maybe<Subscription>;\n\n constructor(\n private readonly _deviceModelDataSource: DeviceModelDataSource,\n private readonly _loggerServiceFactory: (\n tag: string,\n ) => LoggerPublisherService,\n private readonly _apduSenderFactory: ApduSenderServiceFactory,\n private readonly _apduReceiverFactory: ApduReceiverServiceFactory,\n ) {\n this._logger = _loggerServiceFactory(\"ReactNativeBleTransport\");\n this._manager = new BleManager();\n this._isSupported = Maybe.zero();\n this._internalDevicesById = new Map();\n this._deviceConnectionsById = new Map();\n this.requestPermission();\n this._reconnectionSubscription = Maybe.zero();\n }\n\n private _startDiscovering() {\n const ledgerUuids = this._deviceModelDataSource.getBluetoothServices();\n return from(this.requestPermission()).pipe(\n switchMap((isSupported) => {\n if (!isSupported) {\n throw new Error(\"BLE not supported\");\n }\n return this._discoverKnownDevices(ledgerUuids);\n }),\n mergeWith(this._discoverNewDevices(ledgerUuids)),\n );\n }\n\n /**\n * Starts the discovery process to find Bluetooth devices that match specific criteria.\n *\n * This method clears the internal device cache and requests necessary permissions\n * before initiating the discovery of both known and new devices. If the Bluetooth\n * Low Energy (BLE) feature is not supported, an error is thrown.\n *\n * @return {Observable<TransportDiscoveredDevice>} An observable emitting discovered devices\n * that match the specified Bluetooth services.\n */\n startDiscovering(): Observable<TransportDiscoveredDevice> {\n return this._startDiscovering();\n }\n\n /**\n * Stops the device scanning operation currently in progress.\n *\n * @return {Promise<void>} A promise that resolves once the device scanning has been successfully stopped.\n */\n async stopDiscovering(): Promise<void> {\n await this._manager.stopDeviceScan();\n }\n\n /**\n * Establishes a connection to a device and configures the necessary parameters for communication.\n *\n * @param {Object} params - An object containing parameters required for the connection.\n * @param {DeviceId} params.deviceId - The unique identifier of the device to connect to.\n * @param {DisconnectHandler} params.onDisconnect - A callback function to handle device disconnection.\n * @returns {Promise<Either<ConnectError, TransportConnectedDevice>>} A promise resolving to either a connection error or a successfully connected device.\n */\n async connect(params: {\n deviceId: DeviceId;\n onDisconnect: DisconnectHandler;\n }): Promise<Either<ConnectError, TransportConnectedDevice>> {\n return EitherAsync<ConnectError, TransportConnectedDevice>(\n async ({ liftEither, throwE }) => {\n const internalDevice = await liftEither(\n Maybe.fromNullable(\n this._internalDevicesById.get(params.deviceId),\n ).toEither(\n new UnknownDeviceError(`Unknown device ${params.deviceId}`),\n ),\n );\n\n let device: Device;\n\n try {\n device = await this._manager.connectToDevice(params.deviceId, {\n requestMTU: DEFAULT_MTU,\n });\n await this._manager.discoverAllServicesAndCharacteristicsForDevice(\n params.deviceId,\n );\n } catch (error) {\n return throwE(new OpeningConnectionError(error));\n }\n\n const deviceApduSender = new RNBleApduSender(\n {\n apduSenderFactory: this._apduSenderFactory,\n apduReceiverFactory: this._apduReceiverFactory,\n dependencies: {\n device,\n internalDevice,\n manager: this._manager,\n },\n },\n this._loggerServiceFactory,\n );\n\n const deviceConnectionStateMachine =\n new DeviceConnectionStateMachine<RNBleApduSenderDependencies>({\n deviceId: params.deviceId,\n deviceApduSender,\n timeoutDuration: BLE_DISCONNECT_TIMEOUT,\n onTerminated: () => {\n params.onDisconnect(params.deviceId);\n this._deviceConnectionsById.delete(params.deviceId);\n const iDevice = this._internalDevicesById.get(params.deviceId);\n\n if (iDevice) {\n iDevice.disconnectionSubscription.remove();\n }\n\n this._internalDevicesById.delete(params.deviceId);\n },\n });\n\n await deviceApduSender.setupConnection();\n\n this._deviceConnectionsById.set(\n internalDevice.id,\n deviceConnectionStateMachine,\n );\n\n internalDevice.disconnectionSubscription =\n this._manager.onDeviceDisconnected(internalDevice.id, (...args) => {\n this._handleDeviceDisconnected(...args);\n });\n\n internalDevice.lastDiscoveredTimeStamp = Maybe.zero();\n\n return new TransportConnectedDevice({\n id: internalDevice.id,\n deviceModel: internalDevice.discoveredDevice.deviceModel,\n type: \"BLE\",\n sendApdu: (...args) => deviceConnectionStateMachine.sendApdu(...args),\n transport: this.identifier,\n });\n },\n ).run();\n }\n\n /**\n * Terminates the connection with the connected device and cleans up related resources.\n *\n * @param {TransportConnectedDevice} params.connectedDevice - The connected device to be disconnected.\n * @return {Promise<Either<DmkError, void>>} A promise resolving to either a success (void) or a failure (DmkError) value.\n */\n async disconnect(params: {\n connectedDevice: TransportConnectedDevice;\n }): Promise<Either<DmkError, void>> {\n const deviceConnection = Maybe.fromNullable(\n this._deviceConnectionsById.get(params.connectedDevice.id),\n );\n\n deviceConnection.map((d) => {\n d.closeConnection();\n });\n\n return Promise.resolve(Right(undefined));\n }\n\n /**\n * Listens to known devices and emits updates when new devices are discovered or when properties of existing devices are updated.\n *\n * @return {Observable<TransportDiscoveredDevice[]>} An observable stream of discovered devices, containing device information as an array of TransportDiscoveredDevice objects.\n */\n listenToAvailableDevices(): Observable<TransportDiscoveredDevice[]> {\n const scannedDeviceMap: Record<DeviceId, TransportDiscoveredDevice> = {};\n return this._startDiscovering().pipe(\n map((discoveredDevice) => {\n scannedDeviceMap[discoveredDevice.id] = discoveredDevice;\n return Object.values(scannedDeviceMap).filter(\n (device) => device.rssi !== null,\n );\n }),\n );\n }\n\n /**\n * Determines if the feature or permission is supported.\n *\n * This method evaluates the current state of the `_isSupported` property to determine\n * whether the relevant feature is supported or throws an error if its state has\n * not been initialized properly.\n *\n * @return {boolean} Returns `true` if the feature is supported, otherwise `false`.\n * Throws an error if the `_isSupported` property has not been initialized.\n */\n isSupported(): boolean {\n return this._isSupported.caseOf({\n Just: (isSupported) => isSupported,\n Nothing: () => {\n throw new Error(\"Should initialize permission\");\n },\n });\n }\n\n /**\n * Retrieves the transport identifier associated with the object.\n *\n * @return {TransportIdentifier} The transport identifier.\n */\n getIdentifier(): TransportIdentifier {\n return this.identifier;\n }\n\n /**\n * Requests the necessary permissions based on the operating system.\n * For iOS, it automatically sets the permissions as granted.\n * For Android, it checks and requests location, Bluetooth scan, and Bluetooth connect permissions, depending on the API level.\n * If permissions are granted, updates the internal support state and logs the result.\n *\n * @return {Promise<boolean>} A promise that resolves to true if the required permissions are granted, otherwise false.\n */\n async requestPermission(): Promise<boolean> {\n if (Platform.OS === \"ios\") {\n this._isSupported = Maybe.of(true);\n return true;\n }\n\n if (\n Platform.OS === \"android\" &&\n PermissionsAndroid.PERMISSIONS[\"ACCESS_FINE_LOCATION\"]\n ) {\n const apiLevel = parseInt(Platform.Version.toString(), 10);\n\n if (apiLevel < 31) {\n const granted = await PermissionsAndroid.request(\n PermissionsAndroid.PERMISSIONS[\"ACCESS_FINE_LOCATION\"],\n );\n this._isSupported = Maybe.of(\n granted === PermissionsAndroid.RESULTS[\"GRANTED\"],\n );\n }\n if (\n PermissionsAndroid.PERMISSIONS[\"BLUETOOTH_SCAN\"] &&\n PermissionsAndroid.PERMISSIONS[\"BLUETOOTH_CONNECT\"]\n ) {\n const result = await PermissionsAndroid.requestMultiple([\n PermissionsAndroid.PERMISSIONS[\"BLUETOOTH_SCAN\"],\n PermissionsAndroid.PERMISSIONS[\"BLUETOOTH_CONNECT\"],\n PermissionsAndroid.PERMISSIONS[\"ACCESS_FINE_LOCATION\"],\n ]);\n\n this._isSupported = Maybe.of(\n result[\"android.permission.BLUETOOTH_CONNECT\"] ===\n PermissionsAndroid.RESULTS[\"GRANTED\"] &&\n result[\"android.permission.BLUETOOTH_SCAN\"] ===\n PermissionsAndroid.RESULTS[\"GRANTED\"] &&\n result[\"android.permission.ACCESS_FINE_LOCATION\"] ===\n PermissionsAndroid.RESULTS[\"GRANTED\"],\n );\n\n return true;\n }\n }\n\n this._logger.error(\"Permission have not been granted\", {\n data: { isSupported: this.isSupported() },\n });\n\n this._isSupported = Maybe.of(false);\n return false;\n }\n\n /**\n * Retrieves a discovered device and its BLE device information, if available, from the provided input.\n *\n * @param {Device} rnDevice - The Bluetooth device to analyze for discovery.\n * @param {string[]} ledgerUuids - A list of UUIDs associated with the target Ledger devices.\n * @return {Maybe<{ bleDeviceInfos: BleDeviceInfos; discoveredDevice: TransportDiscoveredDevice }>} A Maybe object containing the discovered device and its BLE information, or Nothing if the device or information cannot be determined.\n */\n private _getDiscoveredDeviceFrom(\n rnDevice: Device,\n ledgerUuids: string[],\n ): Maybe<{\n bleDeviceInfos: BleDeviceInfos;\n discoveredDevice: TransportDiscoveredDevice;\n }> {\n const maybeUuid = Maybe.fromNullable(\n rnDevice?.serviceUUIDs?.find((uuid) => ledgerUuids.includes(uuid)),\n );\n\n const existingInternalDevice = Maybe.fromNullable(\n this._internalDevicesById.get(rnDevice.id),\n );\n\n if (existingInternalDevice.isJust()) {\n return existingInternalDevice.map((internalDevice) => ({\n bleDeviceInfos: internalDevice.bleDeviceInfos,\n discoveredDevice: {\n ...internalDevice.discoveredDevice,\n rssi: rnDevice.rssi || undefined,\n },\n }));\n }\n\n return maybeUuid.mapOrDefault((uuid) => {\n const serviceToBleInfos =\n this._deviceModelDataSource.getBluetoothServicesInfos();\n const maybeBleDeviceInfos = Maybe.fromNullable(serviceToBleInfos[uuid]);\n\n return maybeBleDeviceInfos.map((bleDeviceInfos) => {\n const discoveredDevice: TransportDiscoveredDevice = {\n id: rnDevice.id,\n name: rnDevice.localName || bleDeviceInfos.deviceModel.productName,\n deviceModel: bleDeviceInfos.deviceModel,\n transport: this.identifier,\n rssi: rnDevice.rssi || undefined,\n };\n\n return {\n discoveredDevice,\n bleDeviceInfos,\n };\n });\n }, Nothing);\n }\n\n /**\n * Determines whether the delay since the device was last discovered has exceeded a predefined threshold.\n *\n * @param {RNBleInternalDevice} internalDevice - The internal device object containing the last discovered timestamp.\n * @return {boolean} - Returns true if the delay is over, otherwise false.\n */\n private _isDiscoveredDeviceDelayOver(internalDevice: RNBleInternalDevice) {\n return internalDevice.lastDiscoveredTimeStamp.caseOf({\n Just: (lastDiscoveredTimeStamp) =>\n Date.now() > lastDiscoveredTimeStamp + CONNECTION_LOST_DELAY,\n Nothing: () => {\n return false;\n },\n });\n }\n\n /**\n * Handles the processing of devices that have been determined to be \"lost\" by iterating\n * through a collection of internal devices, identifying lost devices, updating their status,\n * and notifying a subscriber about the change.\n *\n * @param {Subscriber<TransportDiscoveredDevice>} subscriber - The observer that will be notified\n * when a device is marked as lost, including updated device information with its availability set to false.\n * @return {void} This method does not return a value.\n */\n private async _handleLostDiscoveredDevices(\n subscriber: Subscriber<TransportDiscoveredDevice>,\n ) {\n const promises = this._internalDevicesById\n .values()\n .map((internalDevice) => async () => {\n if (\n this._isDiscoveredDeviceDelayOver(internalDevice) &&\n !(await this._manager.isDeviceConnected(internalDevice.id))\n ) {\n this._internalDevicesById.delete(internalDevice.id);\n subscriber.next({\n ...internalDevice.discoveredDevice,\n rssi: null,\n });\n }\n });\n await Promise.all(promises);\n }\n\n /**\n * Emits a discovered device to the provided subscriber and manages internal state\n * for the discovered device, including handling its availability status and disconnection events.\n *\n * @param {Subscriber<TransportDiscoveredDevice>} subscriber The subscriber to emit the discovered device to.\n * @param {BleDeviceInfos} bleDeviceInfos The BLE device information associated with the discovered device.\n * @param {TransportDiscoveredDevice} discoveredDevice The newly discovered device to be emitted.\n * @return {void} */\n private _emitDiscoveredDevice(\n subscriber: Subscriber<TransportDiscoveredDevice>,\n bleDeviceInfos: BleDeviceInfos,\n discoveredDevice: TransportDiscoveredDevice,\n ) {\n subscriber.next(discoveredDevice);\n const internalDevice = {\n id: discoveredDevice.id,\n bleDeviceInfos,\n discoveredDevice,\n lastDiscoveredTimeStamp: Maybe.of(Date.now()),\n };\n this._internalDevicesById.set(discoveredDevice.id, {\n ...internalDevice,\n disconnectionSubscription: this._manager.onDeviceDisconnected(\n discoveredDevice.id,\n () => {\n subscriber.next({\n ...discoveredDevice,\n rssi: null,\n });\n },\n ),\n });\n }\n\n /**\n * Discovers new devices by scanning for BLE devices and filtering them based on the provided ledger UUIDs.\n *\n * @param {string[]} ledgerUuids - An array of UUIDs used to identify relevant ledger devices.\n * @return {Observable<TransportDiscoveredDevice>} An observable that emits discovered devices matching the provided UUIDs.\n */\n private _discoverNewDevices(\n ledgerUuids: string[],\n ): Observable<TransportDiscoveredDevice> {\n return new Observable<TransportDiscoveredDevice>((subscriber) => {\n this._manager.startDeviceScan(null, null, (error, device) => {\n if (error || !device) {\n subscriber.error(error);\n return;\n }\n\n this._getDiscoveredDeviceFrom(device, ledgerUuids).map(\n ({ discoveredDevice, bleDeviceInfos }) => {\n this._emitDiscoveredDevice(\n subscriber,\n bleDeviceInfos,\n discoveredDevice,\n );\n },\n );\n this._handleLostDiscoveredDevices(subscriber);\n });\n return {\n unsubscribe: async () => {\n await this._manager.stopDeviceScan();\n subscriber.unsubscribe();\n },\n };\n });\n }\n\n /**\n * Discovers and emits known ledger devices based on the provided UUIDs.\n *\n * @param {string[]} ledgerUuids - An array of UUIDs representing the target ledger devices to discover.\n * @return {Observable<TransportDiscoveredDevice>} An Observable that emits discovered devices matching the provided UUIDs.\n */\n private _discoverKnownDevices(\n ledgerUuids: string[],\n ): Observable<TransportDiscoveredDevice> {\n return from(this._manager.connectedDevices(ledgerUuids)).pipe(\n switchMap(\n (devices) =>\n new Observable<TransportDiscoveredDevice>((subscriber) => {\n for (const fromDevice of devices) {\n fromDevice.readRSSI().then((device) => {\n this._getDiscoveredDeviceFrom(device, ledgerUuids).map(\n ({ bleDeviceInfos, discoveredDevice }) => {\n this._emitDiscoveredDevice(\n subscriber,\n bleDeviceInfos,\n discoveredDevice,\n );\n },\n );\n });\n }\n }),\n ),\n repeat({ delay: BLE_DISCONNECT_TIMEOUT / 5 }),\n );\n }\n\n /**\n * Handles the event when a Bluetooth device gets disconnected. This method attempts\n * to reconnect to the device, retries a certain number of times on failure, and\n * invokes a callback if the reconnection does not succeed.\n *\n * @param {BleError | null} error - The error object representing the reason for the disconnection, or null if no error occurred.\n * @param {Device | null} device - The Bluetooth device that was disconnected, or null if no device is provided.\n * @return {void}\n */\n private _handleDeviceDisconnected(\n error: BleError | null,\n device: Device | null,\n ) {\n if (error) {\n this._logger.error(\"device disconnected error\", {\n data: { error, device },\n });\n return;\n }\n\n if (!device) {\n this._logger.debug(\"disconnected handler didn't found device\");\n return;\n }\n\n if (this._reconnectionSubscription.isJust()) {\n return;\n }\n\n const errorOrDeviceConnection = Maybe.fromNullable(\n this._deviceConnectionsById.get(device.id),\n );\n\n errorOrDeviceConnection.map((deviceConnection) => {\n deviceConnection.eventDeviceDetached();\n });\n\n let reconnectedDevice: Device;\n\n this._reconnectionSubscription = Maybe.of(\n from([0])\n .pipe(\n switchMap(async () => {\n try {\n reconnectedDevice = await device.connect({\n requestMTU: DEFAULT_MTU,\n });\n reconnectedDevice =\n await device.discoverAllServicesAndCharacteristics();\n await this._handleDeviceReconnected(reconnectedDevice);\n } catch (e) {\n this._logger.error(\n \"[_handleDeviceDisconnected] Reconnecting failed\",\n { data: { e } },\n );\n\n throwError(() => e);\n return;\n }\n return reconnectedDevice;\n }),\n retry({\n count: 5,\n delay: BLE_DISCONNECT_TIMEOUT / 5,\n }),\n )\n .subscribe({\n next: (value) =>\n this._logger.debug(\n \"[_handleDeviceDisconnected] Got new device after reconnection\",\n { data: { value } },\n ),\n complete: () => {\n this._reconnectionSubscription = Maybe.zero();\n },\n error: (e) => {\n this._logger.error(\n \"[_handleDeviceDisconnected] Reconnection failed after all retries\",\n { data: { e } },\n );\n this._reconnectionSubscription = Maybe.zero();\n errorOrDeviceConnection.map((deviceConnection) => {\n deviceConnection.closeConnection();\n });\n },\n }),\n );\n }\n\n /**\n * Handles the reconnection of a device. Configures the device connection and its corresponding\n * internal device upon reconnection, including updating the connection state, registering\n * callbacks for write and monitor operations, and initiating a reconnect operation.\n *\n * @param {Device} device - The device object that has been reconnected. Contains device details,\n * such as the device ID.\n * @return {Promise<Either<DeviceConnectionNotFound | InternalDeviceNotFound, void>>} A promise that completes when the device reconnection has been fully\n * configured. Resolves with no value or rejects if an error occurs during\n * the reconnection process.\n */\n private async _handleDeviceReconnected(device: Device) {\n const errorOrDeviceConnection = Maybe.fromNullable(\n this._deviceConnectionsById.get(device.id),\n ).toEither(new DeviceConnectionNotFound());\n\n const errorOrInternalDevice = Maybe.fromNullable(\n this._internalDevicesById.get(device.id),\n ).toEither(new InternalDeviceNotFound());\n\n return EitherAsync(async ({ liftEither }) => {\n const deviceConnectionStateMachine = await liftEither(\n errorOrDeviceConnection,\n );\n\n const internalDevice = await liftEither(errorOrInternalDevice);\n\n deviceConnectionStateMachine.setDependencies({\n device,\n manager: this._manager,\n internalDevice,\n });\n\n await deviceConnectionStateMachine.setupConnection();\n\n deviceConnectionStateMachine.eventDeviceAttached();\n }).run();\n }\n}\n\nexport const RNBleTransportFactory: TransportFactory = ({\n deviceModelDataSource,\n loggerServiceFactory,\n apduSenderServiceFactory,\n apduReceiverServiceFactory,\n}) =>\n new RNBleTransport(\n deviceModelDataSource,\n loggerServiceFactory,\n apduSenderServiceFactory,\n apduReceiverServiceFactory,\n );\n"],
5
- "mappings": "AAAA,OAAS,sBAAAA,EAAoB,YAAAC,MAAgB,eAC7C,OAAwB,cAAAC,MAA+B,uBACvD,OAKE,gCAAAC,EAMA,0BAAAC,EAEA,4BAAAC,EAIA,sBAAAC,MACK,kCACP,OAAsB,eAAAC,EAAa,SAAAC,EAAO,WAAAC,EAAS,SAAAC,MAAa,YAChE,OACE,QAAAC,EACA,OAAAC,EACA,aAAAC,EACA,cAAAC,EACA,UAAAC,EACA,SAAAC,EAGA,aAAAC,EACA,cAAAC,MACK,OAEP,OACE,0BAAAC,EACA,yBAAAC,EACA,eAAAC,MACK,mBACP,OACE,4BAAAC,EACA,0BAAAC,MACK,oBACP,OACE,mBAAAC,MAGK,iCAEA,MAAMC,EAA2B,SAEjC,MAAMC,CAAoC,CAY/C,YACmBC,EACAC,EAGAC,EACAC,EACjB,CANiB,4BAAAH,EACA,2BAAAC,EAGA,wBAAAC,EACA,0BAAAC,EAEjB,KAAK,QAAUF,EAAsB,yBAAyB,EAC9D,KAAK,SAAW,IAAI1B,EACpB,KAAK,aAAeM,EAAM,KAAK,EAC/B,KAAK,qBAAuB,IAAI,IAChC,KAAK,uBAAyB,IAAI,IAClC,KAAK,kBAAkB,EACvB,KAAK,0BAA4BA,EAAM,KAAK,CAC9C,CA1BQ,QACA,aACA,qBACA,uBAIS,SACA,WAAkC,SAC3C,0BAmBA,mBAAoB,CAC1B,MAAMuB,EAAc,KAAK,uBAAuB,qBAAqB,EACrE,OAAOpB,EAAK,KAAK,kBAAkB,CAAC,EAAE,KACpCM,EAAWe,GAAgB,CACzB,GAAI,CAACA,EACH,MAAM,IAAI,MAAM,mBAAmB,EAErC,OAAO,KAAK,sBAAsBD,CAAW,CAC/C,CAAC,EACDlB,EAAU,KAAK,oBAAoBkB,CAAW,CAAC,CACjD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,GACL,KAAK,QAAQ,MACX,gEACA,CAAE,KAAM,CAAE,MAAAA,CAAM,CAAE,CACpB,EACF,SAAU,IAAM,CACd,KAAK,0BAA4BvD,EAAM,KAAK,CAC9C,EACA,MAAQsD,GAAM,CACZ,KAAK,QAAQ,MACX,oEACA,CAAE,KAAM,CAAE,EAAAA,CAAE,CAAE,CAChB,EACA,KAAK,0BAA4BtD,EAAM,KAAK,EAC5CmD,EAAwB,IAAKC,GAAqB,CAChDA,EAAiB,gBAAgB,CACnC,CAAC,CACH,CACF,CAAC,CACL,CACF,CAaA,MAAc,yBAAyBvB,EAAgB,CACrD,MAAMsB,EAA0BnD,EAAM,aACpC,KAAK,uBAAuB,IAAI6B,EAAO,EAAE,CAC3C,EAAE,SAAS,IAAIf,CAA0B,EAEnC0C,EAAwBxD,EAAM,aAClC,KAAK,qBAAqB,IAAI6B,EAAO,EAAE,CACzC,EAAE,SAAS,IAAId,CAAwB,EAEvC,OAAOhB,EAAY,MAAO,CAAE,WAAA2B,CAAW,IAAM,CAC3C,MAAMM,EAA+B,MAAMN,EACzCyB,CACF,EAEMvB,EAAiB,MAAMF,EAAW8B,CAAqB,EAE7DxB,EAA6B,gBAAgB,CAC3C,OAAAH,EACA,QAAS,KAAK,SACd,eAAAD,CACF,CAAC,EAED,MAAMI,EAA6B,gBAAgB,EAEnDA,EAA6B,oBAAoB,CACnD,CAAC,EAAE,IAAI,CACT,CACF,CAEO,MAAMyB,EAA0C,CAAC,CACtD,sBAAAC,EACA,qBAAAC,EACA,yBAAAC,EACA,2BAAAC,CACF,IACE,IAAI3C,EACFwC,EACAC,EACAC,EACAC,CACF",
6
- "names": ["PermissionsAndroid", "Platform", "BleManager", "DeviceConnectionStateMachine", "OpeningConnectionError", "TransportConnectedDevice", "UnknownDeviceError", "EitherAsync", "Maybe", "Nothing", "Right", "from", "map", "mergeWith", "Observable", "repeat", "retry", "switchMap", "throwError", "BLE_DISCONNECT_TIMEOUT", "CONNECTION_LOST_DELAY", "DEFAULT_MTU", "DeviceConnectionNotFound", "InternalDeviceNotFound", "RNBleApduSender", "rnBleTransportIdentifier", "RNBleTransport", "_deviceModelDataSource", "_loggerServiceFactory", "_apduSenderFactory", "_apduReceiverFactory", "ledgerUuids", "isSupported", "params", "liftEither", "throwE", "internalDevice", "device", "error", "deviceApduSender", "deviceConnectionStateMachine", "iDevice", "args", "d", "scannedDeviceMap", "discoveredDevice", "granted", "result", "rnDevice", "maybeUuid", "uuid", "existingInternalDevice", "serviceToBleInfos", "bleDeviceInfos", "lastDiscoveredTimeStamp", "subscriber", "promises", "devices", "fromDevice", "errorOrDeviceConnection", "deviceConnection", "reconnectedDevice", "e", "value", "errorOrInternalDevice", "RNBleTransportFactory", "deviceModelDataSource", "loggerServiceFactory", "apduSenderServiceFactory", "apduReceiverServiceFactory"]
4
+ "sourcesContent": ["import { PermissionsAndroid, Platform } from \"react-native\";\nimport { type BleError, BleManager, type Device } from \"react-native-ble-plx\";\nimport {\n type ApduReceiverServiceFactory,\n type ApduSenderServiceFactory,\n type BleDeviceInfos,\n type ConnectError,\n DeviceConnectionStateMachine,\n type DeviceId,\n type DeviceModelDataSource,\n type DisconnectHandler,\n type DmkError,\n type LoggerPublisherService,\n OpeningConnectionError,\n type Transport,\n TransportConnectedDevice,\n type TransportDiscoveredDevice,\n type TransportFactory,\n type TransportIdentifier,\n UnknownDeviceError,\n} from \"@ledgerhq/device-management-kit\";\nimport { type Either, EitherAsync, Maybe, Nothing, Right } from \"purify-ts\";\nimport {\n from,\n map,\n mergeWith,\n Observable,\n repeat,\n retry,\n type Subscriber,\n type Subscription,\n switchMap,\n throwError,\n} from \"rxjs\";\n\nimport {\n BLE_DISCONNECT_TIMEOUT,\n CONNECTION_LOST_DELAY,\n DEFAULT_MTU,\n} from \"@api/model/Const\";\nimport {\n DeviceConnectionNotFound,\n InternalDeviceNotFound,\n} from \"@api/model/Errors\";\nimport {\n RNBleApduSender,\n type RNBleApduSenderDependencies,\n type RNBleInternalDevice,\n} from \"@api/transport/RNBleApduSender\";\n\nexport const rnBleTransportIdentifier = \"RN_BLE\";\n\nexport class RNBleTransport implements Transport {\n private _logger: LoggerPublisherService;\n private _isSupported: Maybe<boolean>;\n private _internalDevicesById: Map<DeviceId, RNBleInternalDevice>;\n private _deviceConnectionsById: Map<\n DeviceId,\n DeviceConnectionStateMachine<RNBleApduSenderDependencies>\n >;\n private readonly _manager: BleManager;\n private readonly identifier: TransportIdentifier = \"RN_BLE\";\n private _reconnectionSubscription: Maybe<Subscription>;\n\n constructor(\n private readonly _deviceModelDataSource: DeviceModelDataSource,\n private readonly _loggerServiceFactory: (\n tag: string,\n ) => LoggerPublisherService,\n private readonly _apduSenderFactory: ApduSenderServiceFactory,\n private readonly _apduReceiverFactory: ApduReceiverServiceFactory,\n ) {\n this._logger = _loggerServiceFactory(\"ReactNativeBleTransport\");\n this._manager = new BleManager();\n this._isSupported = Maybe.zero();\n this._internalDevicesById = new Map();\n this._deviceConnectionsById = new Map();\n this.requestPermission();\n this._reconnectionSubscription = Maybe.zero();\n }\n\n private _startDiscovering() {\n const ledgerUuids = this._deviceModelDataSource.getBluetoothServices();\n return from(this.requestPermission()).pipe(\n switchMap((isSupported) => {\n if (!isSupported) {\n throw new Error(\"BLE not supported\");\n }\n return this._discoverKnownDevices(ledgerUuids);\n }),\n mergeWith(this._discoverNewDevices(ledgerUuids)),\n );\n }\n\n /**\n * Starts the discovery process to find Bluetooth devices that match specific criteria.\n *\n * This method clears the internal device cache and requests necessary permissions\n * before initiating the discovery of both known and new devices. If the Bluetooth\n * Low Energy (BLE) feature is not supported, an error is thrown.\n *\n * @return {Observable<TransportDiscoveredDevice>} An observable emitting discovered devices\n * that match the specified Bluetooth services.\n */\n startDiscovering(): Observable<TransportDiscoveredDevice> {\n return this._startDiscovering();\n }\n\n /**\n * Stops the device scanning operation currently in progress.\n *\n * @return {Promise<void>} A promise that resolves once the device scanning has been successfully stopped.\n */\n async stopDiscovering(): Promise<void> {\n await this._manager.stopDeviceScan();\n }\n\n /**\n * Establishes a connection to a device and configures the necessary parameters for communication.\n *\n * @param {Object} params - An object containing parameters required for the connection.\n * @param {DeviceId} params.deviceId - The unique identifier of the device to connect to.\n * @param {DisconnectHandler} params.onDisconnect - A callback function to handle device disconnection.\n * @returns {Promise<Either<ConnectError, TransportConnectedDevice>>} A promise resolving to either a connection error or a successfully connected device.\n */\n async connect(params: {\n deviceId: DeviceId;\n onDisconnect: DisconnectHandler;\n }): Promise<Either<ConnectError, TransportConnectedDevice>> {\n return EitherAsync<ConnectError, TransportConnectedDevice>(\n async ({ liftEither, throwE }) => {\n const internalDevice = await liftEither(\n Maybe.fromNullable(\n this._internalDevicesById.get(params.deviceId),\n ).toEither(\n new UnknownDeviceError(`Unknown device ${params.deviceId}`),\n ),\n );\n\n let device: Device;\n\n try {\n device = await this._manager.connectToDevice(params.deviceId, {\n requestMTU: DEFAULT_MTU,\n });\n await this._manager.discoverAllServicesAndCharacteristicsForDevice(\n params.deviceId,\n );\n } catch (error) {\n return throwE(new OpeningConnectionError(error));\n }\n\n const deviceApduSender = new RNBleApduSender(\n {\n apduSenderFactory: this._apduSenderFactory,\n apduReceiverFactory: this._apduReceiverFactory,\n dependencies: {\n device,\n internalDevice,\n manager: this._manager,\n },\n },\n this._loggerServiceFactory,\n );\n\n const deviceConnectionStateMachine =\n new DeviceConnectionStateMachine<RNBleApduSenderDependencies>({\n deviceId: params.deviceId,\n deviceApduSender,\n timeoutDuration: BLE_DISCONNECT_TIMEOUT,\n onTerminated: () => {\n params.onDisconnect(params.deviceId);\n this._deviceConnectionsById.delete(params.deviceId);\n const iDevice = this._internalDevicesById.get(params.deviceId);\n\n if (iDevice) {\n iDevice.disconnectionSubscription.remove();\n }\n\n this._internalDevicesById.delete(params.deviceId);\n },\n });\n\n await deviceApduSender.setupConnection();\n\n this._deviceConnectionsById.set(\n internalDevice.id,\n deviceConnectionStateMachine,\n );\n\n internalDevice.disconnectionSubscription =\n this._manager.onDeviceDisconnected(internalDevice.id, (...args) => {\n this._handleDeviceDisconnected(...args);\n });\n\n internalDevice.lastDiscoveredTimeStamp = Maybe.zero();\n\n return new TransportConnectedDevice({\n id: internalDevice.id,\n deviceModel: internalDevice.discoveredDevice.deviceModel,\n type: \"BLE\",\n sendApdu: (...args) => deviceConnectionStateMachine.sendApdu(...args),\n transport: this.identifier,\n });\n },\n ).run();\n }\n\n /**\n * Terminates the connection with the connected device and cleans up related resources.\n *\n * @param {TransportConnectedDevice} params.connectedDevice - The connected device to be disconnected.\n * @return {Promise<Either<DmkError, void>>} A promise resolving to either a success (void) or a failure (DmkError) value.\n */\n async disconnect(params: {\n connectedDevice: TransportConnectedDevice;\n }): Promise<Either<DmkError, void>> {\n const deviceConnection = Maybe.fromNullable(\n this._deviceConnectionsById.get(params.connectedDevice.id),\n );\n\n deviceConnection.map((d) => {\n d.closeConnection();\n });\n\n return Promise.resolve(Right(undefined));\n }\n\n /**\n * Listens to known devices and emits updates when new devices are discovered or when properties of existing devices are updated.\n *\n * @return {Observable<TransportDiscoveredDevice[]>} An observable stream of discovered devices, containing device information as an array of TransportDiscoveredDevice objects.\n */\n listenToAvailableDevices(): Observable<TransportDiscoveredDevice[]> {\n const scannedDeviceMap: Record<DeviceId, TransportDiscoveredDevice> = {};\n return this._startDiscovering().pipe(\n map((discoveredDevice) => {\n scannedDeviceMap[discoveredDevice.id] = discoveredDevice;\n return Object.values(scannedDeviceMap).filter(\n (device) => device.rssi !== null,\n );\n }),\n );\n }\n\n /**\n * Determines if the feature or permission is supported.\n *\n * This method evaluates the current state of the `_isSupported` property to determine\n * whether the relevant feature is supported or throws an error if its state has\n * not been initialized properly.\n *\n * @return {boolean} Returns `true` if the feature is supported, otherwise `false`.\n * Throws an error if the `_isSupported` property has not been initialized.\n */\n isSupported(): boolean {\n return this._isSupported.caseOf({\n Just: (isSupported) => isSupported,\n Nothing: () => {\n throw new Error(\"Should initialize permission\");\n },\n });\n }\n\n /**\n * Retrieves the transport identifier associated with the object.\n *\n * @return {TransportIdentifier} The transport identifier.\n */\n getIdentifier(): TransportIdentifier {\n return this.identifier;\n }\n\n /**\n * Requests the necessary permissions based on the operating system.\n * For iOS, it automatically sets the permissions as granted.\n * For Android, it checks and requests location, Bluetooth scan, and Bluetooth connect permissions, depending on the API level.\n * If permissions are granted, updates the internal support state and logs the result.\n *\n * @return {Promise<boolean>} A promise that resolves to true if the required permissions are granted, otherwise false.\n */\n async requestPermission(): Promise<boolean> {\n if (Platform.OS === \"ios\") {\n this._isSupported = Maybe.of(true);\n return true;\n }\n\n if (\n Platform.OS === \"android\" &&\n PermissionsAndroid.PERMISSIONS[\"ACCESS_FINE_LOCATION\"]\n ) {\n const apiLevel = parseInt(Platform.Version.toString(), 10);\n\n if (apiLevel < 31) {\n const granted = await PermissionsAndroid.request(\n PermissionsAndroid.PERMISSIONS[\"ACCESS_FINE_LOCATION\"],\n );\n this._isSupported = Maybe.of(\n granted === PermissionsAndroid.RESULTS[\"GRANTED\"],\n );\n }\n if (\n PermissionsAndroid.PERMISSIONS[\"BLUETOOTH_SCAN\"] &&\n PermissionsAndroid.PERMISSIONS[\"BLUETOOTH_CONNECT\"]\n ) {\n const result = await PermissionsAndroid.requestMultiple([\n PermissionsAndroid.PERMISSIONS[\"BLUETOOTH_SCAN\"],\n PermissionsAndroid.PERMISSIONS[\"BLUETOOTH_CONNECT\"],\n PermissionsAndroid.PERMISSIONS[\"ACCESS_FINE_LOCATION\"],\n ]);\n\n this._isSupported = Maybe.of(\n result[\"android.permission.BLUETOOTH_CONNECT\"] ===\n PermissionsAndroid.RESULTS[\"GRANTED\"] &&\n result[\"android.permission.BLUETOOTH_SCAN\"] ===\n PermissionsAndroid.RESULTS[\"GRANTED\"] &&\n result[\"android.permission.ACCESS_FINE_LOCATION\"] ===\n PermissionsAndroid.RESULTS[\"GRANTED\"],\n );\n\n return true;\n }\n }\n\n this._logger.error(\"Permission have not been granted\", {\n data: { isSupported: this.isSupported() },\n });\n\n this._isSupported = Maybe.of(false);\n return false;\n }\n\n /**\n * Retrieves a discovered device and its BLE device information, if available, from the provided input.\n *\n * @param {Device} rnDevice - The Bluetooth device to analyze for discovery.\n * @param {string[]} ledgerUuids - A list of UUIDs associated with the target Ledger devices.\n * @return {Maybe<{ bleDeviceInfos: BleDeviceInfos; discoveredDevice: TransportDiscoveredDevice }>} A Maybe object containing the discovered device and its BLE information, or Nothing if the device or information cannot be determined.\n */\n private _getDiscoveredDeviceFrom(\n rnDevice: Device,\n ledgerUuids: string[],\n ): Maybe<{\n bleDeviceInfos: BleDeviceInfos;\n discoveredDevice: TransportDiscoveredDevice;\n }> {\n const maybeUuid = Maybe.fromNullable(\n rnDevice?.serviceUUIDs?.find((uuid) => ledgerUuids.includes(uuid)),\n );\n\n const existingInternalDevice = Maybe.fromNullable(\n this._internalDevicesById.get(rnDevice.id),\n );\n\n if (existingInternalDevice.isJust()) {\n return existingInternalDevice.map((internalDevice) => ({\n bleDeviceInfos: internalDevice.bleDeviceInfos,\n discoveredDevice: {\n ...internalDevice.discoveredDevice,\n rssi: rnDevice.rssi || undefined,\n },\n }));\n }\n\n return maybeUuid.mapOrDefault((uuid) => {\n const serviceToBleInfos =\n this._deviceModelDataSource.getBluetoothServicesInfos();\n const maybeBleDeviceInfos = Maybe.fromNullable(serviceToBleInfos[uuid]);\n\n return maybeBleDeviceInfos.map((bleDeviceInfos) => {\n const discoveredDevice: TransportDiscoveredDevice = {\n id: rnDevice.id,\n name: rnDevice.localName || bleDeviceInfos.deviceModel.productName,\n deviceModel: bleDeviceInfos.deviceModel,\n transport: this.identifier,\n rssi: rnDevice.rssi || undefined,\n };\n\n return {\n discoveredDevice,\n bleDeviceInfos,\n };\n });\n }, Nothing);\n }\n\n /**\n * Determines whether the delay since the device was last discovered has exceeded a predefined threshold.\n *\n * @param {RNBleInternalDevice} internalDevice - The internal device object containing the last discovered timestamp.\n * @return {boolean} - Returns true if the delay is over, otherwise false.\n */\n private _isDiscoveredDeviceDelayOver(internalDevice: RNBleInternalDevice) {\n return internalDevice.lastDiscoveredTimeStamp.caseOf({\n Just: (lastDiscoveredTimeStamp) =>\n Date.now() > lastDiscoveredTimeStamp + CONNECTION_LOST_DELAY,\n Nothing: () => {\n return false;\n },\n });\n }\n\n /**\n * Handles the processing of devices that have been determined to be \"lost\" by iterating\n * through a collection of internal devices, identifying lost devices, updating their status,\n * and notifying a subscriber about the change.\n *\n * @param {Subscriber<TransportDiscoveredDevice>} subscriber - The observer that will be notified\n * when a device is marked as lost, including updated device information with its availability set to false.\n * @return {void} This method does not return a value.\n */\n private async _handleLostDiscoveredDevices(\n subscriber: Subscriber<TransportDiscoveredDevice>,\n ) {\n for (const internalDevice of this._internalDevicesById.values()) {\n if (\n this._isDiscoveredDeviceDelayOver(internalDevice) &&\n !(await this._manager.isDeviceConnected(internalDevice.id))\n ) {\n this._internalDevicesById.delete(internalDevice.id);\n subscriber.next({\n ...internalDevice.discoveredDevice,\n rssi: null,\n });\n }\n }\n }\n\n /**\n * Emits a discovered device to the provided subscriber and manages internal state\n * for the discovered device, including handling its availability status and disconnection events.\n *\n * @param {Subscriber<TransportDiscoveredDevice>} subscriber The subscriber to emit the discovered device to.\n * @param {BleDeviceInfos} bleDeviceInfos The BLE device information associated with the discovered device.\n * @param {TransportDiscoveredDevice} discoveredDevice The newly discovered device to be emitted.\n * @return {void} */\n private _emitDiscoveredDevice(\n subscriber: Subscriber<TransportDiscoveredDevice>,\n bleDeviceInfos: BleDeviceInfos,\n discoveredDevice: TransportDiscoveredDevice,\n ) {\n subscriber.next(discoveredDevice);\n const internalDevice = {\n id: discoveredDevice.id,\n bleDeviceInfos,\n discoveredDevice,\n lastDiscoveredTimeStamp: Maybe.of(Date.now()),\n };\n this._internalDevicesById.set(discoveredDevice.id, {\n ...internalDevice,\n disconnectionSubscription: this._manager.onDeviceDisconnected(\n discoveredDevice.id,\n () => {\n subscriber.next({\n ...discoveredDevice,\n rssi: null,\n });\n },\n ),\n });\n }\n\n /**\n * Discovers new devices by scanning for BLE devices and filtering them based on the provided ledger UUIDs.\n *\n * @param {string[]} ledgerUuids - An array of UUIDs used to identify relevant ledger devices.\n * @return {Observable<TransportDiscoveredDevice>} An observable that emits discovered devices matching the provided UUIDs.\n */\n private _discoverNewDevices(\n ledgerUuids: string[],\n ): Observable<TransportDiscoveredDevice> {\n return new Observable<TransportDiscoveredDevice>((subscriber) => {\n this._manager.startDeviceScan(null, null, (error, device) => {\n if (error || !device) {\n subscriber.error(error);\n return;\n }\n\n this._getDiscoveredDeviceFrom(device, ledgerUuids).map(\n ({ discoveredDevice, bleDeviceInfos }) => {\n this._emitDiscoveredDevice(\n subscriber,\n bleDeviceInfos,\n discoveredDevice,\n );\n },\n );\n this._handleLostDiscoveredDevices(subscriber);\n });\n return {\n unsubscribe: async () => {\n await this._manager.stopDeviceScan();\n subscriber.unsubscribe();\n },\n };\n });\n }\n\n /**\n * Discovers and emits known ledger devices based on the provided UUIDs.\n *\n * @param {string[]} ledgerUuids - An array of UUIDs representing the target ledger devices to discover.\n * @return {Observable<TransportDiscoveredDevice>} An Observable that emits discovered devices matching the provided UUIDs.\n */\n private _discoverKnownDevices(\n ledgerUuids: string[],\n ): Observable<TransportDiscoveredDevice> {\n return from(this._manager.connectedDevices(ledgerUuids)).pipe(\n switchMap(\n (devices) =>\n new Observable<TransportDiscoveredDevice>((subscriber) => {\n for (const fromDevice of devices) {\n fromDevice.readRSSI().then((device) => {\n this._getDiscoveredDeviceFrom(device, ledgerUuids).map(\n ({ bleDeviceInfos, discoveredDevice }) => {\n this._emitDiscoveredDevice(\n subscriber,\n bleDeviceInfos,\n discoveredDevice,\n );\n },\n );\n });\n }\n this._handleLostDiscoveredDevices(subscriber);\n }),\n ),\n repeat({ delay: BLE_DISCONNECT_TIMEOUT / 5 }),\n );\n }\n\n /**\n * Handles the event when a Bluetooth device gets disconnected. This method attempts\n * to reconnect to the device, retries a certain number of times on failure, and\n * invokes a callback if the reconnection does not succeed.\n *\n * @param {BleError | null} error - The error object representing the reason for the disconnection, or null if no error occurred.\n * @param {Device | null} device - The Bluetooth device that was disconnected, or null if no device is provided.\n * @return {void}\n */\n private _handleDeviceDisconnected(\n error: BleError | null,\n device: Device | null,\n ) {\n if (error) {\n this._logger.error(\"device disconnected error\", {\n data: { error, device },\n });\n return;\n }\n\n if (!device) {\n this._logger.debug(\"disconnected handler didn't found device\");\n return;\n }\n\n if (this._reconnectionSubscription.isJust()) {\n return;\n }\n\n const errorOrDeviceConnection = Maybe.fromNullable(\n this._deviceConnectionsById.get(device.id),\n );\n\n errorOrDeviceConnection.map((deviceConnection) => {\n deviceConnection.eventDeviceDetached();\n });\n\n let reconnectedDevice: Device;\n\n this._reconnectionSubscription = Maybe.of(\n from([0])\n .pipe(\n switchMap(async () => {\n try {\n reconnectedDevice = await device.connect({\n requestMTU: DEFAULT_MTU,\n });\n reconnectedDevice =\n await device.discoverAllServicesAndCharacteristics();\n await this._handleDeviceReconnected(reconnectedDevice);\n } catch (e) {\n this._logger.error(\n \"[_handleDeviceDisconnected] Reconnecting failed\",\n { data: { e } },\n );\n\n throwError(() => e);\n return;\n }\n return reconnectedDevice;\n }),\n retry({\n count: 5,\n delay: BLE_DISCONNECT_TIMEOUT / 5,\n }),\n )\n .subscribe({\n next: (value) =>\n this._logger.debug(\n \"[_handleDeviceDisconnected] Got new device after reconnection\",\n { data: { value } },\n ),\n complete: () => {\n this._reconnectionSubscription = Maybe.zero();\n },\n error: (e) => {\n this._logger.error(\n \"[_handleDeviceDisconnected] Reconnection failed after all retries\",\n { data: { e } },\n );\n this._reconnectionSubscription = Maybe.zero();\n errorOrDeviceConnection.map((deviceConnection) => {\n deviceConnection.closeConnection();\n });\n },\n }),\n );\n }\n\n /**\n * Handles the reconnection of a device. Configures the device connection and its corresponding\n * internal device upon reconnection, including updating the connection state, registering\n * callbacks for write and monitor operations, and initiating a reconnect operation.\n *\n * @param {Device} device - The device object that has been reconnected. Contains device details,\n * such as the device ID.\n * @return {Promise<Either<DeviceConnectionNotFound | InternalDeviceNotFound, void>>} A promise that completes when the device reconnection has been fully\n * configured. Resolves with no value or rejects if an error occurs during\n * the reconnection process.\n */\n private async _handleDeviceReconnected(device: Device) {\n const errorOrDeviceConnection = Maybe.fromNullable(\n this._deviceConnectionsById.get(device.id),\n ).toEither(new DeviceConnectionNotFound());\n\n const errorOrInternalDevice = Maybe.fromNullable(\n this._internalDevicesById.get(device.id),\n ).toEither(new InternalDeviceNotFound());\n\n return EitherAsync(async ({ liftEither }) => {\n const deviceConnectionStateMachine = await liftEither(\n errorOrDeviceConnection,\n );\n\n const internalDevice = await liftEither(errorOrInternalDevice);\n\n deviceConnectionStateMachine.setDependencies({\n device,\n manager: this._manager,\n internalDevice,\n });\n\n await deviceConnectionStateMachine.setupConnection();\n\n deviceConnectionStateMachine.eventDeviceAttached();\n }).run();\n }\n}\n\nexport const RNBleTransportFactory: TransportFactory = ({\n deviceModelDataSource,\n loggerServiceFactory,\n apduSenderServiceFactory,\n apduReceiverServiceFactory,\n}) =>\n new RNBleTransport(\n deviceModelDataSource,\n loggerServiceFactory,\n apduSenderServiceFactory,\n apduReceiverServiceFactory,\n );\n"],
5
+ "mappings": "AAAA,OAAS,sBAAAA,EAAoB,YAAAC,MAAgB,eAC7C,OAAwB,cAAAC,MAA+B,uBACvD,OAKE,gCAAAC,EAMA,0BAAAC,EAEA,4BAAAC,EAIA,sBAAAC,MACK,kCACP,OAAsB,eAAAC,EAAa,SAAAC,EAAO,WAAAC,EAAS,SAAAC,MAAa,YAChE,OACE,QAAAC,EACA,OAAAC,EACA,aAAAC,EACA,cAAAC,EACA,UAAAC,EACA,SAAAC,EAGA,aAAAC,EACA,cAAAC,MACK,OAEP,OACE,0BAAAC,EACA,yBAAAC,EACA,eAAAC,MACK,mBACP,OACE,4BAAAC,EACA,0BAAAC,MACK,oBACP,OACE,mBAAAC,MAGK,iCAEA,MAAMC,EAA2B,SAEjC,MAAMC,CAAoC,CAY/C,YACmBC,EACAC,EAGAC,EACAC,EACjB,CANiB,4BAAAH,EACA,2BAAAC,EAGA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B,EAE7DvB,EAA6B,gBAAgB,CAC3C,OAAAH,EACA,QAAS,KAAK,SACd,eAAAD,CACF,CAAC,EAED,MAAMI,EAA6B,gBAAgB,EAEnDA,EAA6B,oBAAoB,CACnD,CAAC,EAAE,IAAI,CACT,CACF,CAEO,MAAMwB,EAA0C,CAAC,CACtD,sBAAAC,EACA,qBAAAC,EACA,yBAAAC,EACA,2BAAAC,CACF,IACE,IAAI1C,EACFuC,EACAC,EACAC,EACAC,CACF",
6
+ "names": ["PermissionsAndroid", "Platform", "BleManager", "DeviceConnectionStateMachine", "OpeningConnectionError", "TransportConnectedDevice", "UnknownDeviceError", "EitherAsync", "Maybe", "Nothing", "Right", "from", "map", "mergeWith", "Observable", "repeat", "retry", "switchMap", "throwError", "BLE_DISCONNECT_TIMEOUT", "CONNECTION_LOST_DELAY", "DEFAULT_MTU", "DeviceConnectionNotFound", "InternalDeviceNotFound", "RNBleApduSender", "rnBleTransportIdentifier", "RNBleTransport", "_deviceModelDataSource", "_loggerServiceFactory", "_apduSenderFactory", "_apduReceiverFactory", "ledgerUuids", "isSupported", "params", "liftEither", "throwE", "internalDevice", "device", "error", "deviceApduSender", "deviceConnectionStateMachine", "iDevice", "args", "d", "scannedDeviceMap", "discoveredDevice", "granted", "result", "rnDevice", "maybeUuid", "uuid", "existingInternalDevice", "serviceToBleInfos", "bleDeviceInfos", "lastDiscoveredTimeStamp", "subscriber", "devices", "fromDevice", "errorOrDeviceConnection", "deviceConnection", "reconnectedDevice", "e", "value", "errorOrInternalDevice", "RNBleTransportFactory", "deviceModelDataSource", "loggerServiceFactory", "apduSenderServiceFactory", "apduReceiverServiceFactory"]
7
7
  }
@@ -1 +1 @@
1
- {"version":3,"file":"RNBleApduSender.d.ts","sourceRoot":"","sources":["../../../../src/api/transport/RNBleApduSender.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,UAAU,EAEf,KAAK,MAAM,EACX,KAAK,YAAY,IAAI,iBAAiB,EACvC,MAAM,sBAAsB,C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