@ledgerhq/device-transport-kit-web-ble 0.0.0-webhid-20250124164153 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,77 @@
1
+ # Transport Device Kit Web BLE
2
+
3
+ > [!CAUTION]
4
+ > This is still under development and we are free to make new interfaces which may lead to breaking changes.
5
+
6
+ - [Transport Device Kit Web BLE Documentation](#transport-device-kit-web-ble)
7
+ - [Description](#description)
8
+ - [Installation](#installation)
9
+ - [Usage](#usage)
10
+ - [Compatibility](#compatibility)
11
+ - [Pre-requisites](#pre-requisites)
12
+ - [Main Features](#main-features)
13
+ - [How To](#how-to)
14
+
15
+ ## Description
16
+
17
+ This transport is used to interact with a Ledger device through the Web BLE (Bluetooth) implementation by the Device Management Kit.
18
+
19
+ ## Installation
20
+
21
+ To install the core package, run the following command:
22
+
23
+ ```sh
24
+ npm install @ledgerhq/device-transport-kit-web-ble
25
+ ```
26
+
27
+ ## Usage
28
+
29
+ ### Compatibility
30
+
31
+ This library works in [any browser supporting the Web Bluetooth API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Bluetooth_API#browser_compatibility).
32
+
33
+ ### Pre-requisites
34
+
35
+ To use this transport, ensure you have the Device Magement Kit installed in your project.
36
+
37
+ ### Main Features
38
+
39
+ - Exposing a transport factory to be injected into the DeviceManagementKit
40
+ - Exposing the transport directly for a custom configuration
41
+
42
+ ### How To
43
+
44
+ To use the transport, you need to inject it in the DeviceManagementKitBuilder before the build. This will allow the Device Managment Kit to find and interact with devices on the Web BLE protocol.
45
+
46
+ ```typescript
47
+ import { DeviceManagementKitBuilder } from "@ledgerhq/device-management-kit"
48
+ import { webBleTransportFactory, WebBleTransport } from "@ledgerhq/device-transport-kit-web-ble"
49
+
50
+ // Easy setup with the factory
51
+ const dmk = new DeviceManagementKitBuilder()
52
+ .addTransport(webBleTransportFactory)
53
+ .build();
54
+
55
+
56
+ // With custom config
57
+ const dmk = new DeviceManagementKitBuilder()
58
+ .addTransport(({
59
+ deviceModelDataSource: DeviceModelDataSource;
60
+ loggerServiceFactory: (tag: string) => LoggerPublisherService;
61
+ config: DmkConfig;
62
+ apduSenderServiceFactory: ApduSenderServiceFactory;
63
+ apduReceiverServiceFactory: ApduReceiverServiceFactory;
64
+ }) => {
65
+ // custom code
66
+ return new WebBleTransport(
67
+ deviceModelDataSource,
68
+ loggerServiceFactory,
69
+ config,
70
+ apduSenderServiceFactory,
71
+ apduReceiverServiceFactory,
72
+ );
73
+ })
74
+ .build();
75
+
76
+ // You can then make use of the Device Management Kit
77
+ ```
@@ -1,2 +1,2 @@
1
- const t={name:"Ledger Nano X",id:"42",forget:jest.fn(),watchAdvertisements:jest.fn(),dispatchEvent:jest.fn(),watchingAdvertisements:!1,addEventListener:jest.fn(),removeEventListener:jest.fn(),onadvertisementreceived:jest.fn(),ongattserverdisconnected:jest.fn(),oncharacteristicvaluechanged:jest.fn(),onserviceadded:jest.fn(),onservicechanged:jest.fn(),onserviceremoved:jest.fn()},n={device:t,uuid:"13d63400-2c97-0004-0000-4c6564676572",isPrimary:!0,getCharacteristic:jest.fn(()=>Promise.resolve(s())),getCharacteristics:jest.fn(),getIncludedService:jest.fn(),getIncludedServices:jest.fn(),addEventListener:jest.fn(),dispatchEvent:jest.fn(),removeEventListener:jest.fn(),oncharacteristicvaluechanged:jest.fn(),onserviceadded:jest.fn(),onservicechanged:jest.fn(),onserviceremoved:jest.fn()},s=(e={})=>({...e,addEventListener:jest.fn(),removeEventListener:jest.fn(),startNotifications:jest.fn(),writeValueWithResponse:jest.fn(),writeValueWithoutResponse:jest.fn()}),i=(e={})=>({...t,gatt:{device:t,connected:!0,connect:jest.fn(),disconnect:jest.fn(),getPrimaryService:jest.fn(),getPrimaryServices:jest.fn(()=>Promise.resolve([n]))},...e});export{s as bleCharacteristicStubBuilder,i as bleDeviceStubBuilder};
1
+ const i={name:"Ledger Nano X",id:"42",forget:vi.fn(),watchAdvertisements:vi.fn(),dispatchEvent:vi.fn(),watchingAdvertisements:!1,addEventListener:vi.fn(),removeEventListener:vi.fn(),onadvertisementreceived:vi.fn(),ongattserverdisconnected:vi.fn(),oncharacteristicvaluechanged:vi.fn(),onserviceadded:vi.fn(),onservicechanged:vi.fn(),onserviceremoved:vi.fn()},t={device:i,uuid:"13d63400-2c97-0004-0000-4c6564676572",isPrimary:!0,getCharacteristic:vi.fn(()=>Promise.resolve(n())),getCharacteristics:vi.fn(),getIncludedService:vi.fn(),getIncludedServices:vi.fn(),addEventListener:vi.fn(),dispatchEvent:vi.fn(),removeEventListener:vi.fn(),oncharacteristicvaluechanged:vi.fn(),onserviceadded:vi.fn(),onservicechanged:vi.fn(),onserviceremoved:vi.fn()},n=(e={})=>({...e,addEventListener:vi.fn(),removeEventListener:vi.fn(),startNotifications:vi.fn(),writeValueWithResponse:vi.fn(),writeValueWithoutResponse:vi.fn()}),v=(e={})=>({...i,gatt:{device:i,connected:!0,connect:vi.fn(),disconnect:vi.fn(),getPrimaryService:vi.fn(),getPrimaryServices:vi.fn(()=>Promise.resolve([t]))},...e});export{n as bleCharacteristicStubBuilder,v as bleDeviceStubBuilder};
2
2
  //# sourceMappingURL=BleDevice.stub.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/api/model/BleDevice.stub.ts"],
4
- "sourcesContent": ["const bleDeviceWithoutGatt: BluetoothDevice = {\n name: \"Ledger Nano X\",\n id: \"42\",\n forget: jest.fn(),\n watchAdvertisements: jest.fn(),\n dispatchEvent: jest.fn(),\n watchingAdvertisements: false,\n addEventListener: jest.fn(),\n removeEventListener: jest.fn(),\n onadvertisementreceived: jest.fn(),\n ongattserverdisconnected: jest.fn(),\n oncharacteristicvaluechanged: jest.fn(),\n onserviceadded: jest.fn(),\n onservicechanged: jest.fn(),\n onserviceremoved: jest.fn(),\n};\n\nconst bluetoothGattPrimaryService: BluetoothRemoteGATTService = {\n device: bleDeviceWithoutGatt,\n uuid: \"13d63400-2c97-0004-0000-4c6564676572\",\n isPrimary: true,\n getCharacteristic: jest.fn(() =>\n Promise.resolve(bleCharacteristicStubBuilder()),\n ),\n getCharacteristics: jest.fn(),\n getIncludedService: jest.fn(),\n getIncludedServices: jest.fn(),\n addEventListener: jest.fn(),\n dispatchEvent: jest.fn(),\n removeEventListener: jest.fn(),\n oncharacteristicvaluechanged: jest.fn(),\n onserviceadded: jest.fn(),\n onservicechanged: jest.fn(),\n onserviceremoved: jest.fn(),\n};\n\nexport const bleCharacteristicStubBuilder = (\n props: Partial<BluetoothRemoteGATTCharacteristic> = {},\n): BluetoothRemoteGATTCharacteristic =>\n ({\n ...props,\n addEventListener: jest.fn(),\n removeEventListener: jest.fn(),\n startNotifications: jest.fn(),\n writeValueWithResponse: jest.fn(),\n writeValueWithoutResponse: jest.fn(),\n }) as BluetoothRemoteGATTCharacteristic;\n\nexport const bleDeviceStubBuilder = (\n props: Partial<BluetoothDevice> = {},\n): BluetoothDevice => ({\n ...bleDeviceWithoutGatt,\n gatt: {\n device: bleDeviceWithoutGatt,\n connected: true,\n connect: jest.fn(),\n disconnect: jest.fn(),\n getPrimaryService: jest.fn(),\n getPrimaryServices: jest.fn(() =>\n Promise.resolve([bluetoothGattPrimaryService]),\n ),\n },\n ...props,\n});\n"],
5
- "mappings": "AAAA,MAAMA,EAAwC,CAC5C,KAAM,gBACN,GAAI,KACJ,OAAQ,KAAK,GAAG,EAChB,oBAAqB,KAAK,GAAG,EAC7B,cAAe,KAAK,GAAG,EACvB,uBAAwB,GACxB,iBAAkB,KAAK,GAAG,EAC1B,oBAAqB,KAAK,GAAG,EAC7B,wBAAyB,KAAK,GAAG,EACjC,yBAA0B,KAAK,GAAG,EAClC,6BAA8B,KAAK,GAAG,EACtC,eAAgB,KAAK,GAAG,EACxB,iBAAkB,KAAK,GAAG,EAC1B,iBAAkB,KAAK,GAAG,CAC5B,EAEMC,EAA0D,CAC9D,OAAQD,EACR,KAAM,uCACN,UAAW,GACX,kBAAmB,KAAK,GAAG,IACzB,QAAQ,QAAQE,EAA6B,CAAC,CAChD,EACA,mBAAoB,KAAK,GAAG,EAC5B,mBAAoB,KAAK,GAAG,EAC5B,oBAAqB,KAAK,GAAG,EAC7B,iBAAkB,KAAK,GAAG,EAC1B,cAAe,KAAK,GAAG,EACvB,oBAAqB,KAAK,GAAG,EAC7B,6BAA8B,KAAK,GAAG,EACtC,eAAgB,KAAK,GAAG,EACxB,iBAAkB,KAAK,GAAG,EAC1B,iBAAkB,KAAK,GAAG,CAC5B,EAEaA,EAA+B,CAC1CC,EAAoD,CAAC,KAEpD,CACC,GAAGA,EACH,iBAAkB,KAAK,GAAG,EAC1B,oBAAqB,KAAK,GAAG,EAC7B,mBAAoB,KAAK,GAAG,EAC5B,uBAAwB,KAAK,GAAG,EAChC,0BAA2B,KAAK,GAAG,CACrC,GAEWC,EAAuB,CAClCD,EAAkC,CAAC,KACd,CACrB,GAAGH,EACH,KAAM,CACJ,OAAQA,EACR,UAAW,GACX,QAAS,KAAK,GAAG,EACjB,WAAY,KAAK,GAAG,EACpB,kBAAmB,KAAK,GAAG,EAC3B,mBAAoB,KAAK,GAAG,IAC1B,QAAQ,QAAQ,CAACC,CAA2B,CAAC,CAC/C,CACF,EACA,GAAGE,CACL",
4
+ "sourcesContent": ["const bleDeviceWithoutGatt: BluetoothDevice = {\n name: \"Ledger Nano X\",\n id: \"42\",\n forget: vi.fn(),\n watchAdvertisements: vi.fn(),\n dispatchEvent: vi.fn(),\n watchingAdvertisements: false,\n addEventListener: vi.fn(),\n removeEventListener: vi.fn(),\n onadvertisementreceived: vi.fn(),\n ongattserverdisconnected: vi.fn(),\n oncharacteristicvaluechanged: vi.fn(),\n onserviceadded: vi.fn(),\n onservicechanged: vi.fn(),\n onserviceremoved: vi.fn(),\n};\n\nconst bluetoothGattPrimaryService: BluetoothRemoteGATTService = {\n device: bleDeviceWithoutGatt,\n uuid: \"13d63400-2c97-0004-0000-4c6564676572\",\n isPrimary: true,\n getCharacteristic: vi.fn(() =>\n Promise.resolve(bleCharacteristicStubBuilder()),\n ),\n getCharacteristics: vi.fn(),\n getIncludedService: vi.fn(),\n getIncludedServices: vi.fn(),\n addEventListener: vi.fn(),\n dispatchEvent: vi.fn(),\n removeEventListener: vi.fn(),\n oncharacteristicvaluechanged: vi.fn(),\n onserviceadded: vi.fn(),\n onservicechanged: vi.fn(),\n onserviceremoved: vi.fn(),\n};\n\nexport const bleCharacteristicStubBuilder = (\n props: Partial<BluetoothRemoteGATTCharacteristic> = {},\n): BluetoothRemoteGATTCharacteristic =>\n ({\n ...props,\n addEventListener: vi.fn(),\n removeEventListener: vi.fn(),\n startNotifications: vi.fn(),\n writeValueWithResponse: vi.fn(),\n writeValueWithoutResponse: vi.fn(),\n }) as BluetoothRemoteGATTCharacteristic;\n\nexport const bleDeviceStubBuilder = (\n props: Partial<BluetoothDevice> = {},\n): BluetoothDevice => ({\n ...bleDeviceWithoutGatt,\n gatt: {\n device: bleDeviceWithoutGatt,\n connected: true,\n connect: vi.fn(),\n disconnect: vi.fn(),\n getPrimaryService: vi.fn(),\n getPrimaryServices: vi.fn(() =>\n Promise.resolve([bluetoothGattPrimaryService]),\n ),\n },\n ...props,\n});\n"],
5
+ "mappings": "AAAA,MAAMA,EAAwC,CAC5C,KAAM,gBACN,GAAI,KACJ,OAAQ,GAAG,GAAG,EACd,oBAAqB,GAAG,GAAG,EAC3B,cAAe,GAAG,GAAG,EACrB,uBAAwB,GACxB,iBAAkB,GAAG,GAAG,EACxB,oBAAqB,GAAG,GAAG,EAC3B,wBAAyB,GAAG,GAAG,EAC/B,yBAA0B,GAAG,GAAG,EAChC,6BAA8B,GAAG,GAAG,EACpC,eAAgB,GAAG,GAAG,EACtB,iBAAkB,GAAG,GAAG,EACxB,iBAAkB,GAAG,GAAG,CAC1B,EAEMC,EAA0D,CAC9D,OAAQD,EACR,KAAM,uCACN,UAAW,GACX,kBAAmB,GAAG,GAAG,IACvB,QAAQ,QAAQE,EAA6B,CAAC,CAChD,EACA,mBAAoB,GAAG,GAAG,EAC1B,mBAAoB,GAAG,GAAG,EAC1B,oBAAqB,GAAG,GAAG,EAC3B,iBAAkB,GAAG,GAAG,EACxB,cAAe,GAAG,GAAG,EACrB,oBAAqB,GAAG,GAAG,EAC3B,6BAA8B,GAAG,GAAG,EACpC,eAAgB,GAAG,GAAG,EACtB,iBAAkB,GAAG,GAAG,EACxB,iBAAkB,GAAG,GAAG,CAC1B,EAEaA,EAA+B,CAC1CC,EAAoD,CAAC,KAEpD,CACC,GAAGA,EACH,iBAAkB,GAAG,GAAG,EACxB,oBAAqB,GAAG,GAAG,EAC3B,mBAAoB,GAAG,GAAG,EAC1B,uBAAwB,GAAG,GAAG,EAC9B,0BAA2B,GAAG,GAAG,CACnC,GAEWC,EAAuB,CAClCD,EAAkC,CAAC,KACd,CACrB,GAAGH,EACH,KAAM,CACJ,OAAQA,EACR,UAAW,GACX,QAAS,GAAG,GAAG,EACf,WAAY,GAAG,GAAG,EAClB,kBAAmB,GAAG,GAAG,EACzB,mBAAoB,GAAG,GAAG,IACxB,QAAQ,QAAQ,CAACC,CAA2B,CAAC,CAC/C,CACF,EACA,GAAGE,CACL",
6
6
  "names": ["bleDeviceWithoutGatt", "bluetoothGattPrimaryService", "bleCharacteristicStubBuilder", "props", "bleDeviceStubBuilder"]
7
7
  }
@@ -1,2 +1,2 @@
1
- import{ApduResponse as p,defaultApduReceiverServiceStubBuilder as l,defaultApduSenderServiceStubBuilder as S,DeviceNotInitializedError as f}from"@ledgerhq/device-management-kit";import{Left as h,Right as v}from"purify-ts";import{bleCharacteristicStubBuilder as u}from"../model/BleDevice.stub";import{BleDeviceConnection as s}from"./BleDeviceConnection";const A=new Uint8Array([8,0,0,0,0]),d=new Uint8Array([0,0,0,0,0,66]),x=Uint8Array.from([0,0,0,0,0,0,0,0]);class w{subscribers=[];tag;constructor(i,r){this.subscribers=i,this.tag=r}error=jest.fn();warn=jest.fn();info=jest.fn();debug=jest.fn()}describe("BleDeviceConnection",()=>{let t,i,r,o;const n=e=>new w([],e);beforeEach(()=>{t=u(),i=u(),r=jest.fn(()=>S(void 0,n)),o=jest.fn(()=>l(void 0,n))});function a(e,c=Uint8Array.from([])){e.onNotifyCharacteristicValueChanged({target:{value:new DataView(c.buffer)}})}describe("sendApdu",()=>{it("should return an error if the device isn't setup",async()=>{const c=await new s({writeCharacteristic:t,notifyCharacteristic:i,apduSenderFactory:r,apduReceiverFactory:o},n).sendApdu(Uint8Array.from([]));expect(c).toStrictEqual(h(new f("Unknown MTU")))}),it("should send apdu without error if device is setup",async()=>{const e=new s({writeCharacteristic:t,notifyCharacteristic:i,apduSenderFactory:r,apduReceiverFactory:o},n);a(e,d);const c=e.sendApdu(new Uint8Array([]));a(e,x),expect(t.writeValueWithoutResponse).toHaveBeenCalledTimes(1),expect(await c).toStrictEqual(v(new p({statusCode:Uint8Array.from([]),data:Uint8Array.from([])})))})}),describe("setup",()=>{it("should send the apdu 0x0800000000 to get mtu size",async()=>{await new s({writeCharacteristic:t,notifyCharacteristic:i,apduSenderFactory:r,apduReceiverFactory:o},n).setup(),expect(t.writeValueWithoutResponse).toHaveBeenCalledWith(new Uint8Array(A))}),it("should setup apduSender with the correct mtu size",()=>{const e=new s({writeCharacteristic:t,notifyCharacteristic:i,apduSenderFactory:r,apduReceiverFactory:o},n);a(e,d),expect(r).toHaveBeenCalledWith({frameSize:66})})})});
1
+ import{ApduResponse as p,defaultApduReceiverServiceStubBuilder as l,defaultApduSenderServiceStubBuilder as v,DeviceNotInitializedError as S}from"@ledgerhq/device-management-kit";import{Left as f,Right as h}from"purify-ts";import{bleCharacteristicStubBuilder as u}from"../model/BleDevice.stub";import{BleDeviceConnection as s}from"./BleDeviceConnection";const A=new Uint8Array([8,0,0,0,0]),d=new Uint8Array([0,0,0,0,0,66]),x=Uint8Array.from([0,0,0,0,0,0,0,0]);class w{subscribers=[];tag;constructor(i,r){this.subscribers=i,this.tag=r}error=vi.fn();warn=vi.fn();info=vi.fn();debug=vi.fn()}describe("BleDeviceConnection",()=>{let t,i,r,o;const n=e=>new w([],e);beforeEach(()=>{t=u(),i=u(),r=vi.fn(()=>v(void 0,n)),o=vi.fn(()=>l(void 0,n))});function a(e,c=Uint8Array.from([])){e.onNotifyCharacteristicValueChanged({target:{value:new DataView(c.buffer)}})}describe("sendApdu",()=>{it("should return an error if the device isn't setup",async()=>{const c=await new s({writeCharacteristic:t,notifyCharacteristic:i,apduSenderFactory:r,apduReceiverFactory:o},n).sendApdu(Uint8Array.from([]));expect(c).toStrictEqual(f(new S("Unknown MTU")))}),it("should send apdu without error if device is setup",async()=>{const e=new s({writeCharacteristic:t,notifyCharacteristic:i,apduSenderFactory:r,apduReceiverFactory:o},n);a(e,d);const c=e.sendApdu(new Uint8Array([]));a(e,x),expect(t.writeValueWithoutResponse).toHaveBeenCalledTimes(1),expect(await c).toStrictEqual(h(new p({statusCode:Uint8Array.from([]),data:Uint8Array.from([])})))})}),describe("setup",()=>{it("should send the apdu 0x0800000000 to get mtu size",async()=>{await new s({writeCharacteristic:t,notifyCharacteristic:i,apduSenderFactory:r,apduReceiverFactory:o},n).setup(),expect(t.writeValueWithoutResponse).toHaveBeenCalledWith(new Uint8Array(A))}),it("should setup apduSender with the correct mtu size",()=>{const e=new s({writeCharacteristic:t,notifyCharacteristic:i,apduSenderFactory:r,apduReceiverFactory:o},n);a(e,d),expect(r).toHaveBeenCalledWith({frameSize:66})})})});
2
2
  //# sourceMappingURL=BleDeviceConnection.test.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/api/transport/BleDeviceConnection.test.ts"],
4
- "sourcesContent": ["import {\n type ApduReceiverService,\n ApduResponse,\n type ApduSenderService,\n defaultApduReceiverServiceStubBuilder,\n defaultApduSenderServiceStubBuilder,\n DeviceNotInitializedError,\n type LoggerPublisherService,\n type LoggerSubscriberService,\n} from \"@ledgerhq/device-management-kit\";\nimport { Left, Right } from \"purify-ts\";\n\nimport { bleCharacteristicStubBuilder } from \"@api/model/BleDevice.stub\";\n\nimport { BleDeviceConnection, type DataViewEvent } from \"./BleDeviceConnection\";\n\nconst GET_MTU_APDU = new Uint8Array([0x08, 0x00, 0x00, 0x00, 0x00]);\nconst GET_MTU_APDU_RESPONSE = new Uint8Array([\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x42,\n]);\nconst EMPTY_APDU_RESPONSE = Uint8Array.from([\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n]);\n\nclass LoggerPublisherServiceStub implements LoggerPublisherService {\n subscribers: LoggerSubscriberService[] = [];\n tag: string;\n constructor(subscribers: LoggerSubscriberService[], tag: string) {\n this.subscribers = subscribers;\n this.tag = tag;\n }\n error = jest.fn();\n warn = jest.fn();\n info = jest.fn();\n debug = jest.fn();\n}\n\ndescribe(\"BleDeviceConnection\", () => {\n let writeCharacteristic: BluetoothRemoteGATTCharacteristic;\n let notifyCharacteristic: BluetoothRemoteGATTCharacteristic;\n let apduSenderFactory: () => ApduSenderService;\n let apduReceiverFactory: () => ApduReceiverService;\n const logger = (tag: string) => new LoggerPublisherServiceStub([], tag);\n\n beforeEach(() => {\n writeCharacteristic = bleCharacteristicStubBuilder();\n notifyCharacteristic = bleCharacteristicStubBuilder();\n apduSenderFactory = jest.fn(() =>\n defaultApduSenderServiceStubBuilder(undefined, logger),\n );\n apduReceiverFactory = jest.fn(() =>\n defaultApduReceiverServiceStubBuilder(undefined, logger),\n );\n });\n\n function receiveApdu(\n connection: BleDeviceConnection,\n buffer: Uint8Array = Uint8Array.from([]),\n ) {\n // @ts-expect-error private function call to mock web ble response\n connection.onNotifyCharacteristicValueChanged({\n target: {\n value: new DataView(buffer.buffer),\n },\n } as DataViewEvent);\n }\n\n describe(\"sendApdu\", () => {\n it(\"should return an error if the device isn't setup\", async () => {\n // given\n const connection = new BleDeviceConnection(\n {\n writeCharacteristic,\n notifyCharacteristic,\n apduSenderFactory,\n apduReceiverFactory,\n },\n logger,\n );\n // when\n const errorOrApduResponse = await connection.sendApdu(\n Uint8Array.from([]),\n );\n // then\n expect(errorOrApduResponse).toStrictEqual(\n Left(new DeviceNotInitializedError(\"Unknown MTU\")),\n );\n });\n\n it(\"should send apdu without error if device is setup\", async () => {\n // given\n const connection = new BleDeviceConnection(\n {\n writeCharacteristic,\n notifyCharacteristic,\n apduSenderFactory,\n apduReceiverFactory,\n },\n logger,\n );\n // when\n receiveApdu(connection, GET_MTU_APDU_RESPONSE);\n const response = connection.sendApdu(new Uint8Array([]));\n receiveApdu(connection, EMPTY_APDU_RESPONSE);\n // then\n expect(\n writeCharacteristic.writeValueWithoutResponse,\n ).toHaveBeenCalledTimes(1);\n expect(await response).toStrictEqual(\n Right(\n new ApduResponse({\n statusCode: Uint8Array.from([]),\n data: Uint8Array.from([]),\n }),\n ),\n );\n });\n });\n describe(\"setup\", () => {\n it(\"should send the apdu 0x0800000000 to get mtu size\", async () => {\n // given\n const connection = new BleDeviceConnection(\n {\n writeCharacteristic,\n notifyCharacteristic,\n apduSenderFactory,\n apduReceiverFactory,\n },\n logger,\n );\n // when\n await connection.setup();\n // then\n expect(\n writeCharacteristic.writeValueWithoutResponse,\n ).toHaveBeenCalledWith(new Uint8Array(GET_MTU_APDU));\n });\n it(\"should setup apduSender with the correct mtu size\", () => {\n // given\n const connection = new BleDeviceConnection(\n {\n writeCharacteristic,\n notifyCharacteristic,\n apduSenderFactory,\n apduReceiverFactory,\n },\n logger,\n );\n // when\n receiveApdu(connection, GET_MTU_APDU_RESPONSE);\n // then\n expect(apduSenderFactory).toHaveBeenCalledWith({ frameSize: 0x42 });\n });\n });\n});\n"],
5
- "mappings": "AAAA,OAEE,gBAAAA,EAEA,yCAAAC,EACA,uCAAAC,EACA,6BAAAC,MAGK,kCACP,OAAS,QAAAC,EAAM,SAAAC,MAAa,YAE5B,OAAS,gCAAAC,MAAoC,4BAE7C,OAAS,uBAAAC,MAA+C,wBAExD,MAAMC,EAAe,IAAI,WAAW,CAA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AAIb,EACrB,CACE,oBAAAO,EACA,qBAAAC,EACA,kBAAAC,EACA,oBAAAC,CACF,EACAC,CACF,EAEAC,EAAYC,EAAYX,CAAqB,EAC7C,MAAMc,EAAWH,EAAW,SAAS,IAAI,WAAW,CAAC,CAAC,CAAC,EACvDD,EAAYC,EAAYV,CAAmB,EAE3C,OACEI,EAAoB,yBACtB,EAAE,sBAAsB,CAAC,EACzB,OAAO,MAAMS,CAAQ,EAAE,cACrBlB,EACE,IAAIL,EAAa,CACf,WAAY,WAAW,KAAK,CAAC,CAAC,EAC9B,KAAM,WAAW,KAAK,CAAC,CAAC,CAC1B,CAAC,CACH,CACF,CACF,CAAC,CACH,CAAC,EACD,SAAS,QAAS,IAAM,CACtB,GAAG,oDAAqD,SAAY,CAYlE,MAVmB,IAAIO,EACrB,CACE,oBAAAO,EACA,qBAAAC,EACA,kBAAAC,EACA,oBAAAC,CACF,EACAC,CACF,EAEiB,MAAM,EAEvB,OACEJ,EAAoB,yBACtB,EAAE,qBAAqB,IAAI,WAAWN,CAAY,CAAC,CACrD,CAAC,EACD,GAAG,oDAAqD,IAAM,CAE5D,MAAMY,EAAa,IAAIb,EACrB,CACE,oBAAAO,EACA,qBAAAC,EACA,kBAAAC,EACA,oBAAAC,CACF,EACAC,CACF,EAEAC,EAAYC,EAAYX,CAAqB,EAE7C,OAAOO,CAAiB,EAAE,qBAAqB,CAAE,UAAW,EAAK,CAAC,CACpE,CAAC,CACH,CAAC,CACH,CAAC",
4
+ "sourcesContent": ["import {\n type ApduReceiverService,\n ApduResponse,\n type ApduSenderService,\n defaultApduReceiverServiceStubBuilder,\n defaultApduSenderServiceStubBuilder,\n DeviceNotInitializedError,\n type LoggerPublisherService,\n type LoggerSubscriberService,\n} from \"@ledgerhq/device-management-kit\";\nimport { Left, Right } from \"purify-ts\";\n\nimport { bleCharacteristicStubBuilder } from \"@api/model/BleDevice.stub\";\n\nimport { BleDeviceConnection, type DataViewEvent } from \"./BleDeviceConnection\";\n\nconst GET_MTU_APDU = new Uint8Array([0x08, 0x00, 0x00, 0x00, 0x00]);\nconst GET_MTU_APDU_RESPONSE = new Uint8Array([\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x42,\n]);\nconst EMPTY_APDU_RESPONSE = Uint8Array.from([\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n]);\n\nclass LoggerPublisherServiceStub implements LoggerPublisherService {\n subscribers: LoggerSubscriberService[] = [];\n tag: string;\n constructor(subscribers: LoggerSubscriberService[], tag: string) {\n this.subscribers = subscribers;\n this.tag = tag;\n }\n error = vi.fn();\n warn = vi.fn();\n info = vi.fn();\n debug = vi.fn();\n}\n\ndescribe(\"BleDeviceConnection\", () => {\n let writeCharacteristic: BluetoothRemoteGATTCharacteristic;\n let notifyCharacteristic: BluetoothRemoteGATTCharacteristic;\n let apduSenderFactory: () => ApduSenderService;\n let apduReceiverFactory: () => ApduReceiverService;\n const logger = (tag: string) => new LoggerPublisherServiceStub([], tag);\n\n beforeEach(() => {\n writeCharacteristic = bleCharacteristicStubBuilder();\n notifyCharacteristic = bleCharacteristicStubBuilder();\n apduSenderFactory = vi.fn(() =>\n defaultApduSenderServiceStubBuilder(undefined, logger),\n );\n apduReceiverFactory = vi.fn(() =>\n defaultApduReceiverServiceStubBuilder(undefined, logger),\n );\n });\n\n function receiveApdu(\n connection: BleDeviceConnection,\n buffer: Uint8Array = Uint8Array.from([]),\n ) {\n // @ts-expect-error private function call to mock web ble response\n connection.onNotifyCharacteristicValueChanged({\n target: {\n value: new DataView(buffer.buffer),\n },\n } as DataViewEvent);\n }\n\n describe(\"sendApdu\", () => {\n it(\"should return an error if the device isn't setup\", async () => {\n // given\n const connection = new BleDeviceConnection(\n {\n writeCharacteristic,\n notifyCharacteristic,\n apduSenderFactory,\n apduReceiverFactory,\n },\n logger,\n );\n // when\n const errorOrApduResponse = await connection.sendApdu(\n Uint8Array.from([]),\n );\n // then\n expect(errorOrApduResponse).toStrictEqual(\n Left(new DeviceNotInitializedError(\"Unknown MTU\")),\n );\n });\n\n it(\"should send apdu without error if device is setup\", async () => {\n // given\n const connection = new BleDeviceConnection(\n {\n writeCharacteristic,\n notifyCharacteristic,\n apduSenderFactory,\n apduReceiverFactory,\n },\n logger,\n );\n // when\n receiveApdu(connection, GET_MTU_APDU_RESPONSE);\n const response = connection.sendApdu(new Uint8Array([]));\n receiveApdu(connection, EMPTY_APDU_RESPONSE);\n // then\n expect(\n writeCharacteristic.writeValueWithoutResponse,\n ).toHaveBeenCalledTimes(1);\n expect(await response).toStrictEqual(\n Right(\n new ApduResponse({\n statusCode: Uint8Array.from([]),\n data: Uint8Array.from([]),\n }),\n ),\n );\n });\n });\n describe(\"setup\", () => {\n it(\"should send the apdu 0x0800000000 to get mtu size\", async () => {\n // given\n const connection = new BleDeviceConnection(\n {\n writeCharacteristic,\n notifyCharacteristic,\n apduSenderFactory,\n apduReceiverFactory,\n },\n logger,\n );\n // when\n await connection.setup();\n // then\n expect(\n writeCharacteristic.writeValueWithoutResponse,\n ).toHaveBeenCalledWith(new Uint8Array(GET_MTU_APDU));\n });\n it(\"should setup apduSender with the correct mtu size\", () => {\n // given\n const connection = new BleDeviceConnection(\n {\n writeCharacteristic,\n notifyCharacteristic,\n apduSenderFactory,\n apduReceiverFactory,\n },\n logger,\n );\n // when\n receiveApdu(connection, GET_MTU_APDU_RESPONSE);\n // then\n expect(apduSenderFactory).toHaveBeenCalledWith({ frameSize: 0x42 });\n });\n });\n});\n"],
5
+ "mappings": "AAAA,OAEE,gBAAAA,EAEA,yCAAAC,EACA,uCAAAC,EACA,6BAAAC,MAGK,kCACP,OAAS,QAAAC,EAAM,SAAAC,MAAa,YAE5B,OAAS,gCAAAC,MAAoC,4BAE7C,OAAS,uBAAAC,MAA+C,wBAExD,MAAMC,EAAe,IAAI,WAAW,CAAC,EAAM,EAAM,EAAM,EAAM,CAAI,CAAC,EAC5DC,EAAwB,IAAI,WAAW,CAC3C,EAAM,EAAM,EAAM,EAAM,EAA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AqB,EAC7C,MAAMc,EAAWH,EAAW,SAAS,IAAI,WAAW,CAAC,CAAC,CAAC,EACvDD,EAAYC,EAAYV,CAAmB,EAE3C,OACEI,EAAoB,yBACtB,EAAE,sBAAsB,CAAC,EACzB,OAAO,MAAMS,CAAQ,EAAE,cACrBlB,EACE,IAAIL,EAAa,CACf,WAAY,WAAW,KAAK,CAAC,CAAC,EAC9B,KAAM,WAAW,KAAK,CAAC,CAAC,CAC1B,CAAC,CACH,CACF,CACF,CAAC,CACH,CAAC,EACD,SAAS,QAAS,IAAM,CACtB,GAAG,oDAAqD,SAAY,CAYlE,MAVmB,IAAIO,EACrB,CACE,oBAAAO,EACA,qBAAAC,EACA,kBAAAC,EACA,oBAAAC,CACF,EACAC,CACF,EAEiB,MAAM,EAEvB,OACEJ,EAAoB,yBACtB,EAAE,qBAAqB,IAAI,WAAWN,CAAY,CAAC,CACrD,CAAC,EACD,GAAG,oDAAqD,IAAM,CAE5D,MAAMY,EAAa,IAAIb,EACrB,CACE,oBAAAO,EACA,qBAAAC,EACA,kBAAAC,EACA,oBAAAC,CACF,EACAC,CACF,EAEAC,EAAYC,EAAYX,CAAqB,EAE7C,OAAOO,CAAiB,EAAE,qBAAqB,CAAE,UAAW,EAAK,CAAC,CACpE,CAAC,CACH,CAAC,CACH,CAAC",
6
6
  "names": ["ApduResponse", "defaultApduReceiverServiceStubBuilder", "defaultApduSenderServiceStubBuilder", "DeviceNotInitializedError", "Left", "Right", "bleCharacteristicStubBuilder", "BleDeviceConnection", "GET_MTU_APDU", "GET_MTU_APDU_RESPONSE", "EMPTY_APDU_RESPONSE", "LoggerPublisherServiceStub", "subscribers", "tag", "writeCharacteristic", "notifyCharacteristic", "apduSenderFactory", "apduReceiverFactory", "logger", "receiveApdu", "connection", "buffer", "errorOrApduResponse", "response"]
7
7
  }
@@ -1,2 +1,2 @@
1
- import{DeviceAlreadyConnectedError as b,DeviceNotRecognizedError as f,NoAccessibleDeviceError as m,OpeningConnectionError as p,TransportConnectedDevice as I,UnknownDeviceError as h}from"@ledgerhq/device-management-kit";import{EitherAsync as u,Left as c,Maybe as d,Right as a}from"purify-ts";import{from as g,switchMap as _,timer as w}from"rxjs";import{v4 as T}from"uuid";import{RECONNECT_DEVICE_TIMEOUT as S}from"../data/WebBleConfig";import{BleDeviceGattServerError as v,BleTransportNotSupportedError as E}from"../model/Errors";import{BleDeviceConnection as C}from"../transport/BleDeviceConnection";const A="WEB-BLE";class F{constructor(e,i,t,n){this._deviceModelDataSource=e;this._loggerServiceFactory=i;this._apduSenderFactory=t;this._apduReceiverFactory=n;this._connectedDevices=[],this._internalDevicesById=new Map,this._deviceConnectionById=new Map,this._disconnectionHandlersById=new Map,this._logger=i("WebBleTransport")}_connectedDevices;_internalDevicesById;_deviceConnectionById;_disconnectionHandlersById;_logger;connectionType="BLE";identifier=A;getBluetoothApi(){return this.isSupported()?a(navigator.bluetooth):c(new E("WebBle not supported"))}isSupported(){try{return!!navigator?.bluetooth}catch{return!1}}getIdentifier(){return this.identifier}listenToKnownDevices(){return g([])}async getBleGattService(e){if(!e.gatt)return c(new v("Device gatt not found"));try{const[i]=await e.gatt.getPrimaryServices();return i?a(i):c(new v("bluetooth service not found"))}catch(i){return c(new v(i))}}getBleDeviceInfos(e){const t=this._deviceModelDataSource.getBluetoothServicesInfos()[e.uuid];return t?a(t):(this._logger.error(`Device not recognized: ${e.device.name}`),c(new f(`Device not recognized: ${e.device.name}`)))}promptDeviceAccess(){return u(async({liftEither:e,throwE:i})=>{const t=await e(this.getBluetoothApi());let n;try{n=await t.requestDevice({filters:this._deviceModelDataSource.getBluetoothServices().map(r=>({services:[r]}))})}catch(r){return i(new m(r))}return n})}getDiscoveredDeviceFrom(e){return{id:T(),deviceModel:e.deviceModel,transport:this.identifier}}setInternalDeviceFrom(e,i,t,n){const r={id:e.id,bleDevice:i,bleGattService:n,bleDeviceInfos:t,discoveredDevice:e};this._logger.debug(`Discovered device ${r.id} ${e.deviceModel.productName}`),this._internalDevicesById.set(r.id,r)}startDiscovering(){return this._logger.debug("startDiscovering"),g(this.promptDeviceAccess()).pipe(_(async e=>u(async({liftEither:i,fromPromise:t})=>{const n=await i(e);if(n.gatt)try{await n.gatt.connect()}catch(r){throw new p(r)}try{const r=await t(this.getBleGattService(n)),o=await i(this.getBleDeviceInfos(r)),s=this.getDiscoveredDeviceFrom(o);return this.setInternalDeviceFrom(s,n,o,r),s}catch(r){throw await n.forget(),r}}).caseOf({Right:i=>i,Left:i=>{throw this._logger.error("Error while getting accessible device",{data:{error:i}}),i}})))}stopDiscovering(){this._logger.debug("stopDiscovering")}async connect({deviceId:e,onDisconnect:i}){const t=this._internalDevicesById.get(e);if(!t)return this._logger.error(`Unknown device ${e}`,{data:{internalDevices:this._internalDevicesById}}),this._logger.debug("Available devices",{data:{devices:this._internalDevicesById}}),c(new h(`Unknown device ${e}`));if(this._connectedDevices.includes(t.bleDevice))return this._internalDevicesById.delete(e),c(new b("Device already connected"));const{discoveredDevice:{deviceModel:n}}=t;try{const[r,o]=await Promise.all([t.bleGattService.getCharacteristic(t.bleDeviceInfos.writeCmdUuid),t.bleGattService.getCharacteristic(t.bleDeviceInfos.notifyUuid)]),s=new C({writeCharacteristic:r,notifyCharacteristic:o,apduReceiverFactory:this._apduReceiverFactory,apduSenderFactory:this._apduSenderFactory},this._loggerServiceFactory);await s.setup();const D=new I({sendApdu:(y,B)=>s.sendApdu(y,B),deviceModel:n,id:e,type:this.connectionType,transport:this.identifier});return t.bleDevice.ongattserverdisconnected=this._getDeviceDisconnectedHandler(t,s),this._deviceConnectionById.set(t.id,s),this._disconnectionHandlersById.set(t.id,()=>{this.disconnect({connectedDevice:D}).then(()=>i(e))}),this._connectedDevices.push(t.bleDevice),a(D)}catch(r){return await t.bleDevice.forget(),this._internalDevicesById.delete(e),this._logger.error("Error while getting characteristics",{data:{error:r}}),c(new p(r))}}_getDeviceDisconnectedHandler(e,i){return async()=>{const t=w(S).subscribe(()=>{this._logger.debug("disconnection timer over"),d.fromNullable(this._disconnectionHandlersById.get(e.id)).map(o=>o())});await e.bleDevice.gatt?.connect(),t.unsubscribe();const n=await this.getBleGattService(e.bleDevice);if(n.isRight()){const[r,o]=await Promise.all([n.extract().getCharacteristic(e.bleDeviceInfos.writeCmdUuid),n.extract().getCharacteristic(e.bleDeviceInfos.notifyUuid)]);await i.reconnect(r,o)}}}async disconnect(e){const i=d.fromNullable(this._internalDevicesById.get(e.connectedDevice.id));return this._logger.debug("disconnect device",{data:{connectedDevice:e.connectedDevice}}),i.isNothing()?(this._logger.error(`Unknown device ${e.connectedDevice.id}`),Promise.resolve(c(new h(`Unknown device ${e.connectedDevice.id}`)))):(i.map(t=>{const{bleDevice:n}=t;d.fromNullable(this._deviceConnectionById.get(t.id)).map(o=>o.disconnect()),n.gatt?.connected&&n.gatt.disconnect(),this._internalDevicesById.delete(t.id),this._deviceConnectionById.delete(t.id),this._disconnectionHandlersById.delete(t.id),this._connectedDevices.includes(n)&&delete this._connectedDevices[this._connectedDevices.indexOf(n)]}),Promise.resolve(a(void 0)))}}const O=({deviceModelDataSource:l,loggerServiceFactory:e,apduSenderServiceFactory:i,apduReceiverServiceFactory:t})=>new F(l,e,i,t);export{F as WebBleTransport,A as webBleIdentifier,O as webBleTransportFactory};
1
+ import{DeviceAlreadyConnectedError as B,DeviceNotRecognizedError as b,NoAccessibleDeviceError as m,OpeningConnectionError as p,TransportConnectedDevice as I,UnknownDeviceError as h}from"@ledgerhq/device-management-kit";import{EitherAsync as u,Left as c,Maybe as d,Right as a}from"purify-ts";import{from as g,switchMap as _,timer as w}from"rxjs";import{v4 as T}from"uuid";import{RECONNECT_DEVICE_TIMEOUT as S}from"../data/WebBleConfig";import{BleDeviceGattServerError as v,BleTransportNotSupportedError as E}from"../model/Errors";import{BleDeviceConnection as C}from"../transport/BleDeviceConnection";const A="WEB-BLE";class F{constructor(e,i,t,r){this._deviceModelDataSource=e;this._loggerServiceFactory=i;this._apduSenderFactory=t;this._apduReceiverFactory=r;this._connectedDevices=[],this._internalDevicesById=new Map,this._deviceConnectionById=new Map,this._disconnectionHandlersById=new Map,this._logger=i("WebBleTransport")}_connectedDevices;_internalDevicesById;_deviceConnectionById;_disconnectionHandlersById;_logger;connectionType="BLE";identifier=A;getBluetoothApi(){return this.isSupported()?a(navigator.bluetooth):c(new E("WebBle not supported"))}isSupported(){try{return!!navigator?.bluetooth}catch{return!1}}getIdentifier(){return this.identifier}listenToAvailableDevices(){return g([])}async getBleGattService(e){if(!e.gatt)return c(new v("Device gatt not found"));try{const[i]=await e.gatt.getPrimaryServices();return i?a(i):c(new v("bluetooth service not found"))}catch(i){return c(new v(i))}}getBleDeviceInfos(e){const t=this._deviceModelDataSource.getBluetoothServicesInfos()[e.uuid];return t?a(t):(this._logger.error(`Device not recognized: ${e.device.name}`),c(new b(`Device not recognized: ${e.device.name}`)))}promptDeviceAccess(){return u(async({liftEither:e,throwE:i})=>{const t=await e(this.getBluetoothApi());let r;try{r=await t.requestDevice({filters:this._deviceModelDataSource.getBluetoothServices().map(n=>({services:[n]}))})}catch(n){return i(new m(n))}return r})}getDiscoveredDeviceFrom(e){return{id:T(),deviceModel:e.deviceModel,transport:this.identifier}}setInternalDeviceFrom(e,i,t,r){const n={id:e.id,bleDevice:i,bleGattService:r,bleDeviceInfos:t,discoveredDevice:e};this._logger.debug(`Discovered device ${n.id} ${e.deviceModel.productName}`),this._internalDevicesById.set(n.id,n)}startDiscovering(){return this._logger.debug("startDiscovering"),g(this.promptDeviceAccess()).pipe(_(async e=>u(async({liftEither:i,fromPromise:t})=>{const r=await i(e);if(r.gatt)try{await r.gatt.connect()}catch(n){throw new p(n)}try{const n=await t(this.getBleGattService(r)),o=await i(this.getBleDeviceInfos(n)),s=this.getDiscoveredDeviceFrom(o);return this.setInternalDeviceFrom(s,r,o,n),s}catch(n){throw this._logger.error("Error while discovering device",{data:{error:n,bleDevice:r}}),r.forget&&await r.forget(),n}}).caseOf({Right:i=>i,Left:i=>{throw this._logger.error("Error while getting accessible device",{data:{error:i}}),i}})))}stopDiscovering(){this._logger.debug("stopDiscovering")}async connect({deviceId:e,onDisconnect:i}){const t=this._internalDevicesById.get(e);if(!t)return this._logger.error(`Unknown device ${e}`,{data:{internalDevices:this._internalDevicesById}}),this._logger.debug("Available devices",{data:{devices:this._internalDevicesById}}),c(new h(`Unknown device ${e}`));if(this._connectedDevices.includes(t.bleDevice))return this._internalDevicesById.delete(e),c(new B("Device already connected"));const{discoveredDevice:{deviceModel:r}}=t;try{const[n,o]=await Promise.all([t.bleGattService.getCharacteristic(t.bleDeviceInfos.writeCmdUuid),t.bleGattService.getCharacteristic(t.bleDeviceInfos.notifyUuid)]),s=new C({writeCharacteristic:n,notifyCharacteristic:o,apduReceiverFactory:this._apduReceiverFactory,apduSenderFactory:this._apduSenderFactory},this._loggerServiceFactory);await s.setup();const D=new I({sendApdu:(y,f)=>s.sendApdu(y,f),deviceModel:r,id:e,type:this.connectionType,transport:this.identifier});return t.bleDevice.ongattserverdisconnected=this._getDeviceDisconnectedHandler(t,s),this._deviceConnectionById.set(t.id,s),this._disconnectionHandlersById.set(t.id,()=>{this.disconnect({connectedDevice:D}).then(()=>i(e))}),this._connectedDevices.push(t.bleDevice),a(D)}catch(n){return t.bleDevice.forget&&await t.bleDevice.forget(),this._internalDevicesById.delete(e),this._logger.error("Error while getting characteristics",{data:{error:n}}),c(new p(n))}}_getDeviceDisconnectedHandler(e,i){return async()=>{const t=w(S).subscribe(()=>{this._logger.debug("disconnection timer over"),d.fromNullable(this._disconnectionHandlersById.get(e.id)).map(o=>o())});await e.bleDevice.gatt?.connect(),t.unsubscribe();const r=await this.getBleGattService(e.bleDevice);if(r.isRight()){const[n,o]=await Promise.all([r.extract().getCharacteristic(e.bleDeviceInfos.writeCmdUuid),r.extract().getCharacteristic(e.bleDeviceInfos.notifyUuid)]);await i.reconnect(n,o)}}}async disconnect(e){const i=d.fromNullable(this._internalDevicesById.get(e.connectedDevice.id));return this._logger.debug("disconnect device",{data:{connectedDevice:e.connectedDevice}}),i.isNothing()?(this._logger.error(`Unknown device ${e.connectedDevice.id}`),Promise.resolve(c(new h(`Unknown device ${e.connectedDevice.id}`)))):(i.map(t=>{const{bleDevice:r}=t;d.fromNullable(this._deviceConnectionById.get(t.id)).map(o=>o.disconnect()),r.gatt?.connected&&r.gatt.disconnect(),this._internalDevicesById.delete(t.id),this._deviceConnectionById.delete(t.id),this._disconnectionHandlersById.delete(t.id),this._connectedDevices.includes(r)&&delete this._connectedDevices[this._connectedDevices.indexOf(r)]}),Promise.resolve(a(void 0)))}}const O=({deviceModelDataSource:l,loggerServiceFactory:e,apduSenderServiceFactory:i,apduReceiverServiceFactory:t})=>new F(l,e,i,t);export{F as WebBleTransport,A as webBleIdentifier,O as webBleTransportFactory};
2
2
  //# sourceMappingURL=WebBleTransport.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/api/transport/WebBleTransport.ts"],
4
- "sourcesContent": ["import {\n type ApduReceiverServiceFactory,\n type ApduSenderServiceFactory,\n type BleDeviceInfos,\n type ConnectError,\n type ConnectionType,\n DeviceAlreadyConnectedError,\n type DeviceId,\n type DeviceModelDataSource,\n DeviceNotRecognizedError,\n type DisconnectHandler,\n type DmkError,\n type LoggerPublisherService,\n NoAccessibleDeviceError,\n OpeningConnectionError,\n type Transport,\n TransportConnectedDevice,\n type TransportDiscoveredDevice,\n type TransportFactory,\n type TransportIdentifier,\n UnknownDeviceError,\n} from \"@ledgerhq/device-management-kit\";\nimport { type Either, EitherAsync, Left, Maybe, Right } from \"purify-ts\";\nimport { from, type Observable, switchMap, timer } from \"rxjs\";\nimport { v4 as uuid } from \"uuid\";\n\nimport { RECONNECT_DEVICE_TIMEOUT } from \"@api/data/WebBleConfig\";\nimport {\n BleDeviceGattServerError,\n BleTransportNotSupportedError,\n} from \"@api/model/Errors\";\nimport { BleDeviceConnection } from \"@api/transport/BleDeviceConnection\";\n\ntype PromptDeviceAccessError =\n | NoAccessibleDeviceError\n | BleTransportNotSupportedError;\n\n// An attempt to manage the state of several devices with one transport. Not final.\ntype WebBleInternalDevice = {\n id: DeviceId;\n bleDevice: BluetoothDevice;\n bleDeviceInfos: BleDeviceInfos;\n bleGattService: BluetoothRemoteGATTService;\n discoveredDevice: TransportDiscoveredDevice;\n};\n\nexport const webBleIdentifier: TransportIdentifier = \"WEB-BLE\";\n\nexport class WebBleTransport implements Transport {\n private readonly _connectedDevices: Array<BluetoothDevice>;\n private readonly _internalDevicesById: Map<DeviceId, WebBleInternalDevice>;\n private _deviceConnectionById: Map<DeviceId, BleDeviceConnection>;\n private _disconnectionHandlersById: Map<DeviceId, () => void>;\n private _logger: LoggerPublisherService;\n private readonly connectionType: ConnectionType = \"BLE\";\n private readonly identifier: TransportIdentifier = webBleIdentifier;\n\n constructor(\n private readonly _deviceModelDataSource: DeviceModelDataSource,\n private readonly _loggerServiceFactory: (\n tag: string,\n ) => LoggerPublisherService,\n private readonly _apduSenderFactory: ApduSenderServiceFactory,\n private readonly _apduReceiverFactory: ApduReceiverServiceFactory,\n ) {\n this._connectedDevices = [];\n this._internalDevicesById = new Map();\n this._deviceConnectionById = new Map();\n this._disconnectionHandlersById = new Map();\n this._logger = _loggerServiceFactory(\"WebBleTransport\");\n }\n\n /**\n * Get the Bluetooth API if supported or error\n * @returns `Either<BleTransportNotSupportedError, Bluetooth>`\n */\n private getBluetoothApi(): Either<BleTransportNotSupportedError, Bluetooth> {\n if (this.isSupported()) {\n return Right(navigator.bluetooth);\n }\n\n return Left(new BleTransportNotSupportedError(\"WebBle not supported\"));\n }\n\n isSupported(): boolean {\n try {\n const result = !!navigator?.bluetooth;\n return result;\n } catch {\n return false;\n }\n }\n\n getIdentifier(): TransportIdentifier {\n return this.identifier;\n }\n\n listenToKnownDevices(): Observable<TransportDiscoveredDevice[]> {\n return from([]);\n }\n\n /**\n * Get Bluetooth GATT Primary service that is used to get writeCharacteristic and notifyCharacteristic\n * @param bleDevice\n * @private\n */\n private async getBleGattService(\n bleDevice: BluetoothDevice,\n ): Promise<Either<BleDeviceGattServerError, BluetoothRemoteGATTService>> {\n if (!bleDevice.gatt) {\n return Left(new BleDeviceGattServerError(\"Device gatt not found\"));\n }\n try {\n const [bleGattService] = await bleDevice.gatt.getPrimaryServices();\n if (!bleGattService) {\n return Left(\n new BleDeviceGattServerError(\"bluetooth service not found\"),\n );\n }\n return Right(bleGattService);\n } catch (e) {\n return Left(new BleDeviceGattServerError(e));\n }\n }\n\n /**\n * BleDeviceInfos to map primary service uuid to device model & characteristics uuid\n * @param bleGattService\n * @private\n */\n private getBleDeviceInfos(\n bleGattService: BluetoothRemoteGATTService,\n ): Either<DeviceNotRecognizedError, BleDeviceInfos> {\n const serviceToBleInfos =\n this._deviceModelDataSource.getBluetoothServicesInfos();\n const bleDeviceInfos = serviceToBleInfos[bleGattService.uuid];\n\n if (!bleDeviceInfos) {\n this._logger.error(\n `Device not recognized: ${bleGattService.device.name}`,\n );\n return Left(\n new DeviceNotRecognizedError(\n `Device not recognized: ${bleGattService.device.name}`,\n ),\n );\n }\n return Right(bleDeviceInfos);\n }\n\n /**\n * Prompt device selection in navigator\n *\n * @private\n */\n private promptDeviceAccess(): EitherAsync<\n PromptDeviceAccessError,\n BluetoothDevice\n > {\n return EitherAsync(async ({ liftEither, throwE }) => {\n const bluetoothApi = await liftEither(this.getBluetoothApi());\n let bleDevice: BluetoothDevice;\n\n try {\n bleDevice = await bluetoothApi.requestDevice({\n filters: this._deviceModelDataSource\n .getBluetoothServices()\n .map((serviceUuid) => ({\n services: [serviceUuid],\n })),\n });\n } catch (error) {\n return throwE(new NoAccessibleDeviceError(error));\n }\n\n return bleDevice;\n });\n }\n\n /**\n * Generate a discovered device from BluetoothDevice, BleGATT primary service and BLE device infos\n * @param bleDeviceInfos\n * @private\n */\n private getDiscoveredDeviceFrom(\n bleDeviceInfos: BleDeviceInfos,\n ): TransportDiscoveredDevice {\n return {\n id: uuid(),\n deviceModel: bleDeviceInfos.deviceModel,\n transport: this.identifier,\n };\n }\n\n /**\n * Generate an InternalDevice from a unique id, a BluetoothDevice, BleGATT primary service and BLE device infos\n * @param discoveredDevice\n * @param bleDevice\n * @param bleDeviceInfos\n * @param bleGattService\n * @private\n */\n private setInternalDeviceFrom(\n discoveredDevice: TransportDiscoveredDevice,\n bleDevice: BluetoothDevice,\n bleDeviceInfos: BleDeviceInfos,\n bleGattService: BluetoothRemoteGATTService,\n ) {\n const internalDevice: WebBleInternalDevice = {\n id: discoveredDevice.id,\n bleDevice,\n bleGattService,\n bleDeviceInfos,\n discoveredDevice,\n };\n\n this._logger.debug(\n `Discovered device ${internalDevice.id} ${discoveredDevice.deviceModel.productName}`,\n );\n this._internalDevicesById.set(internalDevice.id, internalDevice);\n }\n\n /**\n * Main method to get a device from a button click handler\n * The GATT connection is done here in order to populate TransportDiscoveredDevice with deviceModel\n */\n startDiscovering(): Observable<TransportDiscoveredDevice> {\n this._logger.debug(\"startDiscovering\");\n\n return from(this.promptDeviceAccess()).pipe(\n switchMap(async (errorOrBleDevice) =>\n EitherAsync(async ({ liftEither, fromPromise }) => {\n const bleDevice = await liftEither(errorOrBleDevice);\n if (bleDevice.gatt) {\n try {\n await bleDevice.gatt.connect();\n } catch (error) {\n throw new OpeningConnectionError(error);\n }\n }\n try {\n const bleGattService = await fromPromise(\n this.getBleGattService(bleDevice),\n );\n const bleDeviceInfos = await liftEither(\n this.getBleDeviceInfos(bleGattService),\n );\n const discoveredDevice =\n this.getDiscoveredDeviceFrom(bleDeviceInfos);\n this.setInternalDeviceFrom(\n discoveredDevice,\n bleDevice,\n bleDeviceInfos,\n bleGattService,\n );\n return discoveredDevice;\n } catch (error) {\n await bleDevice.forget();\n throw error;\n }\n }).caseOf({\n Right: (discoveredDevice) => discoveredDevice,\n Left: (error) => {\n this._logger.error(\"Error while getting accessible device\", {\n data: { error },\n });\n throw error;\n },\n }),\n ),\n );\n }\n\n stopDiscovering(): void {\n this._logger.debug(\"stopDiscovering\");\n }\n\n /**\n * Connect to a BLE device and update the internal state of the associated device\n * Handle ondisconnect event on the device in order to try a reconnection\n */\n async connect({\n deviceId,\n onDisconnect,\n }: {\n deviceId: DeviceId;\n onDisconnect: DisconnectHandler;\n }): Promise<Either<ConnectError, TransportConnectedDevice>> {\n const internalDevice = this._internalDevicesById.get(deviceId);\n\n if (!internalDevice) {\n this._logger.error(`Unknown device ${deviceId}`, {\n data: { internalDevices: this._internalDevicesById },\n });\n this._logger.debug(\"Available devices\", {\n data: { devices: this._internalDevicesById },\n });\n return Left(new UnknownDeviceError(`Unknown device ${deviceId}`));\n }\n // if device already connected, remove device id from internal state and remove error\n if (this._connectedDevices.includes(internalDevice.bleDevice)) {\n this._internalDevicesById.delete(deviceId);\n return Left(new DeviceAlreadyConnectedError(\"Device already connected\"));\n }\n\n const {\n discoveredDevice: { deviceModel },\n } = internalDevice;\n\n try {\n const [writeCharacteristic, notifyCharacteristic] = await Promise.all([\n internalDevice.bleGattService.getCharacteristic(\n internalDevice.bleDeviceInfos.writeCmdUuid,\n ),\n internalDevice.bleGattService.getCharacteristic(\n internalDevice.bleDeviceInfos.notifyUuid,\n ),\n ]);\n\n const deviceConnection = new BleDeviceConnection(\n {\n writeCharacteristic,\n notifyCharacteristic,\n apduReceiverFactory: this._apduReceiverFactory,\n apduSenderFactory: this._apduSenderFactory,\n },\n this._loggerServiceFactory,\n );\n\n await deviceConnection.setup();\n\n const connectedDevice = new TransportConnectedDevice({\n sendApdu: (apdu, triggersDisconnection) =>\n deviceConnection.sendApdu(apdu, triggersDisconnection),\n deviceModel,\n id: deviceId,\n type: this.connectionType,\n transport: this.identifier,\n });\n\n internalDevice.bleDevice.ongattserverdisconnected =\n this._getDeviceDisconnectedHandler(internalDevice, deviceConnection);\n\n this._deviceConnectionById.set(internalDevice.id, deviceConnection);\n this._disconnectionHandlersById.set(internalDevice.id, () => {\n this.disconnect({ connectedDevice }).then(() => onDisconnect(deviceId));\n });\n\n this._connectedDevices.push(internalDevice.bleDevice);\n\n return Right(connectedDevice);\n } catch (error) {\n await internalDevice.bleDevice.forget();\n\n this._internalDevicesById.delete(deviceId);\n\n this._logger.error(\"Error while getting characteristics\", {\n data: { error },\n });\n\n return Left(new OpeningConnectionError(error));\n }\n }\n\n /**\n * Get the device disconnected handler\n * @param internalDevice WebBleInternalDevice\n * @param deviceConnection BleDeviceConnection\n * @returns async () => void\n * @private\n */\n private _getDeviceDisconnectedHandler(\n internalDevice: WebBleInternalDevice,\n deviceConnection: BleDeviceConnection,\n ) {\n return async () => {\n // start a timer to disconnect the device if it does not reconnect\n const disconnectObserver = timer(RECONNECT_DEVICE_TIMEOUT).subscribe(\n () => {\n this._logger.debug(\"disconnection timer over\");\n // retrieve the disconnect handler and call it\n const disconnectHandler = Maybe.fromNullable(\n this._disconnectionHandlersById.get(internalDevice.id),\n );\n disconnectHandler.map((handler) => handler());\n },\n );\n\n // connect to the navigator device\n await internalDevice.bleDevice.gatt?.connect();\n\n // cancel disconnection timeout\n disconnectObserver.unsubscribe();\n\n // retrieve new ble characteristics\n const service = await this.getBleGattService(internalDevice.bleDevice);\n\n if (service.isRight()) {\n const [writeC, notifyC] = await Promise.all([\n service\n .extract()\n .getCharacteristic(internalDevice.bleDeviceInfos.writeCmdUuid),\n service\n .extract()\n .getCharacteristic(internalDevice.bleDeviceInfos.notifyUuid),\n ]);\n\n // reconnect device connection\n await deviceConnection.reconnect(writeC, notifyC);\n }\n };\n }\n\n /**\n * Disconnect from a BLE device and delete its handlers\n *\n * @param params { connectedDevice: TransportConnectedDevice }\n */\n async disconnect(params: {\n connectedDevice: TransportConnectedDevice;\n }): Promise<Either<DmkError, void>> {\n // retrieve internal device\n const maybeInternalDevice = Maybe.fromNullable(\n this._internalDevicesById.get(params.connectedDevice.id),\n );\n\n this._logger.debug(\"disconnect device\", {\n data: { connectedDevice: params.connectedDevice },\n });\n\n if (maybeInternalDevice.isNothing()) {\n this._logger.error(`Unknown device ${params.connectedDevice.id}`);\n\n return Promise.resolve(\n Left(\n new UnknownDeviceError(`Unknown device ${params.connectedDevice.id}`),\n ),\n );\n }\n\n maybeInternalDevice.map((device) => {\n const { bleDevice } = device;\n\n // retrieve device connection and disconnect it\n const maybeDeviceConnection = Maybe.fromNullable(\n this._deviceConnectionById.get(device.id),\n );\n\n maybeDeviceConnection.map((dConnection) => dConnection.disconnect());\n\n // disconnect device gatt server\n if (bleDevice.gatt?.connected) {\n bleDevice.gatt.disconnect();\n }\n // clean up objects\n this._internalDevicesById.delete(device.id);\n this._deviceConnectionById.delete(device.id);\n this._disconnectionHandlersById.delete(device.id);\n\n if (this._connectedDevices.includes(bleDevice)) {\n delete this._connectedDevices[\n this._connectedDevices.indexOf(bleDevice)\n ];\n }\n });\n\n return Promise.resolve(Right(undefined));\n }\n}\n\nexport const webBleTransportFactory: TransportFactory = ({\n deviceModelDataSource,\n loggerServiceFactory,\n apduSenderServiceFactory,\n apduReceiverServiceFactory,\n}) =>\n new WebBleTransport(\n deviceModelDataSource,\n loggerServiceFactory,\n apduSenderServiceFactory,\n apduReceiverServiceFactory,\n );\n"],
5
- "mappings": "AAAA,OAME,+BAAAA,EAGA,4BAAAC,EAIA,2BAAAC,EACA,0BAAAC,EAEA,4BAAAC,EAIA,sBAAAC,MACK,kCACP,OAAsB,eAAAC,EAAa,QAAAC,EAAM,SAAAC,EAAO,SAAAC,MAAa,YAC7D,OAAS,QAAAC,EAAuB,aAAAC,EAAW,SAAAC,MAAa,OACxD,OAAS,MAAMC,MAAY,OAE3B,OAAS,4BAAAC,MAAgC,yBACzC,OACE,4BAAAC,EACA,iCAAAC,MACK,oBACP,OAAS,uBAAAC,MAA2B,qCAe7B,MAAMC,EAAwC,UAE9C,MAAMC,CAAqC,CAShD,YACmBC,EACAC,EAGAC,EACAC,EACjB,CANiB,4BAAAH,EACA,2BAAAC,EAGA,wBAAAC,EACA,0BAAAC,EAEjB,KAAK,kBAAoB,CAAC,EAC1B,KAAK,qBAAuB,IAAI,IAChC,KAAK,sBAAwB,IAAI,IACjC,KAAK,2BAA6B,IAAI,IACt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CAAE,gBAAiBA,EAAO,eAAgB,CAClD,CAAC,EAEGC,EAAoB,UAAU,GAChC,KAAK,QAAQ,MAAM,kBAAkBD,EAAO,gBAAgB,EAAE,EAAE,EAEzD,QAAQ,QACb5C,EACE,IAAIF,EAAmB,kBAAkB8C,EAAO,gBAAgB,EAAE,EAAE,CACtE,CACF,IAGFC,EAAoB,IAAKC,GAAW,CAClC,KAAM,CAAE,UAAA7B,CAAU,EAAI6B,EAGQ7C,EAAM,aAClC,KAAK,sBAAsB,IAAI6C,EAAO,EAAE,CAC1C,EAEsB,IAAKC,GAAgBA,EAAY,WAAW,CAAC,EAG/D9B,EAAU,MAAM,WAClBA,EAAU,KAAK,WAAW,EAG5B,KAAK,qBAAqB,OAAO6B,EAAO,EAAE,EAC1C,KAAK,sBAAsB,OAAOA,EAAO,EAAE,EAC3C,KAAK,2BAA2B,OAAOA,EAAO,EAAE,EAE5C,KAAK,kBAAkB,SAAS7B,CAAS,GAC3C,OAAO,KAAK,kBACV,KAAK,kBAAkB,QAAQA,CAAS,CAC1C,CAEJ,CAAC,EAEM,QAAQ,QAAQf,EAAM,MAAS,CAAC,EACzC,CACF,CAEO,MAAM8C,EAA2C,CAAC,CACvD,sBAAAC,EACA,qBAAAC,EACA,yBAAAC,EACA,2BAAAC,CACF,IACE,IAAIxC,EACFqC,EACAC,EACAC,EACAC,CACF",
4
+ "sourcesContent": ["import {\n type ApduReceiverServiceFactory,\n type ApduSenderServiceFactory,\n type BleDeviceInfos,\n type ConnectError,\n type ConnectionType,\n DeviceAlreadyConnectedError,\n type DeviceId,\n type DeviceModelDataSource,\n DeviceNotRecognizedError,\n type DisconnectHandler,\n type DmkError,\n type LoggerPublisherService,\n NoAccessibleDeviceError,\n OpeningConnectionError,\n type Transport,\n TransportConnectedDevice,\n type TransportDiscoveredDevice,\n type TransportFactory,\n type TransportIdentifier,\n UnknownDeviceError,\n} from \"@ledgerhq/device-management-kit\";\nimport { type Either, EitherAsync, Left, Maybe, Right } from \"purify-ts\";\nimport { from, type Observable, switchMap, timer } from \"rxjs\";\nimport { v4 as uuid } from \"uuid\";\n\nimport { RECONNECT_DEVICE_TIMEOUT } from \"@api/data/WebBleConfig\";\nimport {\n BleDeviceGattServerError,\n BleTransportNotSupportedError,\n} from \"@api/model/Errors\";\nimport { BleDeviceConnection } from \"@api/transport/BleDeviceConnection\";\n\ntype PromptDeviceAccessError =\n | NoAccessibleDeviceError\n | BleTransportNotSupportedError;\n\n// An attempt to manage the state of several devices with one transport. Not final.\ntype WebBleInternalDevice = {\n id: DeviceId;\n bleDevice: BluetoothDevice;\n bleDeviceInfos: BleDeviceInfos;\n bleGattService: BluetoothRemoteGATTService;\n discoveredDevice: TransportDiscoveredDevice;\n};\n\nexport const webBleIdentifier: TransportIdentifier = \"WEB-BLE\";\n\nexport class WebBleTransport implements Transport {\n private readonly _connectedDevices: Array<BluetoothDevice>;\n private readonly _internalDevicesById: Map<DeviceId, WebBleInternalDevice>;\n private _deviceConnectionById: Map<DeviceId, BleDeviceConnection>;\n private _disconnectionHandlersById: Map<DeviceId, () => void>;\n private _logger: LoggerPublisherService;\n private readonly connectionType: ConnectionType = \"BLE\";\n private readonly identifier: TransportIdentifier = webBleIdentifier;\n\n constructor(\n private readonly _deviceModelDataSource: DeviceModelDataSource,\n private readonly _loggerServiceFactory: (\n tag: string,\n ) => LoggerPublisherService,\n private readonly _apduSenderFactory: ApduSenderServiceFactory,\n private readonly _apduReceiverFactory: ApduReceiverServiceFactory,\n ) {\n this._connectedDevices = [];\n this._internalDevicesById = new Map();\n this._deviceConnectionById = new Map();\n this._disconnectionHandlersById = new Map();\n this._logger = _loggerServiceFactory(\"WebBleTransport\");\n }\n\n /**\n * Get the Bluetooth API if supported or error\n * @returns `Either<BleTransportNotSupportedError, Bluetooth>`\n */\n private getBluetoothApi(): Either<BleTransportNotSupportedError, Bluetooth> {\n if (this.isSupported()) {\n return Right(navigator.bluetooth);\n }\n\n return Left(new BleTransportNotSupportedError(\"WebBle not supported\"));\n }\n\n isSupported(): boolean {\n try {\n const result = !!navigator?.bluetooth;\n return result;\n } catch {\n return false;\n }\n }\n\n getIdentifier(): TransportIdentifier {\n return this.identifier;\n }\n\n listenToAvailableDevices(): Observable<TransportDiscoveredDevice[]> {\n return from([]);\n }\n\n /**\n * Get Bluetooth GATT Primary service that is used to get writeCharacteristic and notifyCharacteristic\n * @param bleDevice\n * @private\n */\n private async getBleGattService(\n bleDevice: BluetoothDevice,\n ): Promise<Either<BleDeviceGattServerError, BluetoothRemoteGATTService>> {\n if (!bleDevice.gatt) {\n return Left(new BleDeviceGattServerError(\"Device gatt not found\"));\n }\n try {\n const [bleGattService] = await bleDevice.gatt.getPrimaryServices();\n if (!bleGattService) {\n return Left(\n new BleDeviceGattServerError(\"bluetooth service not found\"),\n );\n }\n return Right(bleGattService);\n } catch (e) {\n return Left(new BleDeviceGattServerError(e));\n }\n }\n\n /**\n * BleDeviceInfos to map primary service uuid to device model & characteristics uuid\n * @param bleGattService\n * @private\n */\n private getBleDeviceInfos(\n bleGattService: BluetoothRemoteGATTService,\n ): Either<DeviceNotRecognizedError, BleDeviceInfos> {\n const serviceToBleInfos =\n this._deviceModelDataSource.getBluetoothServicesInfos();\n const bleDeviceInfos = serviceToBleInfos[bleGattService.uuid];\n\n if (!bleDeviceInfos) {\n this._logger.error(\n `Device not recognized: ${bleGattService.device.name}`,\n );\n return Left(\n new DeviceNotRecognizedError(\n `Device not recognized: ${bleGattService.device.name}`,\n ),\n );\n }\n return Right(bleDeviceInfos);\n }\n\n /**\n * Prompt device selection in navigator\n *\n * @private\n */\n private promptDeviceAccess(): EitherAsync<\n PromptDeviceAccessError,\n BluetoothDevice\n > {\n return EitherAsync(async ({ liftEither, throwE }) => {\n const bluetoothApi = await liftEither(this.getBluetoothApi());\n let bleDevice: BluetoothDevice;\n\n try {\n bleDevice = await bluetoothApi.requestDevice({\n filters: this._deviceModelDataSource\n .getBluetoothServices()\n .map((serviceUuid) => ({\n services: [serviceUuid],\n })),\n });\n } catch (error) {\n return throwE(new NoAccessibleDeviceError(error));\n }\n\n return bleDevice;\n });\n }\n\n /**\n * Generate a discovered device from BluetoothDevice, BleGATT primary service and BLE device infos\n * @param bleDeviceInfos\n * @private\n */\n private getDiscoveredDeviceFrom(\n bleDeviceInfos: BleDeviceInfos,\n ): TransportDiscoveredDevice {\n return {\n id: uuid(),\n deviceModel: bleDeviceInfos.deviceModel,\n transport: this.identifier,\n };\n }\n\n /**\n * Generate an InternalDevice from a unique id, a BluetoothDevice, BleGATT primary service and BLE device infos\n * @param discoveredDevice\n * @param bleDevice\n * @param bleDeviceInfos\n * @param bleGattService\n * @private\n */\n private setInternalDeviceFrom(\n discoveredDevice: TransportDiscoveredDevice,\n bleDevice: BluetoothDevice,\n bleDeviceInfos: BleDeviceInfos,\n bleGattService: BluetoothRemoteGATTService,\n ) {\n const internalDevice: WebBleInternalDevice = {\n id: discoveredDevice.id,\n bleDevice,\n bleGattService,\n bleDeviceInfos,\n discoveredDevice,\n };\n\n this._logger.debug(\n `Discovered device ${internalDevice.id} ${discoveredDevice.deviceModel.productName}`,\n );\n this._internalDevicesById.set(internalDevice.id, internalDevice);\n }\n\n /**\n * Main method to get a device from a button click handler\n * The GATT connection is done here in order to populate TransportDiscoveredDevice with deviceModel\n */\n startDiscovering(): Observable<TransportDiscoveredDevice> {\n this._logger.debug(\"startDiscovering\");\n\n return from(this.promptDeviceAccess()).pipe(\n switchMap(async (errorOrBleDevice) =>\n EitherAsync(async ({ liftEither, fromPromise }) => {\n const bleDevice = await liftEither(errorOrBleDevice);\n if (bleDevice.gatt) {\n try {\n await bleDevice.gatt.connect();\n } catch (error) {\n throw new OpeningConnectionError(error);\n }\n }\n try {\n const bleGattService = await fromPromise(\n this.getBleGattService(bleDevice),\n );\n const bleDeviceInfos = await liftEither(\n this.getBleDeviceInfos(bleGattService),\n );\n const discoveredDevice =\n this.getDiscoveredDeviceFrom(bleDeviceInfos);\n this.setInternalDeviceFrom(\n discoveredDevice,\n bleDevice,\n bleDeviceInfos,\n bleGattService,\n );\n return discoveredDevice;\n } catch (error) {\n this._logger.error(\"Error while discovering device\", {\n data: { error, bleDevice },\n });\n if (bleDevice.forget) {\n await bleDevice.forget();\n }\n throw error;\n }\n }).caseOf({\n Right: (discoveredDevice) => discoveredDevice,\n Left: (error) => {\n this._logger.error(\"Error while getting accessible device\", {\n data: { error },\n });\n throw error;\n },\n }),\n ),\n );\n }\n\n stopDiscovering(): void {\n this._logger.debug(\"stopDiscovering\");\n }\n\n /**\n * Connect to a BLE device and update the internal state of the associated device\n * Handle ondisconnect event on the device in order to try a reconnection\n */\n async connect({\n deviceId,\n onDisconnect,\n }: {\n deviceId: DeviceId;\n onDisconnect: DisconnectHandler;\n }): Promise<Either<ConnectError, TransportConnectedDevice>> {\n const internalDevice = this._internalDevicesById.get(deviceId);\n\n if (!internalDevice) {\n this._logger.error(`Unknown device ${deviceId}`, {\n data: { internalDevices: this._internalDevicesById },\n });\n this._logger.debug(\"Available devices\", {\n data: { devices: this._internalDevicesById },\n });\n return Left(new UnknownDeviceError(`Unknown device ${deviceId}`));\n }\n // if device already connected, remove device id from internal state and remove error\n if (this._connectedDevices.includes(internalDevice.bleDevice)) {\n this._internalDevicesById.delete(deviceId);\n return Left(new DeviceAlreadyConnectedError(\"Device already connected\"));\n }\n\n const {\n discoveredDevice: { deviceModel },\n } = internalDevice;\n\n try {\n const [writeCharacteristic, notifyCharacteristic] = await Promise.all([\n internalDevice.bleGattService.getCharacteristic(\n internalDevice.bleDeviceInfos.writeCmdUuid,\n ),\n internalDevice.bleGattService.getCharacteristic(\n internalDevice.bleDeviceInfos.notifyUuid,\n ),\n ]);\n\n const deviceConnection = new BleDeviceConnection(\n {\n writeCharacteristic,\n notifyCharacteristic,\n apduReceiverFactory: this._apduReceiverFactory,\n apduSenderFactory: this._apduSenderFactory,\n },\n this._loggerServiceFactory,\n );\n\n await deviceConnection.setup();\n\n const connectedDevice = new TransportConnectedDevice({\n sendApdu: (apdu, triggersDisconnection) =>\n deviceConnection.sendApdu(apdu, triggersDisconnection),\n deviceModel,\n id: deviceId,\n type: this.connectionType,\n transport: this.identifier,\n });\n\n internalDevice.bleDevice.ongattserverdisconnected =\n this._getDeviceDisconnectedHandler(internalDevice, deviceConnection);\n\n this._deviceConnectionById.set(internalDevice.id, deviceConnection);\n this._disconnectionHandlersById.set(internalDevice.id, () => {\n this.disconnect({ connectedDevice }).then(() => onDisconnect(deviceId));\n });\n\n this._connectedDevices.push(internalDevice.bleDevice);\n\n return Right(connectedDevice);\n } catch (error) {\n if (internalDevice.bleDevice.forget) {\n await internalDevice.bleDevice.forget();\n }\n\n this._internalDevicesById.delete(deviceId);\n\n this._logger.error(\"Error while getting characteristics\", {\n data: { error },\n });\n\n return Left(new OpeningConnectionError(error));\n }\n }\n\n /**\n * Get the device disconnected handler\n * @param internalDevice WebBleInternalDevice\n * @param deviceConnection BleDeviceConnection\n * @returns async () => void\n * @private\n */\n private _getDeviceDisconnectedHandler(\n internalDevice: WebBleInternalDevice,\n deviceConnection: BleDeviceConnection,\n ) {\n return async () => {\n // start a timer to disconnect the device if it does not reconnect\n const disconnectObserver = timer(RECONNECT_DEVICE_TIMEOUT).subscribe(\n () => {\n this._logger.debug(\"disconnection timer over\");\n // retrieve the disconnect handler and call it\n const disconnectHandler = Maybe.fromNullable(\n this._disconnectionHandlersById.get(internalDevice.id),\n );\n disconnectHandler.map((handler) => handler());\n },\n );\n\n // connect to the navigator device\n await internalDevice.bleDevice.gatt?.connect();\n\n // cancel disconnection timeout\n disconnectObserver.unsubscribe();\n\n // retrieve new ble characteristics\n const service = await this.getBleGattService(internalDevice.bleDevice);\n\n if (service.isRight()) {\n const [writeC, notifyC] = await Promise.all([\n service\n .extract()\n .getCharacteristic(internalDevice.bleDeviceInfos.writeCmdUuid),\n service\n .extract()\n .getCharacteristic(internalDevice.bleDeviceInfos.notifyUuid),\n ]);\n\n // reconnect device connection\n await deviceConnection.reconnect(writeC, notifyC);\n }\n };\n }\n\n /**\n * Disconnect from a BLE device and delete its handlers\n *\n * @param params { connectedDevice: TransportConnectedDevice }\n */\n async disconnect(params: {\n connectedDevice: TransportConnectedDevice;\n }): Promise<Either<DmkError, void>> {\n // retrieve internal device\n const maybeInternalDevice = Maybe.fromNullable(\n this._internalDevicesById.get(params.connectedDevice.id),\n );\n\n this._logger.debug(\"disconnect device\", {\n data: { connectedDevice: params.connectedDevice },\n });\n\n if (maybeInternalDevice.isNothing()) {\n this._logger.error(`Unknown device ${params.connectedDevice.id}`);\n\n return Promise.resolve(\n Left(\n new UnknownDeviceError(`Unknown device ${params.connectedDevice.id}`),\n ),\n );\n }\n\n maybeInternalDevice.map((device) => {\n const { bleDevice } = device;\n\n // retrieve device connection and disconnect it\n const maybeDeviceConnection = Maybe.fromNullable(\n this._deviceConnectionById.get(device.id),\n );\n\n maybeDeviceConnection.map((dConnection) => dConnection.disconnect());\n\n // disconnect device gatt server\n if (bleDevice.gatt?.connected) {\n bleDevice.gatt.disconnect();\n }\n // clean up objects\n this._internalDevicesById.delete(device.id);\n this._deviceConnectionById.delete(device.id);\n this._disconnectionHandlersById.delete(device.id);\n\n if (this._connectedDevices.includes(bleDevice)) {\n delete this._connectedDevices[\n this._connectedDevices.indexOf(bleDevice)\n ];\n }\n });\n\n return Promise.resolve(Right(undefined));\n }\n}\n\nexport const webBleTransportFactory: TransportFactory = ({\n deviceModelDataSource,\n loggerServiceFactory,\n apduSenderServiceFactory,\n apduReceiverServiceFactory,\n}) =>\n new WebBleTransport(\n deviceModelDataSource,\n loggerServiceFactory,\n apduSenderServiceFactory,\n apduReceiverServiceFactory,\n );\n"],
5
+ "mappings": "AAAA,OAME,+BAAAA,EAGA,4BAAAC,EAIA,2BAAAC,EACA,0BAAAC,EAEA,4BAAAC,EAIA,sBAAAC,MACK,kCACP,OAAsB,eAAAC,EAAa,QAAAC,EAAM,SAAAC,EAAO,SAAAC,MAAa,YAC7D,OAAS,QAAAC,EAAuB,aAAAC,EAAW,SAAAC,MAAa,OACxD,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CAAC,CACvD,sBAAAC,EACA,qBAAAC,EACA,yBAAAC,EACA,2BAAAC,CACF,IACE,IAAIxC,EACFqC,EACAC,EACAC,EACAC,CACF",
6
6
  "names": ["DeviceAlreadyConnectedError", "DeviceNotRecognizedError", "NoAccessibleDeviceError", "OpeningConnectionError", "TransportConnectedDevice", "UnknownDeviceError", "EitherAsync", "Left", "Maybe", "Right", "from", "switchMap", "timer", "uuid", "RECONNECT_DEVICE_TIMEOUT", "BleDeviceGattServerError", "BleTransportNotSupportedError", "BleDeviceConnection", "webBleIdentifier", "WebBleTransport", "_deviceModelDataSource", "_loggerServiceFactory", "_apduSenderFactory", "_apduReceiverFactory", "bleDevice", "bleGattService", "e", "bleDeviceInfos", "liftEither", "throwE", "bluetoothApi", "serviceUuid", "error", "discoveredDevice", "internalDevice", "errorOrBleDevice", "fromPromise", "deviceId", "onDisconnect", "deviceModel", "writeCharacteristic", "notifyCharacteristic", "deviceConnection", "connectedDevice", "apdu", "triggersDisconnection", "disconnectObserver", "handler", "service", "writeC", "notifyC", "params", "maybeInternalDevice", "device", "dConnection", "webBleTransportFactory", "deviceModelDataSource", "loggerServiceFactory", "apduSenderServiceFactory", "apduReceiverServiceFactory"]
7
7
  }
@@ -1,2 +1,2 @@
1
- import{NoAccessibleDeviceError as v,OpeningConnectionError as b,StaticDeviceModelDataSource as m,UnknownDeviceError as p}from"@ledgerhq/device-management-kit";import{Left as h,Right as S}from"purify-ts";import{RECONNECT_DEVICE_TIMEOUT as f}from"../data/WebBleConfig";import{bleDeviceStubBuilder as w}from"../model/BleDevice.stub";import{BleTransportNotSupportedError as D}from"../model/Errors";import{BleDeviceGattServerError as g}from"../model/Errors";import{WebBleTransport as E}from"./WebBleTransport";class j{subscribers=[];tag;constructor(a,d){this.subscribers=a,this.tag=d}error=jest.fn();warn=jest.fn();info=jest.fn();debug=jest.fn()}const y=new m,k=new j([],"web-ble"),r=w();describe("WebBleTransport",()=>{let n,a,d;beforeEach(()=>{a=jest.fn(),d=jest.fn(),n=new E(y,()=>k,d,a),jest.useFakeTimers()}),afterEach(()=>{jest.restoreAllMocks()});const i=(o,e)=>{n.startDiscovering().subscribe({next:o,error:e})};describe("When Web bluetooth API is not supported",()=>{it("should not support the transport",()=>{expect(n.isSupported()).toBe(!1)}),it("should emit a startDiscovering error",o=>{i(()=>{o("Should not emit any value")},e=>{expect(e).toBeInstanceOf(D),o()})})}),describe("When Web Bluetooth API is supported",()=>{const o=jest.fn();beforeAll(()=>{global.navigator={bluetooth:{requestDevice:o}}}),afterAll(()=>{jest.restoreAllMocks(),global.navigator=void 0}),it("should support the transport",()=>{expect(n.isSupported()).toBe(!0)}),describe("startDiscovering",()=>{it("should emit device if one new grant access",e=>{o.mockResolvedValueOnce(r),i(t=>{try{expect(t).toEqual(expect.objectContaining({deviceModel:expect.objectContaining({id:"nanoX",productName:"Ledger Nano X"})})),e()}catch(c){e(c)}},t=>{e(t)})}),it("should throw DeviceNotRecognizedError if the device is not recognized",e=>{o.mockResolvedValueOnce({...r,gatt:{...r.gatt,getPrimaryServices:jest.fn(()=>Promise.resolve([]))},productId:16962}),i(()=>{e("should not return a device")},t=>{expect(t).toBeInstanceOf(g),e()})}),it("should emit an error if the request device is in error",e=>{const t="request device error";o.mockImplementationOnce(()=>{throw new Error(t)}),i(()=>{e("should not return a device")},c=>{expect(c).toBeInstanceOf(v),expect(c).toStrictEqual(new v(new Error(t))),e()})}),it("should emit an error if the user did not grant us access to a device (clicking on cancel on the browser popup for ex)",e=>{o.mockResolvedValueOnce({forget:jest.fn()}),i(t=>{e(`Should not emit any value, but emitted ${JSON.stringify(t)}`)},t=>{try{expect(t).toBeInstanceOf(g),e()}catch(c){e(c)}})})}),describe("connect",()=>{it("should throw UnknownDeviceError if no internal device",async()=>{const e={deviceId:"fake",onDisconnect:jest.fn()},t=await n.connect(e);expect(t).toStrictEqual(h(new p("Unknown device fake")))}),it("should throw OpeningConnectionError if the device is already opened",async()=>{const e={deviceId:"fake",onDisconnect:jest.fn()},t=await n.connect(e);expect(t).toStrictEqual(h(new p("Unknown device fake")))}),it("should throw OpeningConnectionError if the device cannot be opened",e=>{const t="cannot be opened";o.mockResolvedValueOnce({...r,gatt:{connect:()=>{throw new Error(t)}}}),i(()=>{e()},c=>{expect(c).toBeInstanceOf(b),e()})}),it("should return the opened device",e=>{o.mockResolvedValueOnce({...r,gatt:{...r.gatt,connected:!0}}),i(t=>{n.connect({deviceId:t.id,onDisconnect:jest.fn()}).then(c=>{c.ifRight(s=>{expect(s).toEqual(expect.objectContaining({id:t.id})),e()}).ifLeft(()=>{e(c)})}).catch(c=>{e(c)})},t=>{e(t)})}),it("should return a device if available",e=>{o.mockResolvedValueOnce(r),i(t=>{n.connect({deviceId:t.id,onDisconnect:jest.fn()}).then(c=>{c.ifRight(s=>{expect(s).toEqual(expect.objectContaining({id:t.id})),e()}).ifLeft(()=>{e(c)})}).catch(c=>{e(c)})},t=>{e(t)})})}),describe("disconnect",()=>{it("should disconnect the device",e=>{o.mockResolvedValueOnce(r);const t=jest.fn();i(c=>{n.connect({deviceId:c.id,onDisconnect:t}).then(s=>{s.ifRight(l=>{n.disconnect({connectedDevice:l}).then(u=>{expect(u).toStrictEqual(S(void 0)),e()}).catch(u=>{e(u)})})})},c=>{e(c)})}),it("should call disconnect handler if device is hardware disconnected",e=>{const t=jest.fn(),c=jest.spyOn(n,"disconnect");o.mockResolvedValueOnce(r),i(s=>{n.connect({deviceId:s.id,onDisconnect:t}).then(()=>{r.ongattserverdisconnected(new Event("")),jest.advanceTimersByTime(f),expect(c).toHaveBeenCalled(),e()})},s=>{e(s)})})}),describe("reconnect",()=>{it("should not call disconnection if reconnection happen",e=>{const t=jest.fn(),c=jest.spyOn(n,"disconnect");o.mockResolvedValueOnce(r),i(s=>{n.connect({deviceId:s.id,onDisconnect:t}).then(()=>{r.ongattserverdisconnected(new Event("")),jest.advanceTimersByTime(f/3),expect(c).toHaveBeenCalledTimes(0),e()}).catch(l=>{e(l)})})})})})});
1
+ import{NoAccessibleDeviceError as p,OpeningConnectionError as b,StaticDeviceModelDataSource as w,UnknownDeviceError as h}from"@ledgerhq/device-management-kit";import{Left as f,Right as S}from"purify-ts";import{RECONNECT_DEVICE_TIMEOUT as m}from"../data/WebBleConfig";import{bleDeviceStubBuilder as E}from"../model/BleDevice.stub";import{BleTransportNotSupportedError as D}from"../model/Errors";import{BleDeviceGattServerError as g}from"../model/Errors";import{WebBleTransport as y}from"./WebBleTransport";class k{subscribers=[];tag;constructor(d,v){this.subscribers=d,this.tag=v}error=vi.fn();warn=vi.fn();info=vi.fn();debug=vi.fn()}const x=new w,O=new k([],"web-ble"),c=E();describe("WebBleTransport",()=>{let i,d,v;beforeEach(()=>{d=vi.fn(),v=vi.fn(),i=new y(x,()=>O,v,d),vi.useFakeTimers()}),afterEach(()=>{vi.restoreAllMocks()});const s=(r,t)=>{i.startDiscovering().subscribe({next:r,error:t})};describe("When Web bluetooth API is not supported",()=>{it("should not support the transport",()=>{expect(i.isSupported()).toBe(!1)}),it("should emit a startDiscovering error",()=>new Promise((r,t)=>{s(()=>{t("Should not emit any value")},e=>{expect(e).toBeInstanceOf(D),r()})}))}),describe("When Web Bluetooth API is supported",()=>{const r=vi.fn();beforeAll(()=>{global.navigator={bluetooth:{requestDevice:r}}}),afterAll(()=>{vi.restoreAllMocks(),global.navigator=void 0}),it("should support the transport",()=>{expect(i.isSupported()).toBe(!0)}),describe("startDiscovering",()=>{it("should emit device if one new grant access",()=>new Promise((t,e)=>{r.mockResolvedValueOnce(c),s(o=>{try{expect(o).toEqual(expect.objectContaining({deviceModel:expect.objectContaining({id:"nanoX",productName:"Ledger Nano X"})})),t()}catch(n){e(n)}},o=>{e(o)})})),it("should throw DeviceNotRecognizedError if the device is not recognized",()=>new Promise((t,e)=>{r.mockResolvedValueOnce({...c,gatt:{...c.gatt,getPrimaryServices:vi.fn(()=>Promise.resolve([]))},productId:16962}),s(()=>{e("should not return a device")},o=>{expect(o).toBeInstanceOf(g),t()})})),it("should emit an error if the request device is in error",()=>new Promise((t,e)=>{const o="request device error";r.mockImplementationOnce(()=>{throw new Error(o)}),s(()=>{e("should not return a device")},n=>{expect(n).toBeInstanceOf(p),expect(n).toStrictEqual(new p(new Error(o))),t()})})),it("should emit an error if the user did not grant us access to a device (clicking on cancel on the browser popup for ex)",()=>new Promise((t,e)=>{r.mockResolvedValueOnce({forget:vi.fn()}),s(o=>{e(`Should not emit any value, but emitted ${JSON.stringify(o)}`)},o=>{try{expect(o).toBeInstanceOf(g),t()}catch(n){e(n)}})}))}),describe("connect",()=>{it("should throw UnknownDeviceError if no internal device",async()=>{const t={deviceId:"fake",onDisconnect:vi.fn()},e=await i.connect(t);expect(e).toStrictEqual(f(new h("Unknown device fake")))}),it("should throw OpeningConnectionError if the device is already opened",async()=>{const t={deviceId:"fake",onDisconnect:vi.fn()},e=await i.connect(t);expect(e).toStrictEqual(f(new h("Unknown device fake")))}),it("should throw OpeningConnectionError if the device cannot be opened",()=>new Promise((t,e)=>{const o="cannot be opened";r.mockResolvedValueOnce({...c,gatt:{connect:()=>{throw new Error(o)}}}),s(()=>{e("Should not emit any value")},n=>{expect(n).toBeInstanceOf(b),t()})})),it("should return the opened device",()=>new Promise((t,e)=>{r.mockResolvedValueOnce({...c,gatt:{...c.gatt,connected:!0}}),s(o=>{i.connect({deviceId:o.id,onDisconnect:vi.fn()}).then(n=>{n.ifRight(a=>{expect(a).toEqual(expect.objectContaining({id:o.id})),t()}).ifLeft(()=>{e(n)})}).catch(n=>{e(n)})},o=>{e(o)})})),it("should return a device if available",()=>new Promise((t,e)=>{r.mockResolvedValueOnce(c),s(o=>{i.connect({deviceId:o.id,onDisconnect:vi.fn()}).then(n=>{n.ifRight(a=>{expect(a).toEqual(expect.objectContaining({id:o.id})),t()}).ifLeft(()=>{e(n)})}).catch(n=>{e(n)})},o=>{e(o)})}))}),describe("disconnect",()=>{it("should disconnect the device",()=>new Promise((t,e)=>{r.mockResolvedValueOnce(c);const o=vi.fn();s(n=>{i.connect({deviceId:n.id,onDisconnect:o}).then(a=>{a.ifRight(l=>{i.disconnect({connectedDevice:l}).then(u=>{expect(u).toStrictEqual(S(void 0)),t()}).catch(u=>{e(u)})})})},n=>{e(n)})})),it("should call disconnect handler if device is hardware disconnected",()=>new Promise((t,e)=>{const o=vi.fn(),n=vi.spyOn(i,"disconnect");r.mockResolvedValueOnce(c),s(a=>{i.connect({deviceId:a.id,onDisconnect:o}).then(()=>{c.ongattserverdisconnected(new Event("")),vi.advanceTimersByTime(m),expect(n).toHaveBeenCalled(),t()})},a=>{e(a)})}))}),describe("reconnect",()=>{it("should not call disconnection if reconnection happen",()=>new Promise((t,e)=>{const o=vi.fn(),n=vi.spyOn(i,"disconnect");r.mockResolvedValueOnce(c),s(a=>{i.connect({deviceId:a.id,onDisconnect:o}).then(()=>{c.ongattserverdisconnected(new Event("")),vi.advanceTimersByTime(m/3),expect(n).toHaveBeenCalledTimes(0),t()}).catch(l=>{e(l)})})}))})})});
2
2
  //# sourceMappingURL=WebBleTransport.test.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/api/transport/WebBleTransport.test.ts"],
4
- "sourcesContent": ["import {\n type ApduReceiverServiceFactory,\n type ApduSenderServiceFactory,\n type DeviceModel,\n type LoggerPublisherService,\n type LoggerSubscriberService,\n NoAccessibleDeviceError,\n OpeningConnectionError,\n StaticDeviceModelDataSource,\n type TransportDiscoveredDevice,\n UnknownDeviceError,\n} from \"@ledgerhq/device-management-kit\";\nimport { Left, Right } from \"purify-ts\";\n\nimport { RECONNECT_DEVICE_TIMEOUT } from \"@api/data/WebBleConfig\";\nimport { bleDeviceStubBuilder } from \"@api/model/BleDevice.stub\";\nimport { BleTransportNotSupportedError } from \"@api/model/Errors\";\nimport { BleDeviceGattServerError } from \"@api/model/Errors\";\n\nimport { WebBleTransport } from \"./WebBleTransport\";\n\nclass LoggerPublisherServiceStub implements LoggerPublisherService {\n subscribers: LoggerSubscriberService[] = [];\n tag: string;\n constructor(subscribers: LoggerSubscriberService[], tag: string) {\n this.subscribers = subscribers;\n this.tag = tag;\n }\n error = jest.fn();\n warn = jest.fn();\n info = jest.fn();\n debug = jest.fn();\n}\n\n// Our StaticDeviceModelDataSource can directly be used in our unit tests\nconst bleDeviceModelDataSource = new StaticDeviceModelDataSource();\nconst logger = new LoggerPublisherServiceStub([], \"web-ble\");\n\nconst stubDevice: BluetoothDevice = bleDeviceStubBuilder();\n\ndescribe(\"WebBleTransport\", () => {\n let transport: WebBleTransport;\n let apduReceiverServiceFactoryStub: ApduReceiverServiceFactory;\n let apduSenderServiceFactoryStub: ApduSenderServiceFactory;\n\n beforeEach(() => {\n apduReceiverServiceFactoryStub = jest.fn();\n apduSenderServiceFactoryStub = jest.fn();\n transport = new WebBleTransport(\n bleDeviceModelDataSource,\n () => logger,\n apduSenderServiceFactoryStub,\n apduReceiverServiceFactoryStub,\n );\n jest.useFakeTimers();\n });\n\n afterEach(() => {\n jest.restoreAllMocks();\n });\n\n const discoverDevice = (\n onSuccess: (discoveredDevice: TransportDiscoveredDevice) => void,\n onError?: (error: unknown) => void,\n ) => {\n transport.startDiscovering().subscribe({\n next: onSuccess,\n error: onError,\n });\n };\n\n describe(\"When Web bluetooth API is not supported\", () => {\n it(\"should not support the transport\", () => {\n expect(transport.isSupported()).toBe(false);\n });\n\n it(\"should emit a startDiscovering error\", (done) => {\n discoverDevice(\n () => {\n done(\"Should not emit any value\");\n },\n (error) => {\n expect(error).toBeInstanceOf(BleTransportNotSupportedError);\n done();\n },\n );\n });\n });\n\n describe(\"When Web Bluetooth API is supported\", () => {\n const mockedRequestDevice = jest.fn();\n\n beforeAll(() => {\n global.navigator = {\n bluetooth: {\n requestDevice: mockedRequestDevice,\n },\n } as unknown as Navigator;\n });\n\n afterAll(() => {\n jest.restoreAllMocks();\n global.navigator = undefined as unknown as Navigator;\n });\n\n it(\"should support the transport\", () => {\n expect(transport.isSupported()).toBe(true);\n });\n\n describe(\"startDiscovering\", () => {\n it(\"should emit device if one new grant access\", (done) => {\n mockedRequestDevice.mockResolvedValueOnce(stubDevice);\n\n discoverDevice(\n (discoveredDevice) => {\n try {\n expect(discoveredDevice).toEqual(\n expect.objectContaining({\n deviceModel: expect.objectContaining({\n id: \"nanoX\",\n productName: \"Ledger Nano X\",\n }) as DeviceModel,\n }),\n );\n\n done();\n } catch (expectError) {\n done(expectError);\n }\n },\n (error) => {\n done(error);\n },\n );\n });\n\n it(\"should throw DeviceNotRecognizedError if the device is not recognized\", (done) => {\n mockedRequestDevice.mockResolvedValueOnce({\n ...stubDevice,\n gatt: {\n ...stubDevice.gatt,\n getPrimaryServices: jest.fn(() => Promise.resolve([])),\n },\n productId: 0x4242,\n });\n\n discoverDevice(\n () => {\n done(\"should not return a device\");\n },\n (error) => {\n expect(error).toBeInstanceOf(BleDeviceGattServerError);\n done();\n },\n );\n });\n\n it(\"should emit an error if the request device is in error\", (done) => {\n const message = \"request device error\";\n mockedRequestDevice.mockImplementationOnce(() => {\n throw new Error(message);\n });\n\n discoverDevice(\n () => {\n done(\"should not return a device\");\n },\n (error) => {\n expect(error).toBeInstanceOf(NoAccessibleDeviceError);\n expect(error).toStrictEqual(\n new NoAccessibleDeviceError(new Error(message)),\n );\n done();\n },\n );\n });\n\n it(\"should emit an error if the user did not grant us access to a device (clicking on cancel on the browser popup for ex)\", (done) => {\n mockedRequestDevice.mockResolvedValueOnce({ forget: jest.fn() });\n\n discoverDevice(\n (discoveredDevice) => {\n done(\n `Should not emit any value, but emitted ${JSON.stringify(\n discoveredDevice,\n )}`,\n );\n },\n (error) => {\n try {\n expect(error).toBeInstanceOf(BleDeviceGattServerError);\n done();\n } catch (expectError) {\n done(expectError);\n }\n },\n );\n });\n });\n\n describe(\"connect\", () => {\n it(\"should throw UnknownDeviceError if no internal device\", async () => {\n const connectParams = {\n deviceId: \"fake\",\n onDisconnect: jest.fn(),\n };\n\n const connect = await transport.connect(connectParams);\n\n expect(connect).toStrictEqual(\n Left(new UnknownDeviceError(\"Unknown device fake\")),\n );\n });\n\n it(\"should throw OpeningConnectionError if the device is already opened\", async () => {\n const device = {\n deviceId: \"fake\",\n onDisconnect: jest.fn(),\n };\n\n const connect = await transport.connect(device);\n\n expect(connect).toStrictEqual(\n Left(new UnknownDeviceError(\"Unknown device fake\")),\n );\n });\n\n it(\"should throw OpeningConnectionError if the device cannot be opened\", (done) => {\n const message = \"cannot be opened\";\n mockedRequestDevice.mockResolvedValueOnce({\n ...stubDevice,\n gatt: {\n connect: () => {\n throw new Error(message);\n },\n },\n });\n\n discoverDevice(\n () => {\n done();\n },\n (error) => {\n expect(error).toBeInstanceOf(OpeningConnectionError);\n done();\n },\n );\n });\n\n it(\"should return the opened device\", (done) => {\n mockedRequestDevice.mockResolvedValueOnce({\n ...stubDevice,\n gatt: {\n ...stubDevice.gatt,\n connected: true,\n },\n });\n\n discoverDevice(\n (discoveredDevice) => {\n transport\n .connect({\n deviceId: discoveredDevice.id,\n onDisconnect: jest.fn(),\n })\n .then((connectedDevice) => {\n connectedDevice\n .ifRight((device) => {\n expect(device).toEqual(\n expect.objectContaining({ id: discoveredDevice.id }),\n );\n done();\n })\n .ifLeft(() => {\n done(connectedDevice);\n });\n })\n .catch((error) => {\n done(error);\n });\n },\n (error) => {\n done(error);\n },\n );\n });\n\n it(\"should return a device if available\", (done) => {\n mockedRequestDevice.mockResolvedValueOnce(stubDevice);\n\n discoverDevice(\n (discoveredDevice) => {\n transport\n .connect({\n deviceId: discoveredDevice.id,\n onDisconnect: jest.fn(),\n })\n .then((connectedDevice) => {\n connectedDevice\n .ifRight((device) => {\n expect(device).toEqual(\n expect.objectContaining({ id: discoveredDevice.id }),\n );\n done();\n })\n .ifLeft(() => {\n done(connectedDevice);\n });\n })\n .catch((error) => {\n done(error);\n });\n },\n (error) => {\n done(error);\n },\n );\n });\n });\n\n describe(\"disconnect\", () => {\n it(\"should disconnect the device\", (done) => {\n mockedRequestDevice.mockResolvedValueOnce(stubDevice);\n\n const onDisconnect = jest.fn();\n\n discoverDevice(\n (discoveredDevice) => {\n transport\n .connect({\n deviceId: discoveredDevice.id,\n onDisconnect,\n })\n .then((connectedDevice) => {\n connectedDevice.ifRight((device) => {\n transport\n .disconnect({ connectedDevice: device })\n .then((value) => {\n expect(value).toStrictEqual(Right(void 0));\n done();\n })\n .catch((error) => {\n done(error);\n });\n });\n });\n },\n (error) => {\n done(error);\n },\n );\n });\n it(\"should call disconnect handler if device is hardware disconnected\", (done) => {\n const onDisconnect = jest.fn();\n const disconnectSpy = jest.spyOn(transport, \"disconnect\");\n mockedRequestDevice.mockResolvedValueOnce(stubDevice);\n\n discoverDevice(\n (discoveredDevice) => {\n transport\n .connect({\n deviceId: discoveredDevice.id,\n onDisconnect,\n })\n .then(() => {\n stubDevice.ongattserverdisconnected(new Event(\"\"));\n jest.advanceTimersByTime(RECONNECT_DEVICE_TIMEOUT);\n expect(disconnectSpy).toHaveBeenCalled();\n done();\n });\n },\n (error) => {\n done(error);\n },\n );\n });\n });\n\n describe(\"reconnect\", () => {\n it(\"should not call disconnection if reconnection happen\", (done) => {\n // given\n const onDisconnect = jest.fn();\n const disconnectSpy = jest.spyOn(transport, \"disconnect\");\n mockedRequestDevice.mockResolvedValueOnce(stubDevice);\n\n // when\n discoverDevice((discoveredDevice) => {\n transport\n .connect({\n deviceId: discoveredDevice.id,\n onDisconnect,\n })\n .then(() => {\n stubDevice.ongattserverdisconnected(new Event(\"\"));\n\n jest.advanceTimersByTime(RECONNECT_DEVICE_TIMEOUT / 3);\n\n // then\n expect(disconnectSpy).toHaveBeenCalledTimes(0);\n done();\n })\n .catch((error) => {\n done(error);\n });\n });\n });\n });\n });\n});\n"],
5
- "mappings": "AAAA,OAME,2BAAAA,EACA,0BAAAC,EACA,+BAAAC,EAEA,sBAAAC,MACK,kCACP,OAAS,QAAAC,EAAM,SAAAC,MAAa,YAE5B,OAAS,4BAAAC,MAAgC,yBACzC,OAAS,wBAAAC,MAA4B,4BACrC,OAAS,iCAAAC,MAAqC,oBAC9C,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KAAK,GAAG,EACvBE,EAAgB,KAAK,MAAMlB,EAAW,YAAY,EACxDQ,EAAoB,sBAAsBT,CAAU,EAEpDI,EACGM,GAAqB,CACpBT,EACG,QAAQ,CACP,SAAUS,EAAiB,GAC3B,aAAAO,CACF,CAAC,EACA,KAAK,IAAM,CACVjB,EAAW,yBAAyB,IAAI,MAAM,EAAE,CAAC,EACjD,KAAK,oBAAoBV,CAAwB,EACjD,OAAO6B,CAAa,EAAE,iBAAiB,EACvCZ,EAAK,CACP,CAAC,CACL,EACCC,GAAU,CACTD,EAAKC,CAAK,CACZ,CACF,CACF,CAAC,CACH,CAAC,EAED,SAAS,YAAa,IAAM,CAC1B,GAAG,uDAAyDD,GAAS,CAEnE,MAAMU,EAAe,KAAK,GAAG,EACvBE,EAAgB,KAAK,MAAMlB,EAAW,YAAY,EACxDQ,EAAoB,sBAAsBT,CAAU,EAGpDI,EAAgBM,GAAqB,CACnCT,EACG,QAAQ,CACP,SAAUS,EAAiB,GAC3B,aAAAO,CACF,CAAC,EACA,KAAK,IAAM,CACVjB,EAAW,yBAAyB,IAAI,MAAM,EAAE,CAAC,EAEjD,KAAK,oBAAoBV,EAA2B,CAAC,EAGrD,OAAO6B,CAAa,EAAE,sBAAsB,CAAC,EAC7CZ,EAAK,CACP,CAAC,EACA,MAAOC,GAAU,CAChBD,EAAKC,CAAK,CACZ,CAAC,CACL,CAAC,CACH,CAAC,CACH,CAAC,CACH,CAAC,CACH,CAAC",
6
- "names": ["NoAccessibleDeviceError", "OpeningConnectionError", "StaticDeviceModelDataSource", "UnknownDeviceError", "Left", "Right", "RECONNECT_DEVICE_TIMEOUT", "bleDeviceStubBuilder", "BleTransportNotSupportedError", "BleDeviceGattServerError", "WebBleTransport", "LoggerPublisherServiceStub", "subscribers", "tag", "bleDeviceModelDataSource", "logger", "stubDevice", "transport", "apduReceiverServiceFactoryStub", "apduSenderServiceFactoryStub", "discoverDevice", "onSuccess", "onError", "done", "error", "mockedRequestDevice", "discoveredDevice", "expectError", "message", "connectParams", "connect", "device", "connectedDevice", "onDisconnect", "value", "disconnectSpy"]
4
+ "sourcesContent": ["import {\n type ApduReceiverServiceFactory,\n type ApduSenderServiceFactory,\n type DeviceModel,\n type LoggerPublisherService,\n type LoggerSubscriberService,\n NoAccessibleDeviceError,\n OpeningConnectionError,\n StaticDeviceModelDataSource,\n type TransportDiscoveredDevice,\n UnknownDeviceError,\n} from \"@ledgerhq/device-management-kit\";\nimport { Left, Right } from \"purify-ts\";\n\nimport { RECONNECT_DEVICE_TIMEOUT } from \"@api/data/WebBleConfig\";\nimport { bleDeviceStubBuilder } from \"@api/model/BleDevice.stub\";\nimport { BleTransportNotSupportedError } from \"@api/model/Errors\";\nimport { BleDeviceGattServerError } from \"@api/model/Errors\";\n\nimport { WebBleTransport } from \"./WebBleTransport\";\n\nclass LoggerPublisherServiceStub implements LoggerPublisherService {\n subscribers: LoggerSubscriberService[] = [];\n tag: string;\n constructor(subscribers: LoggerSubscriberService[], tag: string) {\n this.subscribers = subscribers;\n this.tag = tag;\n }\n error = vi.fn();\n warn = vi.fn();\n info = vi.fn();\n debug = vi.fn();\n}\n\n// Our StaticDeviceModelDataSource can directly be used in our unit tests\nconst bleDeviceModelDataSource = new StaticDeviceModelDataSource();\nconst logger = new LoggerPublisherServiceStub([], \"web-ble\");\n\nconst stubDevice: BluetoothDevice = bleDeviceStubBuilder();\n\ndescribe(\"WebBleTransport\", () => {\n let transport: WebBleTransport;\n let apduReceiverServiceFactoryStub: ApduReceiverServiceFactory;\n let apduSenderServiceFactoryStub: ApduSenderServiceFactory;\n\n beforeEach(() => {\n apduReceiverServiceFactoryStub = vi.fn();\n apduSenderServiceFactoryStub = vi.fn();\n transport = new WebBleTransport(\n bleDeviceModelDataSource,\n () => logger,\n apduSenderServiceFactoryStub,\n apduReceiverServiceFactoryStub,\n );\n vi.useFakeTimers();\n });\n\n afterEach(() => {\n vi.restoreAllMocks();\n });\n\n const discoverDevice = (\n onSuccess: (discoveredDevice: TransportDiscoveredDevice) => void,\n onError?: (error: unknown) => void,\n ) => {\n transport.startDiscovering().subscribe({\n next: onSuccess,\n error: onError,\n });\n };\n\n describe(\"When Web bluetooth API is not supported\", () => {\n it(\"should not support the transport\", () => {\n expect(transport.isSupported()).toBe(false);\n });\n\n it(\"should emit a startDiscovering error\", () =>\n new Promise<void>((resolve, reject) => {\n discoverDevice(\n () => {\n reject(\"Should not emit any value\");\n },\n (error) => {\n expect(error).toBeInstanceOf(BleTransportNotSupportedError);\n resolve();\n },\n );\n }));\n });\n\n describe(\"When Web Bluetooth API is supported\", () => {\n const mockedRequestDevice = vi.fn();\n\n beforeAll(() => {\n global.navigator = {\n bluetooth: {\n requestDevice: mockedRequestDevice,\n },\n } as unknown as Navigator;\n });\n\n afterAll(() => {\n vi.restoreAllMocks();\n global.navigator = undefined as unknown as Navigator;\n });\n\n it(\"should support the transport\", () => {\n expect(transport.isSupported()).toBe(true);\n });\n\n describe(\"startDiscovering\", () => {\n it(\"should emit device if one new grant access\", () =>\n new Promise<void>((resolve, reject) => {\n mockedRequestDevice.mockResolvedValueOnce(stubDevice);\n\n discoverDevice(\n (discoveredDevice) => {\n try {\n expect(discoveredDevice).toEqual(\n expect.objectContaining({\n deviceModel: expect.objectContaining({\n id: \"nanoX\",\n productName: \"Ledger Nano X\",\n }) as DeviceModel,\n }),\n );\n\n resolve();\n } catch (expectError) {\n reject(expectError as Error);\n }\n },\n (error) => {\n reject(error as Error);\n },\n );\n }));\n\n it(\"should throw DeviceNotRecognizedError if the device is not recognized\", () =>\n new Promise<void>((resolve, reject) => {\n mockedRequestDevice.mockResolvedValueOnce({\n ...stubDevice,\n gatt: {\n ...stubDevice.gatt,\n getPrimaryServices: vi.fn(() => Promise.resolve([])),\n },\n productId: 0x4242,\n });\n\n discoverDevice(\n () => {\n reject(\"should not return a device\");\n },\n (error) => {\n expect(error).toBeInstanceOf(BleDeviceGattServerError);\n resolve();\n },\n );\n }));\n\n it(\"should emit an error if the request device is in error\", () =>\n new Promise<void>((resolve, reject) => {\n const message = \"request device error\";\n mockedRequestDevice.mockImplementationOnce(() => {\n throw new Error(message);\n });\n\n discoverDevice(\n () => {\n reject(\"should not return a device\");\n },\n (error) => {\n expect(error).toBeInstanceOf(NoAccessibleDeviceError);\n expect(error).toStrictEqual(\n new NoAccessibleDeviceError(new Error(message)),\n );\n resolve();\n },\n );\n }));\n\n it(\"should emit an error if the user did not grant us access to a device (clicking on cancel on the browser popup for ex)\", () =>\n new Promise<void>((resolve, reject) => {\n mockedRequestDevice.mockResolvedValueOnce({ forget: vi.fn() });\n\n discoverDevice(\n (discoveredDevice) => {\n reject(\n `Should not emit any value, but emitted ${JSON.stringify(\n discoveredDevice,\n )}`,\n );\n },\n (error) => {\n try {\n expect(error).toBeInstanceOf(BleDeviceGattServerError);\n resolve();\n } catch (expectError) {\n reject(expectError as Error);\n }\n },\n );\n }));\n });\n\n describe(\"connect\", () => {\n it(\"should throw UnknownDeviceError if no internal device\", async () => {\n const connectParams = {\n deviceId: \"fake\",\n onDisconnect: vi.fn(),\n };\n\n const connect = await transport.connect(connectParams);\n\n expect(connect).toStrictEqual(\n Left(new UnknownDeviceError(\"Unknown device fake\")),\n );\n });\n\n it(\"should throw OpeningConnectionError if the device is already opened\", async () => {\n const device = {\n deviceId: \"fake\",\n onDisconnect: vi.fn(),\n };\n\n const connect = await transport.connect(device);\n\n expect(connect).toStrictEqual(\n Left(new UnknownDeviceError(\"Unknown device fake\")),\n );\n });\n\n it(\"should throw OpeningConnectionError if the device cannot be opened\", () =>\n new Promise<void>((resolve, reject) => {\n const message = \"cannot be opened\";\n mockedRequestDevice.mockResolvedValueOnce({\n ...stubDevice,\n gatt: {\n connect: () => {\n throw new Error(message);\n },\n },\n });\n\n discoverDevice(\n () => {\n reject(\"Should not emit any value\");\n },\n (error) => {\n expect(error).toBeInstanceOf(OpeningConnectionError);\n resolve();\n },\n );\n }));\n\n it(\"should return the opened device\", () =>\n new Promise<void>((resolve, reject) => {\n mockedRequestDevice.mockResolvedValueOnce({\n ...stubDevice,\n gatt: {\n ...stubDevice.gatt,\n connected: true,\n },\n });\n\n discoverDevice(\n (discoveredDevice) => {\n transport\n .connect({\n deviceId: discoveredDevice.id,\n onDisconnect: vi.fn(),\n })\n .then((connectedDevice) => {\n connectedDevice\n .ifRight((device) => {\n expect(device).toEqual(\n expect.objectContaining({ id: discoveredDevice.id }),\n );\n resolve();\n })\n .ifLeft(() => {\n reject(connectedDevice);\n });\n })\n .catch((error) => {\n reject(error);\n });\n },\n (error) => {\n reject(error as Error);\n },\n );\n }));\n\n it(\"should return a device if available\", () =>\n new Promise<void>((resolve, reject) => {\n mockedRequestDevice.mockResolvedValueOnce(stubDevice);\n\n discoverDevice(\n (discoveredDevice) => {\n transport\n .connect({\n deviceId: discoveredDevice.id,\n onDisconnect: vi.fn(),\n })\n .then((connectedDevice) => {\n connectedDevice\n .ifRight((device) => {\n expect(device).toEqual(\n expect.objectContaining({ id: discoveredDevice.id }),\n );\n resolve();\n })\n .ifLeft(() => {\n reject(connectedDevice);\n });\n })\n .catch((error) => {\n reject(error);\n });\n },\n (error) => {\n reject(error as Error);\n },\n );\n }));\n });\n\n describe(\"disconnect\", () => {\n it(\"should disconnect the device\", () =>\n new Promise<void>((resolve, reject) => {\n mockedRequestDevice.mockResolvedValueOnce(stubDevice);\n\n const onDisconnect = vi.fn();\n\n discoverDevice(\n (discoveredDevice) => {\n transport\n .connect({\n deviceId: discoveredDevice.id,\n onDisconnect,\n })\n .then((connectedDevice) => {\n connectedDevice.ifRight((device) => {\n transport\n .disconnect({ connectedDevice: device })\n .then((value) => {\n expect(value).toStrictEqual(Right(void 0));\n resolve();\n })\n .catch((error) => {\n reject(error);\n });\n });\n });\n },\n (error) => {\n reject(error as Error);\n },\n );\n }));\n\n it(\"should call disconnect handler if device is hardware disconnected\", () =>\n new Promise<void>((resolve, reject) => {\n const onDisconnect = vi.fn();\n const disconnectSpy = vi.spyOn(transport, \"disconnect\");\n mockedRequestDevice.mockResolvedValueOnce(stubDevice);\n\n discoverDevice(\n (discoveredDevice) => {\n transport\n .connect({\n deviceId: discoveredDevice.id,\n onDisconnect,\n })\n .then(() => {\n stubDevice.ongattserverdisconnected(new Event(\"\"));\n vi.advanceTimersByTime(RECONNECT_DEVICE_TIMEOUT);\n expect(disconnectSpy).toHaveBeenCalled();\n resolve();\n });\n },\n (error) => {\n reject(error as Error);\n },\n );\n }));\n });\n\n describe(\"reconnect\", () => {\n it(\"should not call disconnection if reconnection happen\", () =>\n new Promise<void>((resolve, reject) => {\n // given\n const onDisconnect = vi.fn();\n const disconnectSpy = vi.spyOn(transport, \"disconnect\");\n mockedRequestDevice.mockResolvedValueOnce(stubDevice);\n\n // when\n discoverDevice((discoveredDevice) => {\n transport\n .connect({\n deviceId: discoveredDevice.id,\n onDisconnect,\n })\n .then(() => {\n stubDevice.ongattserverdisconnected(new Event(\"\"));\n\n vi.advanceTimersByTime(RECONNECT_DEVICE_TIMEOUT / 3);\n\n // then\n expect(disconnectSpy).toHaveBeenCalledTimes(0);\n resolve();\n })\n .catch((error) => {\n reject(error);\n });\n });\n }));\n });\n });\n});\n"],
5
+ "mappings": "AAAA,OAME,2BAAAA,EACA,0BAAAC,EACA,+BAAAC,EAEA,sBAAAC,MACK,kCACP,OAAS,QAAAC,EAAM,SAAAC,MAAa,YAE5B,OAAS,4BAAAC,MAAgC,yBACzC,OAAS,wBAAAC,MAA4B,4BACrC,OAAS,iCAAAC,MAAqC,oBAC9C,OAAS,4BAAAC,MAAgC,oBAEzC,OAAS,mBAAAC,MAAuB,oBAEhC,MAAMC,CAA6D,CACjE,YAAyC,CAAC,EAC1C,IACA,YAAYC,EAAwCC,EAAa,CAC/D,KAAK,YAAcD,EACnB,KAAK,IAAMC,CACb,CACA,MAAQ,GAAG,GAAG,EACd,KAAO,GAAG,GAAG,EACb,KAAO,GAAG,GAAG,EACb,MAAQ,GAAG,GAAG,CAChB,CAGA,MAAMC,EAA2B,IAAIZ,EAC/Ba,EAAS,IAAIJ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,oEAAqE,IACtE,IAAI,QAAc,CAACF,EAASC,IAAW,CACrC,MAAMU,EAAe,GAAG,GAAG,EACrBE,EAAgB,GAAG,MAAMnB,EAAW,YAAY,EACtDS,EAAoB,sBAAsBV,CAAU,EAEpDI,EACGO,GAAqB,CACpBV,EACG,QAAQ,CACP,SAAUU,EAAiB,GAC3B,aAAAO,CACF,CAAC,EACA,KAAK,IAAM,CACVlB,EAAW,yBAAyB,IAAI,MAAM,EAAE,CAAC,EACjD,GAAG,oBAAoBV,CAAwB,EAC/C,OAAO8B,CAAa,EAAE,iBAAiB,EACvCb,EAAQ,CACV,CAAC,CACL,EACCE,GAAU,CACTD,EAAOC,CAAc,CACvB,CACF,CACF,CAAC,CAAC,CACN,CAAC,EAED,SAAS,YAAa,IAAM,CAC1B,GAAG,uDAAwD,IACzD,IAAI,QAAc,CAACF,EAASC,IAAW,CAErC,MAAMU,EAAe,GAAG,GAAG,EACrBE,EAAgB,GAAG,MAAMnB,EAAW,YAAY,EACtDS,EAAoB,sBAAsBV,CAAU,EAGpDI,EAAgBO,GAAqB,CACnCV,EACG,QAAQ,CACP,SAAUU,EAAiB,GAC3B,aAAAO,CACF,CAAC,EACA,KAAK,IAAM,CACVlB,EAAW,yBAAyB,IAAI,MAAM,EAAE,CAAC,EAEjD,GAAG,oBAAoBV,EAA2B,CAAC,EAGnD,OAAO8B,CAAa,EAAE,sBAAsB,CAAC,EAC7Cb,EAAQ,CACV,CAAC,EACA,MAAOE,GAAU,CAChBD,EAAOC,CAAK,CACd,CAAC,CACL,CAAC,CACH,CAAC,CAAC,CACN,CAAC,CACH,CAAC,CACH,CAAC",
6
+ "names": ["NoAccessibleDeviceError", "OpeningConnectionError", "StaticDeviceModelDataSource", "UnknownDeviceError", "Left", "Right", "RECONNECT_DEVICE_TIMEOUT", "bleDeviceStubBuilder", "BleTransportNotSupportedError", "BleDeviceGattServerError", "WebBleTransport", "LoggerPublisherServiceStub", "subscribers", "tag", "bleDeviceModelDataSource", "logger", "stubDevice", "transport", "apduReceiverServiceFactoryStub", "apduSenderServiceFactoryStub", "discoverDevice", "onSuccess", "onError", "resolve", "reject", "error", "mockedRequestDevice", "discoveredDevice", "expectError", "message", "connectParams", "connect", "device", "connectedDevice", "onDisconnect", "value", "disconnectSpy"]
7
7
  }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ledgerhq/device-transport-kit-web-ble",
3
- "version": "0.0.1",
3
+ "version": "1.1.0",
4
4
  "license": "Apache-2.0",
5
5
  "private": false,
6
6
  "exports": {
@@ -25,9 +25,9 @@
25
25
  "prettier": "prettier . --check",
26
26
  "prettier:fix": "prettier . --write",
27
27
  "typecheck": "tsc --noEmit",
28
- "test": "jest --passWithNoTests",
29
- "test:watch": "pnpm test -- --watch",
30
- "test:coverage": "pnpm test -- --coverage"
28
+ "test": "vitest run",
29
+ "test:watch": "vitest",
30
+ "test:coverage": "vitest run --coverage"
31
31
  },
32
32
  "dependencies": {
33
33
  "@sentry/minimal": "^6.19.7",
@@ -38,16 +38,16 @@
38
38
  "@ledgerhq/device-management-kit": "workspace:*",
39
39
  "@ledgerhq/esbuild-tools": "workspace:*",
40
40
  "@ledgerhq/eslint-config-dsdk": "workspace:*",
41
- "@ledgerhq/jest-config-dsdk": "workspace:*",
42
41
  "@ledgerhq/prettier-config-dsdk": "workspace:*",
43
42
  "@ledgerhq/tsconfig-dsdk": "workspace:*",
43
+ "@ledgerhq/vitest-config-dmk": "workspace:*",
44
44
  "@types/uuid": "^10.0.0",
45
45
  "@types/web-bluetooth": "^0.0.20",
46
- "rxjs": "^7.8.1",
46
+ "rxjs": "^7.8.2",
47
47
  "ts-node": "^10.9.2"
48
48
  },
49
49
  "peerDependencies": {
50
- "@ledgerhq/device-management-kit": "workspace:*",
51
- "rxjs": "^7.8.1"
50
+ "@ledgerhq/device-management-kit": "0.6.2",
51
+ "rxjs": "^7.8.2"
52
52
  }
53
53
  }
@@ -22,7 +22,7 @@ export declare class WebBleTransport implements Transport {
22
22
  private getBluetoothApi;
23
23
  isSupported(): boolean;
24
24
  getIdentifier(): TransportIdentifier;
25
- listenToKnownDevices(): Observable<TransportDiscoveredDevice[]>;
25
+ listenToAvailableDevices(): Observable<TransportDiscoveredDevice[]>;
26
26
  /**
27
27
  * Get Bluetooth GATT Primary service that is used to get writeCharacteristic and notifyCharacteristic
28
28
  * @param bleDevice
@@ -1 +1 @@
1
- {"version":3,"file":"WebBleTransport.d.ts","sourceRoot":"","sources":["../../../../src/api/transport/WebBleTransport.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,0BAA0B,EAC/B,KAAK,wBAAwB,EAE7B,KAAK,YAAY,EAGjB,KAAK,QAAQ,EACb,KAAK,qBAAqB,EAE1B,KAAK,iBAAiB,EACtB,KAAK,QAAQ,EACb,KAAK,sBAAsB,EAG3B,KAAK,SAAS,EACd,wBAAwB,EACxB,KAAK,yBAAyB,EAC9B,KAAK,gBAAgB,EACrB,KAAK,mBAAmB,EAEzB,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,KAAK,MAAM,EAAmC,MAAM,WAAW,CAAC;AACzE,OAAO,EAAQ,KAAK,UAAU,EAAoB,MAAM,MAAM,CAAC;AAuB/D,eAAO,MAAM,gBAAgB,EAAE,mBAA+B,CAAC;AAE/D,qBAAa,eAAgB,YAAW,SAAS;IAU7C,OAAO,CAAC,QAAQ,CAAC,sBAAsB;IACvC,OAAO,CAAC,QAAQ,CAAC,qBAAqB;IAGtC,OAAO,CAAC,QAAQ,CAAC,kBAAkB;IACnC,OAAO,CAAC,QAAQ,CAAC,oBAAoB;IAdvC,OAAO,CAAC,QAAQ,CAAC,iBAAiB,CAAyB;IAC3D,OAAO,CAAC,QAAQ,CAAC,oBAAoB,CAAsC;IAC3E,OAAO,CAAC,qBAAqB,CAAqC;IAClE,OAAO,CAAC,0BAA0B,CAA4B;IAC9D,OAAO,CAAC,OAAO,CAAyB;IACxC,OAAO,CAAC,QAAQ,CAAC,cAAc,CAAyB;IACxD,OAAO,C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