@ledgerhq/device-transport-kit-react-native-ble 1.0.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
- "use strict";var v=Object.defineProperty;var _=Object.getOwnPropertyDescriptor;var f=Object.getOwnPropertyNames;var m=Object.prototype.hasOwnProperty;var y=(d,e)=>{for(var t in e)v(d,t,{get:e[t],enumerable:!0})},A=(d,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of f(e))!m.call(d,i)&&i!==t&&v(d,i,{get:()=>e[i],enumerable:!(n=_(e,i))||n.enumerable});return d};var R=d=>A(v({},"__esModule",{value:!0}),d);var D={};y(D,{RNBleApduSender:()=>S});module.exports=R(D);var u=require("@ledgerhq/device-management-kit"),p=require("js-base64"),s=require("purify-ts"),l=require("rxjs"),o=require("../model/Errors");const g=3;class S{_dependencies;_isDeviceReady;_logger;_apduSender;_apduSenderFactory;_apduReceiver;_sendApduPromiseResolver;_writeCharacteristic;_characteristicSubscription=void 0;constructor({apduSenderFactory:e,apduReceiverFactory:t,dependencies:n},i){this._dependencies=n,this._isDeviceReady=new l.BehaviorSubject(!1),this._logger=i("RNBleApduSender"),this._apduSenderFactory=e,this._apduSender=s.Nothing,this._apduReceiver=t(),this._sendApduPromiseResolver=s.Nothing}onReceiveSetupApduResponse(e){const t=new Uint8Array(e),{device:n}=this._dependencies,[i]=t.slice(5);let r=n.mtu-g;i&&i!==r&&(r=i),this._apduSender=s.Maybe.of(this._apduSenderFactory({frameSize:r})),this._isDeviceReady.next(!0)}receiveApdu(e){this._apduReceiver.handleFrame(e).map(n=>{n.map(i=>{this._logger.debug("Received APDU Response",{data:{response:i}}),this._sendApduPromiseResolver.map(r=>r((0,s.Right)(i)))})}).mapLeft(n=>{this._sendApduPromiseResolver.map(i=>i((0,s.Left)(n)))})}onMonitor(e){if(!e.value)return;const t=p.Base64.toUint8Array(e.value);this._isDeviceReady.value?this.receiveApdu(t):this.onReceiveSetupApduResponse(t)}write(e){return this._writeCharacteristic.isWritableWithoutResponse?this._writeCharacteristic.writeWithoutResponse(e):this._writeCharacteristic.writeWithResponse(e)}getDependencies(){return this._dependencies}setDependencies(e){this._dependencies=e,this._isDeviceReady=new l.BehaviorSubject(!1),this._characteristicSubscription&&(this._characteristicSubscription.remove(),this._characteristicSubscription=void 0)}async setupConnection(){this._characteristicSubscription=this._dependencies.device.monitorCharacteristicForService(this._dependencies.internalDevice.bleDeviceInfos.serviceUuid,this._dependencies.internalDevice.bleDeviceInfos.notifyUuid,(r,a)=>{if(r?.message.includes("notify change failed")){this._isDeviceReady.error(new o.PairingRefusedError(r)),this._logger.error("Pairing failed",{data:{error:r}});return}else r&&(this._isDeviceReady.error(new o.UnknownBleError(r)),this._logger.error("Error monitoring characteristic",{data:{error:r}}));!r&&a&&this.onMonitor(a)});const e=await this._dependencies.manager.characteristicsForDevice(this._dependencies.device.id,this._dependencies.internalDevice.bleDeviceInfos.serviceUuid);let t=e.find(r=>r.uuid===this._dependencies.internalDevice.bleDeviceInfos.writeCmdUuid);if(t)this._writeCharacteristic=t;else if(t=e.find(r=>r.uuid===this._dependencies.internalDevice.bleDeviceInfos.writeUuid),t)this._writeCharacteristic=t;else throw this._logger.error("No write characteristic found"),new Error("No write characteristic found");const n=Uint8Array.from([8,0,0,0,0]);await this.write(p.Base64.fromUint8Array(n)).catch(r=>{throw this._logger.error("Pairing failed",{data:{error:r}}),new o.PairingRefusedError(r)});let i;await new Promise((r,a)=>{i&&i.unsubscribe(),i=this._isDeviceReady.subscribe({next:c=>{c&&r()},error:c=>{a(c)}})})}async sendApdu(e,t,n){if(this._logger.debug("[sendApdu]",{data:{apdu:e,abortTimeout:n}}),!this._isDeviceReady.value)return Promise.resolve((0,s.Left)(new u.DeviceNotInitializedError("Unknown MTU")));let i;const r=new Promise(c=>{this._sendApduPromiseResolver=s.Maybe.of((...h)=>(i&&clearTimeout(i),c(...h)))}),a=this._apduSender.caseOf({Just:c=>c.getFrames(e),Nothing:()=>[]});for(const c of a)try{await this.write(p.Base64.fromUint8Array(c.getRawData()))}catch(h){this._logger.info("Error sending frame",{data:{error:h}})}return n&&(i=setTimeout(()=>{this._logger.debug("[sendApdu] Abort timeout",{data:{abortTimeout:n}}),this._sendApduPromiseResolver.map(c=>c((0,s.Left)(new u.SendApduTimeoutError("Abort timeout"))))},n)),r}closeConnection(){this._dependencies.device.cancelConnection()}}0&&(module.exports={RNBleApduSender});
1
+ "use strict";var v=Object.defineProperty;var m=Object.getOwnPropertyDescriptor;var _=Object.getOwnPropertyNames;var f=Object.prototype.hasOwnProperty;var y=(d,e)=>{for(var t in e)v(d,t,{get:e[t],enumerable:!0})},g=(d,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of _(e))!f.call(d,i)&&i!==t&&v(d,i,{get:()=>e[i],enumerable:!(n=m(e,i))||n.enumerable});return d};var A=d=>g(v({},"__esModule",{value:!0}),d);var D={};y(D,{RNBleApduSender:()=>S});module.exports=A(D);var u=require("@ledgerhq/device-management-kit"),p=require("js-base64"),s=require("purify-ts"),l=require("rxjs"),a=require("../model/Errors");const R=3;class S{_dependencies;_isDeviceReady;_logger;_apduSender;_apduSenderFactory;_apduReceiver;_sendApduPromiseResolver;_writeCharacteristic;_characteristicSubscription=void 0;constructor({apduSenderFactory:e,apduReceiverFactory:t,dependencies:n},i){this._dependencies=n,this._isDeviceReady=new l.BehaviorSubject(!1),this._logger=i("RNBleApduSender"),this._apduSenderFactory=e,this._apduSender=s.Nothing,this._apduReceiver=t(),this._sendApduPromiseResolver=s.Nothing}onReceiveSetupApduResponse(e){const t=new Uint8Array(e),{device:n}=this._dependencies,[i]=t.slice(5);let r=n.mtu-R;i&&i!==r&&(r=i),this._apduSender=s.Maybe.of(this._apduSenderFactory({frameSize:r})),this._isDeviceReady.next(!0)}receiveApdu(e){this._apduReceiver.handleFrame(e).map(n=>{n.map(i=>{this._logger.debug("Received APDU Response",{data:{response:i}}),this._sendApduPromiseResolver.map(r=>r((0,s.Right)(i)))})}).mapLeft(n=>{this._sendApduPromiseResolver.map(i=>i((0,s.Left)(n)))})}onMonitor(e){if(!e.value)return;const t=p.Base64.toUint8Array(e.value);this._isDeviceReady.value?this.receiveApdu(t):this.onReceiveSetupApduResponse(t)}write(e){return this._writeCharacteristic.isWritableWithoutResponse?this._writeCharacteristic.writeWithoutResponse(e):this._writeCharacteristic.writeWithResponse(e)}getDependencies(){return this._dependencies}setDependencies(e){this._dependencies=e,this._isDeviceReady=new l.BehaviorSubject(!1),this._characteristicSubscription&&(this._characteristicSubscription.remove(),this._characteristicSubscription=void 0)}async setupConnection(){this._characteristicSubscription=this._dependencies.device.monitorCharacteristicForService(this._dependencies.internalDevice.bleDeviceInfos.serviceUuid,this._dependencies.internalDevice.bleDeviceInfos.notifyUuid,(r,o)=>{if(r?.message.includes("notify change failed")){this._isDeviceReady.error(new a.PairingRefusedError(r)),this._logger.error("Pairing failed",{data:{error:r}});return}else r&&(this._isDeviceReady.error(new a.UnknownBleError(r)),this._logger.error("Error monitoring characteristic",{data:{error:r}}));!r&&o&&this.onMonitor(o)});const e=await this._dependencies.manager.characteristicsForDevice(this._dependencies.device.id,this._dependencies.internalDevice.bleDeviceInfos.serviceUuid);let t=e.find(r=>r.uuid===this._dependencies.internalDevice.bleDeviceInfos.writeCmdUuid);if(t)this._writeCharacteristic=t;else if(t=e.find(r=>r.uuid===this._dependencies.internalDevice.bleDeviceInfos.writeUuid),t)this._writeCharacteristic=t;else throw this._logger.error("No write characteristic found"),new Error("No write characteristic found");const n=Uint8Array.from([8,0,0,0,0]);await this.write(p.Base64.fromUint8Array(n)).catch(r=>{throw this._logger.error("Pairing failed",{data:{error:r}}),new a.PairingRefusedError(r)});let i;await new Promise((r,o)=>{i&&i.unsubscribe(),i=this._isDeviceReady.subscribe({next:c=>{c&&r()},error:c=>{o(c)}})})}async sendApdu(e,t,n){if(this._logger.debug("[sendApdu]",{data:{apdu:e,abortTimeout:n}}),!this._isDeviceReady.value)return Promise.resolve((0,s.Left)(new u.DeviceNotInitializedError("Unknown MTU")));let i;const r=new Promise(c=>{this._sendApduPromiseResolver=s.Maybe.of((...h)=>(i&&clearTimeout(i),c(...h)))}),o=this._apduSender.caseOf({Just:c=>c.getFrames(e),Nothing:()=>[]});for(const c of o)try{await this.write(p.Base64.fromUint8Array(c.getRawData()))}catch(h){this._logger.info("Error sending frame",{data:{error:h}})}return n&&(i=setTimeout(()=>{this._logger.debug("[sendApdu] Abort timeout triggered"),this._sendApduPromiseResolver.map(c=>c((0,s.Left)(new u.SendApduTimeoutError("Abort timeout"))))},n)),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 BleCharacteristicSubscription,\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 SendApduTimeoutError,\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\nimport { PairingRefusedError, UnknownBleError } from \"@api/model/Errors\";\n\nconst FRAME_HEADER_SIZE = 3;\n\nexport type RNBleInternalDevice = {\n id: DeviceId;\n bleDeviceInfos: BleDeviceInfos;\n};\n\nexport type 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 private _writeCharacteristic!: Characteristic;\n private _characteristicSubscription:\n | BleCharacteristicSubscription\n | undefined = undefined;\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 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 maybeApduResponse = this._apduReceiver.handleFrame(apdu);\n\n maybeApduResponse\n .map((response) => {\n response.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 if (this._writeCharacteristic.isWritableWithoutResponse) {\n return this._writeCharacteristic.writeWithoutResponse(value);\n }\n\n return this._writeCharacteristic.writeWithResponse(value);\n }\n\n public getDependencies() {\n return this._dependencies;\n }\n\n public setDependencies(dependencies: RNBleApduSenderDependencies) {\n this._dependencies = dependencies;\n\n //Set dependencies mean we are reconnecting to a new device\n // So we need to reset the state of the sender\n this._isDeviceReady = new BehaviorSubject<boolean>(false);\n if (this._characteristicSubscription) {\n this._characteristicSubscription.remove();\n this._characteristicSubscription = undefined;\n }\n }\n\n public async setupConnection() {\n this._characteristicSubscription =\n this._dependencies.device.monitorCharacteristicForService(\n this._dependencies.internalDevice.bleDeviceInfos.serviceUuid,\n this._dependencies.internalDevice.bleDeviceInfos.notifyUuid,\n (error, characteristic) => {\n if (error?.message.includes(\"notify change failed\")) {\n // iOS pairing refused error\n this._isDeviceReady.error(new PairingRefusedError(error));\n this._logger.error(\"Pairing failed\", {\n data: { error },\n });\n return;\n } else if (error) {\n this._isDeviceReady.error(new UnknownBleError(error));\n this._logger.error(\"Error monitoring characteristic\", {\n data: { error },\n });\n }\n if (!error && characteristic) {\n this.onMonitor(characteristic);\n }\n },\n );\n\n // Setup Write characteristic\n const characteristics =\n await this._dependencies.manager.characteristicsForDevice(\n this._dependencies.device.id,\n this._dependencies.internalDevice.bleDeviceInfos.serviceUuid,\n );\n\n let tmpWriteCharacteristic = characteristics.find(\n (characteristic) =>\n characteristic.uuid ===\n this._dependencies.internalDevice.bleDeviceInfos.writeCmdUuid,\n );\n if (tmpWriteCharacteristic) {\n this._writeCharacteristic = tmpWriteCharacteristic;\n } else {\n tmpWriteCharacteristic = characteristics.find(\n (characteristic) =>\n characteristic.uuid ===\n this._dependencies.internalDevice.bleDeviceInfos.writeUuid,\n );\n\n //This should never happen\n if (tmpWriteCharacteristic) {\n this._writeCharacteristic = tmpWriteCharacteristic;\n } else {\n this._logger.error(\"No write characteristic found\");\n throw new Error(\"No write characteristic found\");\n }\n }\n\n const requestMtuFrame = Uint8Array.from([0x08, 0x00, 0x00, 0x00, 0x00]);\n await this.write(Base64.fromUint8Array(requestMtuFrame)).catch((error) => {\n // Android pairing refused error\n this._logger.error(\"Pairing failed\", {\n data: { error },\n });\n throw new PairingRefusedError(error);\n });\n let sub: Subscription | undefined;\n await new Promise<void>((resolve, reject) => {\n if (sub) {\n sub.unsubscribe();\n }\n\n sub = this._isDeviceReady.subscribe({\n next: (isReady) => {\n if (isReady) {\n resolve(); // FIXME: we should instead return a Right\n }\n },\n error: (error) => {\n reject(error); // FIXME: we should instead return a Left so it's properly typed\n },\n });\n });\n }\n\n async sendApdu(\n apdu: Uint8Array,\n _triggersDisconnection?: boolean,\n abortTimeout?: number,\n ): Promise<Either<DmkError, ApduResponse>> {\n this._logger.debug(\"[sendApdu]\", {\n data: { apdu, abortTimeout },\n });\n if (!this._isDeviceReady.value) {\n return Promise.resolve(\n Left(new DeviceNotInitializedError(\"Unknown MTU\")),\n );\n }\n\n let timeout: ReturnType<typeof setTimeout> | undefined;\n\n const resultPromise = new Promise<Either<DmkError, ApduResponse>>(\n (resolve) => {\n this._sendApduPromiseResolver = Maybe.of((...args) => {\n if (timeout) {\n clearTimeout(timeout);\n }\n return resolve(...args);\n });\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 if (abortTimeout) {\n timeout = setTimeout(() => {\n this._logger.debug(\"[sendApdu] Abort timeout\", {\n data: { abortTimeout },\n });\n this._sendApduPromiseResolver.map((resolve) =>\n resolve(Left(new SendApduTimeoutError(\"Abort timeout\"))),\n );\n }, abortTimeout);\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,gBAEnDC,EAAqD,6BAErD,MAAMC,EAAoB,EAmBnB,MAAMP,CAEb,CACU,cACA,eACA,QACA,YACS,mBACA,cACT,yBAIA,qBACA,4BAEQ,OAEhB,YACE,CACE,kBAAAQ,EACA,oBAAAC,EACA,aAAAC,CACF,EACAC,EACA,CACA,KAAK,cAAgBD,EACrB,KAAK,eAAiB,IAAI,kBAAyB,EAAK,EACxD,KAAK,QAAUC,EAAqB,iBAAiB,EACrD,KAAK,mBAAqBH,EAC1B,KAAK,YAAc,UACnB,KAAK,cAAgBC,EAAoB,EACzC,KAAK,yBAA2B,SAClC,CAEQ,2BAA2BG,EAAmB,CACpD,MAAMC,EAAc,IAAI,WAAWD,CAAK,EAClC,CAAE,OAAAE,CAAO,EAAI,KAAK,cAElB,CAACC,CAAS,EAAIF,EAAY,MAAM,CAAC,EACvC,IAAIG,EAAYF,EAAO,IAAMP,EACzBQ,GAAaA,IAAcC,IAE7BA,EAAYD,GAEd,KAAK,YAAc,QAAM,GAAG,KAAK,mBAAmB,CAAE,UAAAC,CAAU,CAAC,CAAC,EAClE,KAAK,eAAe,KAAK,EAAI,CAC/B,CAEQ,YAAYC,EAAkB,CACV,KAAK,cAAc,YAAYA,CAAI,EAG1D,IAAKC,GAAa,CACjBA,EAAS,IAAKC,GAAiB,CAC7B,KAAK,QAAQ,MAAM,yBAA0B,CAC3C,KAAM,CAAE,S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Ga,CAAI,EACvB,CACH,CACF,EAEMC,EAAS,KAAK,YAAY,OAAO,CACrC,KAAOC,GAAeA,EAAW,UAAUlB,CAAI,EAC/C,QAAS,IAAM,CAAC,CAClB,CAAC,EAED,UAAWmB,KAASF,EAClB,GAAI,CACF,MAAM,KAAK,MAAM,SAAO,eAAeE,EAAM,WAAW,CAAC,CAAC,CAC5D,OAASf,EAAO,CACd,KAAK,QAAQ,KAAK,sBAAuB,CAAE,KAAM,CAAE,MAAAA,CAAM,CAAE,CAAC,CAC9D,CAGF,OAAIS,IACFC,EAAU,WAAW,IAAM,CACzB,KAAK,QAAQ,MAAM,2BAA4B,CAC7C,KAAM,CAAE,aAAAD,CAAa,CACvB,CAAC,EACD,KAAK,yBAAyB,IAAKV,GACjCA,KAAQ,QAAK,IAAI,uBAAqB,eAAe,CAAC,CAAC,CACzD,CACF,EAAGU,CAAY,GAGVE,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 BleCharacteristicSubscription,\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 SendApduTimeoutError,\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\nimport { PairingRefusedError, UnknownBleError } from \"@api/model/Errors\";\n\nconst FRAME_HEADER_SIZE = 3;\n\nexport type RNBleInternalDevice = {\n id: DeviceId;\n bleDeviceInfos: BleDeviceInfos;\n};\n\nexport type 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 private _writeCharacteristic!: Characteristic;\n private _characteristicSubscription:\n | BleCharacteristicSubscription\n | undefined = undefined;\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 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 maybeApduResponse = this._apduReceiver.handleFrame(apdu);\n\n maybeApduResponse\n .map((response) => {\n response.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 if (this._writeCharacteristic.isWritableWithoutResponse) {\n return this._writeCharacteristic.writeWithoutResponse(value);\n }\n\n return this._writeCharacteristic.writeWithResponse(value);\n }\n\n public getDependencies() {\n return this._dependencies;\n }\n\n public setDependencies(dependencies: RNBleApduSenderDependencies) {\n this._dependencies = dependencies;\n\n //Set dependencies mean we are reconnecting to a new device\n // So we need to reset the state of the sender\n this._isDeviceReady = new BehaviorSubject<boolean>(false);\n if (this._characteristicSubscription) {\n this._characteristicSubscription.remove();\n this._characteristicSubscription = undefined;\n }\n }\n\n public async setupConnection() {\n this._characteristicSubscription =\n this._dependencies.device.monitorCharacteristicForService(\n this._dependencies.internalDevice.bleDeviceInfos.serviceUuid,\n this._dependencies.internalDevice.bleDeviceInfos.notifyUuid,\n (error, characteristic) => {\n if (error?.message.includes(\"notify change failed\")) {\n // iOS pairing refused error\n this._isDeviceReady.error(new PairingRefusedError(error));\n this._logger.error(\"Pairing failed\", {\n data: { error },\n });\n return;\n } else if (error) {\n this._isDeviceReady.error(new UnknownBleError(error));\n this._logger.error(\"Error monitoring characteristic\", {\n data: { error },\n });\n }\n if (!error && characteristic) {\n this.onMonitor(characteristic);\n }\n },\n );\n\n // Setup Write characteristic\n const characteristics =\n await this._dependencies.manager.characteristicsForDevice(\n this._dependencies.device.id,\n this._dependencies.internalDevice.bleDeviceInfos.serviceUuid,\n );\n\n let tmpWriteCharacteristic = characteristics.find(\n (characteristic) =>\n characteristic.uuid ===\n this._dependencies.internalDevice.bleDeviceInfos.writeCmdUuid,\n );\n if (tmpWriteCharacteristic) {\n this._writeCharacteristic = tmpWriteCharacteristic;\n } else {\n tmpWriteCharacteristic = characteristics.find(\n (characteristic) =>\n characteristic.uuid ===\n this._dependencies.internalDevice.bleDeviceInfos.writeUuid,\n );\n\n //This should never happen\n if (tmpWriteCharacteristic) {\n this._writeCharacteristic = tmpWriteCharacteristic;\n } else {\n this._logger.error(\"No write characteristic found\");\n throw new Error(\"No write characteristic found\");\n }\n }\n\n const requestMtuFrame = Uint8Array.from([0x08, 0x00, 0x00, 0x00, 0x00]);\n await this.write(Base64.fromUint8Array(requestMtuFrame)).catch((error) => {\n // Android pairing refused error\n this._logger.error(\"Pairing failed\", {\n data: { error },\n });\n throw new PairingRefusedError(error);\n });\n let sub: Subscription | undefined;\n await new Promise<void>((resolve, reject) => {\n if (sub) {\n sub.unsubscribe();\n }\n\n sub = this._isDeviceReady.subscribe({\n next: (isReady) => {\n if (isReady) {\n resolve(); // FIXME: we should instead return a Right\n }\n },\n error: (error) => {\n reject(error); // FIXME: we should instead return a Left so it's properly typed\n },\n });\n });\n }\n\n async sendApdu(\n apdu: Uint8Array,\n _triggersDisconnection?: boolean,\n abortTimeout?: number,\n ): Promise<Either<DmkError, ApduResponse>> {\n this._logger.debug(\"[sendApdu]\", {\n data: { apdu, abortTimeout },\n });\n if (!this._isDeviceReady.value) {\n return Promise.resolve(\n Left(new DeviceNotInitializedError(\"Unknown MTU\")),\n );\n }\n\n let timeout: ReturnType<typeof setTimeout> | undefined;\n\n const resultPromise = new Promise<Either<DmkError, ApduResponse>>(\n (resolve) => {\n this._sendApduPromiseResolver = Maybe.of((...args) => {\n if (timeout) {\n clearTimeout(timeout);\n }\n return resolve(...args);\n });\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 if (abortTimeout) {\n timeout = setTimeout(() => {\n this._logger.debug(\"[sendApdu] Abort timeout triggered\");\n this._sendApduPromiseResolver.map((resolve) =>\n resolve(Left(new SendApduTimeoutError(\"Abort timeout\"))),\n );\n }, abortTimeout);\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,gBAEnDC,EAAqD,6BAErD,MAAMC,EAAoB,EAmBnB,MAAMP,CAEb,CACU,cACA,eACA,QACA,YACS,mBACA,cACT,yBAIA,qBACA,4BAEQ,OAEhB,YACE,CACE,kBAAAQ,EACA,oBAAAC,EACA,aAAAC,CACF,EACAC,EACA,CACA,KAAK,cAAgBD,EACrB,KAAK,eAAiB,IAAI,kBAAyB,EAAK,EACxD,KAAK,QAAUC,EAAqB,iBAAiB,EACrD,KAAK,mBAAqBH,EAC1B,KAAK,YAAc,UACnB,KAAK,cAAgBC,EAAoB,EACzC,KAAK,yBAA2B,SAClC,CAEQ,2BAA2BG,EAAmB,CACpD,MAAMC,EAAc,IAAI,WAAWD,CAAK,EAClC,CAAE,OAAAE,CAAO,EAAI,KAAK,cAElB,CAACC,CAAS,EAAIF,EAAY,MAAM,CAAC,EACvC,IAAIG,EAAYF,EAAO,IAAMP,EACzBQ,GAAaA,IAAcC,IAE7BA,EAAYD,GAEd,KAAK,YAAc,QAAM,GAAG,KAAK,mBAAmB,CAAE,UAAAC,CAAU,CAAC,CAAC,EAClE,KAAK,eAAe,KAAK,EAAI,CAC/B,CAEQ,YAAYC,EAAkB,CACV,KAAK,cAAc,YAAYA,CAAI,EAG1D,IAAKC,GAAa,CACjBA,EAAS,IAAKC,GAAiB,CAC7B,KAAK,Q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vCF,GACF,aAAaA,CAAO,EAEfX,EAAQ,GAAGa,CAAI,EACvB,CACH,CACF,EAEMC,EAAS,KAAK,YAAY,OAAO,CACrC,KAAOC,GAAeA,EAAW,UAAUlB,CAAI,EAC/C,QAAS,IAAM,CAAC,CAClB,CAAC,EAED,UAAWmB,KAASF,EAClB,GAAI,CACF,MAAM,KAAK,MAAM,SAAO,eAAeE,EAAM,WAAW,CAAC,CAAC,CAC5D,OAASf,EAAO,CACd,KAAK,QAAQ,KAAK,sBAAuB,CAAE,KAAM,CAAE,MAAAA,CAAM,CAAE,CAAC,CAC9D,CAGF,OAAIS,IACFC,EAAU,WAAW,IAAM,CACzB,KAAK,QAAQ,MAAM,oCAAoC,EACvD,KAAK,yBAAyB,IAAKX,GACjCA,KAAQ,QAAK,IAAI,uBAAqB,eAAe,CAAC,CAAC,CACzD,CACF,EAAGU,CAAY,GAGVE,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", "import_Errors", "FRAME_HEADER_SIZE", "apduSenderFactory", "apduReceiverFactory", "dependencies", "loggerServiceFactory", "value", "mtuResponse", "device", "ledgerMtu", "frameSize", "apdu", "response", "apduResponse", "resolve", "error", "characteristic", "characteristics", "tmpWriteCharacteristic", "requestMtuFrame", "sub", "reject", "isReady", "_triggersDisconnection", "abortTimeout", "timeout", "resultPromise", "args", "frames", "apduSender", "frame"]
7
7
  }
@@ -1,2 +1,2 @@
1
- "use strict";var m=Object.defineProperty;var C=Object.getOwnPropertyDescriptor;var E=Object.getOwnPropertyNames;var N=Object.prototype.hasOwnProperty;var A=(v,e)=>{for(var i in e)m(v,i,{get:e[i],enumerable:!0})},B=(v,e,i,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of E(e))!N.call(v,o)&&o!==i&&m(v,o,{get:()=>e[o],enumerable:!(n=C(e,o))||n.enumerable});return v};var M=v=>B(m({},"__esModule",{value:!0}),v);var R={};A(R,{RNBleTransport:()=>y,RNBleTransportFactory:()=>O,rnBleTransportIdentifier:()=>w});module.exports=M(R);var _=require("react-native"),D=require("react-native-ble-plx"),p=require("@ledgerhq/device-management-kit"),t=require("purify-ts"),c=require("rxjs"),l=require("../model/Const"),h=require("../model/Errors"),b=require("../transport/RNBleApduSender");const w="RN_BLE";class y{constructor(e,i,n,o,s,r=_.Platform,S=_.PermissionsAndroid,d=u=>new p.DeviceConnectionStateMachine(u),f=(u,g)=>new b.RNBleApduSender(u,g)){this._deviceModelDataSource=e;this._loggerServiceFactory=i;this._apduSenderFactory=n;this._apduReceiverFactory=o;this._manager=s;this._platform=r;this._permissionsAndroid=S;this._deviceConnectionStateMachineFactory=d;this._deviceApduSenderFactory=f;this._logger=i("ReactNativeBleTransport"),this._isSupported=t.Maybe.zero(),this._deviceConnectionsById=new Map,this._reconnectionSubscription=t.Maybe.zero(),this._manager.onStateChange(u=>{this._bleStateSubject.next(u)},!0)}_logger;_isSupported;_deviceConnectionsById;identifier="RN_BLE";_reconnectionSubscription;_bleStateSubject=new c.BehaviorSubject(D.State.Unknown);startDiscovering(){return(0,c.from)([])}async stopDiscovering(){await this._stopScanning()}_maybeScanningSubject=t.Nothing;_scannedDevicesSubject=new c.BehaviorSubject([]);_startedScanningSubscriber=void 0;_startScanning(){this._startedScanningSubscriber==null&&(this._scannedDevicesSubject.next([]),this._startedScanningSubscriber=(0,c.from)(this._bleStateSubject).pipe((0,c.filter)(e=>e==="PoweredOn"),(0,c.switchMap)(()=>this.requestPermission()),(0,c.switchMap)(e=>{if(!e)return(0,c.throwError)(()=>new h.BleNotSupported("BLE not supported"));const i=new c.BehaviorSubject([]);this._maybeScanningSubject=t.Maybe.of(i);const n=new Map;this._logger.info("[RNBleTransport][startScanning] startDeviceScan"),this._manager.startDeviceScan(this._deviceModelDataSource.getBluetoothServices(),{allowDuplicates:!0},(s,r)=>{if(s||!r){i.error(s||new Error("scan error"));return}n.set(r.id,{device:r,timestamp:Date.now()}),i.next(Array.from(n.values()))});const o=setInterval(()=>{i.next(Array.from(n.values()))},1e3);return i.asObservable().pipe((0,c.finalize)(()=>{this._logger.debug("[RNBleTransport][startScanning] finalize"),i.complete(),clearInterval(o),this._maybeScanningSubject=t.Nothing,this._manager.stopDeviceScan()}))}),(0,c.throttleTime)(1e3)).subscribe({next:e=>{this._logger.debug("[RNBleTransport][startScanning] onNext called with devices",{data:{devices:e}}),this._scannedDevicesSubject.next(e)},error:e=>{this._logger.error("Error while scanning",{data:{error:e}})}}))}async _stopScanning(){this._maybeScanningSubject.map(e=>{e.complete(),this._maybeScanningSubject=t.Nothing}),await this._manager.stopDeviceScan(),this._startedScanningSubscriber?.unsubscribe(),this._startedScanningSubscriber=void 0}listenToAvailableDevices(){return this._startScanning(),this._scannedDevicesSubject.asObservable().pipe((0,c.map)(e=>{const i=Array.from(this._deviceConnectionsById.values()).map(r=>this._mapDeviceToTransportDiscoveredDevice(r.getDependencies().device,[r.getDependencies().internalDevice.bleDeviceInfos.serviceUuid])),n=t.Either.rights(i),o=e.filter(({timestamp:r})=>r>Date.now()-l.CONNECTION_LOST_DELAY).sort((r,S)=>(S.device.rssi??-1/0)-(r.device.rssi??-1/0)).map(({device:r})=>this._mapDeviceToTransportDiscoveredDevice(r,r.serviceUUIDs)).filter(r=>!!r),s=t.Either.rights(o);return[...n,...s]}))}_mapServicesUUIDsToBluetoothDeviceInfo(e){for(const i of e||[]){const n=this._deviceModelDataSource.getBluetoothServicesInfos()[i];if(n)return(0,t.Right)(n)}return(0,t.Left)(new h.NoDeviceModelFoundError(`No device model found for [uuids=${e}]`))}_mapServicesUUIDsToDeviceModel(e){return this._mapServicesUUIDsToBluetoothDeviceInfo(e).map(n=>n.deviceModel)}_mapDeviceToTransportDiscoveredDevice(e,i){return this._mapServicesUUIDsToDeviceModel(i).map(o=>({id:e.id,name:e.localName||e.name||"",deviceModel:o,transport:this.identifier,rssi:e.rssi||void 0}))}async connect(e){const i=this._deviceConnectionsById.get(e.deviceId);if(i){const n=i.getDependencies().internalDevice.bleDeviceInfos.deviceModel;return(0,t.Right)(new p.TransportConnectedDevice({id:e.deviceId,deviceModel:n,type:"BLE",sendApdu:(...o)=>i.sendApdu(...o),transport:this.identifier}))}return await this._stopScanning(),await this._safeCancel(e.deviceId),(0,t.EitherAsync)(async({throwE:n})=>{let o,s=[];try{await this._manager.connectToDevice(e.deviceId,{requestMTU:l.DEFAULT_MTU}),o=await this._manager.discoverAllServicesAndCharacteristicsForDevice(e.deviceId),s=(await o.services()).map(a=>a.uuid)}catch(a){return a instanceof D.BleError&&a.iosErrorCode===14?n(new h.PeerRemovedPairingError(a)):n(new p.OpeningConnectionError(a))}const r=this._manager.onDeviceDisconnected(o.id,(a,T)=>{this._handleDeviceDisconnected(a,T)}),S=this._mapServicesUUIDsToBluetoothDeviceInfo(s).caseOf({Right:a=>a,Left:a=>n(new p.OpeningConnectionError(a))}),d=S.deviceModel,f={id:o.id,bleDeviceInfos:S},u=this._deviceApduSenderFactory({apduSenderFactory:this._apduSenderFactory,apduReceiverFactory:this._apduReceiverFactory,dependencies:{device:o,internalDevice:f,manager:this._manager}},this._loggerServiceFactory),g=_.Platform.OS==="ios"?l.BLE_DISCONNECT_TIMEOUT_IOS:l.BLE_DISCONNECT_TIMEOUT_ANDROID,I=this._deviceConnectionStateMachineFactory({deviceId:e.deviceId,deviceApduSender:u,timeoutDuration:g,onTerminated:()=>{try{this._safeCancel(e.deviceId),e.onDisconnect(e.deviceId),this._deviceConnectionsById.delete(e.deviceId),r.remove(),this._reconnectionSubscription.isJust()&&(this._reconnectionSubscription.map(a=>a.unsubscribe()),this._reconnectionSubscription=t.Maybe.zero())}catch(a){this._logger.error("Error in termination of device connection",{data:{e:a}})}}});return await u.setupConnection().catch(a=>{throw this._safeCancel(e.deviceId),r.remove(),a}),this._deviceConnectionsById.set(e.deviceId,I),new p.TransportConnectedDevice({id:o.id,deviceModel:d,type:"BLE",sendApdu:(...a)=>I.sendApdu(...a),transport:this.identifier})}).run()}async disconnect(e){const i=e.connectedDevice.id,n=this._deviceConnectionsById.get(i);if(!n)throw new p.UnknownDeviceError(`No connected device found with id ${i}`);return n.closeConnection(),Promise.resolve((0,t.Right)(void 0))}isSupported(){return this._isSupported.caseOf({Just:e=>e,Nothing:()=>{throw new Error("Should initialize permission")}})}getIdentifier(){return this.identifier}async requestPermission(){if(this._platform.OS==="ios")return this._isSupported=t.Maybe.of(!0),!0;if(this._platform.OS==="android"&&this._permissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION){if(parseInt(this._platform.Version.toString(),10)<31){const i=await this._permissionsAndroid.request(this._permissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION);this._isSupported=t.Maybe.of(i===this._permissionsAndroid.RESULTS.GRANTED)}if(this._permissionsAndroid.PERMISSIONS.BLUETOOTH_SCAN&&this._permissionsAndroid.PERMISSIONS.BLUETOOTH_CONNECT){const i=await this._permissionsAndroid.requestMultiple([this._permissionsAndroid.PERMISSIONS.BLUETOOTH_SCAN,this._permissionsAndroid.PERMISSIONS.BLUETOOTH_CONNECT,this._permissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION]);return this._isSupported=t.Maybe.of(i["android.permission.BLUETOOTH_CONNECT"]===this._permissionsAndroid.RESULTS.GRANTED&&i["android.permission.BLUETOOTH_SCAN"]===this._permissionsAndroid.RESULTS.GRANTED&&i["android.permission.ACCESS_FINE_LOCATION"]===this._permissionsAndroid.RESULTS.GRANTED),!0}}return this._logger.error("Permission have not been granted",{data:{isSupported:this._isSupported.extract()}}),this._isSupported=t.Maybe.of(!1),!1}_handleDeviceDisconnected(e,i){if(this._logger.debug("[RNBLE][_handleDeviceDisconnected]",{data:{error:e,device:i}}),!i){this._logger.debug("[_handleDeviceDisconnected] disconnected handler didn't find device");return}if(!i?.id||!this._deviceConnectionsById.has(i?.id))return;if(e){this._logger.error("device disconnected error",{data:{error:e,device:i}});return}const n=i.id;if(this._reconnectionSubscription.isJust())return;t.Maybe.fromNullable(this._deviceConnectionsById.get(n)).map(s=>s.eventDeviceDetached());const o=(0,c.from)([0]).pipe((0,c.switchMap)(async()=>{await this._stopScanning(),await this._safeCancel(n)}),(0,c.switchMap)(async()=>{this._logger.debug("[_handleDeviceDisconnected] reconnecting to device",{data:{id:i.id}});const s=await this._manager.connectToDevice(n,{requestMTU:l.DEFAULT_MTU,timeout:2e3});this._logger.debug("[_handleDeviceDisconnected] reconnected to device",{data:{id:i.id}});const r=await s.discoverAllServicesAndCharacteristics();return this._logger.debug("[_handleDeviceDisconnected] discovered all services and characteristics",{data:{reconnectedDeviceUsable:r}}),await this._handleDeviceReconnected(r),r}),(0,c.retry)(5));this._reconnectionSubscription=t.Maybe.of(o.subscribe({next:s=>this._logger.debug("[_handleDeviceDisconnected] Reconnected to device",{data:{id:s.id}}),complete:()=>{this._reconnectionSubscription=t.Maybe.zero()},error:s=>{this._logger.error("[_handleDeviceDisconnected] All reconnection attempts failed",{data:{e:s}}),t.Maybe.fromNullable(this._deviceConnectionsById.get(n)).map(r=>r.closeConnection()),this._reconnectionSubscription=t.Maybe.zero()}}))}async _handleDeviceReconnected(e){const i=t.Maybe.fromNullable(this._deviceConnectionsById.get(e.id)).toEither(new h.DeviceConnectionNotFound);return(0,t.EitherAsync)(async({liftEither:n,throwE:o})=>{const s=await n(i),r=(await e.services()).map(d=>d.uuid),S=this._mapServicesUUIDsToBluetoothDeviceInfo(r).caseOf({Right:d=>({id:e.id,bleDeviceInfos:d}),Left:d=>(this._logger.error("Error in mapping services UUIDs to Bluetooth device info",{data:{error:d}}),o(d))});s.setDependencies({device:e,manager:this._manager,internalDevice:S}),await s.setupConnection().catch(d=>{throw this._safeCancel(e.id),d}),s.eventDeviceAttached()}).run()}async _safeCancel(e){if(typeof this._manager.cancelDeviceConnection=="function"){const i=await this._manager.connectedDevices(this._deviceModelDataSource.getBluetoothServices());for(const n of i)n.id===e&&await this._manager.cancelDeviceConnection(e)}}}const O=({deviceModelDataSource:v,loggerServiceFactory:e,apduSenderServiceFactory:i,apduReceiverServiceFactory:n})=>new y(v,e,i,n,new D.BleManager);0&&(module.exports={RNBleTransport,RNBleTransportFactory,rnBleTransportIdentifier});
1
+ "use strict";var m=Object.defineProperty;var C=Object.getOwnPropertyDescriptor;var E=Object.getOwnPropertyNames;var N=Object.prototype.hasOwnProperty;var A=(v,e)=>{for(var i in e)m(v,i,{get:e[i],enumerable:!0})},B=(v,e,i,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let t of E(e))!N.call(v,t)&&t!==i&&m(v,t,{get:()=>e[t],enumerable:!(n=C(e,t))||n.enumerable});return v};var M=v=>B(m({},"__esModule",{value:!0}),v);var R={};A(R,{RNBleTransport:()=>I,RNBleTransportFactory:()=>O,rnBleTransportIdentifier:()=>w});module.exports=M(R);var _=require("react-native"),D=require("react-native-ble-plx"),p=require("@ledgerhq/device-management-kit"),r=require("purify-ts"),o=require("rxjs"),l=require("../model/Const"),h=require("../model/Errors"),y=require("../transport/RNBleApduSender");const w="RN_BLE";class I{constructor(e,i,n,t,a,c=_.Platform,S=_.PermissionsAndroid,d=u=>new p.DeviceConnectionStateMachine(u),f=(u,g)=>new y.RNBleApduSender(u,g)){this._deviceModelDataSource=e;this._loggerServiceFactory=i;this._apduSenderFactory=n;this._apduReceiverFactory=t;this._manager=a;this._platform=c;this._permissionsAndroid=S;this._deviceConnectionStateMachineFactory=d;this._deviceApduSenderFactory=f;this._logger=i("ReactNativeBleTransport"),this._isSupported=r.Maybe.zero(),this._deviceConnectionsById=new Map,this._reconnectionSubscription=r.Maybe.zero(),this._manager.onStateChange(u=>{this._bleStateSubject.next(u)},!0)}_logger;_isSupported;_deviceConnectionsById;identifier="RN_BLE";_reconnectionSubscription;_bleStateSubject=new o.BehaviorSubject(D.State.Unknown);startDiscovering(){return(0,o.from)([])}async stopDiscovering(){await this._stopScanning()}_maybeScanningSubject=r.Nothing;_scannedDevicesSubject=new o.BehaviorSubject([]);_startedScanningSubscriber=void 0;_startScanning(){this._startedScanningSubscriber==null&&(this._scannedDevicesSubject.next([]),this._startedScanningSubscriber=(0,o.from)(this._bleStateSubject).pipe((0,o.filter)(e=>e==="PoweredOn"),(0,o.switchMap)(()=>this.requestPermission()),(0,o.switchMap)(e=>{if(!e)return(0,o.throwError)(()=>new h.BleNotSupported("BLE not supported"));const i=new o.BehaviorSubject([]);this._maybeScanningSubject=r.Maybe.of(i);const n=new Map;this._logger.info("[RNBleTransport][startScanning] startDeviceScan"),this._manager.startDeviceScan(this._deviceModelDataSource.getBluetoothServices(),{allowDuplicates:!0},(a,c)=>{if(a||!c){i.error(a||new Error("scan error"));return}n.set(c.id,{device:c,timestamp:Date.now()}),i.next(Array.from(n.values()))});const t=setInterval(()=>{i.next(Array.from(n.values()))},1e3);return i.asObservable().pipe((0,o.finalize)(()=>{this._logger.debug("[RNBleTransport][startScanning] finalize"),i.complete(),clearInterval(t),this._maybeScanningSubject=r.Nothing,this._manager.stopDeviceScan()}))}),(0,o.throttleTime)(1e3)).subscribe({next:e=>{this._logger.debug("[RNBleTransport][startScanning] onNext called with devices",{data:{devices:e}}),this._scannedDevicesSubject.next(e)},error:e=>{this._logger.error("Error while scanning",{data:{error:e}})}}))}async _stopScanning(){this._maybeScanningSubject.map(e=>{e.complete(),this._maybeScanningSubject=r.Nothing}),await this._manager.stopDeviceScan(),this._startedScanningSubscriber?.unsubscribe(),this._startedScanningSubscriber=void 0}listenToAvailableDevices(){return this._startScanning(),this._scannedDevicesSubject.asObservable().pipe((0,o.map)(e=>{const i=Array.from(this._deviceConnectionsById.values()).map(c=>this._mapDeviceToTransportDiscoveredDevice(c.getDependencies().device,[c.getDependencies().internalDevice.bleDeviceInfos.serviceUuid])),n=r.Either.rights(i),t=e.filter(({timestamp:c})=>c>Date.now()-l.CONNECTION_LOST_DELAY).sort((c,S)=>(S.device.rssi??-1/0)-(c.device.rssi??-1/0)).map(({device:c})=>this._mapDeviceToTransportDiscoveredDevice(c,c.serviceUUIDs)).filter(c=>!!c),a=r.Either.rights(t);return[...n,...a]}))}_mapServicesUUIDsToBluetoothDeviceInfo(e){for(const i of e||[]){const n=this._deviceModelDataSource.getBluetoothServicesInfos()[i];if(n)return(0,r.Right)(n)}return(0,r.Left)(new h.NoDeviceModelFoundError(`No device model found for [uuids=${e}]`))}_mapServicesUUIDsToDeviceModel(e){return this._mapServicesUUIDsToBluetoothDeviceInfo(e).map(n=>n.deviceModel)}_mapDeviceToTransportDiscoveredDevice(e,i){return this._mapServicesUUIDsToDeviceModel(i).map(t=>({id:e.id,name:e.localName||e.name||"",deviceModel:t,transport:this.identifier,rssi:e.rssi||void 0}))}async connect(e){const i=this._deviceConnectionsById.get(e.deviceId);if(i){const n=i.getDependencies().internalDevice.bleDeviceInfos.deviceModel;return(0,r.Right)(new p.TransportConnectedDevice({id:e.deviceId,deviceModel:n,type:"BLE",sendApdu:(...t)=>i.sendApdu(...t),transport:this.identifier}))}return await this._stopScanning(),await this._safeCancel(e.deviceId),(0,r.EitherAsync)(async({throwE:n})=>{let t,a=[];try{await this._manager.connectToDevice(e.deviceId,{requestMTU:l.DEFAULT_MTU}),t=await this._manager.discoverAllServicesAndCharacteristicsForDevice(e.deviceId),a=(await t.services()).map(s=>s.uuid)}catch(s){return s instanceof D.BleError&&s.iosErrorCode===14?n(new h.PeerRemovedPairingError(s)):n(new p.OpeningConnectionError(s))}const c=this._manager.onDeviceDisconnected(t.id,(s,T)=>{this._handleDeviceDisconnected(s,T)}),S=this._mapServicesUUIDsToBluetoothDeviceInfo(a).caseOf({Right:s=>s,Left:s=>n(new p.OpeningConnectionError(s))}),d=S.deviceModel,f={id:t.id,bleDeviceInfos:S},u=this._deviceApduSenderFactory({apduSenderFactory:this._apduSenderFactory,apduReceiverFactory:this._apduReceiverFactory,dependencies:{device:t,internalDevice:f,manager:this._manager}},this._loggerServiceFactory),g=_.Platform.OS==="ios"?l.BLE_DISCONNECT_TIMEOUT_IOS:l.BLE_DISCONNECT_TIMEOUT_ANDROID,b=this._deviceConnectionStateMachineFactory({deviceId:e.deviceId,deviceApduSender:u,timeoutDuration:g,tryToReconnect:()=>{this.tryToReconnect(e.deviceId)},onTerminated:()=>{try{this._safeCancel(e.deviceId),e.onDisconnect(e.deviceId),this._deviceConnectionsById.delete(e.deviceId),c.remove(),this._reconnectionSubscription.isJust()&&(this._reconnectionSubscription.map(s=>s.unsubscribe()),this._reconnectionSubscription=r.Maybe.zero())}catch(s){this._logger.error("Error in termination of device connection",{data:{e:s}})}}});return await u.setupConnection().catch(s=>{throw this._safeCancel(e.deviceId),c.remove(),s}),this._deviceConnectionsById.set(e.deviceId,b),new p.TransportConnectedDevice({id:t.id,deviceModel:d,type:"BLE",sendApdu:(...s)=>b.sendApdu(...s),transport:this.identifier})}).run()}async disconnect(e){const i=e.connectedDevice.id,n=this._deviceConnectionsById.get(i);if(!n)throw new p.UnknownDeviceError(`No connected device found with id ${i}`);return n.closeConnection(),Promise.resolve((0,r.Right)(void 0))}isSupported(){return this._isSupported.caseOf({Just:e=>e,Nothing:()=>{throw new Error("Should initialize permission")}})}getIdentifier(){return this.identifier}async requestPermission(){if(this._platform.OS==="ios")return this._isSupported=r.Maybe.of(!0),!0;if(this._platform.OS==="android"&&this._permissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION){if(parseInt(this._platform.Version.toString(),10)<31){const i=await this._permissionsAndroid.request(this._permissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION);this._isSupported=r.Maybe.of(i===this._permissionsAndroid.RESULTS.GRANTED)}if(this._permissionsAndroid.PERMISSIONS.BLUETOOTH_SCAN&&this._permissionsAndroid.PERMISSIONS.BLUETOOTH_CONNECT){const i=await this._permissionsAndroid.requestMultiple([this._permissionsAndroid.PERMISSIONS.BLUETOOTH_SCAN,this._permissionsAndroid.PERMISSIONS.BLUETOOTH_CONNECT,this._permissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION]);return this._isSupported=r.Maybe.of(i["android.permission.BLUETOOTH_CONNECT"]===this._permissionsAndroid.RESULTS.GRANTED&&i["android.permission.BLUETOOTH_SCAN"]===this._permissionsAndroid.RESULTS.GRANTED&&i["android.permission.ACCESS_FINE_LOCATION"]===this._permissionsAndroid.RESULTS.GRANTED),!0}}return this._logger.error("Permission have not been granted",{data:{isSupported:this._isSupported.extract()}}),this._isSupported=r.Maybe.of(!1),!1}_handleDeviceDisconnected(e,i){if(this._logger.debug("[RNBLE][_handleDeviceDisconnected]",{data:{error:e,device:i}}),!i){this._logger.debug("[_handleDeviceDisconnected] disconnected handler didn't find device");return}if(!i?.id||!this._deviceConnectionsById.has(i?.id))return;if(e){this._logger.error("device disconnected error",{data:{error:e,device:i}});return}const n=i.id;this._reconnectionSubscription.isJust()||r.Maybe.fromNullable(this._deviceConnectionsById.get(n)).map(t=>t.eventDeviceDisconnected())}tryToReconnect(e){const i=(0,o.from)([0]).pipe((0,o.switchMap)(async()=>{await this._stopScanning(),await this._safeCancel(e)}),(0,o.switchMap)(async()=>{this._logger.debug("[_handleDeviceDisconnected] reconnecting to device",{data:{id:e}});const n=await this._manager.connectToDevice(e,{requestMTU:l.DEFAULT_MTU,timeout:2e3});this._logger.debug("[_handleDeviceDisconnected] reconnected to device",{data:{id:e}});const t=await n.discoverAllServicesAndCharacteristics();return this._logger.debug("[_handleDeviceDisconnected] discovered all services and characteristics",{data:{reconnectedDeviceUsable:t}}),await this._handleDeviceReconnected(t),t}),(0,o.retry)(5));this._reconnectionSubscription=r.Maybe.of(i.subscribe({next:n=>this._logger.debug("[_handleDeviceDisconnected] Reconnected to device",{data:{id:n.id}}),complete:()=>{this._reconnectionSubscription=r.Maybe.zero()},error:n=>{this._logger.error("[_handleDeviceDisconnected] All reconnection attempts failed",{data:{e:n}}),r.Maybe.fromNullable(this._deviceConnectionsById.get(e)).map(t=>t.closeConnection()),this._reconnectionSubscription=r.Maybe.zero()}}))}async _handleDeviceReconnected(e){const i=r.Maybe.fromNullable(this._deviceConnectionsById.get(e.id)).toEither(new h.DeviceConnectionNotFound);return(0,r.EitherAsync)(async({liftEither:n,throwE:t})=>{const a=await n(i),c=(await e.services()).map(d=>d.uuid),S=this._mapServicesUUIDsToBluetoothDeviceInfo(c).caseOf({Right:d=>({id:e.id,bleDeviceInfos:d}),Left:d=>(this._logger.error("Error in mapping services UUIDs to Bluetooth device info",{data:{error:d}}),t(d))});a.setDependencies({device:e,manager:this._manager,internalDevice:S}),await a.setupConnection().catch(d=>{throw this._safeCancel(e.id),d}),a.eventDeviceConnected()}).run()}async _safeCancel(e){if(typeof this._manager.cancelDeviceConnection=="function"){const i=await this._manager.connectedDevices(this._deviceModelDataSource.getBluetoothServices());for(const n of i)n.id===e&&await this._manager.cancelDeviceConnection(e)}}}const O=({deviceModelDataSource:v,loggerServiceFactory:e,apduSenderServiceFactory:i,apduReceiverServiceFactory:n})=>new I(v,e,i,n,new D.BleManager);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 { BleError, BleManager, type Device, State } from \"react-native-ble-plx\";\nimport {\n type ApduReceiverServiceFactory,\n type ApduSenderServiceFactory,\n type BleDeviceInfos,\n type ConnectError,\n DeviceConnectionStateMachine,\n type DeviceConnectionStateMachineParams,\n type DeviceId,\n type DeviceModelDataSource,\n type DisconnectHandler,\n type DmkError,\n type LoggerPublisherService,\n OpeningConnectionError,\n type Transport,\n TransportConnectedDevice,\n type TransportDeviceModel,\n type TransportDiscoveredDevice,\n type TransportFactory,\n type TransportIdentifier,\n UnknownDeviceError,\n} from \"@ledgerhq/device-management-kit\";\nimport { Either, EitherAsync, Left, Maybe, Nothing, Right } from \"purify-ts\";\nimport {\n BehaviorSubject,\n filter,\n finalize,\n from,\n map,\n type Observable,\n retry,\n type Subscription,\n switchMap,\n throttleTime,\n throwError,\n} from \"rxjs\";\n\nimport {\n BLE_DISCONNECT_TIMEOUT_ANDROID,\n BLE_DISCONNECT_TIMEOUT_IOS,\n CONNECTION_LOST_DELAY,\n DEFAULT_MTU,\n} from \"@api/model/Const\";\nimport {\n BleNotSupported,\n DeviceConnectionNotFound,\n NoDeviceModelFoundError,\n PeerRemovedPairingError,\n} from \"@api/model/Errors\";\nimport {\n RNBleApduSender,\n type RNBleApduSenderConstructorArgs,\n type RNBleApduSenderDependencies,\n type RNBleInternalDevice,\n} from \"@api/transport/RNBleApduSender\";\n\nexport const rnBleTransportIdentifier = \"RN_BLE\";\n\ntype InternalScannedDevice = {\n device: Device;\n timestamp: number;\n};\n\nexport class RNBleTransport implements Transport {\n private _logger: LoggerPublisherService;\n private _isSupported: Maybe<boolean>;\n private _deviceConnectionsById: Map<\n DeviceId,\n DeviceConnectionStateMachine<RNBleApduSenderDependencies>\n >;\n // private readonly _manager: BleManager;\n private readonly identifier: TransportIdentifier = \"RN_BLE\";\n private _reconnectionSubscription: Maybe<Subscription>;\n private readonly _bleStateSubject: BehaviorSubject<State> =\n new BehaviorSubject<State>(State.Unknown);\n\n constructor(\n private readonly _deviceModelDataSource: DeviceModelDataSource,\n private readonly _loggerServiceFactory: (\n tag: string,\n ) => LoggerPublisherService,\n private readonly _apduSenderFactory: ApduSenderServiceFactory,\n private readonly _apduReceiverFactory: ApduReceiverServiceFactory,\n private readonly _manager: BleManager,\n private readonly _platform: Platform = Platform,\n private readonly _permissionsAndroid: PermissionsAndroid = PermissionsAndroid,\n private readonly _deviceConnectionStateMachineFactory: (\n args: DeviceConnectionStateMachineParams<RNBleApduSenderDependencies>,\n ) => DeviceConnectionStateMachine<RNBleApduSenderDependencies> = (args) =>\n new DeviceConnectionStateMachine(args),\n private readonly _deviceApduSenderFactory: (\n args: RNBleApduSenderConstructorArgs,\n loggerFactory: (tag: string) => LoggerPublisherService,\n ) => RNBleApduSender = (args, loggerFactory) =>\n new RNBleApduSender(args, loggerFactory),\n ) {\n this._logger = _loggerServiceFactory(\"ReactNativeBleTransport\");\n this._isSupported = Maybe.zero();\n this._deviceConnectionsById = new Map();\n this._reconnectionSubscription = Maybe.zero();\n this._manager.onStateChange((state) => {\n this._bleStateSubject.next(state);\n }, true);\n }\n\n /**\n * Not implemented for now as the return signature is not really usable.\n * Use listenToAvailableDevices instead.\n */\n startDiscovering(): Observable<TransportDiscoveredDevice> {\n return from([]);\n }\n\n /**\n * Stops the device scanning operation currently in progress.\n *\n * @return {Promise<void>} A promise that resolves once the device scanning has been successfully stopped.\n */\n async stopDiscovering(): Promise<void> {\n await this._stopScanning();\n }\n\n private _maybeScanningSubject: Maybe<\n BehaviorSubject<InternalScannedDevice[]>\n > = Nothing;\n\n private _scannedDevicesSubject: BehaviorSubject<InternalScannedDevice[]> =\n new BehaviorSubject<InternalScannedDevice[]>([]);\n private _startedScanningSubscriber: Subscription | undefined = undefined;\n\n private _startScanning() {\n if (this._startedScanningSubscriber != undefined) {\n return;\n }\n\n //Reset the scanned devices list as new scan will start\n this._scannedDevicesSubject.next([]);\n\n this._startedScanningSubscriber = from(this._bleStateSubject)\n .pipe(\n filter((state) => state === \"PoweredOn\"),\n switchMap(() => this.requestPermission()),\n switchMap((isSupported) => {\n if (!isSupported) {\n return throwError(() => new BleNotSupported(\"BLE not supported\"));\n }\n\n const subject = new BehaviorSubject<InternalScannedDevice[]>([]);\n this._maybeScanningSubject = Maybe.of(subject);\n const devicesById = new Map<string, InternalScannedDevice>();\n\n this._logger.info(\"[RNBleTransport][startScanning] startDeviceScan\");\n this._manager.startDeviceScan(\n this._deviceModelDataSource.getBluetoothServices(),\n { allowDuplicates: true },\n (error, rnDevice) => {\n if (error || !rnDevice) {\n subject.error(error || new Error(\"scan error\"));\n return;\n }\n devicesById.set(rnDevice.id, {\n device: rnDevice,\n timestamp: Date.now(),\n });\n subject.next(Array.from(devicesById.values()));\n },\n );\n\n /**\n * In case there is no update from startDeviceScan, we still emit the\n * list of devices. This is useful for instance if there is only 1 device\n * in the vicinity and it just got turned off. It will not \"advertise\"\n * anymore so startDeviceScan won't trigger.\n */\n const interval = setInterval(() => {\n subject.next(Array.from(devicesById.values()));\n }, 1000);\n\n return subject.asObservable().pipe(\n finalize(() => {\n this._logger.debug(\"[RNBleTransport][startScanning] finalize\");\n subject.complete();\n clearInterval(interval);\n this._maybeScanningSubject = Nothing;\n this._manager.stopDeviceScan();\n }),\n );\n }),\n throttleTime(1000),\n )\n .subscribe({\n next: (devices) => {\n this._logger.debug(\n \"[RNBleTransport][startScanning] onNext called with devices\",\n { data: { devices } },\n );\n this._scannedDevicesSubject.next(devices);\n },\n error: (error) => {\n this._logger.error(\"Error while scanning\", { data: { error } });\n },\n });\n }\n\n private async _stopScanning(): Promise<void> {\n this._maybeScanningSubject.map((subject) => {\n subject.complete();\n this._maybeScanningSubject = Nothing;\n });\n\n await this._manager.stopDeviceScan();\n //Stop listening the observable from this._startScanning()\n this._startedScanningSubscriber?.unsubscribe();\n this._startedScanningSubscriber = undefined;\n\n return;\n }\n\n /**\n * Listens to known devices and emits updates when new devices are discovered or when properties of existing devices are updated.\n *\n * @return {Observable<TransportDiscoveredDevice[]>} An observable stream of discovered devices, containing device information as an array of TransportDiscoveredDevice objects.\n */\n listenToAvailableDevices(): Observable<TransportDiscoveredDevice[]> {\n this._startScanning();\n\n return this._scannedDevicesSubject.asObservable().pipe(\n map((internalScannedDevices) => {\n const eitherConnectedDevices = Array.from(\n this._deviceConnectionsById.values(),\n ).map((connection) =>\n this._mapDeviceToTransportDiscoveredDevice(\n connection.getDependencies().device,\n [\n connection.getDependencies().internalDevice.bleDeviceInfos\n .serviceUuid,\n ],\n ),\n );\n\n const connectedDevices = Either.rights(eitherConnectedDevices);\n\n const eitherScannedDevices = internalScannedDevices\n .filter(\n ({ timestamp }) => timestamp > Date.now() - CONNECTION_LOST_DELAY,\n )\n .sort(\n (a, b) =>\n (b.device.rssi ?? -Infinity) - (a.device.rssi ?? -Infinity), // RSSI is a negative value and the higher, the stronger the signal\n )\n .map(({ device }) =>\n this._mapDeviceToTransportDiscoveredDevice(\n device,\n device.serviceUUIDs,\n ),\n )\n .filter((d) => !!d);\n\n const scannedDevices = Either.rights(eitherScannedDevices);\n\n return [...connectedDevices, ...scannedDevices];\n }),\n );\n }\n\n private _mapServicesUUIDsToBluetoothDeviceInfo(\n servicesUUIDs: string[] | null | undefined,\n ): Either<NoDeviceModelFoundError, BleDeviceInfos> {\n for (const serviceUUID of servicesUUIDs || []) {\n const bluetoothServiceInfo =\n this._deviceModelDataSource.getBluetoothServicesInfos()[serviceUUID];\n if (bluetoothServiceInfo) return Right(bluetoothServiceInfo);\n }\n\n return Left(\n new NoDeviceModelFoundError(\n `No device model found for [uuids=${servicesUUIDs}]`,\n ),\n );\n }\n\n private _mapServicesUUIDsToDeviceModel(\n servicesUUIDs: string[] | null | undefined,\n ): Either<NoDeviceModelFoundError, TransportDeviceModel> {\n const bluetoothServiceInfo =\n this._mapServicesUUIDsToBluetoothDeviceInfo(servicesUUIDs);\n return bluetoothServiceInfo.map((info) => info.deviceModel);\n }\n\n private _mapDeviceToTransportDiscoveredDevice(\n device: Device,\n servicesUUIDs: string[] | null | undefined,\n ): Either<NoDeviceModelFoundError, TransportDiscoveredDevice> {\n const deviceModel = this._mapServicesUUIDsToDeviceModel(servicesUUIDs);\n return deviceModel.map((model) => ({\n id: device.id,\n name: device.localName || device.name || \"\",\n deviceModel: model,\n transport: this.identifier,\n rssi: device.rssi || undefined,\n }));\n }\n\n /**\n * Establishes a connection to a device and configures the necessary parameters for communication.\n *\n * @param {Object} params - An object containing parameters required for the connection.\n * @param {DeviceId} params.deviceId - The unique identifier of the device to connect to.\n * @param {DisconnectHandler} params.onDisconnect - A callback function to handle device disconnection.\n * @returns {Promise<Either<ConnectError, TransportConnectedDevice>>} A promise resolving to either a connection error or a successfully connected device.\n */\n async connect(params: {\n deviceId: DeviceId;\n onDisconnect: DisconnectHandler;\n }): Promise<Either<ConnectError, TransportConnectedDevice>> {\n const existing = this._deviceConnectionsById.get(params.deviceId);\n if (existing) {\n const deviceModel =\n existing.getDependencies().internalDevice.bleDeviceInfos.deviceModel;\n return Right(\n new TransportConnectedDevice({\n id: params.deviceId,\n deviceModel: deviceModel,\n type: \"BLE\",\n sendApdu: (...a) => existing.sendApdu(...a),\n transport: this.identifier,\n }),\n );\n }\n\n await this._stopScanning();\n await this._safeCancel(params.deviceId);\n\n return EitherAsync<ConnectError, TransportConnectedDevice>(\n async ({ throwE }) => {\n let device: Device;\n let servicesUUIDs: string[] = [];\n try {\n await this._manager.connectToDevice(params.deviceId, {\n requestMTU: DEFAULT_MTU,\n });\n\n device =\n await this._manager.discoverAllServicesAndCharacteristicsForDevice(\n params.deviceId,\n );\n\n servicesUUIDs = (await device.services()).map((s) => s.uuid);\n } catch (error) {\n if (\n error instanceof BleError &&\n (error.iosErrorCode as number) === 14\n ) {\n /**\n * This happens when the Ledger device reset its pairing, but the\n * iOS system still has that device paired.\n */\n return throwE(new PeerRemovedPairingError(error));\n }\n return throwE(new OpeningConnectionError(error));\n }\n\n const disconnectionSubscription = this._manager.onDeviceDisconnected(\n device.id,\n (error, d) => {\n this._handleDeviceDisconnected(error, d);\n },\n );\n\n const bleDeviceInfos = this._mapServicesUUIDsToBluetoothDeviceInfo(\n servicesUUIDs,\n ).caseOf({\n Right: (info) => {\n return info;\n },\n Left: (error) => {\n return throwE(new OpeningConnectionError(error));\n },\n });\n\n const deviceModel = bleDeviceInfos.deviceModel;\n\n const internalDevice: RNBleInternalDevice = {\n id: device.id,\n bleDeviceInfos,\n };\n\n const deviceApduSender = this._deviceApduSenderFactory(\n {\n apduSenderFactory: this._apduSenderFactory,\n apduReceiverFactory: this._apduReceiverFactory,\n dependencies: { device, internalDevice, manager: this._manager },\n },\n this._loggerServiceFactory,\n );\n\n const reconnectionTimeout =\n Platform.OS === \"ios\"\n ? BLE_DISCONNECT_TIMEOUT_IOS\n : BLE_DISCONNECT_TIMEOUT_ANDROID;\n\n const deviceConnectionStateMachine =\n this._deviceConnectionStateMachineFactory({\n deviceId: params.deviceId,\n deviceApduSender,\n timeoutDuration: reconnectionTimeout,\n onTerminated: () => {\n try {\n this._safeCancel(params.deviceId);\n params.onDisconnect(params.deviceId);\n this._deviceConnectionsById.delete(params.deviceId);\n disconnectionSubscription.remove();\n if (this._reconnectionSubscription.isJust()) {\n this._reconnectionSubscription.map((sub) =>\n sub.unsubscribe(),\n );\n this._reconnectionSubscription = Maybe.zero();\n }\n } catch (e) {\n this._logger.error(\n \"Error in termination of device connection\",\n { data: { e } },\n );\n }\n },\n });\n\n await deviceApduSender.setupConnection().catch((e) => {\n this._safeCancel(params.deviceId);\n disconnectionSubscription.remove();\n throw e;\n });\n\n this._deviceConnectionsById.set(\n params.deviceId,\n deviceConnectionStateMachine,\n );\n\n return new TransportConnectedDevice({\n id: device.id,\n deviceModel: deviceModel,\n type: \"BLE\",\n sendApdu: (...args) => deviceConnectionStateMachine.sendApdu(...args),\n transport: this.identifier,\n });\n },\n ).run();\n }\n\n /**\n * Terminates the connection with the connected device and cleans up related resources.\n *\n * @param {TransportConnectedDevice} params.connectedDevice - The connected device to be disconnected.\n * @return {Promise<Either<DmkError, void>>} A promise resolving to either a success (void) or a failure (DmkError) value.\n */\n async disconnect(params: {\n connectedDevice: TransportConnectedDevice;\n }): Promise<Either<DmkError, void>> {\n const deviceId = params.connectedDevice.id;\n const deviceConnection = this._deviceConnectionsById.get(deviceId);\n if (!deviceConnection) {\n throw new UnknownDeviceError(\n `No connected device found with id ${deviceId}`,\n );\n }\n\n deviceConnection.closeConnection();\n\n return Promise.resolve(Right(undefined));\n }\n\n /**\n * Determines if the feature or permission is supported.\n *\n * This method evaluates the current state of the `_isSupported` property to determine\n * whether the relevant feature is supported or throws an error if its state has\n * not been initialized properly.\n *\n * @return {boolean} Returns `true` if the feature is supported, otherwise `false`.\n * Throws an error if the `_isSupported` property has not been initialized.\n */\n isSupported(): boolean {\n return this._isSupported.caseOf({\n Just: (isSupported) => isSupported,\n Nothing: () => {\n throw new Error(\"Should initialize permission\");\n },\n });\n }\n\n /**\n * Retrieves the transport identifier associated with the object.\n *\n * @return {TransportIdentifier} The transport identifier.\n */\n getIdentifier(): TransportIdentifier {\n return this.identifier;\n }\n\n /**\n * Requests the necessary permissions based on the operating system.\n * For iOS, it automatically sets the permissions as granted.\n * For Android, it checks and requests location, Bluetooth scan, and Bluetooth connect permissions, depending on the API level.\n * If permissions are granted, updates the internal support state and logs the result.\n *\n * @return {Promise<boolean>} A promise that resolves to true if the required permissions are granted, otherwise false.\n */\n async requestPermission(): Promise<boolean> {\n if (this._platform.OS === \"ios\") {\n this._isSupported = Maybe.of(true);\n return true;\n }\n\n if (\n this._platform.OS === \"android\" &&\n this._permissionsAndroid.PERMISSIONS[\"ACCESS_FINE_LOCATION\"]\n ) {\n const apiLevel = parseInt(this._platform.Version.toString(), 10);\n\n if (apiLevel < 31) {\n const granted = await this._permissionsAndroid.request(\n this._permissionsAndroid.PERMISSIONS[\"ACCESS_FINE_LOCATION\"],\n );\n this._isSupported = Maybe.of(\n granted === this._permissionsAndroid.RESULTS[\"GRANTED\"],\n );\n }\n if (\n this._permissionsAndroid.PERMISSIONS[\"BLUETOOTH_SCAN\"] &&\n this._permissionsAndroid.PERMISSIONS[\"BLUETOOTH_CONNECT\"]\n ) {\n const result = await this._permissionsAndroid.requestMultiple([\n this._permissionsAndroid.PERMISSIONS[\"BLUETOOTH_SCAN\"],\n this._permissionsAndroid.PERMISSIONS[\"BLUETOOTH_CONNECT\"],\n this._permissionsAndroid.PERMISSIONS[\"ACCESS_FINE_LOCATION\"],\n ]);\n\n this._isSupported = Maybe.of(\n result[\"android.permission.BLUETOOTH_CONNECT\"] ===\n this._permissionsAndroid.RESULTS[\"GRANTED\"] &&\n result[\"android.permission.BLUETOOTH_SCAN\"] ===\n this._permissionsAndroid.RESULTS[\"GRANTED\"] &&\n result[\"android.permission.ACCESS_FINE_LOCATION\"] ===\n this._permissionsAndroid.RESULTS[\"GRANTED\"],\n );\n\n return true;\n }\n }\n\n this._logger.error(\"Permission have not been granted\", {\n data: { isSupported: this._isSupported.extract() },\n });\n\n this._isSupported = Maybe.of(false);\n return false;\n }\n\n /**\n * Handles the event when a Bluetooth device gets disconnected. This method attempts\n * to reconnect to the device, retries a certain number of times on failure, and\n * invokes a callback if the reconnection does not succeed.\n *\n * @param {BleError | null} error - The error object representing the reason for the disconnection, or null if no error occurred.\n * @param {Device | null} device - The Bluetooth device that was disconnected, or null if no device is provided.\n * @return {void}\n */\n private _handleDeviceDisconnected(\n error: BleError | null,\n device: Device | null,\n ) {\n this._logger.debug(\"[RNBLE][_handleDeviceDisconnected]\", {\n data: { error, device },\n });\n if (!device) {\n this._logger.debug(\n \"[_handleDeviceDisconnected] disconnected handler didn't find device\",\n );\n return;\n }\n if (!device?.id || !this._deviceConnectionsById.has(device?.id)) return;\n if (error) {\n this._logger.error(\"device disconnected error\", {\n data: { error, device },\n });\n return;\n }\n const deviceId = device.id;\n if (this._reconnectionSubscription.isJust()) {\n return;\n }\n\n Maybe.fromNullable(this._deviceConnectionsById.get(deviceId)).map(\n (deviceConnection) => deviceConnection.eventDeviceDetached(),\n );\n\n const reconnect$ = from([0]).pipe(\n switchMap(async () => {\n await this._stopScanning();\n await this._safeCancel(deviceId);\n }),\n switchMap(async () => {\n this._logger.debug(\n \"[_handleDeviceDisconnected] reconnecting to device\",\n { data: { id: device.id } },\n );\n const reconnectedDevice = await this._manager.connectToDevice(\n deviceId,\n { requestMTU: DEFAULT_MTU, timeout: 2000 },\n );\n this._logger.debug(\n \"[_handleDeviceDisconnected] reconnected to device\",\n { data: { id: device.id } },\n );\n const reconnectedDeviceUsable =\n await reconnectedDevice.discoverAllServicesAndCharacteristics();\n this._logger.debug(\n \"[_handleDeviceDisconnected] discovered all services and characteristics\",\n { data: { reconnectedDeviceUsable } },\n );\n await this._handleDeviceReconnected(reconnectedDeviceUsable);\n return reconnectedDeviceUsable;\n }),\n retry(5),\n );\n\n this._reconnectionSubscription = Maybe.of(\n reconnect$.subscribe({\n next: (d) =>\n this._logger.debug(\n \"[_handleDeviceDisconnected] Reconnected to device\",\n { data: { id: d.id } },\n ),\n complete: () => {\n this._reconnectionSubscription = Maybe.zero();\n },\n error: (e) => {\n this._logger.error(\n \"[_handleDeviceDisconnected] All reconnection attempts failed\",\n { data: { e } },\n );\n Maybe.fromNullable(this._deviceConnectionsById.get(deviceId)).map(\n (sm) => sm.closeConnection(),\n );\n this._reconnectionSubscription = Maybe.zero();\n },\n }),\n );\n }\n\n /**\n * Handles the reconnection of a device. Configures the device connection and its corresponding\n * internal device upon reconnection, including updating the connection state, registering\n * callbacks for write and monitor operations, and initiating a reconnect operation.\n *\n * @param {Device} device - The ddevice object that has been reconnected. Contains device details,\n * such as the device ID.\n * @return {Promise<Either<DeviceConnectionNotFound | InternalDeviceNotFound, void>>} A promise that completes when the device reconnection has been fully\n * configured. Resolves with no value or rejects if an error occurs during\n * the reconnection process.\n */\n private async _handleDeviceReconnected(device: Device) {\n const errorOrDeviceConnection = Maybe.fromNullable(\n this._deviceConnectionsById.get(device.id),\n ).toEither(new DeviceConnectionNotFound());\n\n return EitherAsync(async ({ liftEither, throwE }) => {\n const deviceConnectionStateMachine = await liftEither(\n errorOrDeviceConnection,\n );\n\n const servicesUUIDs = (await device.services()).map((s) => s.uuid);\n\n const internalDevice = this._mapServicesUUIDsToBluetoothDeviceInfo(\n servicesUUIDs,\n ).caseOf({\n Right: (info) => {\n return {\n id: device.id,\n bleDeviceInfos: info,\n };\n },\n Left: (error) => {\n this._logger.error(\n \"Error in mapping services UUIDs to Bluetooth device info\",\n {\n data: { error },\n },\n );\n\n return throwE(error);\n },\n });\n\n deviceConnectionStateMachine.setDependencies({\n device,\n manager: this._manager,\n internalDevice,\n });\n\n await deviceConnectionStateMachine.setupConnection().catch((e) => {\n this._safeCancel(device.id);\n throw e;\n });\n\n deviceConnectionStateMachine.eventDeviceAttached();\n }).run();\n }\n\n private async _safeCancel(deviceId: DeviceId) {\n // only invoke if the BleManager under test actually has it\n if (typeof this._manager.cancelDeviceConnection === \"function\") {\n const connectedDevices = await this._manager.connectedDevices(\n this._deviceModelDataSource.getBluetoothServices(),\n );\n\n for (const device of connectedDevices) {\n if (device.id === deviceId) {\n await this._manager.cancelDeviceConnection(deviceId);\n }\n }\n }\n }\n}\n\nexport const RNBleTransportFactory: TransportFactory = ({\n deviceModelDataSource,\n loggerServiceFactory,\n apduSenderServiceFactory,\n apduReceiverServiceFactory,\n}) =>\n new RNBleTransport(\n deviceModelDataSource,\n loggerServiceFactory,\n apduSenderServiceFactory,\n apduReceiverServiceFactory,\n new BleManager(),\n );\n"],
5
- "mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,oBAAAE,EAAA,0BAAAC,EAAA,6BAAAC,IAAA,eAAAC,EAAAL,GAAA,IAAAM,EAA6C,wBAC7CC,EAAyD,gCACzDC,EAoBO,2CACPC,EAAiE,qBACjEC,EAYO,gBAEPC,EAKO,4BACPC,EAKO,6BACPC,EAKO,0CAEA,MAAMT,EAA2B,SAOjC,MAAMF,CAAoC,CAa/C,YACmBY,EACAC,EAGAC,EACAC,EACAC,EACAC,EAAsB,WACtBC,EAA0C,qBAC1CC,EAEiDC,GAChE,IAAI,+BAA6BA,CAAI,EACtBC,EAGM,CAACD,EAAME,IAC5B,IAAI,kBAAgBF,EAAME,CAAa,EACzC,CAlBiB,4BAAAV,EACA,2BAAAC,EAGA,wBAAAC,EACA,0BAAAC,EACA,cAAAC,EACA,eAAAC,EACA,yBAAAC,EACA,0CAAAC,EAIA,8BAAAE,EAMjB,KAAK,QAAUR,EAAsB,yBAAyB,EAC9D,KAAK,aAAe,QAAM,KAAK,EAC/B,KAAK,uBAAyB,IAAI,IAClC,KAAK,0BAA4B,QAAM,KAAK,EAC5C,KAAK,SAAS,cAAeU,GAAU,CACrC,KAAK,iBAAiB,KAAKA,CAAK,CAClC,EAAG,EAAI,CACT,C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B,gBAAgB,CAC3C,OAAAlB,EACA,QAAS,KAAK,SACd,eAAAe,CACF,CAAC,EAED,MAAMG,EAA6B,gBAAgB,EAAE,MAAOE,GAAM,CAChE,WAAK,YAAYpB,EAAO,EAAE,EACpBoB,CACR,CAAC,EAEDF,EAA6B,oBAAoB,CACnD,CAAC,EAAE,IAAI,CACT,CAEA,MAAc,YAAYG,EAAoB,CAE5C,GAAI,OAAO,KAAK,SAAS,wBAA2B,WAAY,CAC9D,MAAM1B,EAAmB,MAAM,KAAK,SAAS,iBAC3C,KAAK,uBAAuB,qBAAqB,CACnD,EAEA,UAAWK,KAAUL,EACfK,EAAO,KAAOqB,GAChB,MAAM,KAAK,SAAS,uBAAuBA,CAAQ,CAGzD,CACF,CACF,CAEO,MAAM3D,EAA0C,CAAC,CACtD,sBAAAqE,EACA,qBAAAC,EACA,yBAAAC,EACA,2BAAAC,CACF,IACE,IAAIzE,EACFsE,EACAC,EACAC,EACAC,EACA,IAAI,YACN",
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", "_manager", "_platform", "_permissionsAndroid", "_deviceConnectionStateMachineFactory", "args", "_deviceApduSenderFactory", "loggerFactory", "state", "isSupported", "subject", "devicesById", "error", "rnDevice", "interval", "devices", "internalScannedDevices", "eitherConnectedDevices", "connection", "connectedDevices", "eitherScannedDevices", "timestamp", "a", "b", "device", "d", "scannedDevices", "servicesUUIDs", "serviceUUID", "bluetoothServiceInfo", "info", "model", "params", "existing", "deviceModel", "throwE", "s", "disconnectionSubscription", "bleDeviceInfos", "internalDevice", "deviceApduSender", "reconnectionTimeout", "deviceConnectionStateMachine", "sub", "e", "deviceId", "deviceConnection", "granted", "result", "reconnect$", "reconnectedDevice", "reconnectedDeviceUsable", "sm", "errorOrDeviceConnection", "liftEither", "deviceModelDataSource", "loggerServiceFactory", "apduSenderServiceFactory", "apduReceiverServiceFactory"]
4
+ "sourcesContent": ["import { PermissionsAndroid, Platform } from \"react-native\";\nimport { BleError, BleManager, type Device, State } from \"react-native-ble-plx\";\nimport {\n type ApduReceiverServiceFactory,\n type ApduSenderServiceFactory,\n type BleDeviceInfos,\n type ConnectError,\n DeviceConnectionStateMachine,\n type DeviceConnectionStateMachineParams,\n type DeviceId,\n type DeviceModelDataSource,\n type DisconnectHandler,\n type DmkError,\n type LoggerPublisherService,\n OpeningConnectionError,\n type Transport,\n TransportConnectedDevice,\n type TransportDeviceModel,\n type TransportDiscoveredDevice,\n type TransportFactory,\n type TransportIdentifier,\n UnknownDeviceError,\n} from \"@ledgerhq/device-management-kit\";\nimport { Either, EitherAsync, Left, Maybe, Nothing, Right } from \"purify-ts\";\nimport {\n BehaviorSubject,\n filter,\n finalize,\n from,\n map,\n type Observable,\n retry,\n type Subscription,\n switchMap,\n throttleTime,\n throwError,\n} from \"rxjs\";\n\nimport {\n BLE_DISCONNECT_TIMEOUT_ANDROID,\n BLE_DISCONNECT_TIMEOUT_IOS,\n CONNECTION_LOST_DELAY,\n DEFAULT_MTU,\n} from \"@api/model/Const\";\nimport {\n BleNotSupported,\n DeviceConnectionNotFound,\n NoDeviceModelFoundError,\n PeerRemovedPairingError,\n} from \"@api/model/Errors\";\nimport {\n RNBleApduSender,\n type RNBleApduSenderConstructorArgs,\n type RNBleApduSenderDependencies,\n type RNBleInternalDevice,\n} from \"@api/transport/RNBleApduSender\";\n\nexport const rnBleTransportIdentifier = \"RN_BLE\";\n\ntype InternalScannedDevice = {\n device: Device;\n timestamp: number;\n};\n\nexport class RNBleTransport implements Transport {\n private _logger: LoggerPublisherService;\n private _isSupported: Maybe<boolean>;\n private _deviceConnectionsById: Map<\n DeviceId,\n DeviceConnectionStateMachine<RNBleApduSenderDependencies>\n >;\n // private readonly _manager: BleManager;\n private readonly identifier: TransportIdentifier = \"RN_BLE\";\n private _reconnectionSubscription: Maybe<Subscription>;\n private readonly _bleStateSubject: BehaviorSubject<State> =\n new BehaviorSubject<State>(State.Unknown);\n\n constructor(\n private readonly _deviceModelDataSource: DeviceModelDataSource,\n private readonly _loggerServiceFactory: (\n tag: string,\n ) => LoggerPublisherService,\n private readonly _apduSenderFactory: ApduSenderServiceFactory,\n private readonly _apduReceiverFactory: ApduReceiverServiceFactory,\n private readonly _manager: BleManager,\n private readonly _platform: Platform = Platform,\n private readonly _permissionsAndroid: PermissionsAndroid = PermissionsAndroid,\n private readonly _deviceConnectionStateMachineFactory: (\n args: DeviceConnectionStateMachineParams<RNBleApduSenderDependencies>,\n ) => DeviceConnectionStateMachine<RNBleApduSenderDependencies> = (args) =>\n new DeviceConnectionStateMachine(args),\n private readonly _deviceApduSenderFactory: (\n args: RNBleApduSenderConstructorArgs,\n loggerFactory: (tag: string) => LoggerPublisherService,\n ) => RNBleApduSender = (args, loggerFactory) =>\n new RNBleApduSender(args, loggerFactory),\n ) {\n this._logger = _loggerServiceFactory(\"ReactNativeBleTransport\");\n this._isSupported = Maybe.zero();\n this._deviceConnectionsById = new Map();\n this._reconnectionSubscription = Maybe.zero();\n this._manager.onStateChange((state) => {\n this._bleStateSubject.next(state);\n }, true);\n }\n\n /**\n * Not implemented for now as the return signature is not really usable.\n * Use listenToAvailableDevices instead.\n */\n startDiscovering(): Observable<TransportDiscoveredDevice> {\n return from([]);\n }\n\n /**\n * Stops the device scanning operation currently in progress.\n *\n * @return {Promise<void>} A promise that resolves once the device scanning has been successfully stopped.\n */\n async stopDiscovering(): Promise<void> {\n await this._stopScanning();\n }\n\n private _maybeScanningSubject: Maybe<\n BehaviorSubject<InternalScannedDevice[]>\n > = Nothing;\n\n private _scannedDevicesSubject: BehaviorSubject<InternalScannedDevice[]> =\n new BehaviorSubject<InternalScannedDevice[]>([]);\n private _startedScanningSubscriber: Subscription | undefined = undefined;\n\n private _startScanning() {\n if (this._startedScanningSubscriber != undefined) {\n return;\n }\n\n //Reset the scanned devices list as new scan will start\n this._scannedDevicesSubject.next([]);\n\n this._startedScanningSubscriber = from(this._bleStateSubject)\n .pipe(\n filter((state) => state === \"PoweredOn\"),\n switchMap(() => this.requestPermission()),\n switchMap((isSupported) => {\n if (!isSupported) {\n return throwError(() => new BleNotSupported(\"BLE not supported\"));\n }\n\n const subject = new BehaviorSubject<InternalScannedDevice[]>([]);\n this._maybeScanningSubject = Maybe.of(subject);\n const devicesById = new Map<string, InternalScannedDevice>();\n\n this._logger.info(\"[RNBleTransport][startScanning] startDeviceScan\");\n this._manager.startDeviceScan(\n this._deviceModelDataSource.getBluetoothServices(),\n { allowDuplicates: true },\n (error, rnDevice) => {\n if (error || !rnDevice) {\n subject.error(error || new Error(\"scan error\"));\n return;\n }\n devicesById.set(rnDevice.id, {\n device: rnDevice,\n timestamp: Date.now(),\n });\n subject.next(Array.from(devicesById.values()));\n },\n );\n\n /**\n * In case there is no update from startDeviceScan, we still emit the\n * list of devices. This is useful for instance if there is only 1 device\n * in the vicinity and it just got turned off. It will not \"advertise\"\n * anymore so startDeviceScan won't trigger.\n */\n const interval = setInterval(() => {\n subject.next(Array.from(devicesById.values()));\n }, 1000);\n\n return subject.asObservable().pipe(\n finalize(() => {\n this._logger.debug(\"[RNBleTransport][startScanning] finalize\");\n subject.complete();\n clearInterval(interval);\n this._maybeScanningSubject = Nothing;\n this._manager.stopDeviceScan();\n }),\n );\n }),\n throttleTime(1000),\n )\n .subscribe({\n next: (devices) => {\n this._logger.debug(\n \"[RNBleTransport][startScanning] onNext called with devices\",\n { data: { devices } },\n );\n this._scannedDevicesSubject.next(devices);\n },\n error: (error) => {\n this._logger.error(\"Error while scanning\", { data: { error } });\n },\n });\n }\n\n private async _stopScanning(): Promise<void> {\n this._maybeScanningSubject.map((subject) => {\n subject.complete();\n this._maybeScanningSubject = Nothing;\n });\n\n await this._manager.stopDeviceScan();\n //Stop listening the observable from this._startScanning()\n this._startedScanningSubscriber?.unsubscribe();\n this._startedScanningSubscriber = undefined;\n\n return;\n }\n\n /**\n * Listens to known devices and emits updates when new devices are discovered or when properties of existing devices are updated.\n *\n * @return {Observable<TransportDiscoveredDevice[]>} An observable stream of discovered devices, containing device information as an array of TransportDiscoveredDevice objects.\n */\n listenToAvailableDevices(): Observable<TransportDiscoveredDevice[]> {\n this._startScanning();\n\n return this._scannedDevicesSubject.asObservable().pipe(\n map((internalScannedDevices) => {\n const eitherConnectedDevices = Array.from(\n this._deviceConnectionsById.values(),\n ).map((connection) =>\n this._mapDeviceToTransportDiscoveredDevice(\n connection.getDependencies().device,\n [\n connection.getDependencies().internalDevice.bleDeviceInfos\n .serviceUuid,\n ],\n ),\n );\n\n const connectedDevices = Either.rights(eitherConnectedDevices);\n\n const eitherScannedDevices = internalScannedDevices\n .filter(\n ({ timestamp }) => timestamp > Date.now() - CONNECTION_LOST_DELAY,\n )\n .sort(\n (a, b) =>\n (b.device.rssi ?? -Infinity) - (a.device.rssi ?? -Infinity), // RSSI is a negative value and the higher, the stronger the signal\n )\n .map(({ device }) =>\n this._mapDeviceToTransportDiscoveredDevice(\n device,\n device.serviceUUIDs,\n ),\n )\n .filter((d) => !!d);\n\n const scannedDevices = Either.rights(eitherScannedDevices);\n\n return [...connectedDevices, ...scannedDevices];\n }),\n );\n }\n\n private _mapServicesUUIDsToBluetoothDeviceInfo(\n servicesUUIDs: string[] | null | undefined,\n ): Either<NoDeviceModelFoundError, BleDeviceInfos> {\n for (const serviceUUID of servicesUUIDs || []) {\n const bluetoothServiceInfo =\n this._deviceModelDataSource.getBluetoothServicesInfos()[serviceUUID];\n if (bluetoothServiceInfo) return Right(bluetoothServiceInfo);\n }\n\n return Left(\n new NoDeviceModelFoundError(\n `No device model found for [uuids=${servicesUUIDs}]`,\n ),\n );\n }\n\n private _mapServicesUUIDsToDeviceModel(\n servicesUUIDs: string[] | null | undefined,\n ): Either<NoDeviceModelFoundError, TransportDeviceModel> {\n const bluetoothServiceInfo =\n this._mapServicesUUIDsToBluetoothDeviceInfo(servicesUUIDs);\n return bluetoothServiceInfo.map((info) => info.deviceModel);\n }\n\n private _mapDeviceToTransportDiscoveredDevice(\n device: Device,\n servicesUUIDs: string[] | null | undefined,\n ): Either<NoDeviceModelFoundError, TransportDiscoveredDevice> {\n const deviceModel = this._mapServicesUUIDsToDeviceModel(servicesUUIDs);\n return deviceModel.map((model) => ({\n id: device.id,\n name: device.localName || device.name || \"\",\n deviceModel: model,\n transport: this.identifier,\n rssi: device.rssi || undefined,\n }));\n }\n\n /**\n * Establishes a connection to a device and configures the necessary parameters for communication.\n *\n * @param {Object} params - An object containing parameters required for the connection.\n * @param {DeviceId} params.deviceId - The unique identifier of the device to connect to.\n * @param {DisconnectHandler} params.onDisconnect - A callback function to handle device disconnection.\n * @returns {Promise<Either<ConnectError, TransportConnectedDevice>>} A promise resolving to either a connection error or a successfully connected device.\n */\n async connect(params: {\n deviceId: DeviceId;\n onDisconnect: DisconnectHandler;\n }): Promise<Either<ConnectError, TransportConnectedDevice>> {\n const existing = this._deviceConnectionsById.get(params.deviceId);\n if (existing) {\n const deviceModel =\n existing.getDependencies().internalDevice.bleDeviceInfos.deviceModel;\n return Right(\n new TransportConnectedDevice({\n id: params.deviceId,\n deviceModel: deviceModel,\n type: \"BLE\",\n sendApdu: (...a) => existing.sendApdu(...a),\n transport: this.identifier,\n }),\n );\n }\n\n await this._stopScanning();\n await this._safeCancel(params.deviceId);\n\n return EitherAsync<ConnectError, TransportConnectedDevice>(\n async ({ throwE }) => {\n let device: Device;\n let servicesUUIDs: string[] = [];\n try {\n await this._manager.connectToDevice(params.deviceId, {\n requestMTU: DEFAULT_MTU,\n });\n\n device =\n await this._manager.discoverAllServicesAndCharacteristicsForDevice(\n params.deviceId,\n );\n\n servicesUUIDs = (await device.services()).map((s) => s.uuid);\n } catch (error) {\n if (\n error instanceof BleError &&\n (error.iosErrorCode as number) === 14\n ) {\n /**\n * This happens when the Ledger device reset its pairing, but the\n * iOS system still has that device paired.\n */\n return throwE(new PeerRemovedPairingError(error));\n }\n return throwE(new OpeningConnectionError(error));\n }\n\n const disconnectionSubscription = this._manager.onDeviceDisconnected(\n device.id,\n (error, d) => {\n this._handleDeviceDisconnected(error, d);\n },\n );\n\n const bleDeviceInfos = this._mapServicesUUIDsToBluetoothDeviceInfo(\n servicesUUIDs,\n ).caseOf({\n Right: (info) => {\n return info;\n },\n Left: (error) => {\n return throwE(new OpeningConnectionError(error));\n },\n });\n\n const deviceModel = bleDeviceInfos.deviceModel;\n\n const internalDevice: RNBleInternalDevice = {\n id: device.id,\n bleDeviceInfos,\n };\n\n const deviceApduSender = this._deviceApduSenderFactory(\n {\n apduSenderFactory: this._apduSenderFactory,\n apduReceiverFactory: this._apduReceiverFactory,\n dependencies: { device, internalDevice, manager: this._manager },\n },\n this._loggerServiceFactory,\n );\n\n const reconnectionTimeout =\n Platform.OS === \"ios\"\n ? BLE_DISCONNECT_TIMEOUT_IOS\n : BLE_DISCONNECT_TIMEOUT_ANDROID;\n\n const deviceConnectionStateMachine =\n this._deviceConnectionStateMachineFactory({\n deviceId: params.deviceId,\n deviceApduSender,\n timeoutDuration: reconnectionTimeout,\n tryToReconnect: () => {\n this.tryToReconnect(params.deviceId);\n },\n onTerminated: () => {\n try {\n this._safeCancel(params.deviceId);\n params.onDisconnect(params.deviceId);\n this._deviceConnectionsById.delete(params.deviceId);\n disconnectionSubscription.remove();\n if (this._reconnectionSubscription.isJust()) {\n this._reconnectionSubscription.map((sub) =>\n sub.unsubscribe(),\n );\n this._reconnectionSubscription = Maybe.zero();\n }\n } catch (e) {\n this._logger.error(\n \"Error in termination of device connection\",\n { data: { e } },\n );\n }\n },\n });\n\n await deviceApduSender.setupConnection().catch((e) => {\n this._safeCancel(params.deviceId);\n disconnectionSubscription.remove();\n throw e;\n });\n\n this._deviceConnectionsById.set(\n params.deviceId,\n deviceConnectionStateMachine,\n );\n\n return new TransportConnectedDevice({\n id: device.id,\n deviceModel: deviceModel,\n type: \"BLE\",\n sendApdu: (...args) => deviceConnectionStateMachine.sendApdu(...args),\n transport: this.identifier,\n });\n },\n ).run();\n }\n\n /**\n * Terminates the connection with the connected device and cleans up related resources.\n *\n * @param {TransportConnectedDevice} params.connectedDevice - The connected device to be disconnected.\n * @return {Promise<Either<DmkError, void>>} A promise resolving to either a success (void) or a failure (DmkError) value.\n */\n async disconnect(params: {\n connectedDevice: TransportConnectedDevice;\n }): Promise<Either<DmkError, void>> {\n const deviceId = params.connectedDevice.id;\n const deviceConnection = this._deviceConnectionsById.get(deviceId);\n if (!deviceConnection) {\n throw new UnknownDeviceError(\n `No connected device found with id ${deviceId}`,\n );\n }\n\n deviceConnection.closeConnection();\n\n return Promise.resolve(Right(undefined));\n }\n\n /**\n * Determines if the feature or permission is supported.\n *\n * This method evaluates the current state of the `_isSupported` property to determine\n * whether the relevant feature is supported or throws an error if its state has\n * not been initialized properly.\n *\n * @return {boolean} Returns `true` if the feature is supported, otherwise `false`.\n * Throws an error if the `_isSupported` property has not been initialized.\n */\n isSupported(): boolean {\n return this._isSupported.caseOf({\n Just: (isSupported) => isSupported,\n Nothing: () => {\n throw new Error(\"Should initialize permission\");\n },\n });\n }\n\n /**\n * Retrieves the transport identifier associated with the object.\n *\n * @return {TransportIdentifier} The transport identifier.\n */\n getIdentifier(): TransportIdentifier {\n return this.identifier;\n }\n\n /**\n * Requests the necessary permissions based on the operating system.\n * For iOS, it automatically sets the permissions as granted.\n * For Android, it checks and requests location, Bluetooth scan, and Bluetooth connect permissions, depending on the API level.\n * If permissions are granted, updates the internal support state and logs the result.\n *\n * @return {Promise<boolean>} A promise that resolves to true if the required permissions are granted, otherwise false.\n */\n async requestPermission(): Promise<boolean> {\n if (this._platform.OS === \"ios\") {\n this._isSupported = Maybe.of(true);\n return true;\n }\n\n if (\n this._platform.OS === \"android\" &&\n this._permissionsAndroid.PERMISSIONS[\"ACCESS_FINE_LOCATION\"]\n ) {\n const apiLevel = parseInt(this._platform.Version.toString(), 10);\n\n if (apiLevel < 31) {\n const granted = await this._permissionsAndroid.request(\n this._permissionsAndroid.PERMISSIONS[\"ACCESS_FINE_LOCATION\"],\n );\n this._isSupported = Maybe.of(\n granted === this._permissionsAndroid.RESULTS[\"GRANTED\"],\n );\n }\n if (\n this._permissionsAndroid.PERMISSIONS[\"BLUETOOTH_SCAN\"] &&\n this._permissionsAndroid.PERMISSIONS[\"BLUETOOTH_CONNECT\"]\n ) {\n const result = await this._permissionsAndroid.requestMultiple([\n this._permissionsAndroid.PERMISSIONS[\"BLUETOOTH_SCAN\"],\n this._permissionsAndroid.PERMISSIONS[\"BLUETOOTH_CONNECT\"],\n this._permissionsAndroid.PERMISSIONS[\"ACCESS_FINE_LOCATION\"],\n ]);\n\n this._isSupported = Maybe.of(\n result[\"android.permission.BLUETOOTH_CONNECT\"] ===\n this._permissionsAndroid.RESULTS[\"GRANTED\"] &&\n result[\"android.permission.BLUETOOTH_SCAN\"] ===\n this._permissionsAndroid.RESULTS[\"GRANTED\"] &&\n result[\"android.permission.ACCESS_FINE_LOCATION\"] ===\n this._permissionsAndroid.RESULTS[\"GRANTED\"],\n );\n\n return true;\n }\n }\n\n this._logger.error(\"Permission have not been granted\", {\n data: { isSupported: this._isSupported.extract() },\n });\n\n this._isSupported = Maybe.of(false);\n return false;\n }\n\n /**\n * Handles the event when a Bluetooth device gets disconnected. This method attempts\n * to reconnect to the device, retries a certain number of times on failure, and\n * invokes a callback if the reconnection does not succeed.\n *\n * @param {BleError | null} error - The error object representing the reason for the disconnection, or null if no error occurred.\n * @param {Device | null} device - The Bluetooth device that was disconnected, or null if no device is provided.\n * @return {void}\n */\n private _handleDeviceDisconnected(\n error: BleError | null,\n device: Device | null,\n ) {\n this._logger.debug(\"[RNBLE][_handleDeviceDisconnected]\", {\n data: { error, device },\n });\n if (!device) {\n this._logger.debug(\n \"[_handleDeviceDisconnected] disconnected handler didn't find device\",\n );\n return;\n }\n if (!device?.id || !this._deviceConnectionsById.has(device?.id)) return;\n if (error) {\n this._logger.error(\"device disconnected error\", {\n data: { error, device },\n });\n return;\n }\n const deviceId = device.id;\n if (this._reconnectionSubscription.isJust()) {\n return;\n }\n\n Maybe.fromNullable(this._deviceConnectionsById.get(deviceId)).map(\n (deviceConnection) => deviceConnection.eventDeviceDisconnected(),\n );\n }\n\n private tryToReconnect(deviceId: DeviceId) {\n const reconnect$ = from([0]).pipe(\n switchMap(async () => {\n await this._stopScanning();\n await this._safeCancel(deviceId);\n }),\n switchMap(async () => {\n this._logger.debug(\n \"[_handleDeviceDisconnected] reconnecting to device\",\n { data: { id: deviceId } },\n );\n const reconnectedDevice = await this._manager.connectToDevice(\n deviceId,\n { requestMTU: DEFAULT_MTU, timeout: 2000 },\n );\n this._logger.debug(\n \"[_handleDeviceDisconnected] reconnected to device\",\n { data: { id: deviceId } },\n );\n const reconnectedDeviceUsable =\n await reconnectedDevice.discoverAllServicesAndCharacteristics();\n this._logger.debug(\n \"[_handleDeviceDisconnected] discovered all services and characteristics\",\n { data: { reconnectedDeviceUsable } },\n );\n await this._handleDeviceReconnected(reconnectedDeviceUsable);\n return reconnectedDeviceUsable;\n }),\n retry(5),\n );\n\n this._reconnectionSubscription = Maybe.of(\n reconnect$.subscribe({\n next: (d) =>\n this._logger.debug(\n \"[_handleDeviceDisconnected] Reconnected to device\",\n { data: { id: d.id } },\n ),\n complete: () => {\n this._reconnectionSubscription = Maybe.zero();\n },\n error: (e) => {\n this._logger.error(\n \"[_handleDeviceDisconnected] All reconnection attempts failed\",\n { data: { e } },\n );\n Maybe.fromNullable(this._deviceConnectionsById.get(deviceId)).map(\n (sm) => sm.closeConnection(),\n );\n this._reconnectionSubscription = Maybe.zero();\n },\n }),\n );\n }\n\n /**\n * Handles the reconnection of a device. Configures the device connection and its corresponding\n * internal device upon reconnection, including updating the connection state, registering\n * callbacks for write and monitor operations, and initiating a reconnect operation.\n *\n * @param {Device} device - The ddevice object that has been reconnected. Contains device details,\n * such as the device ID.\n * @return {Promise<Either<DeviceConnectionNotFound | InternalDeviceNotFound, void>>} A promise that completes when the device reconnection has been fully\n * configured. Resolves with no value or rejects if an error occurs during\n * the reconnection process.\n */\n private async _handleDeviceReconnected(device: Device) {\n const errorOrDeviceConnection = Maybe.fromNullable(\n this._deviceConnectionsById.get(device.id),\n ).toEither(new DeviceConnectionNotFound());\n\n return EitherAsync(async ({ liftEither, throwE }) => {\n const deviceConnectionStateMachine = await liftEither(\n errorOrDeviceConnection,\n );\n\n const servicesUUIDs = (await device.services()).map((s) => s.uuid);\n\n const internalDevice = this._mapServicesUUIDsToBluetoothDeviceInfo(\n servicesUUIDs,\n ).caseOf({\n Right: (info) => {\n return {\n id: device.id,\n bleDeviceInfos: info,\n };\n },\n Left: (error) => {\n this._logger.error(\n \"Error in mapping services UUIDs to Bluetooth device info\",\n {\n data: { error },\n },\n );\n\n return throwE(error);\n },\n });\n\n deviceConnectionStateMachine.setDependencies({\n device,\n manager: this._manager,\n internalDevice,\n });\n\n await deviceConnectionStateMachine.setupConnection().catch((e) => {\n this._safeCancel(device.id);\n throw e;\n });\n\n deviceConnectionStateMachine.eventDeviceConnected();\n }).run();\n }\n\n private async _safeCancel(deviceId: DeviceId) {\n // only invoke if the BleManager under test actually has it\n if (typeof this._manager.cancelDeviceConnection === \"function\") {\n const connectedDevices = await this._manager.connectedDevices(\n this._deviceModelDataSource.getBluetoothServices(),\n );\n\n for (const device of connectedDevices) {\n if (device.id === deviceId) {\n await this._manager.cancelDeviceConnection(deviceId);\n }\n }\n }\n }\n}\n\nexport const RNBleTransportFactory: TransportFactory = ({\n deviceModelDataSource,\n loggerServiceFactory,\n apduSenderServiceFactory,\n apduReceiverServiceFactory,\n}) =>\n new RNBleTransport(\n deviceModelDataSource,\n loggerServiceFactory,\n apduSenderServiceFactory,\n apduReceiverServiceFactory,\n new BleManager(),\n );\n"],
5
+ "mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,oBAAAE,EAAA,0BAAAC,EAAA,6BAAAC,IAAA,e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C,CAAC,CACtD,sBAAAqE,EACA,qBAAAC,EACA,yBAAAC,EACA,2BAAAC,CACF,IACE,IAAIzE,EACFsE,EACAC,EACAC,EACAC,EACA,IAAI,YACN",
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", "_manager", "_platform", "_permissionsAndroid", "_deviceConnectionStateMachineFactory", "args", "_deviceApduSenderFactory", "loggerFactory", "state", "isSupported", "subject", "devicesById", "error", "rnDevice", "interval", "devices", "internalScannedDevices", "eitherConnectedDevices", "connection", "connectedDevices", "eitherScannedDevices", "timestamp", "a", "b", "device", "d", "scannedDevices", "servicesUUIDs", "serviceUUID", "bluetoothServiceInfo", "info", "model", "params", "existing", "deviceModel", "throwE", "disconnectionSubscription", "bleDeviceInfos", "internalDevice", "deviceApduSender", "reconnectionTimeout", "deviceConnectionStateMachine", "sub", "e", "deviceId", "deviceConnection", "granted", "result", "reconnect$", "reconnectedDevice", "reconnectedDeviceUsable", "sm", "errorOrDeviceConnection", "liftEither", "s", "deviceModelDataSource", "loggerServiceFactory", "apduSenderServiceFactory", "apduReceiverServiceFactory"]
7
7
  }
@@ -1,2 +1,2 @@
1
- "use strict";var t=require("react-native-ble-plx"),f=require("@ledgerhq/device-management-kit"),R=require("purify-ts"),w=require("rxjs"),o=require("vitest"),E=require("../model/Errors"),r=require("./RNBleTransport");const l={error:vi.fn(),info:vi.fn(),warn:vi.fn(),debug:vi.fn()};vi.mock("react-native",()=>({Platform:{},PermissionsAndroid:{}}));vi.mock("react-native-ble-plx",()=>({Device:vi.fn(),State:{PoweredOn:"PoweredOn",Unknown:"Unknown"},BleError:vi.fn(),BleManager:vi.fn().mockReturnValue({onStateChange:vi.fn(),startDeviceScan:vi.fn(),stopDeviceScan:vi.fn(),connectToDevice:vi.fn(),disconnectFromDevice:vi.fn(),cancelDeviceConnection:vi.fn(),connectedDevices:vi.fn(),monitorCharacteristicForDevice:vi.fn(),writeCharacteristicWithoutResponseForDevice:vi.fn(),discoverAllServicesAndCharacteristicsForDevice:vi.fn(),onDeviceDisconnected:vi.fn(),isDeviceConnected:vi.fn()})}));const h=async(v,O)=>{const b={OS:"android",Version:v.version},T={request:vi.fn().mockImplementation(i=>Promise.resolve({ACCESS_FINE_LOCATION:v.accessFineLocationResult}[i])),PERMISSIONS:v.permissions,RESULTS:{GRANTED:"granted"},requestMultiple:vi.fn().mockImplementation(()=>Promise.resolve(v.requestPermissionResult))},u=new r.RNBleTransport("DeviceModelDataSource",()=>l,()=>{},()=>{},new t.BleManager,b,T);await u.requestPermission();const C=u.isSupported();O.callRequestPermission&&(0,o.expect)(T.request).toHaveBeenCalledWith("ACCESS_FINE_LOCATION"),(0,o.expect)(C).toBe(O.isSupported)};describe("RNBleTransportFactory",()=>{it("should return a RNBleTransport",()=>{const O=(0,r.RNBleTransportFactory)({deviceModelDataSource:"DeviceModelDataSource",loggerServiceFactory:()=>l,apduSenderServiceFactory:()=>{},apduReceiverServiceFactory:()=>{},config:{}});(0,o.expect)(O).toBeInstanceOf(r.RNBleTransport)})});describe("RNBleTransport",()=>{const v={OS:"ios"},O=new f.TransportDeviceModel({id:f.DeviceModelId.FLEX,productName:"Ledger Flex",usbProductId:112,bootloaderUsbProductId:7,usbOnly:!1,memorySize:1533*1024,blockSize:32,masks:[858783744]}),b=vi.fn(()=>["ledgerId"]),T=vi.fn(()=>({ledgerId:new f.BleDeviceInfos(O,"serviceUuid","notifyUuid","writeCmdUuid","readCmdUuid")})),u={getBluetoothServices:b,getBluetoothServicesInfos:T};let C;(0,o.beforeEach)(()=>{vi.clearAllMocks()}),afterEach(()=>{C&&C.unsubscribe()}),describe("getIdentifier",()=>{it("should return rnBleTransportIdentifier",()=>{const i=new t.BleManager,e=new r.RNBleTransport("DeviceModelDataSource",()=>l,()=>{},()=>{},i).getIdentifier();(0,o.expect)(e).toStrictEqual("RN_BLE")})}),describe("isSupported",()=>{it("should return true if platform is ios",async()=>{const i={OS:"ios"},n=new t.BleManager,e=new r.RNBleTransport("DeviceModelDataSource",()=>l,()=>{},()=>{},n,i);await e.requestPermission();const s=e.isSupported();(0,o.expect)(s).toBe(!0)}),it("should return true if platform is android and apiLevel < 31 with good permissions",async()=>{await h({version:30,permissions:{ACCESS_FINE_LOCATION:"ACCESS_FINE_LOCATION",BLUETOOTH_SCAN:"BLUETOOTH_SCAN",BLUETOOTH_CONNECT:"BLUETOOTH_CONNECT"},requestPermissionResult:{"android.permission.BLUETOOTH_CONNECT":"granted","android.permission.BLUETOOTH_SCAN":"granted","android.permission.ACCESS_FINE_LOCATION":"granted"}},{isSupported:!0,callRequestPermission:!0})}),it("should return true if platform is android and apiLevel >= 31 with good permissions",async()=>{await h({version:31,permissions:{ACCESS_FINE_LOCATION:"ACCESS_FINE_LOCATION",BLUETOOTH_SCAN:"BLUETOOTH_SCAN",BLUETOOTH_CONNECT:"BLUETOOTH_CONNECT"},requestPermissionResult:{"android.permission.BLUETOOTH_CONNECT":"granted","android.permission.BLUETOOTH_SCAN":"granted","android.permission.ACCESS_FINE_LOCATION":"granted"}},{isSupported:!0,callRequestPermission:!1})}),it("should return false if platform is android with bad permissions",async()=>{await h({version:31,permissions:{ACCESS_FINE_LOCATION:"",BLUETOOTH_SCAN:"",BLUETOOTH_CONNECT:"BLUETOOTH_CONNECT"},requestPermissionResult:{"android.permission.ACCESS_FINE_LOCATION":"denied","android.permission.BLUETOOTH_CONNECT":"granted","android.permission.BLUETOOTH_SCAN":"granted"}},{isSupported:!1,callRequestPermission:!1})}),it("should return false if platform is android and denied permissions",async()=>{await h({version:31,permissions:{ACCESS_FINE_LOCATION:"ACCESS_FINE_LOCATION",BLUETOOTH_SCAN:"BLUETOOTH_SCAN",BLUETOOTH_CONNECT:"BLUETOOTH_CONNECT"},requestPermissionResult:{"android.permission.BLUETOOTH_CONNECT":"denied","android.permission.BLUETOOTH_SCAN":"denied","android.permission.ACCESS_FINE_LOCATION":"denied"}},{isSupported:!1,callRequestPermission:!1})}),it("should return false if platform isn't android nor ios",async()=>{const i=new t.BleManager,n=new r.RNBleTransport("DeviceModelDataSource",()=>l,()=>{},()=>{},i,{OS:"windows"});await n.requestPermission();const e=n.isSupported();(0,o.expect)(e).toBe(!1)})}),describe("startDiscovering",()=>{it("should throw error if transport is not supported",()=>{const i={OS:"windows"},n=new t.BleManager,e=new r.RNBleTransport(u,()=>l,()=>{},()=>{},n,i);try{e.startDiscovering()}catch(s){(0,o.expect)(s).toBeInstanceOf(E.BleNotSupported)}}),it("should emit an empty array",()=>new Promise(i=>{const n=new t.BleManager;C=new r.RNBleTransport(u,()=>l,()=>{},()=>{},n,v,{}).startDiscovering().subscribe({next:a=>{(0,o.expect)(a).toStrictEqual([]),i(void 0)},error:a=>{throw a},complete:()=>{i(void 0)}})})),it.skip("should emit discovered new device",()=>new Promise(i=>{let n=null;const e=new t.BleManager,s=vi.fn().mockImplementation((c,k,d)=>(n=setInterval(()=>{d(null,{id:"id",localName:"name",serviceUUIDs:["ledgerId"],rssi:42})},500),d(null,{id:"43",localName:"name43",serviceUUIDs:["notLedgerId"],rssi:43}),Promise.resolve())),a=vi.fn().mockImplementation(()=>(n&&(clearInterval(n),n=null),Promise.resolve()));vi.spyOn(e,"connectedDevices").mockResolvedValueOnce([]),vi.spyOn(e,"startDeviceScan").mockImplementation(s),vi.spyOn(e,"stopDeviceScan").mockImplementation(a),C=new r.RNBleTransport(u,()=>l,()=>{},()=>{},e,v,{}).startDiscovering().subscribe({next:c=>{(0,o.expect)(c).toStrictEqual([]),i(void 0)},error:c=>{throw c},complete:()=>{throw new Error("complete should not be called")}})})),it.skip("should emit both known and new device",()=>new Promise(i=>{let n=null;const e=new t.BleManager,s={readRSSI:vi.fn().mockResolvedValueOnce({discoverAllServicesAndCharacteristics:vi.fn().mockResolvedValueOnce({services:vi.fn().mockResolvedValueOnce({}),serviceUUIDs:["ledgerId"],rssi:64,id:"knownDeviceId",localName:"knownDeviceName"})})},a=vi.fn().mockImplementation((d,I,D)=>(n=setInterval(()=>{D(null,{id:"newDeviceId",localName:"newDeviceName",serviceUUIDs:["ledgerId"],rssi:42})},500),D(null,{id:"43",localName:"name43",serviceUUIDs:["notLedgerId"],rssi:43}),Promise.resolve())),p=vi.fn().mockImplementation(()=>(n&&(clearInterval(n),n=null),Promise.resolve()));vi.spyOn(e,"connectedDevices").mockResolvedValueOnce([s]),vi.spyOn(e,"startDeviceScan").mockImplementation(a),vi.spyOn(e,"stopDeviceScan").mockImplementation(p),vi.spyOn(e,"onDeviceDisconnected").mockImplementation(vi.fn());const c=new r.RNBleTransport(u,()=>l,()=>{},()=>{},e,v,{}).startDiscovering(),k={};C=c.subscribe({next:d=>{k[d.id]=d,Object.values(k).length===2&&((0,o.expect)(Object.values(k)).toStrictEqual([{id:"knownDeviceId",name:"knownDeviceName",deviceModel:O,transport:"RN_BLE",rssi:64},{id:"newDeviceId",name:"newDeviceName",deviceModel:O,transport:"RN_BLE",rssi:42}]),i(void 0))}})}))}),describe("stopDiscovering",()=>{it("should call ble manager stop scan on stop discovering",()=>{const i=new t.BleManager,n=vi.fn();vi.spyOn(i,"connectedDevices").mockResolvedValueOnce([]),vi.spyOn(i,"stopDeviceScan").mockImplementation(n),new r.RNBleTransport(u,()=>l,()=>{},()=>{},i,v,{}).stopDiscovering(),(0,o.expect)(n).toHaveBeenCalled()}),it.skip("should call ble manager stop scan when unsubscribe startDiscovering obs",()=>{let i=null;const n=new t.BleManager,e=vi.fn().mockImplementation((p,S,c)=>(i=setInterval(()=>{c(null,{id:"id",localName:"name",serviceUUIDs:["ledgerId"],rssi:42})},500),c(null,{id:"43",localName:"name43",serviceUUIDs:["notLedgerId"],rssi:43}),Promise.resolve())),s=vi.fn().mockImplementation(()=>(i&&(clearInterval(i),i=null),Promise.resolve()));vi.spyOn(n,"connectedDevices").mockResolvedValueOnce([]),vi.spyOn(n,"startDeviceScan").mockImplementation(e),vi.spyOn(n,"stopDeviceScan").mockImplementation(s),vi.spyOn(n,"onDeviceDisconnected").mockImplementation(vi.fn()),new r.RNBleTransport(u,()=>l,()=>{},()=>{},n,v,{}).startDiscovering().subscribe().unsubscribe(),(0,o.expect)(e).toHaveBeenCalled(),(0,o.expect)(s).toHaveBeenCalled()})}),describe("listenToAvailableDevices",()=>{it("should call startScan and connectedDevices from ble manager",()=>new Promise(i=>{let n=null;const e=new t.BleManager,s={readRSSI:vi.fn().mockResolvedValueOnce({discoverAllServicesAndCharacteristics:vi.fn().mockResolvedValueOnce({services:vi.fn().mockResolvedValueOnce({}),serviceUUIDs:["ledgerId"],rssi:64,id:"knownDeviceId",localName:"knownDeviceName"})})},a=vi.fn().mockImplementation((c,k,d)=>{n=setInterval(()=>{d(null,{id:"id",localName:"name",serviceUUIDs:["ledgerId"],rssi:42})},10),d(null,{id:"43",localName:"name43",serviceUUIDs:["notLedgerId"],rssi:43})}),p=vi.fn().mockImplementation(()=>{n&&(clearInterval(n),n=null)});vi.spyOn(e,"connectedDevices").mockResolvedValueOnce([s]),vi.spyOn(e,"startDeviceScan").mockImplementation(a),vi.spyOn(e,"stopDeviceScan").mockImplementation(p),vi.spyOn(e,"onDeviceDisconnected").mockImplementation(vi.fn()),vi.spyOn(e,"isDeviceConnected").mockImplementation(vi.fn()),vi.spyOn(e,"onStateChange").mockImplementation(c=>(c(t.State.PoweredOn),{remove:vi.fn()})),C=new r.RNBleTransport(u,()=>l,()=>{},()=>{},e,v,{}).listenToAvailableDevices().subscribe({next:c=>{c.length===1&&((0,o.expect)(c).toEqual([{id:"id",name:"name",deviceModel:O,transport:"RN_BLE",rssi:42}]),i(void 0))}})}))}),describe("connect",()=>{let i;(0,o.beforeEach)(()=>{i=vi.fn().mockResolvedValueOnce([{readRSSI:vi.fn().mockResolvedValueOnce({discoverAllServicesAndCharacteristics:vi.fn().mockResolvedValueOnce({services:vi.fn().mockResolvedValueOnce({}),serviceUUIDs:["ledgerId"],rssi:64,id:"deviceId",localName:"knownDeviceName"})})}])}),it("should throw an error if device id is unknown",async()=>{const n=new t.BleManager;vi.spyOn(n,"connectedDevices").mockImplementation(i),vi.spyOn(n,"discoverAllServicesAndCharacteristicsForDevice").mockRejectedValueOnce(new Error("discoverAllServicesAndCharacteristicsForDevice error"));const e=vi.fn().mockReturnValue({setupConnection:vi.fn().mockResolvedValue(void 0)}),a=await new r.RNBleTransport(u,()=>l,()=>{},()=>{},n,v,{},vi.fn(),e).connect({deviceId:null,onDisconnect:vi.fn()});(0,o.expect)(a).toEqual((0,R.Left)(new f.OpeningConnectionError("discoverAllServicesAndCharacteristicsForDevice error")))}),it("should connect to a discovered device with correct MTU and discover services and setup apdu sender",async()=>{let n=null;const e=new t.BleManager,s={readRSSI:vi.fn().mockResolvedValueOnce({discoverAllServicesAndCharacteristics:vi.fn().mockResolvedValueOnce({services:vi.fn().mockResolvedValueOnce({}),serviceUUIDs:["ledgerId"],rssi:64,id:"knownDeviceId",localName:"knownDeviceName"})}),services:vi.fn().mockResolvedValueOnce([{uuid:"ledgerId"}])},a=vi.fn().mockImplementation((A,y,g)=>{n=setInterval(()=>{g(null,{id:"deviceId",localName:"name",serviceUUIDs:["ledgerId"],rssi:42})},500),g(null,{id:"43",localName:"name43",serviceUUIDs:["notLedgerId"],rssi:43})}),p=vi.fn().mockImplementation(()=>{n&&(clearInterval(n),n=null)});vi.spyOn(e,"connectedDevices").mockImplementation(i),vi.spyOn(e,"startDeviceScan").mockImplementation(a),vi.spyOn(e,"stopDeviceScan").mockImplementation(p),vi.spyOn(e,"connectToDevice").mockResolvedValueOnce(s),vi.spyOn(e,"discoverAllServicesAndCharacteristicsForDevice").mockResolvedValueOnce(s),vi.spyOn(e,"monitorCharacteristicForDevice").mockImplementation(vi.fn()),vi.spyOn(e,"writeCharacteristicWithoutResponseForDevice").mockImplementation(vi.fn()),vi.spyOn(e,"onDeviceDisconnected").mockImplementation(vi.fn()),vi.spyOn(e,"isDeviceConnected").mockImplementation(vi.fn()),vi.spyOn(e,"onStateChange").mockImplementation(A=>(A(t.State.PoweredOn),{remove:vi.fn()}));const S=vi.fn().mockResolvedValue(void 0),c=vi.fn().mockReturnValue({sendApdu:vi.fn()}),k=vi.fn().mockReturnValue({setupConnection:S}),d=new r.RNBleTransport(u,()=>l,()=>{},()=>{},e,v,{},c,k),[I]=await(0,w.lastValueFrom)(d.listenToAvailableDevices().pipe((0,w.take)(3))),D=await d.connect({deviceId:I.id,onDisconnect:vi.fn()});(0,o.expect)(D.isRight()).toBe(!0),(0,o.expect)(e.connectToDevice).toHaveBeenCalledWith("deviceId",{requestMTU:156}),(0,o.expect)(e.discoverAllServicesAndCharacteristicsForDevice).toHaveBeenCalledWith("deviceId"),(0,o.expect)(S).toHaveBeenCalled()}),it("should return a connected device which calls state machine sendApdu",async()=>{let n=null;const e=new t.BleManager,s={id:"deviceId",readRSSI:vi.fn().mockResolvedValueOnce({discoverAllServicesAndCharacteristics:vi.fn().mockResolvedValueOnce({services:vi.fn().mockResolvedValueOnce({}),serviceUUIDs:["ledgerId"],rssi:64,id:"knownDeviceId",localName:"knownDeviceName"})}),services:vi.fn().mockResolvedValueOnce([{uuid:"ledgerId"}])},a=vi.fn().mockImplementation((y,g,m)=>{n=setInterval(()=>{m(null,{id:"deviceId",localName:"name",serviceUUIDs:["ledgerId"],rssi:42})},100)}),p=vi.fn().mockImplementation(()=>{n&&(clearInterval(n),n=null)});vi.spyOn(e,"connectedDevices").mockImplementation(i),vi.spyOn(e,"startDeviceScan").mockImplementation(a),vi.spyOn(e,"stopDeviceScan").mockImplementation(p),vi.spyOn(e,"connectToDevice").mockResolvedValueOnce(s),vi.spyOn(e,"discoverAllServicesAndCharacteristicsForDevice").mockResolvedValueOnce(s),vi.spyOn(e,"monitorCharacteristicForDevice").mockImplementation(vi.fn()),vi.spyOn(e,"writeCharacteristicWithoutResponseForDevice").mockImplementation(vi.fn()),vi.spyOn(e,"onDeviceDisconnected").mockImplementation(vi.fn()),vi.spyOn(e,"isDeviceConnected").mockImplementation(vi.fn()),vi.spyOn(e,"onStateChange").mockImplementation(y=>(y(t.State.PoweredOn),{remove:vi.fn()}));const S=vi.fn(),c=vi.fn().mockReturnValue({sendApdu:S}),k=vi.fn().mockReturnValue({setupConnection:vi.fn().mockResolvedValue(void 0)}),d=new r.RNBleTransport(u,()=>l,()=>{},()=>{},e,v,{},c,k),[I]=await(0,w.lastValueFrom)(d.listenToAvailableDevices().pipe((0,w.take)(3))),D=await d.connect({deviceId:I.id,onDisconnect:vi.fn()});D.extract().sendApdu(Uint8Array.from([67,50])),(0,o.expect)(D).toEqual((0,R.Right)(new f.TransportConnectedDevice({id:"deviceId",deviceModel:O,type:"BLE",transport:"RN_BLE",sendApdu:o.expect.any(Function)}))),(0,o.expect)(S).toHaveBeenCalledWith(Uint8Array.from([67,50]))})}),describe("disconnect",()=>{let i;(0,o.beforeEach)(()=>{i=vi.fn().mockResolvedValue([{readRSSI:vi.fn().mockResolvedValueOnce({discoverAllServicesAndCharacteristics:vi.fn().mockResolvedValueOnce({services:vi.fn().mockResolvedValueOnce({}),serviceUUIDs:["ledgerId"],rssi:64,id:"deviceId",localName:"knownDeviceName"})})}])}),it("should disconnect gracefully",async()=>{let n=null;const e=new t.BleManager,s={id:"deviceId",readRSSI:vi.fn().mockResolvedValueOnce({discoverAllServicesAndCharacteristics:vi.fn().mockResolvedValueOnce({services:vi.fn().mockResolvedValueOnce({}),serviceUUIDs:["ledgerId"],rssi:64,id:"knownDeviceId",localName:"knownDeviceName"})}),services:vi.fn().mockResolvedValueOnce([{uuid:"ledgerId"}])},a=vi.fn().mockImplementation((m,N,P)=>{n=setInterval(()=>{P(null,{id:"deviceId",localName:"name",serviceUUIDs:["ledgerId"],rssi:42})},100)}),p=vi.fn().mockImplementation(()=>{n&&(clearInterval(n),n=null)}),S=vi.fn().mockImplementation((m,N)=>(N(null,{deviceId:"deviceId",connect:vi.fn().mockResolvedValue({services:vi.fn().mockResolvedValueOnce({}),serviceUUIDs:["ledgerId"],rssi:64,id:"deviceId",localName:"knownDeviceName"}),discoverAllServicesAndCharacteristics:vi.fn().mockResolvedValueOnce({services:vi.fn().mockResolvedValueOnce({}),serviceUUIDs:["ledgerId"],rssi:64,id:"deviceId",localName:"knownDeviceName"})}),{remove:vi.fn()})),c=vi.fn();vi.spyOn(e,"connectedDevices").mockImplementation(i),vi.spyOn(e,"startDeviceScan").mockImplementation(a),vi.spyOn(e,"stopDeviceScan").mockImplementation(p),vi.spyOn(e,"connectToDevice").mockResolvedValueOnce(s),vi.spyOn(e,"discoverAllServicesAndCharacteristicsForDevice").mockResolvedValueOnce(s),vi.spyOn(e,"monitorCharacteristicForDevice").mockImplementation(vi.fn()),vi.spyOn(e,"writeCharacteristicWithoutResponseForDevice").mockImplementation(vi.fn()),vi.spyOn(e,"onDeviceDisconnected").mockImplementation(vi.fn()),vi.spyOn(e,"isDeviceConnected").mockImplementation(vi.fn()),vi.spyOn(e,"onStateChange").mockImplementation(m=>(m(t.State.PoweredOn),{remove:vi.fn()})),vi.spyOn(e,"onDeviceDisconnected").mockImplementation(S),vi.spyOn(e,"isDeviceConnected").mockImplementation(vi.fn());const k=m=>new f.DeviceConnectionStateMachine({deviceId:"deviceId",deviceApduSender:m.deviceApduSender,timeoutDuration:1e3,onTerminated:m.onTerminated}),d=vi.fn().mockReturnValue({setupConnection:vi.fn().mockResolvedValue(void 0),closeConnection:c}),I=new r.RNBleTransport(u,()=>l,()=>{},()=>{},e,v,{},k,d),D=vi.fn(),[A]=await(0,w.lastValueFrom)(I.listenToAvailableDevices().pipe((0,w.take)(3))),y=await I.connect({deviceId:A.id,onDisconnect:D}),g=await I.disconnect({connectedDevice:y.extract()});(0,o.expect)(g).toEqual((0,R.Right)(void 0)),(0,o.expect)(D).toHaveBeenCalled(),(0,o.expect)(c).toHaveBeenCalled()}),it("should handle error while disconnecting",async()=>{let n=null;const e=new t.BleManager,s={id:"deviceId",readRSSI:vi.fn().mockResolvedValueOnce({discoverAllServicesAndCharacteristics:vi.fn().mockResolvedValueOnce({services:vi.fn().mockResolvedValueOnce({}),serviceUUIDs:["ledgerId"],rssi:64,id:"knownDeviceId",localName:"knownDeviceName"})}),services:vi.fn().mockResolvedValueOnce([{uuid:"ledgerId"}])},a=vi.fn().mockImplementation((m,N,P)=>{n=setInterval(()=>{P(null,{id:"deviceId",localName:"name",serviceUUIDs:["ledgerId"],rssi:42})},100)}),p=vi.fn().mockImplementation(()=>{n&&(clearInterval(n),n=null)}),S=vi.fn().mockImplementation((m,N)=>(N(new Error("yolo"),null),{remove:vi.fn()})),c=vi.fn();vi.spyOn(e,"connectedDevices").mockImplementation(i),vi.spyOn(e,"startDeviceScan").mockImplementation(a),vi.spyOn(e,"stopDeviceScan").mockImplementation(p),vi.spyOn(e,"connectToDevice").mockResolvedValueOnce(s),vi.spyOn(e,"discoverAllServicesAndCharacteristicsForDevice").mockResolvedValueOnce(s),vi.spyOn(e,"monitorCharacteristicForDevice").mockImplementation(vi.fn()),vi.spyOn(e,"writeCharacteristicWithoutResponseForDevice").mockImplementation(vi.fn()),vi.spyOn(e,"onDeviceDisconnected").mockImplementation(vi.fn()),vi.spyOn(e,"isDeviceConnected").mockImplementation(vi.fn()),vi.spyOn(e,"onStateChange").mockImplementation(m=>(m(t.State.PoweredOn),{remove:vi.fn()})),vi.spyOn(e,"onDeviceDisconnected").mockImplementation(S),vi.spyOn(e,"isDeviceConnected").mockImplementation(vi.fn());const k=m=>new f.DeviceConnectionStateMachine({deviceId:"deviceId",deviceApduSender:m.deviceApduSender,timeoutDuration:1e3,onTerminated:m.onTerminated}),d=vi.fn().mockReturnValue({setupConnection:vi.fn().mockResolvedValue(void 0),closeConnection:c}),I=new r.RNBleTransport(u,()=>l,()=>{},()=>{},e,v,{},k,d),D=vi.fn(),[A]=await(0,w.lastValueFrom)(I.listenToAvailableDevices().pipe((0,w.take)(3))),y=await I.connect({deviceId:A.id,onDisconnect:D}),g=await I.disconnect({connectedDevice:y.extract()});(0,o.expect)(g).toEqual((0,R.Right)(void 0)),(0,o.expect)(D).toHaveBeenCalled()})})});
1
+ "use strict";var t=require("react-native-ble-plx"),f=require("@ledgerhq/device-management-kit"),R=require("purify-ts"),w=require("rxjs"),i=require("vitest"),E=require("../model/Errors"),r=require("./RNBleTransport");const u={error:vi.fn(),info:vi.fn(),warn:vi.fn(),debug:vi.fn()};vi.mock("react-native",()=>({Platform:{},PermissionsAndroid:{}}));vi.mock("react-native-ble-plx",()=>({Device:vi.fn(),State:{PoweredOn:"PoweredOn",Unknown:"Unknown"},BleError:vi.fn(),BleManager:vi.fn().mockReturnValue({onStateChange:vi.fn(),startDeviceScan:vi.fn(),stopDeviceScan:vi.fn(),connectToDevice:vi.fn(),disconnectFromDevice:vi.fn(),cancelDeviceConnection:vi.fn(),connectedDevices:vi.fn(),monitorCharacteristicForDevice:vi.fn(),writeCharacteristicWithoutResponseForDevice:vi.fn(),discoverAllServicesAndCharacteristicsForDevice:vi.fn(),onDeviceDisconnected:vi.fn(),isDeviceConnected:vi.fn()})}));const h=async(v,O)=>{const b={OS:"android",Version:v.version},T={request:vi.fn().mockImplementation(o=>Promise.resolve({ACCESS_FINE_LOCATION:v.accessFineLocationResult}[o])),PERMISSIONS:v.permissions,RESULTS:{GRANTED:"granted"},requestMultiple:vi.fn().mockImplementation(()=>Promise.resolve(v.requestPermissionResult))},m=new r.RNBleTransport("DeviceModelDataSource",()=>u,()=>{},()=>{},new t.BleManager,b,T);await m.requestPermission();const C=m.isSupported();O.callRequestPermission&&(0,i.expect)(T.request).toHaveBeenCalledWith("ACCESS_FINE_LOCATION"),(0,i.expect)(C).toBe(O.isSupported)};describe("RNBleTransportFactory",()=>{it("should return a RNBleTransport",()=>{const O=(0,r.RNBleTransportFactory)({deviceModelDataSource:"DeviceModelDataSource",loggerServiceFactory:()=>u,apduSenderServiceFactory:()=>{},apduReceiverServiceFactory:()=>{},config:{}});(0,i.expect)(O).toBeInstanceOf(r.RNBleTransport)})});describe("RNBleTransport",()=>{const v={OS:"ios"},O=new f.TransportDeviceModel({id:f.DeviceModelId.FLEX,productName:"Ledger Flex",usbProductId:112,bootloaderUsbProductId:7,usbOnly:!1,memorySize:1533*1024,blockSize:32,masks:[858783744]}),b=vi.fn(()=>["ledgerId"]),T=vi.fn(()=>({ledgerId:new f.BleDeviceInfos(O,"serviceUuid","notifyUuid","writeCmdUuid","readCmdUuid")})),m={getBluetoothServices:b,getBluetoothServicesInfos:T};let C;(0,i.beforeEach)(()=>{vi.clearAllMocks()}),afterEach(()=>{C&&C.unsubscribe()}),describe("getIdentifier",()=>{it("should return rnBleTransportIdentifier",()=>{const o=new t.BleManager,e=new r.RNBleTransport("DeviceModelDataSource",()=>u,()=>{},()=>{},o).getIdentifier();(0,i.expect)(e).toStrictEqual("RN_BLE")})}),describe("isSupported",()=>{it("should return true if platform is ios",async()=>{const o={OS:"ios"},n=new t.BleManager,e=new r.RNBleTransport("DeviceModelDataSource",()=>u,()=>{},()=>{},n,o);await e.requestPermission();const s=e.isSupported();(0,i.expect)(s).toBe(!0)}),it("should return true if platform is android and apiLevel < 31 with good permissions",async()=>{await h({version:30,permissions:{ACCESS_FINE_LOCATION:"ACCESS_FINE_LOCATION",BLUETOOTH_SCAN:"BLUETOOTH_SCAN",BLUETOOTH_CONNECT:"BLUETOOTH_CONNECT"},requestPermissionResult:{"android.permission.BLUETOOTH_CONNECT":"granted","android.permission.BLUETOOTH_SCAN":"granted","android.permission.ACCESS_FINE_LOCATION":"granted"}},{isSupported:!0,callRequestPermission:!0})}),it("should return true if platform is android and apiLevel >= 31 with good permissions",async()=>{await h({version:31,permissions:{ACCESS_FINE_LOCATION:"ACCESS_FINE_LOCATION",BLUETOOTH_SCAN:"BLUETOOTH_SCAN",BLUETOOTH_CONNECT:"BLUETOOTH_CONNECT"},requestPermissionResult:{"android.permission.BLUETOOTH_CONNECT":"granted","android.permission.BLUETOOTH_SCAN":"granted","android.permission.ACCESS_FINE_LOCATION":"granted"}},{isSupported:!0,callRequestPermission:!1})}),it("should return false if platform is android with bad permissions",async()=>{await h({version:31,permissions:{ACCESS_FINE_LOCATION:"",BLUETOOTH_SCAN:"",BLUETOOTH_CONNECT:"BLUETOOTH_CONNECT"},requestPermissionResult:{"android.permission.ACCESS_FINE_LOCATION":"denied","android.permission.BLUETOOTH_CONNECT":"granted","android.permission.BLUETOOTH_SCAN":"granted"}},{isSupported:!1,callRequestPermission:!1})}),it("should return false if platform is android and denied permissions",async()=>{await h({version:31,permissions:{ACCESS_FINE_LOCATION:"ACCESS_FINE_LOCATION",BLUETOOTH_SCAN:"BLUETOOTH_SCAN",BLUETOOTH_CONNECT:"BLUETOOTH_CONNECT"},requestPermissionResult:{"android.permission.BLUETOOTH_CONNECT":"denied","android.permission.BLUETOOTH_SCAN":"denied","android.permission.ACCESS_FINE_LOCATION":"denied"}},{isSupported:!1,callRequestPermission:!1})}),it("should return false if platform isn't android nor ios",async()=>{const o=new t.BleManager,n=new r.RNBleTransport("DeviceModelDataSource",()=>u,()=>{},()=>{},o,{OS:"windows"});await n.requestPermission();const e=n.isSupported();(0,i.expect)(e).toBe(!1)})}),describe("startDiscovering",()=>{it("should throw error if transport is not supported",()=>{const o={OS:"windows"},n=new t.BleManager,e=new r.RNBleTransport(m,()=>u,()=>{},()=>{},n,o);try{e.startDiscovering()}catch(s){(0,i.expect)(s).toBeInstanceOf(E.BleNotSupported)}}),it("should emit an empty array",()=>new Promise(o=>{const n=new t.BleManager;C=new r.RNBleTransport(m,()=>u,()=>{},()=>{},n,v,{}).startDiscovering().subscribe({next:a=>{(0,i.expect)(a).toStrictEqual([]),o(void 0)},error:a=>{throw a},complete:()=>{o(void 0)}})})),it.skip("should emit discovered new device",()=>new Promise(o=>{let n=null;const e=new t.BleManager,s=vi.fn().mockImplementation((c,k,d)=>(n=setInterval(()=>{d(null,{id:"id",localName:"name",serviceUUIDs:["ledgerId"],rssi:42})},500),d(null,{id:"43",localName:"name43",serviceUUIDs:["notLedgerId"],rssi:43}),Promise.resolve())),a=vi.fn().mockImplementation(()=>(n&&(clearInterval(n),n=null),Promise.resolve()));vi.spyOn(e,"connectedDevices").mockResolvedValueOnce([]),vi.spyOn(e,"startDeviceScan").mockImplementation(s),vi.spyOn(e,"stopDeviceScan").mockImplementation(a),C=new r.RNBleTransport(m,()=>u,()=>{},()=>{},e,v,{}).startDiscovering().subscribe({next:c=>{(0,i.expect)(c).toStrictEqual([]),o(void 0)},error:c=>{throw c},complete:()=>{throw new Error("complete should not be called")}})})),it.skip("should emit both known and new device",()=>new Promise(o=>{let n=null;const e=new t.BleManager,s={readRSSI:vi.fn().mockResolvedValueOnce({discoverAllServicesAndCharacteristics:vi.fn().mockResolvedValueOnce({services:vi.fn().mockResolvedValueOnce({}),serviceUUIDs:["ledgerId"],rssi:64,id:"knownDeviceId",localName:"knownDeviceName"})})},a=vi.fn().mockImplementation((d,I,D)=>(n=setInterval(()=>{D(null,{id:"newDeviceId",localName:"newDeviceName",serviceUUIDs:["ledgerId"],rssi:42})},500),D(null,{id:"43",localName:"name43",serviceUUIDs:["notLedgerId"],rssi:43}),Promise.resolve())),p=vi.fn().mockImplementation(()=>(n&&(clearInterval(n),n=null),Promise.resolve()));vi.spyOn(e,"connectedDevices").mockResolvedValueOnce([s]),vi.spyOn(e,"startDeviceScan").mockImplementation(a),vi.spyOn(e,"stopDeviceScan").mockImplementation(p),vi.spyOn(e,"onDeviceDisconnected").mockImplementation(vi.fn());const c=new r.RNBleTransport(m,()=>u,()=>{},()=>{},e,v,{}).startDiscovering(),k={};C=c.subscribe({next:d=>{k[d.id]=d,Object.values(k).length===2&&((0,i.expect)(Object.values(k)).toStrictEqual([{id:"knownDeviceId",name:"knownDeviceName",deviceModel:O,transport:"RN_BLE",rssi:64},{id:"newDeviceId",name:"newDeviceName",deviceModel:O,transport:"RN_BLE",rssi:42}]),o(void 0))}})}))}),describe("stopDiscovering",()=>{it("should call ble manager stop scan on stop discovering",()=>{const o=new t.BleManager,n=vi.fn();vi.spyOn(o,"connectedDevices").mockResolvedValueOnce([]),vi.spyOn(o,"stopDeviceScan").mockImplementation(n),new r.RNBleTransport(m,()=>u,()=>{},()=>{},o,v,{}).stopDiscovering(),(0,i.expect)(n).toHaveBeenCalled()}),it.skip("should call ble manager stop scan when unsubscribe startDiscovering obs",()=>{let o=null;const n=new t.BleManager,e=vi.fn().mockImplementation((p,S,c)=>(o=setInterval(()=>{c(null,{id:"id",localName:"name",serviceUUIDs:["ledgerId"],rssi:42})},500),c(null,{id:"43",localName:"name43",serviceUUIDs:["notLedgerId"],rssi:43}),Promise.resolve())),s=vi.fn().mockImplementation(()=>(o&&(clearInterval(o),o=null),Promise.resolve()));vi.spyOn(n,"connectedDevices").mockResolvedValueOnce([]),vi.spyOn(n,"startDeviceScan").mockImplementation(e),vi.spyOn(n,"stopDeviceScan").mockImplementation(s),vi.spyOn(n,"onDeviceDisconnected").mockImplementation(vi.fn()),new r.RNBleTransport(m,()=>u,()=>{},()=>{},n,v,{}).startDiscovering().subscribe().unsubscribe(),(0,i.expect)(e).toHaveBeenCalled(),(0,i.expect)(s).toHaveBeenCalled()})}),describe("listenToAvailableDevices",()=>{it("should call startScan and connectedDevices from ble manager",()=>new Promise(o=>{let n=null;const e=new t.BleManager,s={readRSSI:vi.fn().mockResolvedValueOnce({discoverAllServicesAndCharacteristics:vi.fn().mockResolvedValueOnce({services:vi.fn().mockResolvedValueOnce({}),serviceUUIDs:["ledgerId"],rssi:64,id:"knownDeviceId",localName:"knownDeviceName"})})},a=vi.fn().mockImplementation((c,k,d)=>{n=setInterval(()=>{d(null,{id:"id",localName:"name",serviceUUIDs:["ledgerId"],rssi:42})},10),d(null,{id:"43",localName:"name43",serviceUUIDs:["notLedgerId"],rssi:43})}),p=vi.fn().mockImplementation(()=>{n&&(clearInterval(n),n=null)});vi.spyOn(e,"connectedDevices").mockResolvedValueOnce([s]),vi.spyOn(e,"startDeviceScan").mockImplementation(a),vi.spyOn(e,"stopDeviceScan").mockImplementation(p),vi.spyOn(e,"onDeviceDisconnected").mockImplementation(vi.fn()),vi.spyOn(e,"isDeviceConnected").mockImplementation(vi.fn()),vi.spyOn(e,"onStateChange").mockImplementation(c=>(c(t.State.PoweredOn),{remove:vi.fn()})),C=new r.RNBleTransport(m,()=>u,()=>{},()=>{},e,v,{}).listenToAvailableDevices().subscribe({next:c=>{c.length===1&&((0,i.expect)(c).toEqual([{id:"id",name:"name",deviceModel:O,transport:"RN_BLE",rssi:42}]),o(void 0))}})}))}),describe("connect",()=>{let o;(0,i.beforeEach)(()=>{o=vi.fn().mockResolvedValueOnce([{readRSSI:vi.fn().mockResolvedValueOnce({discoverAllServicesAndCharacteristics:vi.fn().mockResolvedValueOnce({services:vi.fn().mockResolvedValueOnce({}),serviceUUIDs:["ledgerId"],rssi:64,id:"deviceId",localName:"knownDeviceName"})})}])}),it("should throw an error if device id is unknown",async()=>{const n=new t.BleManager;vi.spyOn(n,"connectedDevices").mockImplementation(o),vi.spyOn(n,"discoverAllServicesAndCharacteristicsForDevice").mockRejectedValueOnce(new Error("discoverAllServicesAndCharacteristicsForDevice error"));const e=vi.fn().mockReturnValue({setupConnection:vi.fn().mockResolvedValue(void 0)}),a=await new r.RNBleTransport(m,()=>u,()=>{},()=>{},n,v,{},vi.fn(),e).connect({deviceId:null,onDisconnect:vi.fn()});(0,i.expect)(a).toEqual((0,R.Left)(new f.OpeningConnectionError("discoverAllServicesAndCharacteristicsForDevice error")))}),it("should connect to a discovered device with correct MTU and discover services and setup apdu sender",async()=>{let n=null;const e=new t.BleManager,s={readRSSI:vi.fn().mockResolvedValueOnce({discoverAllServicesAndCharacteristics:vi.fn().mockResolvedValueOnce({services:vi.fn().mockResolvedValueOnce({}),serviceUUIDs:["ledgerId"],rssi:64,id:"knownDeviceId",localName:"knownDeviceName"})}),services:vi.fn().mockResolvedValueOnce([{uuid:"ledgerId"}])},a=vi.fn().mockImplementation((A,y,g)=>{n=setInterval(()=>{g(null,{id:"deviceId",localName:"name",serviceUUIDs:["ledgerId"],rssi:42})},500),g(null,{id:"43",localName:"name43",serviceUUIDs:["notLedgerId"],rssi:43})}),p=vi.fn().mockImplementation(()=>{n&&(clearInterval(n),n=null)});vi.spyOn(e,"connectedDevices").mockImplementation(o),vi.spyOn(e,"startDeviceScan").mockImplementation(a),vi.spyOn(e,"stopDeviceScan").mockImplementation(p),vi.spyOn(e,"connectToDevice").mockResolvedValueOnce(s),vi.spyOn(e,"discoverAllServicesAndCharacteristicsForDevice").mockResolvedValueOnce(s),vi.spyOn(e,"monitorCharacteristicForDevice").mockImplementation(vi.fn()),vi.spyOn(e,"writeCharacteristicWithoutResponseForDevice").mockImplementation(vi.fn()),vi.spyOn(e,"onDeviceDisconnected").mockImplementation(vi.fn()),vi.spyOn(e,"isDeviceConnected").mockImplementation(vi.fn()),vi.spyOn(e,"onStateChange").mockImplementation(A=>(A(t.State.PoweredOn),{remove:vi.fn()}));const S=vi.fn().mockResolvedValue(void 0),c=vi.fn().mockReturnValue({sendApdu:vi.fn()}),k=vi.fn().mockReturnValue({setupConnection:S}),d=new r.RNBleTransport(m,()=>u,()=>{},()=>{},e,v,{},c,k),[I]=await(0,w.lastValueFrom)(d.listenToAvailableDevices().pipe((0,w.take)(3))),D=await d.connect({deviceId:I.id,onDisconnect:vi.fn()});(0,i.expect)(D.isRight()).toBe(!0),(0,i.expect)(e.connectToDevice).toHaveBeenCalledWith("deviceId",{requestMTU:156}),(0,i.expect)(e.discoverAllServicesAndCharacteristicsForDevice).toHaveBeenCalledWith("deviceId"),(0,i.expect)(S).toHaveBeenCalled()}),it("should return a connected device which calls state machine sendApdu",async()=>{let n=null;const e=new t.BleManager,s={id:"deviceId",readRSSI:vi.fn().mockResolvedValueOnce({discoverAllServicesAndCharacteristics:vi.fn().mockResolvedValueOnce({services:vi.fn().mockResolvedValueOnce({}),serviceUUIDs:["ledgerId"],rssi:64,id:"knownDeviceId",localName:"knownDeviceName"})}),services:vi.fn().mockResolvedValueOnce([{uuid:"ledgerId"}])},a=vi.fn().mockImplementation((y,g,l)=>{n=setInterval(()=>{l(null,{id:"deviceId",localName:"name",serviceUUIDs:["ledgerId"],rssi:42})},100)}),p=vi.fn().mockImplementation(()=>{n&&(clearInterval(n),n=null)});vi.spyOn(e,"connectedDevices").mockImplementation(o),vi.spyOn(e,"startDeviceScan").mockImplementation(a),vi.spyOn(e,"stopDeviceScan").mockImplementation(p),vi.spyOn(e,"connectToDevice").mockResolvedValueOnce(s),vi.spyOn(e,"discoverAllServicesAndCharacteristicsForDevice").mockResolvedValueOnce(s),vi.spyOn(e,"monitorCharacteristicForDevice").mockImplementation(vi.fn()),vi.spyOn(e,"writeCharacteristicWithoutResponseForDevice").mockImplementation(vi.fn()),vi.spyOn(e,"onDeviceDisconnected").mockImplementation(vi.fn()),vi.spyOn(e,"isDeviceConnected").mockImplementation(vi.fn()),vi.spyOn(e,"onStateChange").mockImplementation(y=>(y(t.State.PoweredOn),{remove:vi.fn()}));const S=vi.fn(),c=vi.fn().mockReturnValue({sendApdu:S}),k=vi.fn().mockReturnValue({setupConnection:vi.fn().mockResolvedValue(void 0)}),d=new r.RNBleTransport(m,()=>u,()=>{},()=>{},e,v,{},c,k),[I]=await(0,w.lastValueFrom)(d.listenToAvailableDevices().pipe((0,w.take)(3))),D=await d.connect({deviceId:I.id,onDisconnect:vi.fn()});D.extract().sendApdu(Uint8Array.from([67,50])),(0,i.expect)(D).toEqual((0,R.Right)(new f.TransportConnectedDevice({id:"deviceId",deviceModel:O,type:"BLE",transport:"RN_BLE",sendApdu:i.expect.any(Function)}))),(0,i.expect)(S).toHaveBeenCalledWith(Uint8Array.from([67,50]))})}),describe("disconnect",()=>{let o;(0,i.beforeEach)(()=>{o=vi.fn().mockResolvedValue([{readRSSI:vi.fn().mockResolvedValueOnce({discoverAllServicesAndCharacteristics:vi.fn().mockResolvedValueOnce({services:vi.fn().mockResolvedValueOnce({}),serviceUUIDs:["ledgerId"],rssi:64,id:"deviceId",localName:"knownDeviceName"})})}])}),it("should disconnect gracefully",async()=>{let n=null;const e=new t.BleManager,s={id:"deviceId",readRSSI:vi.fn().mockResolvedValueOnce({discoverAllServicesAndCharacteristics:vi.fn().mockResolvedValueOnce({services:vi.fn().mockResolvedValueOnce({}),serviceUUIDs:["ledgerId"],rssi:64,id:"knownDeviceId",localName:"knownDeviceName"})}),services:vi.fn().mockResolvedValueOnce([{uuid:"ledgerId"}])},a=vi.fn().mockImplementation((l,N,P)=>{n=setInterval(()=>{P(null,{id:"deviceId",localName:"name",serviceUUIDs:["ledgerId"],rssi:42})},100)}),p=vi.fn().mockImplementation(()=>{n&&(clearInterval(n),n=null)}),S=vi.fn().mockImplementation((l,N)=>(N(null,{deviceId:"deviceId",connect:vi.fn().mockResolvedValue({services:vi.fn().mockResolvedValueOnce({}),serviceUUIDs:["ledgerId"],rssi:64,id:"deviceId",localName:"knownDeviceName"}),discoverAllServicesAndCharacteristics:vi.fn().mockResolvedValueOnce({services:vi.fn().mockResolvedValueOnce({}),serviceUUIDs:["ledgerId"],rssi:64,id:"deviceId",localName:"knownDeviceName"})}),{remove:vi.fn()})),c=vi.fn();vi.spyOn(e,"connectedDevices").mockImplementation(o),vi.spyOn(e,"startDeviceScan").mockImplementation(a),vi.spyOn(e,"stopDeviceScan").mockImplementation(p),vi.spyOn(e,"connectToDevice").mockResolvedValueOnce(s),vi.spyOn(e,"discoverAllServicesAndCharacteristicsForDevice").mockResolvedValueOnce(s),vi.spyOn(e,"monitorCharacteristicForDevice").mockImplementation(vi.fn()),vi.spyOn(e,"writeCharacteristicWithoutResponseForDevice").mockImplementation(vi.fn()),vi.spyOn(e,"onDeviceDisconnected").mockImplementation(vi.fn()),vi.spyOn(e,"isDeviceConnected").mockImplementation(vi.fn()),vi.spyOn(e,"onStateChange").mockImplementation(l=>(l(t.State.PoweredOn),{remove:vi.fn()})),vi.spyOn(e,"onDeviceDisconnected").mockImplementation(S),vi.spyOn(e,"isDeviceConnected").mockImplementation(vi.fn());const k=l=>new f.DeviceConnectionStateMachine({deviceId:"deviceId",deviceApduSender:l.deviceApduSender,timeoutDuration:1e3,onTerminated:l.onTerminated,tryToReconnect:l.tryToReconnect}),d=vi.fn().mockReturnValue({setupConnection:vi.fn().mockResolvedValue(void 0),closeConnection:c}),I=new r.RNBleTransport(m,()=>u,()=>{},()=>{},e,v,{},k,d),D=vi.fn(),[A]=await(0,w.lastValueFrom)(I.listenToAvailableDevices().pipe((0,w.take)(3))),y=await I.connect({deviceId:A.id,onDisconnect:D}),g=await I.disconnect({connectedDevice:y.extract()});(0,i.expect)(g).toEqual((0,R.Right)(void 0)),(0,i.expect)(D).toHaveBeenCalled(),(0,i.expect)(c).toHaveBeenCalled()}),it("should handle error while disconnecting",async()=>{let n=null;const e=new t.BleManager,s={id:"deviceId",readRSSI:vi.fn().mockResolvedValueOnce({discoverAllServicesAndCharacteristics:vi.fn().mockResolvedValueOnce({services:vi.fn().mockResolvedValueOnce({}),serviceUUIDs:["ledgerId"],rssi:64,id:"knownDeviceId",localName:"knownDeviceName"})}),services:vi.fn().mockResolvedValueOnce([{uuid:"ledgerId"}])},a=vi.fn().mockImplementation((l,N,P)=>{n=setInterval(()=>{P(null,{id:"deviceId",localName:"name",serviceUUIDs:["ledgerId"],rssi:42})},100)}),p=vi.fn().mockImplementation(()=>{n&&(clearInterval(n),n=null)}),S=vi.fn().mockImplementation((l,N)=>(N(new Error("yolo"),null),{remove:vi.fn()})),c=vi.fn();vi.spyOn(e,"connectedDevices").mockImplementation(o),vi.spyOn(e,"startDeviceScan").mockImplementation(a),vi.spyOn(e,"stopDeviceScan").mockImplementation(p),vi.spyOn(e,"connectToDevice").mockResolvedValueOnce(s),vi.spyOn(e,"discoverAllServicesAndCharacteristicsForDevice").mockResolvedValueOnce(s),vi.spyOn(e,"monitorCharacteristicForDevice").mockImplementation(vi.fn()),vi.spyOn(e,"writeCharacteristicWithoutResponseForDevice").mockImplementation(vi.fn()),vi.spyOn(e,"onDeviceDisconnected").mockImplementation(vi.fn()),vi.spyOn(e,"isDeviceConnected").mockImplementation(vi.fn()),vi.spyOn(e,"onStateChange").mockImplementation(l=>(l(t.State.PoweredOn),{remove:vi.fn()})),vi.spyOn(e,"onDeviceDisconnected").mockImplementation(S),vi.spyOn(e,"isDeviceConnected").mockImplementation(vi.fn());const k=l=>new f.DeviceConnectionStateMachine({deviceId:"deviceId",deviceApduSender:l.deviceApduSender,timeoutDuration:1e3,onTerminated:l.onTerminated,tryToReconnect:l.tryToReconnect}),d=vi.fn().mockReturnValue({setupConnection:vi.fn().mockResolvedValue(void 0),closeConnection:c}),I=new r.RNBleTransport(m,()=>u,()=>{},()=>{},e,v,{},k,d),D=vi.fn(),[A]=await(0,w.lastValueFrom)(I.listenToAvailableDevices().pipe((0,w.take)(3))),y=await I.connect({deviceId:A.id,onDisconnect:D}),g=await I.disconnect({connectedDevice:y.extract()});(0,i.expect)(g).toEqual((0,R.Right)(void 0)),(0,i.expect)(D).toHaveBeenCalled()})})});
2
2
  //# sourceMappingURL=RNBleTransport.test.js.map