@ledgerhq/device-transport-kit-react-native-hid 0.0.0-rn-ble-pairing-removed-while-reconnecting-20250807094338 → 0.0.0-rn-hid-issues-20251022142715

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.
Files changed (32) hide show
  1. package/android/src/main/kotlin/com/ledger/androidtransporthid/TransportHidModule.kt +41 -14
  2. package/android/src/main/kotlin/com/ledger/devicesdk/shared/androidMain/transport/usb/DefaultAndroidUsbTransport.kt +58 -25
  3. package/android/src/main/kotlin/com/ledger/devicesdk/shared/androidMain/transport/usb/connection/AndroidUsbApduSender.kt +33 -34
  4. package/android/src/main/kotlin/com/ledger/devicesdk/shared/androidMainInternal/transport/deviceconnection/DeviceConnectionStateMachine.kt +100 -31
  5. package/android/src/test/kotlin/com/ledger/devicesdk/shared/androidMainInternal/transport/deviceconnection/DeviceConnectionStateMachineTest.kt +142 -15
  6. package/lib/cjs/api/bridge/mapper.js +1 -1
  7. package/lib/cjs/api/bridge/mapper.js.map +2 -2
  8. package/lib/cjs/api/bridge/mapper.test.js +1 -1
  9. package/lib/cjs/api/bridge/mapper.test.js.map +2 -2
  10. package/lib/cjs/api/transport/Errors.js +1 -1
  11. package/lib/cjs/api/transport/Errors.js.map +3 -3
  12. package/lib/cjs/api/transport/RNHidTransport.js +1 -1
  13. package/lib/cjs/api/transport/RNHidTransport.js.map +2 -2
  14. package/lib/cjs/api/transport/RNHidTransport.test.js +1 -1
  15. package/lib/cjs/api/transport/RNHidTransport.test.js.map +2 -2
  16. package/lib/cjs/package.json +1 -1
  17. package/lib/esm/api/bridge/mapper.js +1 -1
  18. package/lib/esm/api/bridge/mapper.js.map +3 -3
  19. package/lib/esm/api/bridge/mapper.test.js +1 -1
  20. package/lib/esm/api/bridge/mapper.test.js.map +3 -3
  21. package/lib/esm/api/transport/Errors.js +1 -1
  22. package/lib/esm/api/transport/Errors.js.map +3 -3
  23. package/lib/esm/api/transport/RNHidTransport.js +1 -1
  24. package/lib/esm/api/transport/RNHidTransport.js.map +3 -3
  25. package/lib/esm/api/transport/RNHidTransport.test.js +1 -1
  26. package/lib/esm/api/transport/RNHidTransport.test.js.map +3 -3
  27. package/lib/esm/package.json +1 -1
  28. package/lib/types/api/bridge/mapper.d.ts.map +1 -1
  29. package/lib/types/api/transport/Errors.d.ts +1 -1
  30. package/lib/types/api/transport/Errors.d.ts.map +1 -1
  31. package/lib/types/tsconfig.prod.tsbuildinfo +1 -1
  32. package/package.json +5 -5
@@ -2,6 +2,7 @@ package com.ledger.devicesdk.shared.androidMainInternal.transport.deviceconnecti
2
2
 
3
3
  import com.ledger.devicesdk.shared.api.apdu.SendApduFailureReason
4
4
  import com.ledger.devicesdk.shared.api.apdu.SendApduResult
5
+ import com.ledger.devicesdk.shared.api.utils.fromHexStringToBytesOrThrow
5
6
  import com.ledger.devicesdk.shared.internal.service.logger.LogInfo
6
7
  import com.ledger.devicesdk.shared.internal.service.logger.LoggerService
7
8
  import kotlinx.coroutines.ExperimentalCoroutinesApi
@@ -12,6 +13,7 @@ import kotlin.time.Duration
12
13
  import kotlin.time.Duration.Companion.seconds
13
14
  import kotlin.test.Test
14
15
  import org.junit.Assert.*
16
+ import kotlin.test.assertIs
15
17
  import kotlin.time.Duration.Companion.milliseconds
16
18
 
17
19
  @OptIn(ExperimentalCoroutinesApi::class)
@@ -88,7 +90,7 @@ class DeviceConnectionStateMachineTest {
88
90
  stateMachine.handleApduResult(mockedFailureResult)
89
91
 
90
92
  // Then
91
- assertEquals(sendApduResult, mockedFailureResult)
93
+ assertEquals(mockedFailureResult, sendApduResult)
92
94
  assertTrue(terminated)
93
95
  assertNull(error)
94
96
  }
@@ -134,14 +136,13 @@ class DeviceConnectionStateMachineTest {
134
136
  }
135
137
 
136
138
  @Test
137
- fun `GIVEN the device connection state machine WHEN an APDU with triggersDisconnection is sent THEN the machine moves to WaitingForReconnection and recovers when device reconnects`() =
139
+ fun `GIVEN the device connection state machine WHEN an APDU with triggersDisconnection is sent and triggers a disconnection THEN the machine moves to WaitingForReconnection and recovers when device reconnects`() =
138
140
  runTest {
139
141
  var sendApduCalled: ByteArray? = null
140
142
  var sendApduResult: SendApduResult? = null
141
143
  var terminated = false
142
144
  var error: Throwable? = null
143
145
 
144
- val dispatcher = StandardTestDispatcher(testScheduler)
145
146
  val stateMachine = DeviceConnectionStateMachine(
146
147
  sendApduFn = { apdu, _ -> sendApduCalled = apdu },
147
148
  onTerminated = { terminated = true },
@@ -167,6 +168,10 @@ class DeviceConnectionStateMachineTest {
167
168
  val mockedSuccessApduResult = SendApduResult.Success(mockedResultApduSuccessA)
168
169
  stateMachine.handleApduResult(mockedSuccessApduResult)
169
170
 
171
+ assertNull(sendApduResult)
172
+ // Simulate a disconnection
173
+ stateMachine.handleDeviceDisconnected()
174
+
170
175
  // Result should have been returned
171
176
  assertEquals(mockedSuccessApduResult, sendApduResult)
172
177
 
@@ -203,7 +208,118 @@ class DeviceConnectionStateMachineTest {
203
208
  }
204
209
 
205
210
  @Test
206
- fun `GIVEN the device connection state machine WHEN an APDU with triggersDisconnection is sent THEN the machine moves to WaitingForReconnection and the next APDU is queued until reconnection`() =
211
+ fun `GIVEN the device connection state machine WHEN an APDU with triggersDisconnection is sent and device does not disconnect THEN the machine moves to Connected`() =
212
+ runTest {
213
+ var sendApduCalled: ByteArray? = null
214
+ var sendApduResult: SendApduResult? = null
215
+ var terminated = false
216
+ var error: Throwable? = null
217
+
218
+ val stateMachine = DeviceConnectionStateMachine(
219
+ sendApduFn = { apdu, _ -> sendApduCalled = apdu },
220
+ onTerminated = { terminated = true },
221
+ isFatalSendApduFailure = { false },
222
+ reconnectionTimeoutDuration = reconnectionTimeout,
223
+ onError = { error = it },
224
+ loggerService = FakeLoggerService(),
225
+ coroutineDispatcher = StandardTestDispatcher(testScheduler)
226
+ )
227
+
228
+ // Request sending an APDU (with triggersDisconnection = true)
229
+ stateMachine.requestSendApdu(DeviceConnectionStateMachine.SendApduRequestContent(
230
+ apdu = mockedRequestApduA,
231
+ triggersDisconnection = true,
232
+ resultCallback = { result -> sendApduResult = result },
233
+ abortTimeoutDuration = Duration.INFINITE
234
+ ))
235
+
236
+ // Send APDU should have been called
237
+ assertArrayEquals(mockedRequestApduA, sendApduCalled)
238
+
239
+ // Simulate a successful response
240
+ val mockedSuccessApduResult = SendApduResult.Success(mockedResultApduSuccessA)
241
+ stateMachine.handleApduResult(mockedSuccessApduResult)
242
+
243
+ assertNull(sendApduResult)
244
+
245
+ // Simulate Response from GetAppAndVersion
246
+ val mockedSuccessApduResultGetAppAndVersion = SendApduResult.Success(mockedGetAppAndVersionSuccessfulResponse)
247
+ stateMachine.handleApduResult(mockedSuccessApduResultGetAppAndVersion)
248
+
249
+ // Should be in Connected state
250
+ assertEquals(
251
+ DeviceConnectionStateMachine.State.Connected,
252
+ stateMachine.getState()
253
+ )
254
+
255
+ // Response should have been returned
256
+ assertEquals(mockedSuccessApduResult, sendApduResult)
257
+ }
258
+
259
+ @Test
260
+ fun `GIVEN the device connection state machine WHEN an APDU with triggersDisconnection is sent and device does not disconnect but is first busy THEN the machine retries and moves to Connected`() =
261
+ runTest {
262
+ var sendApduCalled: ByteArray? = null
263
+ var sendApduResult: SendApduResult? = null
264
+ var terminated = false
265
+ var error: Throwable? = null
266
+
267
+ val stateMachine = DeviceConnectionStateMachine(
268
+ sendApduFn = { apdu, _ -> sendApduCalled = apdu },
269
+ onTerminated = { terminated = true },
270
+ isFatalSendApduFailure = { false },
271
+ reconnectionTimeoutDuration = reconnectionTimeout,
272
+ onError = { error = it },
273
+ loggerService = FakeLoggerService(),
274
+ coroutineDispatcher = StandardTestDispatcher(testScheduler)
275
+ )
276
+
277
+ // Request sending an APDU (with triggersDisconnection = true)
278
+ stateMachine.requestSendApdu(DeviceConnectionStateMachine.SendApduRequestContent(
279
+ apdu = mockedRequestApduA,
280
+ triggersDisconnection = true,
281
+ resultCallback = { result -> sendApduResult = result },
282
+ abortTimeoutDuration = Duration.INFINITE
283
+ ))
284
+
285
+ // Send APDU should have been called
286
+ assertArrayEquals(mockedRequestApduA, sendApduCalled)
287
+
288
+ // Simulate a successful response
289
+ val mockedSuccessApduResult = SendApduResult.Success(mockedResultApduSuccessA)
290
+ stateMachine.handleApduResult(mockedSuccessApduResult)
291
+
292
+ assertNull(sendApduResult)
293
+
294
+ assertIs<DeviceConnectionStateMachine.State.WaitingForDisconnection>(
295
+ stateMachine.getState()
296
+ )
297
+
298
+ // Simulate Busy Response from GetAppAndVersion
299
+ val mockedBusyApduResultGetAppAndVersion = SendApduResult.Success(mockedGetAppAndVersionBusyResponse)
300
+ stateMachine.handleApduResult(mockedBusyApduResultGetAppAndVersion)
301
+
302
+ assertIs<DeviceConnectionStateMachine.State.WaitingForDisconnection>(
303
+ stateMachine.getState()
304
+ )
305
+
306
+ // Simulate Successful Response from GetAppAndVersion
307
+ val mockedSuccessApduResultGetAppAndVersion = SendApduResult.Success(mockedGetAppAndVersionSuccessfulResponse)
308
+ stateMachine.handleApduResult(mockedSuccessApduResultGetAppAndVersion)
309
+
310
+ // Should be in Connected state
311
+ assertEquals(
312
+ DeviceConnectionStateMachine.State.Connected,
313
+ stateMachine.getState()
314
+ )
315
+
316
+ // Response should have been returned
317
+ assertEquals(mockedSuccessApduResult, sendApduResult)
318
+ }
319
+
320
+
321
+ @Test
322
+ fun `GIVEN the device connection state machine WHEN an APDU with triggersDisconnection is sent and triggers a disconnection THEN the machine moves to WaitingForReconnection and the next APDU is queued until reconnection`() =
207
323
  runTest {
208
324
  val sendApduCalled: MutableList<ByteArray> = mutableListOf()
209
325
  var terminated = false
@@ -231,10 +347,19 @@ class DeviceConnectionStateMachineTest {
231
347
  val mockedSuccessApduResult = SendApduResult.Success(mockedResultApduSuccessA)
232
348
  stateMachine.handleApduResult(mockedSuccessApduResult)
233
349
 
234
- // sendApduFn should have been called once
235
- assertEquals(1, sendApduCalled.size)
350
+ // sendApduFn should have been called twice (for the mockedRequestApduA and an extra call for the getAppAndVersion APDU)
351
+ assertEquals(2, sendApduCalled.size)
352
+
353
+ // Should be in WaitingForDisconnection state
354
+ assertIs<DeviceConnectionStateMachine.State.WaitingForDisconnection>(
355
+ stateMachine.getState()
356
+ )
357
+
358
+ // Simulate disconnection
359
+ stateMachine.handleDeviceDisconnected()
360
+
361
+ // Should be in WaitingForReconnection state
236
362
 
237
- // Should be in waiting state
238
363
  assertEquals(
239
364
  DeviceConnectionStateMachine.State.WaitingForReconnection,
240
365
  stateMachine.getState()
@@ -256,7 +381,7 @@ class DeviceConnectionStateMachineTest {
256
381
  )
257
382
 
258
383
  // sendApduFn should not have been called one more time
259
- assertEquals(1, sendApduCalled.size)
384
+ assertEquals(2, sendApduCalled.size)
260
385
 
261
386
  // Simulate reconnection
262
387
  stateMachine.handleDeviceConnected()
@@ -267,9 +392,9 @@ class DeviceConnectionStateMachineTest {
267
392
  stateMachine.getState()::class
268
393
  )
269
394
 
270
- // Send APDU should have been called a second time, and the result should have been returned
271
- assertEquals(2, sendApduCalled.size)
272
- assertArrayEquals(mockedRequestApduB, sendApduCalled[1])
395
+ // Send APDU should have been called a 3rd time, and the result should have been returned
396
+ assertEquals(3, sendApduCalled.size)
397
+ assertArrayEquals(mockedRequestApduB, sendApduCalled[2])
273
398
 
274
399
  // Simulate a successful response
275
400
  val mockedSuccessApduResultB = SendApduResult.Success(mockedResultApduSuccessB)
@@ -721,9 +846,11 @@ class DeviceConnectionStateMachineTest {
721
846
  }
722
847
 
723
848
  val reconnectionTimeout: Duration = 5.seconds
724
- val mockedRequestApduA: ByteArray = byteArrayOf(0x01, 0x02)
725
- val mockedRequestApduB: ByteArray = byteArrayOf(0x03, 0x04)
726
- val mockedResultApduSuccessA: ByteArray = byteArrayOf(0x05, 0x06, 0x90.toByte(), 0x00)
727
- val mockedResultApduSuccessB: ByteArray = byteArrayOf(0x07, 0x08, 0x90.toByte(), 0x00)
849
+ val mockedRequestApduA: ByteArray = "1234".fromHexStringToBytesOrThrow()
850
+ val mockedRequestApduB: ByteArray = "5678".fromHexStringToBytesOrThrow()
851
+ val mockedGetAppAndVersionSuccessfulResponse: ByteArray = "12349000".fromHexStringToBytesOrThrow()
852
+ val mockedGetAppAndVersionBusyResponse: ByteArray = "12346601".fromHexStringToBytesOrThrow()
853
+ val mockedResultApduSuccessA: ByteArray = "56789000".fromHexStringToBytesOrThrow()
854
+ val mockedResultApduSuccessB: ByteArray = "abcd9000".fromHexStringToBytesOrThrow()
728
855
  }
729
856
  }
@@ -1,2 +1,2 @@
1
- "use strict";var a=Object.defineProperty;var v=Object.getOwnPropertyDescriptor;var l=Object.getOwnPropertyNames;var m=Object.prototype.hasOwnProperty;var D=(e,t)=>{for(var o in t)a(e,o,{get:t[o],enumerable:!0})},f=(e,t,o,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of l(t))!m.call(e,i)&&i!==o&&a(e,i,{get:()=>t[i],enumerable:!(s=v(t,i))||s.enumerable});return e};var y=e=>f(a({},"__esModule",{value:!0}),e);var b={};D(b,{mapNativeConnectionResultToConnectionResult:()=>R,mapNativeDeviceConnectionLostToDeviceDisconnected:()=>T,mapNativeDiscoveryDeviceToTransportDiscoveredDevice:()=>N,mapNativeLedgerDeviceToDeviceModel:()=>c,mapNativeSendApduResultToSendApduResult:()=>L,mapNativeTransportLogToLog:()=>g});module.exports=y(b);var r=require("@ledgerhq/device-management-kit"),n=require("purify-ts"),d=require("../helpers/base64Utils"),p=require("../transport/Errors"),u=require("../transport/rnHidTransportIdentifier");function c(e,t){return t.filterDeviceModels({usbProductId:Number.parseInt(e.usbProductIdMask,16)})[0]??null}function N(e,t){const o=c(e.ledgerDevice,t);return o==null?null:{id:e.uid,deviceModel:o,transport:u.TRANSPORT_IDENTIFIER,name:e.name}}function g(e){let t;switch(e.level){case"error":t=r.LogLevel.Error;break;case"warning":t=r.LogLevel.Warning;break;case"info":t=r.LogLevel.Info;break;case"debug":t=r.LogLevel.Debug;break;default:I(e.level),t=r.LogLevel.Info;break}return[t,e.message,{tag:e.tag,data:e.jsonPayload,timestamp:Number.parseInt(e.timestamp,10)}]}function I(e){throw new Error("Unexpected object: "+e)}function R(e,t){if(e.success){const o=c(e.ledgerDevice,t);return o?(0,n.Right)({sessionId:e.sessionId,transportDeviceModel:o}):(0,n.Left)(new r.OpeningConnectionError(`Could not find device model for the connected device with usbProductIdMask: ${e.ledgerDevice.usbProductIdMask}`))}else return(0,n.Left)(new r.OpeningConnectionError(e.error))}function L(e){if(e.success){const t=(0,d.base64ToUint8Array)(e.apdu),o=r.FramerUtils.getFirstBytesFrom(t,t.length-2),s=r.FramerUtils.getLastBytesFrom(t,2);return(0,n.Right)(new r.ApduResponse({data:o,statusCode:s}))}else return e.error==="SendApduTimeout"?(0,n.Left)(new r.SendApduTimeoutError("Abort timeout")):e.error==="EmptyResponse"?(0,n.Left)(new r.SendApduEmptyResponseError("Empty response")):(0,n.Left)(new p.SendApduError(e.error))}function T(e){return{sessionId:e.id}}0&&(module.exports={mapNativeConnectionResultToConnectionResult,mapNativeDeviceConnectionLostToDeviceDisconnected,mapNativeDiscoveryDeviceToTransportDiscoveredDevice,mapNativeLedgerDeviceToDeviceModel,mapNativeSendApduResultToSendApduResult,mapNativeTransportLogToLog});
1
+ "use strict";var c=Object.defineProperty;var v=Object.getOwnPropertyDescriptor;var l=Object.getOwnPropertyNames;var D=Object.prototype.hasOwnProperty;var m=(e,t)=>{for(var r in t)c(e,r,{get:t[r],enumerable:!0})},f=(e,t,r,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of l(t))!D.call(e,i)&&i!==r&&c(e,i,{get:()=>t[i],enumerable:!(s=v(t,i))||s.enumerable});return e};var y=e=>f(c({},"__esModule",{value:!0}),e);var b={};m(b,{mapNativeConnectionResultToConnectionResult:()=>R,mapNativeDeviceConnectionLostToDeviceDisconnected:()=>L,mapNativeDiscoveryDeviceToTransportDiscoveredDevice:()=>N,mapNativeLedgerDeviceToDeviceModel:()=>a,mapNativeSendApduResultToSendApduResult:()=>T,mapNativeTransportLogToLog:()=>g});module.exports=y(b);var n=require("@ledgerhq/device-management-kit"),o=require("purify-ts"),d=require("../helpers/base64Utils"),p=require("../transport/Errors"),u=require("../transport/rnHidTransportIdentifier");function a(e,t){return t.filterDeviceModels({usbProductId:Number.parseInt(e.usbProductIdMask,16)})[0]??null}function N(e,t){const r=a(e.ledgerDevice,t);return r==null?null:{id:e.uid,deviceModel:r,transport:u.TRANSPORT_IDENTIFIER,name:e.name}}function g(e){let t;switch(e.level){case"error":t=n.LogLevel.Error;break;case"warning":t=n.LogLevel.Warning;break;case"info":t=n.LogLevel.Info;break;case"debug":t=n.LogLevel.Debug;break;default:I(e.level),t=n.LogLevel.Info;break}return[t,e.message,{tag:e.tag,data:e.jsonPayload,timestamp:Number.parseInt(e.timestamp,10)}]}function I(e){throw new Error("Unexpected object: "+e)}function R(e,t){if(e.success){const r=a(e.ledgerDevice,t);return r?(0,o.Right)({sessionId:e.sessionId,transportDeviceModel:r}):(0,o.Left)(new n.OpeningConnectionError(`Could not find device model for the connected device with usbProductIdMask: ${e.ledgerDevice.usbProductIdMask}`))}else return(0,o.Left)(new n.OpeningConnectionError(e.error))}function T(e){if(e.success){const t=(0,d.base64ToUint8Array)(e.apdu),r=n.FramerUtils.getFirstBytesFrom(t,t.length-2),s=n.FramerUtils.getLastBytesFrom(t,2);return(0,o.Right)(new n.ApduResponse({data:r,statusCode:s}))}else return e.error==="SendApduTimeout"?(0,o.Left)(new n.SendApduTimeoutError("Abort timeout")):e.error==="EmptyResponse"?(0,o.Left)(new n.SendApduEmptyResponseError("Empty response")):e.error==="DeviceDisconnected"?(0,o.Left)(new n.DeviceDisconnectedWhileSendingError("Device disconnected")):(0,o.Left)(new p.HidTransportSendApduUnknownError(e.error))}function L(e){return{sessionId:e.id}}0&&(module.exports={mapNativeConnectionResultToConnectionResult,mapNativeDeviceConnectionLostToDeviceDisconnected,mapNativeDiscoveryDeviceToTransportDiscoveredDevice,mapNativeLedgerDeviceToDeviceModel,mapNativeSendApduResultToSendApduResult,mapNativeTransportLogToLog});
2
2
  //# sourceMappingURL=mapper.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/api/bridge/mapper.ts"],
4
- "sourcesContent": ["import {\n ApduResponse,\n type DeviceModelDataSource,\n FramerUtils,\n LogLevel,\n type LogParams,\n OpeningConnectionError,\n SendApduEmptyResponseError,\n type SendApduResult,\n SendApduTimeoutError,\n type TransportDeviceModel,\n type TransportDiscoveredDevice,\n} from \"@ledgerhq/device-management-kit\";\nimport { Left, Right } from \"purify-ts\";\n\nimport { base64ToUint8Array } from \"@api/helpers/base64Utils\";\nimport { SendApduError } from \"@api/transport/Errors\";\nimport { TRANSPORT_IDENTIFIER } from \"@api/transport/rnHidTransportIdentifier\";\nimport {\n type InternalConnectionResult,\n type InternalDeviceDisconnected,\n} from \"@api/transport/types\";\n\nimport {\n type NativeDeviceConnectionLost,\n type NativeDiscoveryDevice,\n type NativeInternalConnectionResult,\n type NativeLedgerDevice,\n type NativeLog,\n type NativeSendApduResult,\n} from \"./types\";\n\nexport function mapNativeLedgerDeviceToDeviceModel(\n nativeLedgerDevice: NativeLedgerDevice,\n deviceModelDataSource: DeviceModelDataSource,\n): TransportDeviceModel | null {\n return (\n deviceModelDataSource.filterDeviceModels({\n usbProductId: Number.parseInt(nativeLedgerDevice.usbProductIdMask, 16),\n })[0] ?? null\n );\n}\n\nexport function mapNativeDiscoveryDeviceToTransportDiscoveredDevice(\n nativeDevice: NativeDiscoveryDevice,\n deviceModelDataSource: DeviceModelDataSource,\n): TransportDiscoveredDevice | null {\n const deviceModel = mapNativeLedgerDeviceToDeviceModel(\n nativeDevice.ledgerDevice,\n deviceModelDataSource,\n );\n if (deviceModel == null) return null;\n\n return {\n id: nativeDevice.uid,\n deviceModel,\n transport: TRANSPORT_IDENTIFIER,\n name: nativeDevice.name,\n };\n}\n\nexport function mapNativeTransportLogToLog(log: NativeLog): LogParams {\n let level: LogLevel;\n switch (log.level) {\n case \"error\":\n level = LogLevel.Error;\n break;\n case \"warning\":\n level = LogLevel.Warning;\n break;\n case \"info\":\n level = LogLevel.Info;\n break;\n case \"debug\":\n level = LogLevel.Debug;\n break;\n default:\n assertNever(log.level);\n level = LogLevel.Info;\n break;\n }\n\n return [\n level,\n log.message,\n {\n tag: log.tag,\n data: log.jsonPayload,\n timestamp: Number.parseInt(log.timestamp, 10),\n },\n ];\n}\n\nfunction assertNever(x: never) {\n throw new Error(\"Unexpected object: \" + x);\n}\n\nexport function mapNativeConnectionResultToConnectionResult(\n result: NativeInternalConnectionResult,\n deviceModelDataSource: DeviceModelDataSource,\n): InternalConnectionResult {\n if (result.success) {\n const transportDeviceModel = mapNativeLedgerDeviceToDeviceModel(\n result.ledgerDevice,\n deviceModelDataSource,\n );\n if (!transportDeviceModel)\n return Left(\n new OpeningConnectionError(\n `Could not find device model for the connected device with usbProductIdMask: ${result.ledgerDevice.usbProductIdMask}`,\n ),\n );\n return Right({ sessionId: result.sessionId, transportDeviceModel });\n } else {\n return Left(new OpeningConnectionError(result.error));\n }\n}\n\nexport function mapNativeSendApduResultToSendApduResult(\n result: NativeSendApduResult,\n): SendApduResult {\n if (result.success) {\n const responseBytes = base64ToUint8Array(result.apdu);\n const data = FramerUtils.getFirstBytesFrom(\n responseBytes,\n responseBytes.length - 2,\n );\n const statusCode = FramerUtils.getLastBytesFrom(responseBytes, 2);\n return Right(new ApduResponse({ data, statusCode }));\n } else if (result.error === \"SendApduTimeout\") {\n return Left(new SendApduTimeoutError(\"Abort timeout\"));\n } else if (result.error === \"EmptyResponse\") {\n return Left(new SendApduEmptyResponseError(\"Empty response\"));\n } else {\n return Left(new SendApduError(result.error));\n }\n}\n\nexport function mapNativeDeviceConnectionLostToDeviceDisconnected(\n nativeDeviceConnectionLost: NativeDeviceConnectionLost,\n): InternalDeviceDisconnected {\n return {\n sessionId: nativeDeviceConnectionLost.id,\n };\n}\n"],
5
- "mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,iDAAAE,EAA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,QAAK,IAAI,yBAAuBA,EAAO,KAAK,CAAC,CAExD,CAEO,SAAShB,EACdgB,EACgB,CAChB,GAAIA,EAAO,QAAS,CAClB,MAAME,KAAgB,sBAAmBF,EAAO,IAAI,EAC9CG,EAAO,cAAY,kBACvBD,EACAA,EAAc,OAAS,CACzB,EACME,EAAa,cAAY,iBAAiBF,EAAe,CAAC,EAChE,SAAO,SAAM,IAAI,eAAa,CAAE,KAAAC,EAAM,WAAAC,CAAW,CAAC,CAAC,CACrD,KAAO,QAAIJ,EAAO,QAAU,qBACnB,QAAK,IAAI,uBAAqB,eAAe,CAAC,EAC5CA,EAAO,QAAU,mBACnB,QAAK,IAAI,6BAA2B,gBAAgB,CAAC,KAErD,QAAK,IAAI,gBAAcA,EAAO,KAAK,CAAC,CAE/C,CAEO,SAASnB,EACdwB,EAC4B,CAC5B,MAAO,CACL,UAAWA,EAA2B,EACxC,CACF",
4
+ "sourcesContent": ["import {\n ApduResponse,\n DeviceDisconnectedWhileSendingError,\n type DeviceModelDataSource,\n FramerUtils,\n LogLevel,\n type LogParams,\n OpeningConnectionError,\n SendApduEmptyResponseError,\n type SendApduResult,\n SendApduTimeoutError,\n type TransportDeviceModel,\n type TransportDiscoveredDevice,\n} from \"@ledgerhq/device-management-kit\";\nimport { Left, Right } from \"purify-ts\";\n\nimport { base64ToUint8Array } from \"@api/helpers/base64Utils\";\nimport { HidTransportSendApduUnknownError } from \"@api/transport/Errors\";\nimport { TRANSPORT_IDENTIFIER } from \"@api/transport/rnHidTransportIdentifier\";\nimport {\n type InternalConnectionResult,\n type InternalDeviceDisconnected,\n} from \"@api/transport/types\";\n\nimport {\n type NativeDeviceConnectionLost,\n type NativeDiscoveryDevice,\n type NativeInternalConnectionResult,\n type NativeLedgerDevice,\n type NativeLog,\n type NativeSendApduResult,\n} from \"./types\";\n\nexport function mapNativeLedgerDeviceToDeviceModel(\n nativeLedgerDevice: NativeLedgerDevice,\n deviceModelDataSource: DeviceModelDataSource,\n): TransportDeviceModel | null {\n return (\n deviceModelDataSource.filterDeviceModels({\n usbProductId: Number.parseInt(nativeLedgerDevice.usbProductIdMask, 16),\n })[0] ?? null\n );\n}\n\nexport function mapNativeDiscoveryDeviceToTransportDiscoveredDevice(\n nativeDevice: NativeDiscoveryDevice,\n deviceModelDataSource: DeviceModelDataSource,\n): TransportDiscoveredDevice | null {\n const deviceModel = mapNativeLedgerDeviceToDeviceModel(\n nativeDevice.ledgerDevice,\n deviceModelDataSource,\n );\n if (deviceModel == null) return null;\n\n return {\n id: nativeDevice.uid,\n deviceModel,\n transport: TRANSPORT_IDENTIFIER,\n name: nativeDevice.name,\n };\n}\n\nexport function mapNativeTransportLogToLog(log: NativeLog): LogParams {\n let level: LogLevel;\n switch (log.level) {\n case \"error\":\n level = LogLevel.Error;\n break;\n case \"warning\":\n level = LogLevel.Warning;\n break;\n case \"info\":\n level = LogLevel.Info;\n break;\n case \"debug\":\n level = LogLevel.Debug;\n break;\n default:\n assertNever(log.level);\n level = LogLevel.Info;\n break;\n }\n\n return [\n level,\n log.message,\n {\n tag: log.tag,\n data: log.jsonPayload,\n timestamp: Number.parseInt(log.timestamp, 10),\n },\n ];\n}\n\nfunction assertNever(x: never) {\n throw new Error(\"Unexpected object: \" + x);\n}\n\nexport function mapNativeConnectionResultToConnectionResult(\n result: NativeInternalConnectionResult,\n deviceModelDataSource: DeviceModelDataSource,\n): InternalConnectionResult {\n if (result.success) {\n const transportDeviceModel = mapNativeLedgerDeviceToDeviceModel(\n result.ledgerDevice,\n deviceModelDataSource,\n );\n if (!transportDeviceModel)\n return Left(\n new OpeningConnectionError(\n `Could not find device model for the connected device with usbProductIdMask: ${result.ledgerDevice.usbProductIdMask}`,\n ),\n );\n return Right({ sessionId: result.sessionId, transportDeviceModel });\n } else {\n return Left(new OpeningConnectionError(result.error));\n }\n}\n\nexport function mapNativeSendApduResultToSendApduResult(\n result: NativeSendApduResult,\n): SendApduResult {\n if (result.success) {\n const responseBytes = base64ToUint8Array(result.apdu);\n const data = FramerUtils.getFirstBytesFrom(\n responseBytes,\n responseBytes.length - 2,\n );\n const statusCode = FramerUtils.getLastBytesFrom(responseBytes, 2);\n return Right(new ApduResponse({ data, statusCode }));\n } else if (result.error === \"SendApduTimeout\") {\n return Left(new SendApduTimeoutError(\"Abort timeout\"));\n } else if (result.error === \"EmptyResponse\") {\n return Left(new SendApduEmptyResponseError(\"Empty response\"));\n } else if (result.error === \"DeviceDisconnected\") {\n return Left(new DeviceDisconnectedWhileSendingError(\"Device disconnected\"));\n } else {\n return Left(new HidTransportSendApduUnknownError(result.error));\n }\n}\n\nexport function mapNativeDeviceConnectionLostToDeviceDisconnected(\n nativeDeviceConnectionLost: NativeDeviceConnectionLost,\n): InternalDeviceDisconnected {\n return {\n sessionId: nativeDeviceConnectionLost.id,\n };\n}\n"],
5
+ "mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,iDAAAE,EAAA,sDAAAC,EAAA,wDAAAC,EAAA,uCAAAC,EAAA,4CAAAC,EAAA,+BAAAC,IAAA,eAAAC,EAAAR,GAAA,IAAAS,EAaO,2CACPC,EAA4B,qBAE5BC,EAAmC,oCACnCC,EAAiD,iCACjDC,EAAqC,mDAe9B,SAASR,EACdS,EACAC,EAC6B,CAC7B,OACEA,EAAsB,mBAAmB,CACvC,aAAc,OAAO,SAASD,EAAmB,iBAAkB,EAAE,CACvE,CAAC,EAAE,CAAC,GAAK,IAEb,CAEO,SAASV,EACdY,EACAD,EACkC,CAClC,MAAME,EAAcZ,EAClBW,EAAa,aACbD,CACF,EACA,OAAIE,GAAe,KAAa,KAEzB,CACL,GAAID,EAAa,IACjB,YAAAC,EACA,UAAW,uBACX,KAAMD,EAAa,IACrB,CACF,CAEO,SAAST,EAA2BW,EAA2B,CACpE,IAAIC,EACJ,OAAQD,EAAI,MAAO,CACjB,IAAK,QACHC,EAAQ,WAAS,MACjB,MACF,IAAK,UACHA,EAAQ,WAAS,QACjB,MACF,IAAK,OACHA,EAAQ,WAAS,K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ResultToConnectionResult", "mapNativeDeviceConnectionLostToDeviceDisconnected", "mapNativeDiscoveryDeviceToTransportDiscoveredDevice", "mapNativeLedgerDeviceToDeviceModel", "mapNativeSendApduResultToSendApduResult", "mapNativeTransportLogToLog", "__toCommonJS", "import_device_management_kit", "import_purify_ts", "import_base64Utils", "import_Errors", "import_rnHidTransportIdentifier", "nativeLedgerDevice", "deviceModelDataSource", "nativeDevice", "deviceModel", "log", "level", "assertNever", "x", "result", "transportDeviceModel", "responseBytes", "data", "statusCode", "nativeDeviceConnectionLost"]
7
7
  }
@@ -1,2 +1,2 @@
1
- "use strict";var e=require("@ledgerhq/device-management-kit"),n=require("purify-ts"),d=require("../transport/Errors"),c=require("../transport/rnHidTransportIdentifier"),o=require("./mapper");describe("mapper",()=>{const a=new e.StaticDeviceModelDataSource;describe("mapNativeLedgerDeviceToDeviceModel",()=>{[{nativeLedgerDevice:{name:"NanoS",usbProductIdMask:"0x10"},deviceModel:a.getDeviceModel({id:e.DeviceModelId.NANO_S})},{nativeLedgerDevice:{name:"NanoX",usbProductIdMask:"0x40"},deviceModel:a.getDeviceModel({id:e.DeviceModelId.NANO_X})},{nativeLedgerDevice:{name:"NanoSPlus",usbProductIdMask:"0x50"},deviceModel:a.getDeviceModel({id:e.DeviceModelId.NANO_SP})},{nativeLedgerDevice:{name:"Stax",usbProductIdMask:"0x60"},deviceModel:a.getDeviceModel({id:e.DeviceModelId.STAX})},{nativeLedgerDevice:{name:"Flex",usbProductIdMask:"0x70"},deviceModel:a.getDeviceModel({id:e.DeviceModelId.FLEX})},{nativeLedgerDevice:{name:"NanoX",usbProductIdMask:"0x12345678"},deviceModel:null}].forEach(({nativeLedgerDevice:t,deviceModel:i})=>{it(`should map USB device with usbProductIdMask ${t.usbProductIdMask} to ${i?.productName??"null"}`,()=>{expect((0,o.mapNativeLedgerDeviceToDeviceModel)(t,a)).toEqual(i)})})}),describe("mapNativeDiscoveryDeviceToTransportDiscoveredDevice",()=>{it("should map NativeDiscoveryDevice to TransportDiscoveredDevice",()=>{const s={name:"NanoS",uid:"abcd",ledgerDevice:{name:"NanoS",usbProductIdMask:"0x10"}},t={id:"abcd",deviceModel:a.getDeviceModel({id:e.DeviceModelId.NANO_S}),transport:c.TRANSPORT_IDENTIFIER,name:"NanoS"};expect((0,o.mapNativeDiscoveryDeviceToTransportDiscoveredDevice)(s,a)).toEqual(t)}),it("should return null if the device model is not recognized",()=>{const s={name:"NanoX",uid:"efgh",ledgerDevice:{name:"NanoX",usbProductIdMask:"0x4567890"}};expect((0,o.mapNativeDiscoveryDeviceToTransportDiscoveredDevice)(s,a)).toEqual(null)})}),describe("mapNativeTransportLogToLog",()=>{[{nativeLog:{level:"debug",tag:"tag",message:"debug message",jsonPayload:{key:"value"},timestamp:"123456789"},log:[e.LogLevel.Debug,"debug message",{timestamp:123456789,tag:"tag",data:{key:"value"}}]},{nativeLog:{level:"info",tag:"tag",message:"info message",jsonPayload:{key:"value"},timestamp:"123456789"},log:[e.LogLevel.Info,"info message",{timestamp:123456789,tag:"tag",data:{key:"value"}}]},{nativeLog:{level:"error",tag:"tag",message:"error message",jsonPayload:{key:"value"},timestamp:"123456789"},log:[e.LogLevel.Error,"error message",{timestamp:123456789,tag:"tag",data:{key:"value"}}]},{nativeLog:{level:"warning",tag:"tag",message:"warning message",jsonPayload:{key:"value"},timestamp:"123456789"},log:[e.LogLevel.Warning,"warning message",{timestamp:123456789,tag:"tag",data:{key:"value"}}]}].forEach(({nativeLog:t,log:i})=>{it(`should map NativeLog with level "${t.level}" to Log`,()=>{expect((0,o.mapNativeTransportLogToLog)(t)).toEqual(i)})})}),describe("mapNativeConnectionResultToConnectionResult",()=>{[{testTitle:"Success",nativeConnectionResult:{success:!0,sessionId:"1234",ledgerDevice:{name:"NanoS",usbProductIdMask:"0x10"},deviceName:"NanoS"},connectionResult:(0,n.Right)({sessionId:"1234",transportDeviceModel:a.getDeviceModel({id:e.DeviceModelId.NANO_S})})},{testTitle:"Failure",nativeConnectionResult:{success:!1,error:"error message"},connectionResult:(0,n.Left)(new e.OpeningConnectionError("error message"))},{testTitle:"Unknown device model",nativeConnectionResult:{success:!0,sessionId:"1234",ledgerDevice:{name:"NanoX",usbProductIdMask:"0x12345678"},deviceName:"NanoX"},connectionResult:(0,n.Left)(new e.OpeningConnectionError("Could not find device model for the connected device with usbProductIdMask: 0x12345678"))}].forEach(({testTitle:t,nativeConnectionResult:i,connectionResult:r})=>{it(t,()=>{expect((0,o.mapNativeConnectionResultToConnectionResult)(i,a)).toEqual(r)})})}),describe("mapNativeSendApduResultToSendApduResult",()=>{test("success",()=>{const t={success:!0,apdu:"AQIDkAA="},i=(0,n.Right)(new e.ApduResponse({data:new Uint8Array([1,2,3]),statusCode:new Uint8Array([144,0])}));expect((0,o.mapNativeSendApduResultToSendApduResult)(t)).toEqual(i)}),test("failure",()=>{const s={success:!1,error:"error message"},t=(0,n.Left)(new d.SendApduError("error message"));expect((0,o.mapNativeSendApduResultToSendApduResult)(s)).toEqual(t)}),test("timeout error",()=>{const s={success:!1,error:"SendApduTimeout"},t=(0,n.Left)(new e.SendApduTimeoutError("Abort timeout"));expect((0,o.mapNativeSendApduResultToSendApduResult)(s)).toEqual(t)}),test("empty response error",()=>{const s={success:!1,error:"EmptyResponse"},t=(0,n.Left)(new e.SendApduEmptyResponseError("Empty response"));expect((0,o.mapNativeSendApduResultToSendApduResult)(s)).toEqual(t)})}),describe("mapNativeDeviceConnectionLostToDeviceDisconnected",()=>{it("should map NativeDeviceConnectionLost to DeviceDisconnected",()=>{const s={id:"1234"},t={sessionId:"1234"};expect((0,o.mapNativeDeviceConnectionLostToDeviceDisconnected)(s)).toEqual(t)})})});
1
+ "use strict";var e=require("@ledgerhq/device-management-kit"),a=require("purify-ts"),d=require("../transport/Errors"),c=require("../transport/rnHidTransportIdentifier"),o=require("./mapper");describe("mapper",()=>{const n=new e.StaticDeviceModelDataSource;describe("mapNativeLedgerDeviceToDeviceModel",()=>{[{nativeLedgerDevice:{name:"NanoS",usbProductIdMask:"0x10"},deviceModel:n.getDeviceModel({id:e.DeviceModelId.NANO_S})},{nativeLedgerDevice:{name:"NanoX",usbProductIdMask:"0x40"},deviceModel:n.getDeviceModel({id:e.DeviceModelId.NANO_X})},{nativeLedgerDevice:{name:"NanoSPlus",usbProductIdMask:"0x50"},deviceModel:n.getDeviceModel({id:e.DeviceModelId.NANO_SP})},{nativeLedgerDevice:{name:"Stax",usbProductIdMask:"0x60"},deviceModel:n.getDeviceModel({id:e.DeviceModelId.STAX})},{nativeLedgerDevice:{name:"Flex",usbProductIdMask:"0x70"},deviceModel:n.getDeviceModel({id:e.DeviceModelId.FLEX})},{nativeLedgerDevice:{name:"NanoX",usbProductIdMask:"0x12345678"},deviceModel:null}].forEach(({nativeLedgerDevice:t,deviceModel:i})=>{it(`should map USB device with usbProductIdMask ${t.usbProductIdMask} to ${i?.productName??"null"}`,()=>{expect((0,o.mapNativeLedgerDeviceToDeviceModel)(t,n)).toEqual(i)})})}),describe("mapNativeDiscoveryDeviceToTransportDiscoveredDevice",()=>{it("should map NativeDiscoveryDevice to TransportDiscoveredDevice",()=>{const s={name:"NanoS",uid:"abcd",ledgerDevice:{name:"NanoS",usbProductIdMask:"0x10"}},t={id:"abcd",deviceModel:n.getDeviceModel({id:e.DeviceModelId.NANO_S}),transport:c.TRANSPORT_IDENTIFIER,name:"NanoS"};expect((0,o.mapNativeDiscoveryDeviceToTransportDiscoveredDevice)(s,n)).toEqual(t)}),it("should return null if the device model is not recognized",()=>{const s={name:"NanoX",uid:"efgh",ledgerDevice:{name:"NanoX",usbProductIdMask:"0x4567890"}};expect((0,o.mapNativeDiscoveryDeviceToTransportDiscoveredDevice)(s,n)).toEqual(null)})}),describe("mapNativeTransportLogToLog",()=>{[{nativeLog:{level:"debug",tag:"tag",message:"debug message",jsonPayload:{key:"value"},timestamp:"123456789"},log:[e.LogLevel.Debug,"debug message",{timestamp:123456789,tag:"tag",data:{key:"value"}}]},{nativeLog:{level:"info",tag:"tag",message:"info message",jsonPayload:{key:"value"},timestamp:"123456789"},log:[e.LogLevel.Info,"info message",{timestamp:123456789,tag:"tag",data:{key:"value"}}]},{nativeLog:{level:"error",tag:"tag",message:"error message",jsonPayload:{key:"value"},timestamp:"123456789"},log:[e.LogLevel.Error,"error message",{timestamp:123456789,tag:"tag",data:{key:"value"}}]},{nativeLog:{level:"warning",tag:"tag",message:"warning message",jsonPayload:{key:"value"},timestamp:"123456789"},log:[e.LogLevel.Warning,"warning message",{timestamp:123456789,tag:"tag",data:{key:"value"}}]}].forEach(({nativeLog:t,log:i})=>{it(`should map NativeLog with level "${t.level}" to Log`,()=>{expect((0,o.mapNativeTransportLogToLog)(t)).toEqual(i)})})}),describe("mapNativeConnectionResultToConnectionResult",()=>{[{testTitle:"Success",nativeConnectionResult:{success:!0,sessionId:"1234",ledgerDevice:{name:"NanoS",usbProductIdMask:"0x10"},deviceName:"NanoS"},connectionResult:(0,a.Right)({sessionId:"1234",transportDeviceModel:n.getDeviceModel({id:e.DeviceModelId.NANO_S})})},{testTitle:"Failure",nativeConnectionResult:{success:!1,error:"error message"},connectionResult:(0,a.Left)(new e.OpeningConnectionError("error message"))},{testTitle:"Unknown device model",nativeConnectionResult:{success:!0,sessionId:"1234",ledgerDevice:{name:"NanoX",usbProductIdMask:"0x12345678"},deviceName:"NanoX"},connectionResult:(0,a.Left)(new e.OpeningConnectionError("Could not find device model for the connected device with usbProductIdMask: 0x12345678"))}].forEach(({testTitle:t,nativeConnectionResult:i,connectionResult:r})=>{it(t,()=>{expect((0,o.mapNativeConnectionResultToConnectionResult)(i,n)).toEqual(r)})})}),describe("mapNativeSendApduResultToSendApduResult",()=>{test("success",()=>{const t={success:!0,apdu:"AQIDkAA="},i=(0,a.Right)(new e.ApduResponse({data:new Uint8Array([1,2,3]),statusCode:new Uint8Array([144,0])}));expect((0,o.mapNativeSendApduResultToSendApduResult)(t)).toEqual(i)}),test("failure",()=>{const s={success:!1,error:"error message"},t=(0,a.Left)(new d.HidTransportSendApduUnknownError("error message"));expect((0,o.mapNativeSendApduResultToSendApduResult)(s)).toEqual(t)}),test("timeout error",()=>{const s={success:!1,error:"SendApduTimeout"},t=(0,a.Left)(new e.SendApduTimeoutError("Abort timeout"));expect((0,o.mapNativeSendApduResultToSendApduResult)(s)).toEqual(t)}),test("empty response error",()=>{const s={success:!1,error:"EmptyResponse"},t=(0,a.Left)(new e.SendApduEmptyResponseError("Empty response"));expect((0,o.mapNativeSendApduResultToSendApduResult)(s)).toEqual(t)})}),describe("mapNativeDeviceConnectionLostToDeviceDisconnected",()=>{it("should map NativeDeviceConnectionLost to DeviceDisconnected",()=>{const s={id:"1234"},t={sessionId:"1234"};expect((0,o.mapNativeDeviceConnectionLostToDeviceDisconnected)(s)).toEqual(t)})})});
2
2
  //# sourceMappingURL=mapper.test.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/api/bridge/mapper.test.ts"],
4
- "sourcesContent": ["import {\n ApduResponse,\n DeviceModelId,\n LogLevel,\n type LogParams,\n OpeningConnectionError,\n SendApduEmptyResponseError,\n type SendApduResult,\n SendApduTimeoutError,\n StaticDeviceModelDataSource,\n type TransportDeviceModel,\n type TransportDiscoveredDevice,\n} from \"@ledgerhq/device-management-kit\";\nimport { Left, Right } from \"purify-ts\";\n\nimport { SendApduError } from \"@api/transport/Errors\";\nimport { TRANSPORT_IDENTIFIER } from \"@api/transport/rnHidTransportIdentifier\";\nimport { type InternalConnectionResult } from \"@api/transport/types\";\n\nimport {\n mapNativeConnectionResultToConnectionResult,\n mapNativeDeviceConnectionLostToDeviceDisconnected,\n mapNativeDiscoveryDeviceToTransportDiscoveredDevice,\n mapNativeLedgerDeviceToDeviceModel,\n mapNativeSendApduResultToSendApduResult,\n mapNativeTransportLogToLog,\n} from \"./mapper\";\nimport {\n type NativeDiscoveryDevice,\n type NativeInternalConnectionResult,\n type NativeLedgerDevice,\n type NativeLog,\n type NativeSendApduResult,\n} from \"./types\";\n\ndescribe(\"mapper\", () => {\n const deviceModelDataSource = new StaticDeviceModelDataSource();\n\n describe(\"mapNativeLedgerDeviceToDeviceModel\", () => {\n const testCases: Array<{\n nativeLedgerDevice: NativeLedgerDevice;\n deviceModel: TransportDeviceModel | null;\n }> = [\n {\n nativeLedgerDevice: {\n name: \"NanoS\",\n usbProductIdMask: \"0x10\",\n },\n deviceModel: deviceModelDataSource.getDeviceModel({\n id: DeviceModelId.NANO_S,\n }),\n },\n {\n nativeLedgerDevice: {\n name: \"NanoX\",\n usbProductIdMask: \"0x40\",\n },\n deviceModel: deviceModelDataSource.getDeviceModel({\n id: DeviceModelId.NANO_X,\n }),\n },\n {\n nativeLedgerDevice: {\n name: \"NanoSPlus\",\n usbProductIdMask: \"0x50\",\n },\n deviceModel: deviceModelDataSource.getDeviceModel({\n id: DeviceModelId.NANO_SP,\n }),\n },\n {\n nativeLedgerDevice: {\n name: \"Stax\",\n usbProductIdMask: \"0x60\",\n },\n deviceModel: deviceModelDataSource.getDeviceModel({\n id: DeviceModelId.STAX,\n }),\n },\n {\n nativeLedgerDevice: {\n name: \"Flex\",\n usbProductIdMask: \"0x70\",\n },\n deviceModel: deviceModelDataSource.getDeviceModel({\n id: DeviceModelId.FLEX,\n }),\n },\n {\n nativeLedgerDevice: {\n name: \"NanoX\",\n usbProductIdMask: \"0x12345678\",\n },\n deviceModel: null, // because the usbProductIdMask is not recognized\n },\n ];\n testCases.forEach(({ nativeLedgerDevice, deviceModel }) => {\n it(`should map USB device with usbProductIdMask ${nativeLedgerDevice.usbProductIdMask} to ${\n deviceModel?.productName ?? \"null\"\n }`, () => {\n expect(\n mapNativeLedgerDeviceToDeviceModel(\n nativeLedgerDevice,\n deviceModelDataSource,\n ),\n ).toEqual(deviceModel);\n });\n });\n });\n\n describe(\"mapNativeDiscoveryDeviceToTransportDiscoveredDevice\", () => {\n it(\"should map NativeDiscoveryDevice to TransportDiscoveredDevice\", () => {\n const nativeDevice: NativeDiscoveryDevice = {\n name: \"NanoS\",\n uid: \"abcd\",\n ledgerDevice: {\n name: \"NanoS\",\n usbProductIdMask: \"0x10\",\n },\n };\n const expectedDiscoveredDevice: TransportDiscoveredDevice = {\n id: \"abcd\",\n deviceModel: deviceModelDataSource.getDeviceModel({\n id: DeviceModelId.NANO_S,\n }),\n transport: TRANSPORT_IDENTIFIER,\n name: \"NanoS\",\n };\n expect(\n mapNativeDiscoveryDeviceToTransportDiscoveredDevice(\n nativeDevice,\n deviceModelDataSource,\n ),\n ).toEqual(expectedDiscoveredDevice);\n });\n\n it(\"should return null if the device model is not recognized\", () => {\n const nativeDevice: NativeDiscoveryDevice = {\n name: \"NanoX\",\n uid: \"efgh\",\n ledgerDevice: {\n name: \"NanoX\",\n usbProductIdMask: \"0x4567890\", // some invalid value\n },\n };\n const expectedDiscoveredDevice = null; // because the usbProductIdMask is not recognized\n expect(\n mapNativeDiscoveryDeviceToTransportDiscoveredDevice(\n nativeDevice,\n deviceModelDataSource,\n ),\n ).toEqual(expectedDiscoveredDevice);\n });\n });\n\n describe(\"mapNativeTransportLogToLog\", () => {\n const testCases: Array<{\n nativeLog: NativeLog;\n log: LogParams;\n }> = [\n {\n // debug\n nativeLog: {\n level: \"debug\",\n tag: \"tag\",\n message: \"debug message\",\n jsonPayload: { key: \"value\" },\n timestamp: \"123456789\",\n },\n log: [\n LogLevel.Debug,\n \"debug message\",\n {\n timestamp: 123456789,\n tag: \"tag\",\n data: { key: \"value\" },\n },\n ],\n },\n // info\n {\n nativeLog: {\n level: \"info\",\n tag: \"tag\",\n message: \"info message\",\n jsonPayload: { key: \"value\" },\n timestamp: \"123456789\",\n },\n log: [\n LogLevel.Info,\n \"info message\",\n {\n timestamp: 123456789,\n tag: \"tag\",\n data: { key: \"value\" },\n },\n ],\n },\n // error\n {\n nativeLog: {\n level: \"error\",\n tag: \"tag\",\n message: \"error message\",\n jsonPayload: { key: \"value\" },\n timestamp: \"123456789\",\n },\n log: [\n LogLevel.Error,\n \"error message\",\n {\n timestamp: 123456789,\n tag: \"tag\",\n data: { key: \"value\" },\n },\n ],\n },\n // warning\n {\n nativeLog: {\n level: \"warning\",\n tag: \"tag\",\n message: \"warning message\",\n jsonPayload: { key: \"value\" },\n timestamp: \"123456789\",\n },\n log: [\n LogLevel.Warning,\n \"warning message\",\n {\n timestamp: 123456789,\n tag: \"tag\",\n data: { key: \"value\" },\n },\n ],\n },\n ];\n\n testCases.forEach(({ nativeLog, log }) => {\n it(`should map NativeLog with level \"${nativeLog.level}\" to Log`, () => {\n expect(mapNativeTransportLogToLog(nativeLog)).toEqual(log);\n });\n });\n });\n\n describe(\"mapNativeConnectionResultToConnectionResult\", () => {\n const testCases: Array<{\n nativeConnectionResult: NativeInternalConnectionResult;\n connectionResult: InternalConnectionResult;\n testTitle: string;\n }> = [\n {\n testTitle: \"Success\",\n nativeConnectionResult: {\n success: true,\n sessionId: \"1234\",\n ledgerDevice: {\n name: \"NanoS\",\n usbProductIdMask: \"0x10\",\n },\n deviceName: \"NanoS\",\n },\n connectionResult: Right({\n sessionId: \"1234\",\n transportDeviceModel: deviceModelDataSource.getDeviceModel({\n id: DeviceModelId.NANO_S,\n }),\n }),\n },\n {\n testTitle: \"Failure\",\n nativeConnectionResult: {\n success: false,\n error: \"error message\",\n },\n connectionResult: Left(new OpeningConnectionError(\"error message\")),\n },\n {\n testTitle: \"Unknown device model\",\n nativeConnectionResult: {\n success: true,\n sessionId: \"1234\",\n ledgerDevice: {\n name: \"NanoX\",\n usbProductIdMask: \"0x12345678\",\n },\n deviceName: \"NanoX\",\n },\n connectionResult: Left(\n new OpeningConnectionError(\n \"Could not find device model for the connected device with usbProductIdMask: 0x12345678\",\n ),\n ),\n },\n ];\n\n testCases.forEach(\n ({ testTitle, nativeConnectionResult, connectionResult }) => {\n it(testTitle, () => {\n expect(\n mapNativeConnectionResultToConnectionResult(\n nativeConnectionResult,\n deviceModelDataSource,\n ),\n ).toEqual(connectionResult);\n });\n },\n );\n });\n\n describe(\"mapNativeSendApduResultToSendApduResult\", () => {\n test(\"success\", () => {\n const resultApduString = \"AQIDkAA=\";\n const nativeSendApduResult: NativeSendApduResult = {\n success: true,\n apdu: resultApduString,\n };\n const expectedSendApduResult: SendApduResult = Right(\n new ApduResponse({\n data: new Uint8Array([0x01, 0x02, 0x03]),\n statusCode: new Uint8Array([0x90, 0x00]),\n }),\n );\n expect(\n mapNativeSendApduResultToSendApduResult(nativeSendApduResult),\n ).toEqual(expectedSendApduResult);\n });\n\n test(\"failure\", () => {\n const nativeSendApduResult: NativeSendApduResult = {\n success: false,\n error: \"error message\",\n };\n const expectedSendApduResult: SendApduResult = Left(\n new SendApduError(\"error message\"),\n );\n expect(\n mapNativeSendApduResultToSendApduResult(nativeSendApduResult),\n ).toEqual(expectedSendApduResult);\n });\n\n test(\"timeout error\", () => {\n const nativeSendApduResult: NativeSendApduResult = {\n success: false,\n error: \"SendApduTimeout\",\n };\n const expectedSendApduResult: SendApduResult = Left(\n new SendApduTimeoutError(\"Abort timeout\"),\n );\n expect(\n mapNativeSendApduResultToSendApduResult(nativeSendApduResult),\n ).toEqual(expectedSendApduResult);\n });\n\n test(\"empty response error\", () => {\n const nativeSendApduResult: NativeSendApduResult = {\n success: false,\n error: \"EmptyResponse\",\n };\n const expectedSendApduResult: SendApduResult = Left(\n new SendApduEmptyResponseError(\"Empty response\"),\n );\n expect(\n mapNativeSendApduResultToSendApduResult(nativeSendApduResult),\n ).toEqual(expectedSendApduResult);\n });\n });\n\n describe(\"mapNativeDeviceConnectionLostToDeviceDisconnected\", () => {\n it(\"should map NativeDeviceConnectionLost to DeviceDisconnected\", () => {\n const nativeDeviceConnectionLost = {\n id: \"1234\",\n };\n const expectedDeviceDisconnected = {\n sessionId: \"1234\",\n };\n expect(\n mapNativeDeviceConnectionLostToDeviceDisconnected(\n nativeDeviceConnectionLost,\n ),\n ).toEqual(expectedDeviceDisconnected);\n });\n });\n});\n"],
5
- "mappings": "aAAA,IAAAA,EAYO,2CACPC,EAA4B,qBAE5BC,EAA8B,iCAC9BC,EA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AK,gBAAiB,IAAM,CAC1B,MAAMD,EAA6C,CACjD,QAAS,GACT,MAAO,iBACT,EACMC,KAAyC,QAC7C,IAAI,uBAAqB,eAAe,CAC1C,EACA,UACE,2CAAwCD,CAAoB,CAC9D,EAAE,QAAQC,CAAsB,CAClC,CAAC,EAED,KAAK,uBAAwB,IAAM,CACjC,MAAMD,EAA6C,CACjD,QAAS,GACT,MAAO,eACT,EACMC,KAAyC,QAC7C,IAAI,6BAA2B,gBAAgB,CACjD,EACA,UACE,2CAAwCD,CAAoB,CAC9D,EAAE,QAAQC,CAAsB,CAClC,CAAC,CACH,CAAC,EAED,SAAS,oDAAqD,IAAM,CAClE,GAAG,8DAA+D,IAAM,CACtE,MAAMC,EAA6B,CACjC,GAAI,MACN,EACMC,EAA6B,CACjC,UAAW,MACb,EACA,UACE,qDACED,CACF,CACF,EAAE,QAAQC,CAA0B,CACtC,CAAC,CACH,CAAC,CACH,CAAC",
4
+ "sourcesContent": ["import {\n ApduResponse,\n DeviceModelId,\n LogLevel,\n type LogParams,\n OpeningConnectionError,\n SendApduEmptyResponseError,\n type SendApduResult,\n SendApduTimeoutError,\n StaticDeviceModelDataSource,\n type TransportDeviceModel,\n type TransportDiscoveredDevice,\n} from \"@ledgerhq/device-management-kit\";\nimport { Left, Right } from \"purify-ts\";\n\nimport { HidTransportSendApduUnknownError } from \"@api/transport/Errors\";\nimport { TRANSPORT_IDENTIFIER } from \"@api/transport/rnHidTransportIdentifier\";\nimport { type InternalConnectionResult } from \"@api/transport/types\";\n\nimport {\n mapNativeConnectionResultToConnectionResult,\n mapNativeDeviceConnectionLostToDeviceDisconnected,\n mapNativeDiscoveryDeviceToTransportDiscoveredDevice,\n mapNativeLedgerDeviceToDeviceModel,\n mapNativeSendApduResultToSendApduResult,\n mapNativeTransportLogToLog,\n} from \"./mapper\";\nimport {\n type NativeDiscoveryDevice,\n type NativeInternalConnectionResult,\n type NativeLedgerDevice,\n type NativeLog,\n type NativeSendApduResult,\n} from \"./types\";\n\ndescribe(\"mapper\", () => {\n const deviceModelDataSource = new StaticDeviceModelDataSource();\n\n describe(\"mapNativeLedgerDeviceToDeviceModel\", () => {\n const testCases: Array<{\n nativeLedgerDevice: NativeLedgerDevice;\n deviceModel: TransportDeviceModel | null;\n }> = [\n {\n nativeLedgerDevice: {\n name: \"NanoS\",\n usbProductIdMask: \"0x10\",\n },\n deviceModel: deviceModelDataSource.getDeviceModel({\n id: DeviceModelId.NANO_S,\n }),\n },\n {\n nativeLedgerDevice: {\n name: \"NanoX\",\n usbProductIdMask: \"0x40\",\n },\n deviceModel: deviceModelDataSource.getDeviceModel({\n id: DeviceModelId.NANO_X,\n }),\n },\n {\n nativeLedgerDevice: {\n name: \"NanoSPlus\",\n usbProductIdMask: \"0x50\",\n },\n deviceModel: deviceModelDataSource.getDeviceModel({\n id: DeviceModelId.NANO_SP,\n }),\n },\n {\n nativeLedgerDevice: {\n name: \"Stax\",\n usbProductIdMask: \"0x60\",\n },\n deviceModel: deviceModelDataSource.getDeviceModel({\n id: DeviceModelId.STAX,\n }),\n },\n {\n nativeLedgerDevice: {\n name: \"Flex\",\n usbProductIdMask: \"0x70\",\n },\n deviceModel: deviceModelDataSource.getDeviceModel({\n id: DeviceModelId.FLEX,\n }),\n },\n {\n nativeLedgerDevice: {\n name: \"NanoX\",\n usbProductIdMask: \"0x12345678\",\n },\n deviceModel: null, // because the usbProductIdMask is not recognized\n },\n ];\n testCases.forEach(({ nativeLedgerDevice, deviceModel }) => {\n it(`should map USB device with usbProductIdMask ${nativeLedgerDevice.usbProductIdMask} to ${\n deviceModel?.productName ?? \"null\"\n }`, () => {\n expect(\n mapNativeLedgerDeviceToDeviceModel(\n nativeLedgerDevice,\n deviceModelDataSource,\n ),\n ).toEqual(deviceModel);\n });\n });\n });\n\n describe(\"mapNativeDiscoveryDeviceToTransportDiscoveredDevice\", () => {\n it(\"should map NativeDiscoveryDevice to TransportDiscoveredDevice\", () => {\n const nativeDevice: NativeDiscoveryDevice = {\n name: \"NanoS\",\n uid: \"abcd\",\n ledgerDevice: {\n name: \"NanoS\",\n usbProductIdMask: \"0x10\",\n },\n };\n const expectedDiscoveredDevice: TransportDiscoveredDevice = {\n id: \"abcd\",\n deviceModel: deviceModelDataSource.getDeviceModel({\n id: DeviceModelId.NANO_S,\n }),\n transport: TRANSPORT_IDENTIFIER,\n name: \"NanoS\",\n };\n expect(\n mapNativeDiscoveryDeviceToTransportDiscoveredDevice(\n nativeDevice,\n deviceModelDataSource,\n ),\n ).toEqual(expectedDiscoveredDevice);\n });\n\n it(\"should return null if the device model is not recognized\", () => {\n const nativeDevice: NativeDiscoveryDevice = {\n name: \"NanoX\",\n uid: \"efgh\",\n ledgerDevice: {\n name: \"NanoX\",\n usbProductIdMask: \"0x4567890\", // some invalid value\n },\n };\n const expectedDiscoveredDevice = null; // because the usbProductIdMask is not recognized\n expect(\n mapNativeDiscoveryDeviceToTransportDiscoveredDevice(\n nativeDevice,\n deviceModelDataSource,\n ),\n ).toEqual(expectedDiscoveredDevice);\n });\n });\n\n describe(\"mapNativeTransportLogToLog\", () => {\n const testCases: Array<{\n nativeLog: NativeLog;\n log: LogParams;\n }> = [\n {\n // debug\n nativeLog: {\n level: \"debug\",\n tag: \"tag\",\n message: \"debug message\",\n jsonPayload: { key: \"value\" },\n timestamp: \"123456789\",\n },\n log: [\n LogLevel.Debug,\n \"debug message\",\n {\n timestamp: 123456789,\n tag: \"tag\",\n data: { key: \"value\" },\n },\n ],\n },\n // info\n {\n nativeLog: {\n level: \"info\",\n tag: \"tag\",\n message: \"info message\",\n jsonPayload: { key: \"value\" },\n timestamp: \"123456789\",\n },\n log: [\n LogLevel.Info,\n \"info message\",\n {\n timestamp: 123456789,\n tag: \"tag\",\n data: { key: \"value\" },\n },\n ],\n },\n // error\n {\n nativeLog: {\n level: \"error\",\n tag: \"tag\",\n message: \"error message\",\n jsonPayload: { key: \"value\" },\n timestamp: \"123456789\",\n },\n log: [\n LogLevel.Error,\n \"error message\",\n {\n timestamp: 123456789,\n tag: \"tag\",\n data: { key: \"value\" },\n },\n ],\n },\n // warning\n {\n nativeLog: {\n level: \"warning\",\n tag: \"tag\",\n message: \"warning message\",\n jsonPayload: { key: \"value\" },\n timestamp: \"123456789\",\n },\n log: [\n LogLevel.Warning,\n \"warning message\",\n {\n timestamp: 123456789,\n tag: \"tag\",\n data: { key: \"value\" },\n },\n ],\n },\n ];\n\n testCases.forEach(({ nativeLog, log }) => {\n it(`should map NativeLog with level \"${nativeLog.level}\" to Log`, () => {\n expect(mapNativeTransportLogToLog(nativeLog)).toEqual(log);\n });\n });\n });\n\n describe(\"mapNativeConnectionResultToConnectionResult\", () => {\n const testCases: Array<{\n nativeConnectionResult: NativeInternalConnectionResult;\n connectionResult: InternalConnectionResult;\n testTitle: string;\n }> = [\n {\n testTitle: \"Success\",\n nativeConnectionResult: {\n success: true,\n sessionId: \"1234\",\n ledgerDevice: {\n name: \"NanoS\",\n usbProductIdMask: \"0x10\",\n },\n deviceName: \"NanoS\",\n },\n connectionResult: Right({\n sessionId: \"1234\",\n transportDeviceModel: deviceModelDataSource.getDeviceModel({\n id: DeviceModelId.NANO_S,\n }),\n }),\n },\n {\n testTitle: \"Failure\",\n nativeConnectionResult: {\n success: false,\n error: \"error message\",\n },\n connectionResult: Left(new OpeningConnectionError(\"error message\")),\n },\n {\n testTitle: \"Unknown device model\",\n nativeConnectionResult: {\n success: true,\n sessionId: \"1234\",\n ledgerDevice: {\n name: \"NanoX\",\n usbProductIdMask: \"0x12345678\",\n },\n deviceName: \"NanoX\",\n },\n connectionResult: Left(\n new OpeningConnectionError(\n \"Could not find device model for the connected device with usbProductIdMask: 0x12345678\",\n ),\n ),\n },\n ];\n\n testCases.forEach(\n ({ testTitle, nativeConnectionResult, connectionResult }) => {\n it(testTitle, () => {\n expect(\n mapNativeConnectionResultToConnectionResult(\n nativeConnectionResult,\n deviceModelDataSource,\n ),\n ).toEqual(connectionResult);\n });\n },\n );\n });\n\n describe(\"mapNativeSendApduResultToSendApduResult\", () => {\n test(\"success\", () => {\n const resultApduString = \"AQIDkAA=\";\n const nativeSendApduResult: NativeSendApduResult = {\n success: true,\n apdu: resultApduString,\n };\n const expectedSendApduResult: SendApduResult = Right(\n new ApduResponse({\n data: new Uint8Array([0x01, 0x02, 0x03]),\n statusCode: new Uint8Array([0x90, 0x00]),\n }),\n );\n expect(\n mapNativeSendApduResultToSendApduResult(nativeSendApduResult),\n ).toEqual(expectedSendApduResult);\n });\n\n test(\"failure\", () => {\n const nativeSendApduResult: NativeSendApduResult = {\n success: false,\n error: \"error message\",\n };\n const expectedSendApduResult: SendApduResult = Left(\n new HidTransportSendApduUnknownError(\"error message\"),\n );\n expect(\n mapNativeSendApduResultToSendApduResult(nativeSendApduResult),\n ).toEqual(expectedSendApduResult);\n });\n\n test(\"timeout error\", () => {\n const nativeSendApduResult: NativeSendApduResult = {\n success: false,\n error: \"SendApduTimeout\",\n };\n const expectedSendApduResult: SendApduResult = Left(\n new SendApduTimeoutError(\"Abort timeout\"),\n );\n expect(\n mapNativeSendApduResultToSendApduResult(nativeSendApduResult),\n ).toEqual(expectedSendApduResult);\n });\n\n test(\"empty response error\", () => {\n const nativeSendApduResult: NativeSendApduResult = {\n success: false,\n error: \"EmptyResponse\",\n };\n const expectedSendApduResult: SendApduResult = Left(\n new SendApduEmptyResponseError(\"Empty response\"),\n );\n expect(\n mapNativeSendApduResultToSendApduResult(nativeSendApduResult),\n ).toEqual(expectedSendApduResult);\n });\n });\n\n describe(\"mapNativeDeviceConnectionLostToDeviceDisconnected\", () => {\n it(\"should map NativeDeviceConnectionLost to DeviceDisconnected\", () => {\n const nativeDeviceConnectionLost = {\n id: \"1234\",\n };\n const expectedDeviceDisconnected = {\n sessionId: \"1234\",\n };\n expect(\n mapNativeDeviceConnectionLostToDeviceDisconnected(\n nativeDeviceConnectionLost,\n ),\n ).toEqual(expectedDeviceDisconnected);\n });\n });\n});\n"],
5
+ "mappings": "aAAA,IAAAA,EAYO,2CACPC,EAA4B,qBA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AAsB,CAClC,CAAC,EAED,KAAK,gBAAiB,IAAM,CAC1B,MAAMD,EAA6C,CACjD,QAAS,GACT,MAAO,iBACT,EACMC,KAAyC,QAC7C,IAAI,uBAAqB,eAAe,CAC1C,EACA,UACE,2CAAwCD,CAAoB,CAC9D,EAAE,QAAQC,CAAsB,CAClC,CAAC,EAED,KAAK,uBAAwB,IAAM,CACjC,MAAMD,EAA6C,CACjD,QAAS,GACT,MAAO,eACT,EACMC,KAAyC,QAC7C,IAAI,6BAA2B,gBAAgB,CACjD,EACA,UACE,2CAAwCD,CAAoB,CAC9D,EAAE,QAAQC,CAAsB,CAClC,CAAC,CACH,CAAC,EAED,SAAS,oDAAqD,IAAM,CAClE,GAAG,8DAA+D,IAAM,CACtE,MAAMC,EAA6B,CACjC,GAAI,MACN,EACMC,EAA6B,CACjC,UAAW,MACb,EACA,UACE,qDACED,CACF,CACF,EAAE,QAAQC,CAA0B,CACtC,CAAC,CACH,CAAC,CACH,CAAC",
6
6
  "names": ["import_device_management_kit", "import_purify_ts", "import_Errors", "import_rnHidTransportIdentifier", "import_mapper", "deviceModelDataSource", "nativeLedgerDevice", "deviceModel", "nativeDevice", "expectedDiscoveredDevice", "nativeLog", "log", "testTitle", "nativeConnectionResult", "connectionResult", "nativeSendApduResult", "expectedSendApduResult", "nativeDeviceConnectionLost", "expectedDeviceDisconnected"]
7
7
  }
@@ -1,2 +1,2 @@
1
- "use strict";var d=Object.defineProperty;var p=Object.getOwnPropertyDescriptor;var s=Object.getOwnPropertyNames;var u=Object.prototype.hasOwnProperty;var l=(n,r)=>{for(var o in r)d(n,o,{get:r[o],enumerable:!0})},c=(n,r,o,t)=>{if(r&&typeof r=="object"||typeof r=="function")for(let e of s(r))!u.call(n,e)&&e!==o&&d(n,e,{get:()=>r[e],enumerable:!(t=p(r,e))||t.enumerable});return n};var i=n=>c(d({},"__esModule",{value:!0}),n);var m={};l(m,{SendApduError:()=>k});module.exports=i(m);var a=require("@ledgerhq/device-management-kit");class k extends a.GeneralDmkError{constructor(o){super(o);this.err=o}_tag="HidTransportSendApduUnknownError"}0&&(module.exports={SendApduError});
1
+ "use strict";var d=Object.defineProperty;var p=Object.getOwnPropertyDescriptor;var s=Object.getOwnPropertyNames;var u=Object.prototype.hasOwnProperty;var i=(n,r)=>{for(var o in r)d(n,o,{get:r[o],enumerable:!0})},k=(n,r,o,t)=>{if(r&&typeof r=="object"||typeof r=="function")for(let e of s(r))!u.call(n,e)&&e!==o&&d(n,e,{get:()=>r[e],enumerable:!(t=p(r,e))||t.enumerable});return n};var l=n=>k(d({},"__esModule",{value:!0}),n);var m={};i(m,{HidTransportSendApduUnknownError:()=>c});module.exports=l(m);var a=require("@ledgerhq/device-management-kit");class c extends a.GeneralDmkError{constructor(o){super(o);this.err=o}_tag="HidTransportSendApduUnknownError"}0&&(module.exports={HidTransportSendApduUnknownError});
2
2
  //# sourceMappingURL=Errors.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/api/transport/Errors.ts"],
4
- "sourcesContent": ["import { GeneralDmkError } from \"@ledgerhq/device-management-kit\";\n\nexport class SendApduError extends GeneralDmkError {\n override readonly _tag = \"HidTransportSendApduUnknownError\";\n constructor(readonly err?: unknown) {\n super(err);\n }\n}\n"],
5
- "mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,mBAAAE,IAAA,eAAAC,EAAAH,GAAA,IAAAI,EAAgC,2CAEzB,MAAMF,UAAsB,iBAAgB,CAEjD,YAAqBG,EAAe,CAClC,MAAMA,CAAG,EADU,SAAAA,CAErB,CAHkB,KAAO,kCAI3B",
6
- "names": ["Errors_exports", "__export", "SendApduError", "__toCommonJS", "import_device_management_kit", "err"]
4
+ "sourcesContent": ["import { GeneralDmkError } from \"@ledgerhq/device-management-kit\";\n\nexport class HidTransportSendApduUnknownError extends GeneralDmkError {\n override readonly _tag = \"HidTransportSendApduUnknownError\";\n constructor(readonly err?: unknown) {\n super(err);\n }\n}\n"],
5
+ "mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,sCAAAE,IAAA,eAAAC,EAAAH,GAAA,IAAAI,EAAgC,2CAEzB,MAAMF,UAAyC,iBAAgB,CAEpE,YAAqBG,EAAe,CAClC,MAAMA,CAAG,EADU,SAAAA,CAErB,CAHkB,KAAO,kCAI3B",
6
+ "names": ["Errors_exports", "__export", "HidTransportSendApduUnknownError", "__toCommonJS", "import_device_management_kit", "err"]
7
7
  }
@@ -1,2 +1,2 @@
1
- "use strict";var d=Object.defineProperty;var D=Object.getOwnPropertyDescriptor;var _=Object.getOwnPropertyNames;var S=Object.prototype.hasOwnProperty;var T=(n,r)=>{for(var t in r)d(n,t,{get:r[t],enumerable:!0})},m=(n,r,t,i)=>{if(r&&typeof r=="object"||typeof r=="function")for(let e of _(r))!S.call(n,e)&&e!==t&&d(n,e,{get:()=>r[e],enumerable:!(i=D(r,e))||i.enumerable});return n};var f=n=>m(d({},"__esModule",{value:!0}),n);var M={};T(M,{RNHidTransport:()=>E});module.exports=f(M);var o=require("@ledgerhq/device-management-kit"),s=require("purify-ts"),g=require("rxjs"),l=require("../helpers/getObservableOfArraysNewItems"),u=require("../transport/rnHidTransportIdentifier"),b=require("./Errors");class E{constructor(r,t,i){this._isSupported=r;this._nativeModuleWrapper=t;this._loggerService=i("RNHidTransport"),this._nativeModuleWrapper.subscribeToTransportLogs().subscribe(e=>{const[a,c,p]=e,v={[o.LogLevel.Fatal]:this._loggerService.error.bind(this._loggerService),[o.LogLevel.Error]:this._loggerService.error.bind(this._loggerService),[o.LogLevel.Warning]:this._loggerService.warn.bind(this._loggerService),[o.LogLevel.Info]:this._loggerService.info.bind(this._loggerService),[o.LogLevel.Debug]:this._loggerService.debug.bind(this._loggerService)}[a];v(c,p)})}_loggerService;getIdentifier(){return u.TRANSPORT_IDENTIFIER}isSupported(){return this._isSupported}startDiscovering(){return new g.Observable(t=>{const i=(0,l.getObservableOfArraysNewItems)(this._nativeModuleWrapper.subscribeToDiscoveredDevicesEvents(),e=>e.id).subscribe(t);return this._nativeModuleWrapper.startScan().catch(e=>{t.error(e),this._loggerService.error("startDiscovering error",e)}),()=>i.unsubscribe()})}stopDiscovering(){this._nativeModuleWrapper.stopScan().catch(r=>{this._loggerService.error("stopDiscovering error",r)})}listenToAvailableDevices(){return new g.Observable(t=>{const i=this._nativeModuleWrapper.subscribeToDiscoveredDevicesEvents().subscribe(e=>{t.next(e)});return this._nativeModuleWrapper.startScan().catch(e=>{this._loggerService.error("startDiscovering error",e),t.error(e)}),()=>{i.unsubscribe(),this._nativeModuleWrapper.stopScan().catch(e=>{this._loggerService.error("stopDiscovering error",e)})}})}connect(r){return this._nativeModuleWrapper.connectDevice(r.deviceId).then(t=>t.map(({sessionId:i,transportDeviceModel:e})=>{const a=this._nativeModuleWrapper.subscribeToDeviceDisconnectedEvents().subscribe(c=>{c.sessionId===i&&(r.onDisconnect(i),a.unsubscribe())});return new o.TransportConnectedDevice({id:i,deviceModel:e,sendApdu:async(c,p=!1,v=-1)=>this._nativeModuleWrapper.sendApdu(i,c,p,v).catch(h=>(0,s.Left)(new b.SendApduError(h))),transport:this.getIdentifier(),type:"USB"})})).catch(t=>(0,s.Left)(new o.OpeningConnectionError(t)))}disconnect(r){return this._nativeModuleWrapper.disconnectDevice(r.connectedDevice.id).then(()=>(0,s.Right)(void 0)).catch(t=>(0,s.Left)(new o.DisconnectError(t)))}}0&&(module.exports={RNHidTransport});
1
+ "use strict";var d=Object.defineProperty;var D=Object.getOwnPropertyDescriptor;var _=Object.getOwnPropertyNames;var S=Object.prototype.hasOwnProperty;var T=(n,r)=>{for(var t in r)d(n,t,{get:r[t],enumerable:!0})},m=(n,r,t,i)=>{if(r&&typeof r=="object"||typeof r=="function")for(let e of _(r))!S.call(n,e)&&e!==t&&d(n,e,{get:()=>r[e],enumerable:!(i=D(r,e))||i.enumerable});return n};var f=n=>m(d({},"__esModule",{value:!0}),n);var M={};T(M,{RNHidTransport:()=>E});module.exports=f(M);var o=require("@ledgerhq/device-management-kit"),s=require("purify-ts"),g=require("rxjs"),l=require("../helpers/getObservableOfArraysNewItems"),u=require("../transport/rnHidTransportIdentifier"),b=require("./Errors");class E{constructor(r,t,i){this._isSupported=r;this._nativeModuleWrapper=t;this._loggerService=i("RNHidTransport"),this._nativeModuleWrapper.subscribeToTransportLogs().subscribe(e=>{const[a,c,p]=e,v={[o.LogLevel.Fatal]:this._loggerService.error.bind(this._loggerService),[o.LogLevel.Error]:this._loggerService.error.bind(this._loggerService),[o.LogLevel.Warning]:this._loggerService.warn.bind(this._loggerService),[o.LogLevel.Info]:this._loggerService.info.bind(this._loggerService),[o.LogLevel.Debug]:this._loggerService.debug.bind(this._loggerService)}[a];v(c,p)})}_loggerService;getIdentifier(){return u.TRANSPORT_IDENTIFIER}isSupported(){return this._isSupported}startDiscovering(){return new g.Observable(t=>{const i=(0,l.getObservableOfArraysNewItems)(this._nativeModuleWrapper.subscribeToDiscoveredDevicesEvents(),e=>e.id).subscribe(t);return this._nativeModuleWrapper.startScan().catch(e=>{t.error(e),this._loggerService.error("startDiscovering error",e)}),()=>i.unsubscribe()})}stopDiscovering(){this._nativeModuleWrapper.stopScan().catch(r=>{this._loggerService.error("stopDiscovering error",r)})}listenToAvailableDevices(){return new g.Observable(t=>{const i=this._nativeModuleWrapper.subscribeToDiscoveredDevicesEvents().subscribe(e=>{t.next(e)});return this._nativeModuleWrapper.startScan().catch(e=>{this._loggerService.error("startDiscovering error",e),t.error(e)}),()=>{i.unsubscribe(),this._nativeModuleWrapper.stopScan().catch(e=>{this._loggerService.error("stopDiscovering error",e)})}})}connect(r){return this._nativeModuleWrapper.connectDevice(r.deviceId).then(t=>t.map(({sessionId:i,transportDeviceModel:e})=>{const a=this._nativeModuleWrapper.subscribeToDeviceDisconnectedEvents().subscribe(c=>{c.sessionId===i&&(r.onDisconnect(i),a.unsubscribe())});return new o.TransportConnectedDevice({id:i,deviceModel:e,sendApdu:async(c,p=!1,v=-1)=>this._nativeModuleWrapper.sendApdu(i,c,p,v).catch(h=>(0,s.Left)(new b.HidTransportSendApduUnknownError(h))),transport:this.getIdentifier(),type:"USB"})})).catch(t=>(0,s.Left)(new o.OpeningConnectionError(t)))}disconnect(r){return this._nativeModuleWrapper.disconnectDevice(r.connectedDevice.id).then(()=>(0,s.Right)(void 0)).catch(t=>(0,s.Left)(new o.DisconnectError(t)))}}0&&(module.exports={RNHidTransport});
2
2
  //# sourceMappingURL=RNHidTransport.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/api/transport/RNHidTransport.ts"],
4
- "sourcesContent": ["import {\n type ConnectError,\n type DeviceId,\n DisconnectError,\n type DisconnectHandler,\n type DmkError,\n type LoggerPublisherService,\n LogLevel,\n OpeningConnectionError,\n type Transport,\n TransportConnectedDevice,\n type TransportDiscoveredDevice,\n type TransportIdentifier,\n} from \"@ledgerhq/device-management-kit\";\nimport { type Either, Left, Right } from \"purify-ts\";\nimport { Observable } from \"rxjs\";\n\nimport { getObservableOfArraysNewItems } from \"@api/helpers/getObservableOfArraysNewItems\";\nimport { TRANSPORT_IDENTIFIER } from \"@api/transport/rnHidTransportIdentifier\";\n\nimport { SendApduError } from \"./Errors\";\nimport { type NativeModuleWrapper } from \"./NativeModuleWrapper\";\n\nexport class RNHidTransport implements Transport {\n private _loggerService: LoggerPublisherService;\n\n constructor(\n private readonly _isSupported: boolean,\n private readonly _nativeModuleWrapper: NativeModuleWrapper,\n _loggerServiceFactory: (tag: string) => LoggerPublisherService,\n ) {\n this._loggerService = _loggerServiceFactory(\"RNHidTransport\");\n this._nativeModuleWrapper.subscribeToTransportLogs().subscribe((log) => {\n const [logLevel, message, options] = log;\n const logMethod = {\n [LogLevel.Fatal]: this._loggerService.error.bind(this._loggerService),\n [LogLevel.Error]: this._loggerService.error.bind(this._loggerService),\n [LogLevel.Warning]: this._loggerService.warn.bind(this._loggerService),\n [LogLevel.Info]: this._loggerService.info.bind(this._loggerService),\n [LogLevel.Debug]: this._loggerService.debug.bind(this._loggerService),\n }[logLevel];\n logMethod(message, options);\n });\n }\n\n getIdentifier(): TransportIdentifier {\n return TRANSPORT_IDENTIFIER;\n }\n\n isSupported(): boolean {\n return this._isSupported;\n }\n\n startDiscovering(): Observable<TransportDiscoveredDevice> {\n const observable = new Observable<TransportDiscoveredDevice>(\n (subscriber) => {\n const subscription = getObservableOfArraysNewItems(\n this._nativeModuleWrapper.subscribeToDiscoveredDevicesEvents(),\n (device) => device.id,\n ).subscribe(subscriber);\n\n this._nativeModuleWrapper.startScan().catch((error) => {\n subscriber.error(error);\n this._loggerService.error(\"startDiscovering error\", error);\n });\n return () => subscription.unsubscribe();\n },\n );\n return observable;\n }\n\n stopDiscovering(): void {\n this._nativeModuleWrapper.stopScan().catch((error) => {\n this._loggerService.error(\"stopDiscovering error\", error);\n });\n }\n\n listenToAvailableDevices(): Observable<TransportDiscoveredDevice[]> {\n /**\n * NB: here we need to define the unsubscribe logic as there is no\n * \"stopListeningToKnownDevices\" method.\n * That's why we create a new observable rather than returning the one\n * returned by subscribeToDiscoveredDevicesEvents.\n */\n const observable = new Observable<TransportDiscoveredDevice[]>(\n (subscriber) => {\n const subscription = this._nativeModuleWrapper\n .subscribeToDiscoveredDevicesEvents()\n .subscribe((devices) => {\n subscriber.next(devices);\n });\n this._nativeModuleWrapper.startScan().catch((error) => {\n this._loggerService.error(\"startDiscovering error\", error);\n subscriber.error(error);\n });\n return () => {\n subscription.unsubscribe();\n this._nativeModuleWrapper.stopScan().catch((error) => {\n this._loggerService.error(\"stopDiscovering error\", error);\n });\n };\n },\n );\n return observable;\n }\n\n connect(_params: {\n deviceId: DeviceId;\n onDisconnect: DisconnectHandler;\n }): Promise<Either<ConnectError, TransportConnectedDevice>> {\n return this._nativeModuleWrapper\n .connectDevice(_params.deviceId)\n .then((result) => {\n return result.map(\n ({ sessionId, transportDeviceModel: deviceModel }) => {\n const sub = this._nativeModuleWrapper\n .subscribeToDeviceDisconnectedEvents()\n .subscribe((device) => {\n if (device.sessionId === sessionId) {\n _params.onDisconnect(sessionId);\n sub.unsubscribe();\n }\n });\n\n return new TransportConnectedDevice({\n id: sessionId,\n deviceModel,\n sendApdu: async (\n apdu,\n triggersDisconnection = false,\n abortTimeout = -1,\n ) => {\n return this._nativeModuleWrapper\n .sendApdu(\n sessionId,\n apdu,\n triggersDisconnection,\n abortTimeout,\n )\n .catch((e) => Left(new SendApduError(e)));\n },\n transport: this.getIdentifier(),\n type: \"USB\",\n });\n },\n );\n })\n .catch((error) => {\n return Left(new OpeningConnectionError(error));\n });\n }\n\n disconnect(_params: {\n connectedDevice: TransportConnectedDevice;\n }): Promise<Either<DmkError, void>> {\n return this._nativeModuleWrapper\n .disconnectDevice(_params.connectedDevice.id)\n .then(() => Right(undefined))\n .catch((error) => {\n return Left(new DisconnectError(error));\n });\n }\n}\n"],
5
- "mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,oBAAAE,IAAA,eAAAC,EAAAH,GAAA,IAAAI,EAaO,2CACPC,EAAyC,qBACzCC,EAA2B,gBAE3BC,EAA8C,sDAC9CC,EAAqC,mDAErCC,EAA8B,oBAGvB,MAAMP,CAAoC,CAG/C,YACmBQ,EACAC,EACjBC,EACA,CAHiB,kBAAAF,EACA,0BAAAC,EAGjB,KAAK,eAAiBC,EAAsB,gBAAgB,EAC5D,KAAK,qBAAqB,yBAAyB,EAAE,UAAWC,GAAQ,CACtE,KAAM,CAACC,EAAUC,EAASC,CAAO,EAAIH,EAC/BI,EAAY,CAChB,CAAC,WAAS,KAAK,EAAG,KAAK,eAAe,MAAM,KAAK,KAAK,cAAc,EACpE,CAAC,WAAS,KAAK,EAAG,KAAK,eAAe,MAAM,KAAK,KAAK,cAAc,EACpE,CAAC,WAAS,OAAO,EAAG,KAAK,eAAe,KAAK,KAAK,KAAK,cAAc,EACrE,CAAC,WAAS,IAAI,EAAG,KAAK,eAAe,KAAK,KAAK,KAAK,cAAc,EAClE,CAAC,WAAS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AWP,GAAW,CACjBA,EAAO,YAAcK,IACvBF,EAAQ,aAAaE,CAAS,EAC9BE,EAAI,YAAY,EAEpB,CAAC,EAEH,OAAO,IAAI,2BAAyB,CAClC,GAAIF,EACJ,YAAAC,EACA,SAAU,MACRE,EACAC,EAAwB,GACxBC,EAAe,KAER,KAAK,qBACT,SACCL,EACAG,EACAC,EACAC,CACF,EACC,MAAOC,MAAM,QAAK,IAAI,gBAAcA,CAAC,CAAC,CAAC,EAE5C,UAAW,KAAK,cAAc,EAC9B,KAAM,KACR,CAAC,CACH,CACF,CACD,EACA,MAAOV,MACC,QAAK,IAAI,yBAAuBA,CAAK,CAAC,CAC9C,CACL,CAEA,WAAWE,EAEyB,CAClC,OAAO,KAAK,qBACT,iBAAiBA,EAAQ,gBAAgB,EAAE,EAC3C,KAAK,OAAM,SAAM,MAAS,CAAC,EAC3B,MAAOF,MACC,QAAK,IAAI,kBAAgBA,CAAK,CAAC,CACvC,CACL,CACF",
4
+ "sourcesContent": ["import {\n type ConnectError,\n type DeviceId,\n DisconnectError,\n type DisconnectHandler,\n type DmkError,\n type LoggerPublisherService,\n LogLevel,\n OpeningConnectionError,\n type Transport,\n TransportConnectedDevice,\n type TransportDiscoveredDevice,\n type TransportIdentifier,\n} from \"@ledgerhq/device-management-kit\";\nimport { type Either, Left, Right } from \"purify-ts\";\nimport { Observable } from \"rxjs\";\n\nimport { getObservableOfArraysNewItems } from \"@api/helpers/getObservableOfArraysNewItems\";\nimport { TRANSPORT_IDENTIFIER } from \"@api/transport/rnHidTransportIdentifier\";\n\nimport { HidTransportSendApduUnknownError } from \"./Errors\";\nimport { type NativeModuleWrapper } from \"./NativeModuleWrapper\";\n\nexport class RNHidTransport implements Transport {\n private _loggerService: LoggerPublisherService;\n\n constructor(\n private readonly _isSupported: boolean,\n private readonly _nativeModuleWrapper: NativeModuleWrapper,\n _loggerServiceFactory: (tag: string) => LoggerPublisherService,\n ) {\n this._loggerService = _loggerServiceFactory(\"RNHidTransport\");\n this._nativeModuleWrapper.subscribeToTransportLogs().subscribe((log) => {\n const [logLevel, message, options] = log;\n const logMethod = {\n [LogLevel.Fatal]: this._loggerService.error.bind(this._loggerService),\n [LogLevel.Error]: this._loggerService.error.bind(this._loggerService),\n [LogLevel.Warning]: this._loggerService.warn.bind(this._loggerService),\n [LogLevel.Info]: this._loggerService.info.bind(this._loggerService),\n [LogLevel.Debug]: this._loggerService.debug.bind(this._loggerService),\n }[logLevel];\n logMethod(message, options);\n });\n }\n\n getIdentifier(): TransportIdentifier {\n return TRANSPORT_IDENTIFIER;\n }\n\n isSupported(): boolean {\n return this._isSupported;\n }\n\n startDiscovering(): Observable<TransportDiscoveredDevice> {\n const observable = new Observable<TransportDiscoveredDevice>(\n (subscriber) => {\n const subscription = getObservableOfArraysNewItems(\n this._nativeModuleWrapper.subscribeToDiscoveredDevicesEvents(),\n (device) => device.id,\n ).subscribe(subscriber);\n\n this._nativeModuleWrapper.startScan().catch((error) => {\n subscriber.error(error);\n this._loggerService.error(\"startDiscovering error\", error);\n });\n return () => subscription.unsubscribe();\n },\n );\n return observable;\n }\n\n stopDiscovering(): void {\n this._nativeModuleWrapper.stopScan().catch((error) => {\n this._loggerService.error(\"stopDiscovering error\", error);\n });\n }\n\n listenToAvailableDevices(): Observable<TransportDiscoveredDevice[]> {\n /**\n * NB: here we need to define the unsubscribe logic as there is no\n * \"stopListeningToKnownDevices\" method.\n * That's why we create a new observable rather than returning the one\n * returned by subscribeToDiscoveredDevicesEvents.\n */\n const observable = new Observable<TransportDiscoveredDevice[]>(\n (subscriber) => {\n const subscription = this._nativeModuleWrapper\n .subscribeToDiscoveredDevicesEvents()\n .subscribe((devices) => {\n subscriber.next(devices);\n });\n this._nativeModuleWrapper.startScan().catch((error) => {\n this._loggerService.error(\"startDiscovering error\", error);\n subscriber.error(error);\n });\n return () => {\n subscription.unsubscribe();\n this._nativeModuleWrapper.stopScan().catch((error) => {\n this._loggerService.error(\"stopDiscovering error\", error);\n });\n };\n },\n );\n return observable;\n }\n\n connect(_params: {\n deviceId: DeviceId;\n onDisconnect: DisconnectHandler;\n }): Promise<Either<ConnectError, TransportConnectedDevice>> {\n return this._nativeModuleWrapper\n .connectDevice(_params.deviceId)\n .then((result) => {\n return result.map(\n ({ sessionId, transportDeviceModel: deviceModel }) => {\n const sub = this._nativeModuleWrapper\n .subscribeToDeviceDisconnectedEvents()\n .subscribe((device) => {\n if (device.sessionId === sessionId) {\n _params.onDisconnect(sessionId);\n sub.unsubscribe();\n }\n });\n\n return new TransportConnectedDevice({\n id: sessionId,\n deviceModel,\n sendApdu: async (\n apdu,\n triggersDisconnection = false,\n abortTimeout = -1,\n ) => {\n return this._nativeModuleWrapper\n .sendApdu(\n sessionId,\n apdu,\n triggersDisconnection,\n abortTimeout,\n )\n .catch((e) => Left(new HidTransportSendApduUnknownError(e)));\n },\n transport: this.getIdentifier(),\n type: \"USB\",\n });\n },\n );\n })\n .catch((error) => {\n return Left(new OpeningConnectionError(error));\n });\n }\n\n disconnect(_params: {\n connectedDevice: TransportConnectedDevice;\n }): Promise<Either<DmkError, void>> {\n return this._nativeModuleWrapper\n .disconnectDevice(_params.connectedDevice.id)\n .then(() => Right(undefined))\n .catch((error) => {\n return Left(new DisconnectError(error));\n });\n }\n}\n"],
5
+ "mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,oBAAAE,IAAA,eAAAC,EAAAH,GAAA,IAAAI,EAaO,2CACPC,EAAyC,qBACzCC,EAA2B,gBAE3BC,EAA8C,sDAC9CC,EAAqC,mDAErCC,EAAiD,oBAG1C,MAAMP,CAAoC,CAG/C,YACmBQ,EACAC,EACjBC,EACA,CAHiB,kBAAAF,EACA,0BAAAC,EAGjB,KAAK,eAAiBC,EAAsB,gBAAgB,EAC5D,KAAK,qBAAqB,yBAAyB,EAAE,UAAWC,GAAQ,CACtE,KAAM,CAACC,EAAUC,EAASC,CAAO,EAAIH,EAC/BI,EAAY,CAChB,CAAC,WAAS,KAAK,EAAG,KAAK,e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wBAAyBA,CAAK,CAC1D,CAAC,CACH,CACF,CACF,CAEF,CAEA,QAAQE,EAGoD,CAC1D,OAAO,KAAK,qBACT,cAAcA,EAAQ,QAAQ,EAC9B,KAAMC,GACEA,EAAO,IACZ,CAAC,CAAE,UAAAC,EAAW,qBAAsBC,CAAY,IAAM,CACpD,MAAMC,EAAM,KAAK,qBACd,oCAAoC,EACpC,UAAWP,GAAW,CACjBA,EAAO,YAAcK,IACvBF,EAAQ,aAAaE,CAAS,EAC9BE,EAAI,YAAY,EAEpB,CAAC,EAEH,OAAO,IAAI,2BAAyB,CAClC,GAAIF,EACJ,YAAAC,EACA,SAAU,MACRE,EACAC,EAAwB,GACxBC,EAAe,KAER,KAAK,qBACT,SACCL,EACAG,EACAC,EACAC,CACF,EACC,MAAOC,MAAM,QAAK,IAAI,mCAAiCA,CAAC,CAAC,CAAC,EAE/D,UAAW,KAAK,cAAc,EAC9B,KAAM,KACR,CAAC,CACH,CACF,CACD,EACA,MAAOV,MACC,QAAK,IAAI,yBAAuBA,CAAK,CAAC,CAC9C,CACL,CAEA,WAAWE,EAEyB,CAClC,OAAO,KAAK,qBACT,iBAAiBA,EAAQ,gBAAgB,EAAE,EAC3C,KAAK,OAAM,SAAM,MAAS,CAAC,EAC3B,MAAOF,MACC,QAAK,IAAI,kBAAgBA,CAAK,CAAC,CACvC,CACL,CACF",
6
6
  "names": ["RNHidTransport_exports", "__export", "RNHidTransport", "__toCommonJS", "import_device_management_kit", "import_purify_ts", "import_rxjs", "import_getObservableOfArraysNewItems", "import_rnHidTransportIdentifier", "import_Errors", "_isSupported", "_nativeModuleWrapper", "_loggerServiceFactory", "log", "logLevel", "message", "options", "logMethod", "subscriber", "subscription", "device", "error", "devices", "_params", "result", "sessionId", "deviceModel", "sub", "apdu", "triggersDisconnection", "abortTimeout", "e"]
7
7
  }
@@ -1,2 +1,2 @@
1
- "use strict";var l=require("@ledgerhq/device-management-kit"),a=require("purify-ts/Either"),T=require("rxjs"),h=require("../transport/rnHidTransportIdentifier"),E=require("./Errors"),s=require("./RNHidTransport");const M=new l.StaticDeviceModelDataSource,y=(p,D)=>({id:p,transport:h.TRANSPORT_IDENTIFIER,name:D,deviceModel:M.getDeviceModel({id:D})}),v=y("1",l.DeviceModelId.NANO_S),g=y("2",l.DeviceModelId.NANO_X),x=y("3",l.DeviceModelId.NANO_S);describe("RNHidTransport",()=>{let p,D,R,n;const S={error:vi.fn(),warn:vi.fn(),info:vi.fn(),debug:vi.fn(),subscribers:[]},c=vi.fn(()=>S),f=vi.fn(),w=vi.fn(),u=vi.fn(),k=vi.fn(),m=vi.fn();beforeEach(()=>{p=new T.Subject,D=new T.Subject,R=new T.Subject,vi.clearAllMocks(),f.mockResolvedValue(void 0),w.mockResolvedValue(void 0),u.mockResolvedValue(void 0),k.mockResolvedValue(void 0),m.mockResolvedValue(void 0),n={startScan:f,stopScan:w,subscribeToDiscoveredDevicesEvents:vi.fn(()=>p.asObservable()),subscribeToDeviceDisconnectedEvents:vi.fn(()=>D.asObservable()),subscribeToTransportLogs:vi.fn(()=>R.asObservable()),connectDevice:u,disconnectDevice:k,sendApdu:m}}),test("getIdentifier returns TRANSPORT_IDENTIFIER",()=>{const t=new s.RNHidTransport(!0,n,c);expect(t.getIdentifier()).toBe(h.TRANSPORT_IDENTIFIER)}),describe("isSupported returns the provided support flag",()=>{test("supported",()=>{const t=new s.RNHidTransport(!0,n,c);expect(t.isSupported()).toBe(!0)}),test("not supported",()=>{const t=new s.RNHidTransport(!1,n,c);expect(t.isSupported()).toBe(!1)})}),test("constructor subscribes to transport logs and calls logger methods",()=>{new s.RNHidTransport(!0,n,c);const t=[l.LogLevel.Info,"Test message",{tag:"TestTag",data:{key:"value"},timestamp:123456789}];R.next(t),expect(S.info).toHaveBeenCalledWith("Test message",{tag:"TestTag",data:{key:"value"},timestamp:123456789})}),describe("startDiscovering",()=>{it("calls startScan",()=>{new s.RNHidTransport(!0,n,c).startDiscovering().subscribe(),expect(f).toHaveBeenCalled()}),it("emits new discovered devices",()=>new Promise((t,e)=>{const r=new s.RNHidTransport(!0,n,c),o=[];r.startDiscovering().subscribe({next:i=>{if(o.push(i),o.length===3)try{expect(o).toEqual([v,g,x]),t()}catch(d){e(d)}},error:e}),p.next([v]),p.next([v,g]),p.next([v,g,x])})),it("propagates startScan error",()=>new Promise((t,e)=>{const r=new s.RNHidTransport(!0,n,c),o=new Error("scan failed");f.mockRejectedValueOnce(o),r.startDiscovering().subscribe({next:()=>{},error:i=>{try{expect(i).toBe(o),t()}catch(d){e(d)}}})}))}),describe("stopDiscovering",()=>{it("calls stopScan",async()=>{await new s.RNHidTransport(!0,n,c).stopDiscovering(),expect(n.stopScan).toHaveBeenCalled()}),it("logs error when stopScan fails",async()=>{const t=new s.RNHidTransport(!0,n,c),e=new Error("stop failed");w.mockRejectedValueOnce(e),await t.stopDiscovering(),expect(S.error).toHaveBeenCalledWith("stopDiscovering error",e)})}),describe("listenToKnownDevices",()=>{it("emits arrays of discovered devices",()=>new Promise((t,e)=>{const r=new s.RNHidTransport(!0,n,c),o=[];r.listenToAvailableDevices().subscribe({next:i=>{if(o.push(i),o.length===2)try{expect(o).toEqual([[v,g],[v,x]]),t()}catch(d){e(d)}},complete:()=>{e("should not complete")},error:e}),p.next([v,g]),p.next([v,x])})),it("propagates startScan error",()=>new Promise((t,e)=>{const r=new s.RNHidTransport(!0,n,c),o=new Error("start scan failed");f.mockRejectedValueOnce(o),r.listenToAvailableDevices().subscribe({error:i=>{try{expect(i).toBe(o),t()}catch(d){e(d)}}})})),it("calls stopScan on unsubscribe",()=>{const t=new s.RNHidTransport(!0,n,c),e=new Error("stop scan failed");w.mockRejectedValueOnce(e),t.listenToAvailableDevices().subscribe({}).unsubscribe(),expect(w).toHaveBeenCalled()})}),describe("connect",()=>{describe("connection successful",()=>{it("should return a Right(TransportConnectedDevice) on successful connection",async()=>{const t={model:"TestModel"},e="session123";u.mockResolvedValueOnce((0,a.Right)({sessionId:e,transportDeviceModel:t}));const o=await new s.RNHidTransport(!0,n,c).connect({deviceId:e,onDisconnect:vi.fn()});expect(o.isRight()).toBe(!0);const i=o.extract();expect(i).toBeInstanceOf(l.TransportConnectedDevice),expect(i.id).toBe(e),expect(i.deviceModel).toEqual(t),expect(i.transport).toBe(h.TRANSPORT_IDENTIFIER),expect(i.type).toBe("USB")}),test("should trigger onDisconnect when a matching disconnect event is emitted",async()=>{const t={model:"TestModel"},e="session123";u.mockResolvedValueOnce((0,a.Right)({sessionId:e,transportDeviceModel:t}));const r=new s.RNHidTransport(!0,n,c),o=vi.fn();await r.connect({deviceId:e,onDisconnect:o}),D.next({sessionId:e}),expect(o).toHaveBeenCalledWith(e)}),test("should handle sendApdu success (Right)",async()=>{const t={model:"TestModel"},e="session123";u.mockResolvedValueOnce((0,a.Right)({sessionId:e,transportDeviceModel:t}));const i=(await new s.RNHidTransport(!0,n,c).connect({deviceId:e,onDisconnect:vi.fn()})).extract();m.mockResolvedValueOnce((0,a.Right)("apduResponse"));const d=new Uint8Array([1,2,3]),b=await i.sendApdu(d,!1,0);expect(n.sendApdu).toHaveBeenCalledWith(e,d,!1,0),expect(b).toEqual((0,a.Right)("apduResponse"))}),test("should handle sendApdu failure (Left)",async()=>{const t={model:"TestModel"},e="session123";u.mockResolvedValueOnce((0,a.Right)({sessionId:e,transportDeviceModel:t}));const i=(await new s.RNHidTransport(!0,n,c).connect({deviceId:e,onDisconnect:vi.fn()})).extract();m.mockResolvedValueOnce((0,a.Left)("some error"));const d=new Uint8Array([1,2,3]),b=await i.sendApdu(d);expect(b).toEqual((0,a.Left)("some error"))}),test("should handle sendApdu rejection",async()=>{const t={model:"TestModel"},e="session123";u.mockResolvedValueOnce((0,a.Right)({sessionId:e,transportDeviceModel:t}));const i=(await new s.RNHidTransport(!0,n,c).connect({deviceId:e,onDisconnect:vi.fn()})).extract(),d=new Error("apdu failed");m.mockRejectedValueOnce(d);const b=await i.sendApdu(new Uint8Array([]));expect(b).toEqual((0,a.Left)(new E.SendApduError(d)))})}),describe("connection failure",()=>{test("should return a Left when nativeModuleWrapper.connectDevice resolves a Left",async()=>{const t=new s.RNHidTransport(!0,n,c),e=(0,a.Left)(new l.OpeningConnectionError("connection failed"));u.mockResolvedValueOnce(e);const r=await t.connect({deviceId:"any",onDisconnect:vi.fn()});expect(r).toEqual(e)}),test("should return a Left when nativeModuleWrapper.connectDevice rejects",async()=>{const t=new Error("connection failed"),e=new s.RNHidTransport(!0,n,c);u.mockRejectedValueOnce(t);const r=await e.connect({deviceId:"any",onDisconnect:vi.fn()});expect(r).toEqual((0,a.Left)(new l.OpeningConnectionError(t)))})})}),describe("disconnect",()=>{it("returns Right on successful disconnect",async()=>{const e=await new s.RNHidTransport(!0,n,c).disconnect({connectedDevice:{id:"session789"}});expect(n.disconnectDevice).toHaveBeenCalledWith("session789"),expect(e).toEqual((0,a.Right)(void 0))}),it("returns Left on disconnect failure",async()=>{const t=new s.RNHidTransport(!0,n,c),e=new Error("disconnect failed");k.mockRejectedValueOnce(e);const r=await t.disconnect({connectedDevice:{id:"session000"}});expect(r).toEqual((0,a.Left)(new l.DisconnectError(e)))})})});
1
+ "use strict";var l=require("@ledgerhq/device-management-kit"),a=require("purify-ts/Either"),x=require("rxjs"),h=require("../transport/rnHidTransportIdentifier"),E=require("./Errors"),s=require("./RNHidTransport");const M=new l.StaticDeviceModelDataSource,y=(p,D)=>({id:p,transport:h.TRANSPORT_IDENTIFIER,name:D,deviceModel:M.getDeviceModel({id:D})}),v=y("1",l.DeviceModelId.NANO_S),g=y("2",l.DeviceModelId.NANO_X),T=y("3",l.DeviceModelId.NANO_S);describe("RNHidTransport",()=>{let p,D,R,n;const S={error:vi.fn(),warn:vi.fn(),info:vi.fn(),debug:vi.fn(),subscribers:[]},c=vi.fn(()=>S),f=vi.fn(),w=vi.fn(),u=vi.fn(),k=vi.fn(),m=vi.fn();beforeEach(()=>{p=new x.Subject,D=new x.Subject,R=new x.Subject,vi.clearAllMocks(),f.mockResolvedValue(void 0),w.mockResolvedValue(void 0),u.mockResolvedValue(void 0),k.mockResolvedValue(void 0),m.mockResolvedValue(void 0),n={startScan:f,stopScan:w,subscribeToDiscoveredDevicesEvents:vi.fn(()=>p.asObservable()),subscribeToDeviceDisconnectedEvents:vi.fn(()=>D.asObservable()),subscribeToTransportLogs:vi.fn(()=>R.asObservable()),connectDevice:u,disconnectDevice:k,sendApdu:m}}),test("getIdentifier returns TRANSPORT_IDENTIFIER",()=>{const t=new s.RNHidTransport(!0,n,c);expect(t.getIdentifier()).toBe(h.TRANSPORT_IDENTIFIER)}),describe("isSupported returns the provided support flag",()=>{test("supported",()=>{const t=new s.RNHidTransport(!0,n,c);expect(t.isSupported()).toBe(!0)}),test("not supported",()=>{const t=new s.RNHidTransport(!1,n,c);expect(t.isSupported()).toBe(!1)})}),test("constructor subscribes to transport logs and calls logger methods",()=>{new s.RNHidTransport(!0,n,c);const t=[l.LogLevel.Info,"Test message",{tag:"TestTag",data:{key:"value"},timestamp:123456789}];R.next(t),expect(S.info).toHaveBeenCalledWith("Test message",{tag:"TestTag",data:{key:"value"},timestamp:123456789})}),describe("startDiscovering",()=>{it("calls startScan",()=>{new s.RNHidTransport(!0,n,c).startDiscovering().subscribe(),expect(f).toHaveBeenCalled()}),it("emits new discovered devices",()=>new Promise((t,e)=>{const r=new s.RNHidTransport(!0,n,c),o=[];r.startDiscovering().subscribe({next:i=>{if(o.push(i),o.length===3)try{expect(o).toEqual([v,g,T]),t()}catch(d){e(d)}},error:e}),p.next([v]),p.next([v,g]),p.next([v,g,T])})),it("propagates startScan error",()=>new Promise((t,e)=>{const r=new s.RNHidTransport(!0,n,c),o=new Error("scan failed");f.mockRejectedValueOnce(o),r.startDiscovering().subscribe({next:()=>{},error:i=>{try{expect(i).toBe(o),t()}catch(d){e(d)}}})}))}),describe("stopDiscovering",()=>{it("calls stopScan",async()=>{await new s.RNHidTransport(!0,n,c).stopDiscovering(),expect(n.stopScan).toHaveBeenCalled()}),it("logs error when stopScan fails",async()=>{const t=new s.RNHidTransport(!0,n,c),e=new Error("stop failed");w.mockRejectedValueOnce(e),await t.stopDiscovering(),expect(S.error).toHaveBeenCalledWith("stopDiscovering error",e)})}),describe("listenToKnownDevices",()=>{it("emits arrays of discovered devices",()=>new Promise((t,e)=>{const r=new s.RNHidTransport(!0,n,c),o=[];r.listenToAvailableDevices().subscribe({next:i=>{if(o.push(i),o.length===2)try{expect(o).toEqual([[v,g],[v,T]]),t()}catch(d){e(d)}},complete:()=>{e("should not complete")},error:e}),p.next([v,g]),p.next([v,T])})),it("propagates startScan error",()=>new Promise((t,e)=>{const r=new s.RNHidTransport(!0,n,c),o=new Error("start scan failed");f.mockRejectedValueOnce(o),r.listenToAvailableDevices().subscribe({error:i=>{try{expect(i).toBe(o),t()}catch(d){e(d)}}})})),it("calls stopScan on unsubscribe",()=>{const t=new s.RNHidTransport(!0,n,c),e=new Error("stop scan failed");w.mockRejectedValueOnce(e),t.listenToAvailableDevices().subscribe({}).unsubscribe(),expect(w).toHaveBeenCalled()})}),describe("connect",()=>{describe("connection successful",()=>{it("should return a Right(TransportConnectedDevice) on successful connection",async()=>{const t={model:"TestModel"},e="session123";u.mockResolvedValueOnce((0,a.Right)({sessionId:e,transportDeviceModel:t}));const o=await new s.RNHidTransport(!0,n,c).connect({deviceId:e,onDisconnect:vi.fn()});expect(o.isRight()).toBe(!0);const i=o.extract();expect(i).toBeInstanceOf(l.TransportConnectedDevice),expect(i.id).toBe(e),expect(i.deviceModel).toEqual(t),expect(i.transport).toBe(h.TRANSPORT_IDENTIFIER),expect(i.type).toBe("USB")}),test("should trigger onDisconnect when a matching disconnect event is emitted",async()=>{const t={model:"TestModel"},e="session123";u.mockResolvedValueOnce((0,a.Right)({sessionId:e,transportDeviceModel:t}));const r=new s.RNHidTransport(!0,n,c),o=vi.fn();await r.connect({deviceId:e,onDisconnect:o}),D.next({sessionId:e}),expect(o).toHaveBeenCalledWith(e)}),test("should handle sendApdu success (Right)",async()=>{const t={model:"TestModel"},e="session123";u.mockResolvedValueOnce((0,a.Right)({sessionId:e,transportDeviceModel:t}));const i=(await new s.RNHidTransport(!0,n,c).connect({deviceId:e,onDisconnect:vi.fn()})).extract();m.mockResolvedValueOnce((0,a.Right)("apduResponse"));const d=new Uint8Array([1,2,3]),b=await i.sendApdu(d,!1,0);expect(n.sendApdu).toHaveBeenCalledWith(e,d,!1,0),expect(b).toEqual((0,a.Right)("apduResponse"))}),test("should handle sendApdu failure (Left)",async()=>{const t={model:"TestModel"},e="session123";u.mockResolvedValueOnce((0,a.Right)({sessionId:e,transportDeviceModel:t}));const i=(await new s.RNHidTransport(!0,n,c).connect({deviceId:e,onDisconnect:vi.fn()})).extract();m.mockResolvedValueOnce((0,a.Left)("some error"));const d=new Uint8Array([1,2,3]),b=await i.sendApdu(d);expect(b).toEqual((0,a.Left)("some error"))}),test("should handle sendApdu rejection",async()=>{const t={model:"TestModel"},e="session123";u.mockResolvedValueOnce((0,a.Right)({sessionId:e,transportDeviceModel:t}));const i=(await new s.RNHidTransport(!0,n,c).connect({deviceId:e,onDisconnect:vi.fn()})).extract(),d=new Error("apdu failed");m.mockRejectedValueOnce(d);const b=await i.sendApdu(new Uint8Array([]));expect(b).toEqual((0,a.Left)(new E.HidTransportSendApduUnknownError(d)))})}),describe("connection failure",()=>{test("should return a Left when nativeModuleWrapper.connectDevice resolves a Left",async()=>{const t=new s.RNHidTransport(!0,n,c),e=(0,a.Left)(new l.OpeningConnectionError("connection failed"));u.mockResolvedValueOnce(e);const r=await t.connect({deviceId:"any",onDisconnect:vi.fn()});expect(r).toEqual(e)}),test("should return a Left when nativeModuleWrapper.connectDevice rejects",async()=>{const t=new Error("connection failed"),e=new s.RNHidTransport(!0,n,c);u.mockRejectedValueOnce(t);const r=await e.connect({deviceId:"any",onDisconnect:vi.fn()});expect(r).toEqual((0,a.Left)(new l.OpeningConnectionError(t)))})})}),describe("disconnect",()=>{it("returns Right on successful disconnect",async()=>{const e=await new s.RNHidTransport(!0,n,c).disconnect({connectedDevice:{id:"session789"}});expect(n.disconnectDevice).toHaveBeenCalledWith("session789"),expect(e).toEqual((0,a.Right)(void 0))}),it("returns Left on disconnect failure",async()=>{const t=new s.RNHidTransport(!0,n,c),e=new Error("disconnect failed");k.mockRejectedValueOnce(e);const r=await t.disconnect({connectedDevice:{id:"session000"}});expect(r).toEqual((0,a.Left)(new l.DisconnectError(e)))})})});
2
2
  //# sourceMappingURL=RNHidTransport.test.js.map