@ledgerhq/device-management-kit 0.0.0-hid-candidate-4-20250528125313 → 0.0.0-io-revamp-20250618083854

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 (169) hide show
  1. package/lib/cjs/src/api/apdu/utils/ByteArrayBuilder.js +1 -1
  2. package/lib/cjs/src/api/apdu/utils/ByteArrayBuilder.js.map +3 -3
  3. package/lib/cjs/src/api/apdu/utils/ByteArrayBuilder.test.js +1 -1
  4. package/lib/cjs/src/api/apdu/utils/ByteArrayBuilder.test.js.map +2 -2
  5. package/lib/cjs/src/api/command/utils/CommandUtils.js +1 -1
  6. package/lib/cjs/src/api/command/utils/CommandUtils.js.map +2 -2
  7. package/lib/cjs/src/api/command/utils/CommandUtils.test.js +1 -1
  8. package/lib/cjs/src/api/command/utils/CommandUtils.test.js.map +2 -2
  9. package/lib/cjs/src/api/device-action/model/UserInteractionRequired.js +1 -1
  10. package/lib/cjs/src/api/device-action/model/UserInteractionRequired.js.map +2 -2
  11. package/lib/cjs/src/api/device-action/os/Errors.js +1 -1
  12. package/lib/cjs/src/api/device-action/os/Errors.js.map +3 -3
  13. package/lib/cjs/src/api/device-action/os/GetDeviceMetadata/GetDeviceMetadataDeviceAction.js +1 -1
  14. package/lib/cjs/src/api/device-action/os/GetDeviceMetadata/GetDeviceMetadataDeviceAction.js.map +2 -2
  15. package/lib/cjs/src/api/device-action/os/GetDeviceMetadata/types.js.map +1 -1
  16. package/lib/cjs/src/api/device-action/os/InstallOrUpdateApps/InstallOrUpdateAppsDeviceAction.js +1 -1
  17. package/lib/cjs/src/api/device-action/os/InstallOrUpdateApps/InstallOrUpdateAppsDeviceAction.js.map +2 -2
  18. package/lib/cjs/src/api/device-action/os/InstallOrUpdateApps/types.js +1 -1
  19. package/lib/cjs/src/api/device-action/os/InstallOrUpdateApps/types.js.map +1 -1
  20. package/lib/cjs/src/api/device-action/os/OpenAppDeviceAction/OpenAppDeviceAction.js +1 -1
  21. package/lib/cjs/src/api/device-action/os/OpenAppDeviceAction/OpenAppDeviceAction.js.map +2 -2
  22. package/lib/cjs/src/api/device-action/os/OpenAppDeviceAction/OpenAppDeviceAction.test.js +1 -1
  23. package/lib/cjs/src/api/device-action/os/OpenAppDeviceAction/OpenAppDeviceAction.test.js.map +2 -2
  24. package/lib/cjs/src/api/device-action/task/BuildAppsInstallPlanTask.js +1 -1
  25. package/lib/cjs/src/api/device-action/task/BuildAppsInstallPlanTask.js.map +2 -2
  26. package/lib/cjs/src/api/device-action/task/BuildAppsInstallPlanTask.test.js +1 -1
  27. package/lib/cjs/src/api/device-action/task/BuildAppsInstallPlanTask.test.js.map +2 -2
  28. package/lib/cjs/src/api/index.js +1 -1
  29. package/lib/cjs/src/api/index.js.map +2 -2
  30. package/lib/cjs/src/api/secure-channel/device-action/GenuineCheck/GenuineCheckDeviceAction.js +1 -1
  31. package/lib/cjs/src/api/secure-channel/device-action/GenuineCheck/GenuineCheckDeviceAction.js.map +2 -2
  32. package/lib/cjs/src/api/secure-channel/device-action/GenuineCheck/types.js.map +1 -1
  33. package/lib/cjs/src/api/secure-channel/device-action/InstallApp/InstallAppDeviceAction.js +1 -1
  34. package/lib/cjs/src/api/secure-channel/device-action/InstallApp/InstallAppDeviceAction.js.map +2 -2
  35. package/lib/cjs/src/api/secure-channel/device-action/InstallApp/types.js +1 -1
  36. package/lib/cjs/src/api/secure-channel/device-action/InstallApp/types.js.map +1 -1
  37. package/lib/cjs/src/api/secure-channel/device-action/ListInstalledApps/ListInstalledAppsDeviceAction.js +1 -1
  38. package/lib/cjs/src/api/secure-channel/device-action/ListInstalledApps/ListInstalledAppsDeviceAction.js.map +2 -2
  39. package/lib/cjs/src/api/secure-channel/device-action/ListInstalledApps/types.js +1 -1
  40. package/lib/cjs/src/api/secure-channel/device-action/ListInstalledApps/types.js.map +2 -2
  41. package/lib/cjs/src/api/secure-channel/device-action/UninstallApp/UninstallAppDeviceAction.js +1 -1
  42. package/lib/cjs/src/api/secure-channel/device-action/UninstallApp/UninstallAppDeviceAction.js.map +2 -2
  43. package/lib/cjs/src/api/secure-channel/device-action/UninstallApp/types.js +1 -1
  44. package/lib/cjs/src/api/secure-channel/device-action/UninstallApp/types.js.map +1 -1
  45. package/lib/cjs/src/api/secure-channel/task/ConnectToSecureChannelTask.js +1 -1
  46. package/lib/cjs/src/api/secure-channel/task/ConnectToSecureChannelTask.js.map +3 -3
  47. package/lib/cjs/src/api/secure-channel/task/ConnectToSecureChannelTask.test.js +1 -1
  48. package/lib/cjs/src/api/secure-channel/task/ConnectToSecureChannelTask.test.js.map +3 -3
  49. package/lib/cjs/src/api/secure-channel/task/types.js +1 -1
  50. package/lib/cjs/src/api/secure-channel/task/types.js.map +2 -2
  51. package/lib/cjs/src/api/secure-channel/utils.js +1 -1
  52. package/lib/cjs/src/api/secure-channel/utils.js.map +3 -3
  53. package/lib/cjs/src/api/secure-channel/utils.test.js +1 -1
  54. package/lib/cjs/src/api/secure-channel/utils.test.js.map +3 -3
  55. package/lib/cjs/src/api/transport/model/DeviceConnectionStateMachine.js +1 -1
  56. package/lib/cjs/src/api/transport/model/DeviceConnectionStateMachine.js.map +3 -3
  57. package/lib/cjs/src/api/transport/model/DeviceConnectionStateMachine.test.js +2 -0
  58. package/lib/cjs/src/api/transport/model/DeviceConnectionStateMachine.test.js.map +7 -0
  59. package/lib/cjs/src/api/transport/model/Errors.js +1 -1
  60. package/lib/cjs/src/api/transport/model/Errors.js.map +3 -3
  61. package/lib/cjs/src/internal/secure-channel/model/Errors.js +1 -1
  62. package/lib/cjs/src/internal/secure-channel/model/Errors.js.map +3 -3
  63. package/lib/cjs/src/internal/send/use-case/SendApduUseCase.js +1 -1
  64. package/lib/cjs/src/internal/send/use-case/SendApduUseCase.js.map +3 -3
  65. package/lib/esm/src/api/apdu/utils/ByteArrayBuilder.js +1 -1
  66. package/lib/esm/src/api/apdu/utils/ByteArrayBuilder.js.map +3 -3
  67. package/lib/esm/src/api/apdu/utils/ByteArrayBuilder.test.js +1 -1
  68. package/lib/esm/src/api/apdu/utils/ByteArrayBuilder.test.js.map +2 -2
  69. package/lib/esm/src/api/command/utils/CommandUtils.js +1 -1
  70. package/lib/esm/src/api/command/utils/CommandUtils.js.map +3 -3
  71. package/lib/esm/src/api/command/utils/CommandUtils.test.js +1 -1
  72. package/lib/esm/src/api/command/utils/CommandUtils.test.js.map +2 -2
  73. package/lib/esm/src/api/device-action/model/UserInteractionRequired.js +1 -1
  74. package/lib/esm/src/api/device-action/model/UserInteractionRequired.js.map +2 -2
  75. package/lib/esm/src/api/device-action/os/Errors.js +1 -1
  76. package/lib/esm/src/api/device-action/os/Errors.js.map +3 -3
  77. package/lib/esm/src/api/device-action/os/GetDeviceMetadata/GetDeviceMetadataDeviceAction.js +1 -1
  78. package/lib/esm/src/api/device-action/os/GetDeviceMetadata/GetDeviceMetadataDeviceAction.js.map +2 -2
  79. package/lib/esm/src/api/device-action/os/InstallOrUpdateApps/InstallOrUpdateAppsDeviceAction.js +1 -1
  80. package/lib/esm/src/api/device-action/os/InstallOrUpdateApps/InstallOrUpdateAppsDeviceAction.js.map +2 -2
  81. package/lib/esm/src/api/device-action/os/OpenAppDeviceAction/OpenAppDeviceAction.js +1 -1
  82. package/lib/esm/src/api/device-action/os/OpenAppDeviceAction/OpenAppDeviceAction.js.map +3 -3
  83. package/lib/esm/src/api/device-action/os/OpenAppDeviceAction/OpenAppDeviceAction.test.js +1 -1
  84. package/lib/esm/src/api/device-action/os/OpenAppDeviceAction/OpenAppDeviceAction.test.js.map +3 -3
  85. package/lib/esm/src/api/device-action/task/BuildAppsInstallPlanTask.js +1 -1
  86. package/lib/esm/src/api/device-action/task/BuildAppsInstallPlanTask.js.map +3 -3
  87. package/lib/esm/src/api/device-action/task/BuildAppsInstallPlanTask.test.js +1 -1
  88. package/lib/esm/src/api/device-action/task/BuildAppsInstallPlanTask.test.js.map +3 -3
  89. package/lib/esm/src/api/index.js +1 -1
  90. package/lib/esm/src/api/index.js.map +3 -3
  91. package/lib/esm/src/api/secure-channel/device-action/GenuineCheck/GenuineCheckDeviceAction.js +1 -1
  92. package/lib/esm/src/api/secure-channel/device-action/GenuineCheck/GenuineCheckDeviceAction.js.map +2 -2
  93. package/lib/esm/src/api/secure-channel/device-action/InstallApp/InstallAppDeviceAction.js +1 -1
  94. package/lib/esm/src/api/secure-channel/device-action/InstallApp/InstallAppDeviceAction.js.map +2 -2
  95. package/lib/esm/src/api/secure-channel/device-action/ListInstalledApps/ListInstalledAppsDeviceAction.js +1 -1
  96. package/lib/esm/src/api/secure-channel/device-action/ListInstalledApps/ListInstalledAppsDeviceAction.js.map +2 -2
  97. package/lib/esm/src/api/secure-channel/device-action/ListInstalledApps/types.js +1 -1
  98. package/lib/esm/src/api/secure-channel/device-action/ListInstalledApps/types.js.map +2 -2
  99. package/lib/esm/src/api/secure-channel/device-action/UninstallApp/UninstallAppDeviceAction.js +1 -1
  100. package/lib/esm/src/api/secure-channel/device-action/UninstallApp/UninstallAppDeviceAction.js.map +2 -2
  101. package/lib/esm/src/api/secure-channel/task/ConnectToSecureChannelTask.js +1 -1
  102. package/lib/esm/src/api/secure-channel/task/ConnectToSecureChannelTask.js.map +3 -3
  103. package/lib/esm/src/api/secure-channel/task/ConnectToSecureChannelTask.test.js +1 -1
  104. package/lib/esm/src/api/secure-channel/task/ConnectToSecureChannelTask.test.js.map +3 -3
  105. package/lib/esm/src/api/secure-channel/task/types.js +1 -1
  106. package/lib/esm/src/api/secure-channel/task/types.js.map +2 -2
  107. package/lib/esm/src/api/secure-channel/utils.js +1 -1
  108. package/lib/esm/src/api/secure-channel/utils.js.map +3 -3
  109. package/lib/esm/src/api/secure-channel/utils.test.js +1 -1
  110. package/lib/esm/src/api/secure-channel/utils.test.js.map +3 -3
  111. package/lib/esm/src/api/transport/model/DeviceConnectionStateMachine.js +1 -1
  112. package/lib/esm/src/api/transport/model/DeviceConnectionStateMachine.js.map +3 -3
  113. package/lib/esm/src/api/transport/model/DeviceConnectionStateMachine.test.js +2 -0
  114. package/lib/esm/src/api/transport/model/DeviceConnectionStateMachine.test.js.map +7 -0
  115. package/lib/esm/src/api/transport/model/Errors.js +1 -1
  116. package/lib/esm/src/api/transport/model/Errors.js.map +3 -3
  117. package/lib/esm/src/internal/secure-channel/model/Errors.js +1 -1
  118. package/lib/esm/src/internal/secure-channel/model/Errors.js.map +3 -3
  119. package/lib/esm/src/internal/send/use-case/SendApduUseCase.js +1 -1
  120. package/lib/esm/src/internal/send/use-case/SendApduUseCase.js.map +3 -3
  121. package/lib/types/src/api/apdu/utils/ByteArrayBuilder.d.ts +28 -0
  122. package/lib/types/src/api/apdu/utils/ByteArrayBuilder.d.ts.map +1 -1
  123. package/lib/types/src/api/command/utils/CommandUtils.d.ts +3 -0
  124. package/lib/types/src/api/command/utils/CommandUtils.d.ts.map +1 -1
  125. package/lib/types/src/api/device-action/model/UserInteractionRequired.d.ts +1 -0
  126. package/lib/types/src/api/device-action/model/UserInteractionRequired.d.ts.map +1 -1
  127. package/lib/types/src/api/device-action/os/Errors.d.ts +10 -0
  128. package/lib/types/src/api/device-action/os/Errors.d.ts.map +1 -1
  129. package/lib/types/src/api/device-action/os/GetDeviceMetadata/GetDeviceMetadataDeviceAction.d.ts.map +1 -1
  130. package/lib/types/src/api/device-action/os/GetDeviceMetadata/types.d.ts +2 -1
  131. package/lib/types/src/api/device-action/os/GetDeviceMetadata/types.d.ts.map +1 -1
  132. package/lib/types/src/api/device-action/os/InstallOrUpdateApps/InstallOrUpdateAppsDeviceAction.d.ts.map +1 -1
  133. package/lib/types/src/api/device-action/os/InstallOrUpdateApps/types.d.ts +3 -2
  134. package/lib/types/src/api/device-action/os/InstallOrUpdateApps/types.d.ts.map +1 -1
  135. package/lib/types/src/api/device-action/os/OpenAppDeviceAction/OpenAppDeviceAction.d.ts.map +1 -1
  136. package/lib/types/src/api/device-action/task/BuildAppsInstallPlanTask.d.ts +2 -2
  137. package/lib/types/src/api/device-action/task/BuildAppsInstallPlanTask.d.ts.map +1 -1
  138. package/lib/types/src/api/index.d.ts +1 -1
  139. package/lib/types/src/api/index.d.ts.map +1 -1
  140. package/lib/types/src/api/secure-channel/device-action/GenuineCheck/GenuineCheckDeviceAction.d.ts.map +1 -1
  141. package/lib/types/src/api/secure-channel/device-action/GenuineCheck/types.d.ts +2 -1
  142. package/lib/types/src/api/secure-channel/device-action/GenuineCheck/types.d.ts.map +1 -1
  143. package/lib/types/src/api/secure-channel/device-action/InstallApp/InstallAppDeviceAction.d.ts.map +1 -1
  144. package/lib/types/src/api/secure-channel/device-action/InstallApp/types.d.ts +2 -1
  145. package/lib/types/src/api/secure-channel/device-action/InstallApp/types.d.ts.map +1 -1
  146. package/lib/types/src/api/secure-channel/device-action/ListInstalledApps/ListInstalledAppsDeviceAction.d.ts.map +1 -1
  147. package/lib/types/src/api/secure-channel/device-action/ListInstalledApps/types.d.ts +2 -1
  148. package/lib/types/src/api/secure-channel/device-action/ListInstalledApps/types.d.ts.map +1 -1
  149. package/lib/types/src/api/secure-channel/device-action/UninstallApp/UninstallAppDeviceAction.d.ts.map +1 -1
  150. package/lib/types/src/api/secure-channel/device-action/UninstallApp/types.d.ts +2 -1
  151. package/lib/types/src/api/secure-channel/device-action/UninstallApp/types.d.ts.map +1 -1
  152. package/lib/types/src/api/secure-channel/task/ConnectToSecureChannelTask.d.ts +5 -2
  153. package/lib/types/src/api/secure-channel/task/ConnectToSecureChannelTask.d.ts.map +1 -1
  154. package/lib/types/src/api/secure-channel/task/types.d.ts +6 -1
  155. package/lib/types/src/api/secure-channel/task/types.d.ts.map +1 -1
  156. package/lib/types/src/api/secure-channel/utils.d.ts +0 -11
  157. package/lib/types/src/api/secure-channel/utils.d.ts.map +1 -1
  158. package/lib/types/src/api/transport/model/DeviceConnectionStateMachine.d.ts +8 -7
  159. package/lib/types/src/api/transport/model/DeviceConnectionStateMachine.d.ts.map +1 -1
  160. package/lib/types/src/api/transport/model/DeviceConnectionStateMachine.test.d.ts +2 -0
  161. package/lib/types/src/api/transport/model/DeviceConnectionStateMachine.test.d.ts.map +1 -0
  162. package/lib/types/src/api/transport/model/Errors.d.ts +0 -5
  163. package/lib/types/src/api/transport/model/Errors.d.ts.map +1 -1
  164. package/lib/types/src/internal/secure-channel/model/Errors.d.ts +22 -2
  165. package/lib/types/src/internal/secure-channel/model/Errors.d.ts.map +1 -1
  166. package/lib/types/src/internal/send/use-case/SendApduUseCase.d.ts +5 -1
  167. package/lib/types/src/internal/send/use-case/SendApduUseCase.d.ts.map +1 -1
  168. package/lib/types/tsconfig.prod.tsbuildinfo +1 -1
  169. package/package.json +1 -1
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../../src/api/secure-channel/task/ConnectToSecureChannelTask.test.ts"],
4
- "sourcesContent": ["import WebSocket from \"isomorphic-ws\";\nimport { Right } from \"purify-ts\";\nimport { describe, it, vi } from \"vitest\";\n\nimport { type InternalApi } from \"@api/index\";\nimport {\n type SecureChannelEvent,\n SecureChannelEventType,\n} from \"@api/secure-channel/task/types\";\nimport { SecureChannelError } from \"@internal/secure-channel/model/Errors\";\n\nimport {\n ConnectToSecureChannelTask,\n type ConnectToSecureChannelTaskArgs,\n} from \"./ConnectToSecureChannelTask\";\n\nvi.mock(\"isomorphic-ws\", () => ({\n ...vi.importActual(\"isomorphic-ws\"),\n __esModule: true,\n default: class {\n onopen: (() => void) | null = null;\n onmessage: ((event: { data: string }) => void) | null = null;\n send = vi.fn();\n close = vi.fn();\n url: string;\n constructor(url: string) {\n this.url = url;\n }\n },\n}));\n\nconst TEST_DELAY = 5;\n\ndescribe(\"ConnectToSecureChannelTask\", () => {\n let mockWebSocket: WebSocket;\n let mockInternalApi: InternalApi;\n let taskArgs: ConnectToSecureChannelTaskArgs;\n let task: ConnectToSecureChannelTask;\n const sendApduFn = vi.fn();\n\n beforeEach(() => {\n // vi.useFakeTimers({ shouldAdvanceTime: true });\n\n mockWebSocket = new WebSocket(\"wss://test-host.com\");\n mockInternalApi = {\n sendApdu: sendApduFn,\n disableRefresher: vi.fn(),\n } as unknown as InternalApi;\n taskArgs = { connection: Right(mockWebSocket) };\n task = new ConnectToSecureChannelTask(mockInternalApi, taskArgs);\n });\n\n afterEach(() => {\n vi.resetAllMocks();\n });\n\n it(\"should emit Opened event on WebSocket open\", async () => {\n const events: SecureChannelEvent[] = [];\n const obs = task.run();\n obs.subscribe((e) => events.push(e));\n\n expect(mockWebSocket.onopen).toBeDefined();\n mockWebSocket.onopen!({\n type: \"open\",\n target: {} as WebSocket,\n });\n\n await new Promise((resolve) => setTimeout(resolve, TEST_DELAY));\n\n expect(events).toStrictEqual([{ type: SecureChannelEventType.Opened }]);\n });\n\n it(\"should handle incoming EXCHANGE message including requesting user permission\", async () => {\n sendApduFn.mockResolvedValue(\n Right({\n data: new Uint8Array([0x90, 0x00]),\n statusCode: new Uint8Array([0x90, 0x00]),\n }),\n );\n\n const sendSpy = vi.spyOn(mockWebSocket, \"send\");\n vi.spyOn(task, \"isSecureConnectionAllowed\").mockReturnValueOnce(false);\n\n const events: SecureChannelEvent[] = [];\n const obs = task.run();\n obs.subscribe({\n next: (event) => {\n events.push(event);\n },\n });\n\n expect(mockWebSocket.onmessage).toBeDefined();\n mockWebSocket.onmessage!({\n data: JSON.stringify({\n query: \"exchange\",\n nonce: 1,\n data: \"e051000000\",\n }),\n type: \"\",\n target: {} as WebSocket,\n });\n\n await new Promise((resolve) => setTimeout(resolve, TEST_DELAY));\n\n expect(sendSpy).toHaveBeenCalledExactlyOnceWith(\n JSON.stringify({\n nonce: 1,\n response: \"success\",\n data: \"9000\",\n }),\n );\n expect(events).toStrictEqual([\n {\n type: SecureChannelEventType.PreExchange,\n payload: {\n nonce: 1,\n apdu: new Uint8Array([0xe0, 0x51, 0x00, 0x00, 0x00]),\n },\n },\n {\n type: SecureChannelEventType.PermissionRequested,\n },\n {\n type: SecureChannelEventType.Exchange,\n payload: {\n nonce: 1,\n apdu: new Uint8Array([0xe0, 0x51, 0x00, 0x00, 0x00]),\n data: new Uint8Array([0x90, 0x00]),\n status: new Uint8Array([0x90, 0x00]),\n },\n },\n {\n type: SecureChannelEventType.PermissionGranted,\n },\n ]);\n });\n\n it(\"should handle incoming BULK message\", async () => {\n sendApduFn.mockResolvedValue(\n Right({\n data: new Uint8Array([0x90, 0x00]),\n statusCode: new Uint8Array([0x90, 0x00]),\n }),\n );\n const completeFn: () => void = vi.fn();\n const obs = task.run();\n const events: SecureChannelEvent[] = [];\n obs.subscribe({\n next: (event: SecureChannelEvent) => {\n events.push(event);\n },\n complete: () => completeFn(),\n });\n\n expect(mockWebSocket.onmessage).toBeDefined();\n mockWebSocket.onmessage!({\n data: JSON.stringify({\n query: \"bulk\",\n nonce: 1,\n data: [\"0000000100\", \"0000000200\", \"0000000300\"],\n }),\n type: \"\",\n target: {} as WebSocket,\n });\n\n await new Promise((resolve) => setTimeout(resolve, TEST_DELAY));\n\n expect(sendApduFn).toHaveBeenCalledTimes(3);\n expect(events).toStrictEqual([\n {\n type: SecureChannelEventType.Progress,\n payload: { progress: 0.33, index: 0, total: 3 },\n },\n {\n type: SecureChannelEventType.Progress,\n payload: { progress: 0.67, index: 1, total: 3 },\n },\n {\n type: SecureChannelEventType.Progress,\n payload: { progress: 1.0, index: 2, total: 3 },\n },\n ]);\n expect(completeFn).toHaveBeenCalledOnce();\n });\n\n it(\"should handle incoming SUCCESS message\", () => {\n const completeFn: () => void = vi.fn();\n const events: SecureChannelEvent[] = [];\n const observable = task.run();\n observable.subscribe({\n next: (event: SecureChannelEvent) => events.push(event),\n complete: () => completeFn(),\n });\n\n mockWebSocket.onmessage!({\n data: JSON.stringify({\n query: \"success\",\n nonce: 1,\n result: \"success result\",\n }),\n type: \"\",\n target: {} as WebSocket,\n });\n\n expect(events).toStrictEqual([\n { type: SecureChannelEventType.Result, payload: \"success result\" },\n ]);\n expect(completeFn).toHaveBeenCalledOnce();\n });\n\n it(\"should handle incoming WARNING message\", () => {\n const events: SecureChannelEvent[] = [];\n const observable = task.run();\n observable.subscribe({\n next: (event: SecureChannelEvent) => events.push(event),\n });\n\n expect(mockWebSocket.onmessage).toBeDefined();\n mockWebSocket.onmessage!({\n data: JSON.stringify({\n query: \"warning\",\n nonce: 1,\n data: \"warning message\",\n }),\n type: \"\",\n target: {} as WebSocket,\n });\n\n expect(events).toStrictEqual([\n {\n type: SecureChannelEventType.Warning,\n payload: { message: \"warning message\" },\n },\n ]);\n });\n\n it(\"should handle incoming ERROR message\", () => {\n const errorFn = vi.fn();\n const observable = task.run();\n observable.subscribe({\n error: (err) => {\n expect(err).toBeInstanceOf(SecureChannelError);\n errorFn(err);\n },\n });\n\n expect(mockWebSocket.onmessage).toBeDefined();\n mockWebSocket.onmessage!({\n data: JSON.stringify({\n query: \"error\",\n }),\n type: \"\",\n target: {} as WebSocket,\n });\n\n expect(errorFn).toHaveBeenCalled();\n });\n});\n"],
5
- "mappings": "wdAAA,IAAAA,EAAsB,4BACtBC,EAAsB,qBACtBC,EAAiC,kBAGjCC,EAGO,0CACPC,EAAmC,iDAEnCC,EAGO,wCAEP,KAAG,KAAK,gBAAiB,KAAO,CAC9B,GAAG,KAAG,aAAa,eAAe,EAClC,WAAY,GACZ,QAAS,KAAM,CACb,OAA8B,KAC9B,UAAwD,KACxD,KAAO,KAAG,GAAG,EACb,MAAQ,KAAG,GAAG,EACd,IACA,YAAYC,EAAa,CACvB,KAAK,IAAMA,CACb,CACF,CACF,EAAE,EAEF,MAAMC,EAAa,KAEnB,YAAS,6BAA8B,IAAM,CAC3C,IAAIC,EACAC,EACAC,EACAC,EACJ,MAAMC,EAAa,KAAG,GAAG,EAEzB,WAAW,IAAM,CAGfJ,EAAgB,IAAI,EAAAK,QAAU,qBAAqB,EACnDJ,EAAkB,CAChB,SAAUG,EACV,iBAAkB,KAAG,GAAG,CAC1B,EACAF,EAAW,CAAE,cAAY,SAAMF,CAAa,CAAE,EAC9CG,EAAO,IAAI,6BAA2BF,EAAiBC,CAAQ,CACjE,CAAC,EAED,UAAU,IAAM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AO,OACT,CAAC,EACD,KAAM,GACN,OAAQ,CAAC,CACX,CAAC,EAED,OAAOa,CAAO,EAAE,iBAAiB,CACnC,CAAC,CACH,CAAC",
6
- "names": ["import_isomorphic_ws", "import_purify_ts", "import_vitest", "import_types", "import_Errors", "import_ConnectToSecureChannelTask", "url", "TEST_DELAY", "mockWebSocket", "mockInternalApi", "taskArgs", "task", "sendApduFn", "WebSocket", "events", "e", "resolve", "sendSpy", "event", "completeFn", "obs", "errorFn", "err"]
4
+ "sourcesContent": ["import WebSocket from \"isomorphic-ws\";\nimport { Right } from \"purify-ts\";\nimport { describe, it, vi } from \"vitest\";\n\nimport { type InternalApi } from \"@api/index\";\nimport {\n type SecureChannelEvent,\n SecureChannelEventType,\n} from \"@api/secure-channel/task/types\";\nimport {\n SecureChannelError,\n SecureChannelErrorType,\n} from \"@internal/secure-channel/model/Errors\";\n\nimport {\n ConnectToSecureChannelTask,\n type ConnectToSecureChannelTaskArgs,\n} from \"./ConnectToSecureChannelTask\";\n\nvi.mock(\"isomorphic-ws\", () => ({\n ...vi.importActual(\"isomorphic-ws\"),\n __esModule: true,\n default: class {\n onopen: (() => void) | null = null;\n onmessage: ((event: { data: string }) => void) | null = null;\n send = vi.fn();\n close = vi.fn();\n url: string;\n constructor(url: string) {\n this.url = url;\n }\n },\n}));\n\nconst TEST_DELAY = 5;\n\ndescribe(\"ConnectToSecureChannelTask\", () => {\n let mockWebSocket: WebSocket;\n let mockInternalApi: InternalApi;\n let taskArgs: ConnectToSecureChannelTaskArgs;\n let task: ConnectToSecureChannelTask;\n const sendApduFn = vi.fn();\n const mockMessage = {\n uuid: \"5b776c8d-8af2-48c0-8250-04edca2ef5e9\",\n session: \"39ce749e-00a4-4c31-a697-1dc1a29e2cab\",\n query: \"success\",\n nonce: 15,\n };\n\n beforeEach(() => {\n // vi.useFakeTimers({ shouldAdvanceTime: true });\n\n mockWebSocket = new WebSocket(\"wss://test-host.com\");\n mockInternalApi = {\n sendApdu: sendApduFn,\n disableRefresher: (_: unknown) => vi.fn(),\n } as unknown as InternalApi;\n taskArgs = { connection: Right(mockWebSocket) };\n task = new ConnectToSecureChannelTask(mockInternalApi, taskArgs);\n });\n\n afterEach(() => {\n vi.resetAllMocks();\n });\n\n it(\"should emit Opened event on WebSocket open\", async () => {\n const events: SecureChannelEvent[] = [];\n const obs = task.run();\n obs.subscribe((e) => events.push(e));\n\n expect(mockWebSocket.onopen).toBeDefined();\n mockWebSocket.onopen!({\n type: \"open\",\n target: {} as WebSocket,\n });\n\n await new Promise((resolve) => setTimeout(resolve, TEST_DELAY));\n\n expect(events).toStrictEqual([{ type: SecureChannelEventType.Opened }]);\n });\n\n it(\"Error on wrongly formatted message\", async () => {\n const events: SecureChannelEvent[] = [];\n const obs = task.run();\n obs.subscribe({\n next: (event) => {\n events.push(event);\n },\n });\n\n expect(mockWebSocket.onmessage).toBeDefined();\n mockWebSocket.onmessage!({\n data: \"invalidData\",\n type: \"\",\n target: {} as WebSocket,\n });\n\n await new Promise((resolve) => setTimeout(resolve, TEST_DELAY));\n\n expect(events).toStrictEqual([\n {\n type: SecureChannelEventType.Error,\n error: new SecureChannelError({\n url: \"wss://test-host.com\",\n errorMessage: \"Invalid message received: invalidData\",\n }),\n },\n ]);\n });\n\n it(\"should handle incoming EXCHANGE message including requesting user permission\", async () => {\n sendApduFn.mockResolvedValue(\n Right({\n data: new Uint8Array([0x90, 0x00]),\n statusCode: new Uint8Array([0x90, 0x00]),\n }),\n );\n\n const sendSpy = vi.spyOn(mockWebSocket, \"send\");\n vi.spyOn(task, \"isSecureConnectionAllowed\").mockReturnValueOnce(false);\n\n const events: SecureChannelEvent[] = [];\n const obs = task.run();\n obs.subscribe({\n next: (event) => {\n events.push(event);\n },\n });\n\n expect(mockWebSocket.onmessage).toBeDefined();\n mockWebSocket.onmessage!({\n data: JSON.stringify({\n ...mockMessage,\n query: \"exchange\",\n nonce: 1,\n data: \"e051000000\",\n }),\n type: \"\",\n target: {} as WebSocket,\n });\n\n await new Promise((resolve) => setTimeout(resolve, TEST_DELAY));\n\n expect(sendSpy).toHaveBeenCalledExactlyOnceWith(\n JSON.stringify({\n nonce: 1,\n response: \"success\",\n data: \"9000\",\n }),\n );\n expect(events).toStrictEqual([\n {\n type: SecureChannelEventType.PreExchange,\n payload: {\n nonce: 1,\n apdu: new Uint8Array([0xe0, 0x51, 0x00, 0x00, 0x00]),\n },\n },\n {\n type: SecureChannelEventType.PermissionRequested,\n },\n {\n type: SecureChannelEventType.Exchange,\n payload: {\n nonce: 1,\n apdu: new Uint8Array([0xe0, 0x51, 0x00, 0x00, 0x00]),\n data: new Uint8Array([0x90, 0x00]),\n status: new Uint8Array([0x90, 0x00]),\n },\n },\n {\n type: SecureChannelEventType.PermissionGranted,\n },\n ]);\n });\n\n it(\"should handle incoming EXCHANGE message with a device error\", async () => {\n sendApduFn.mockResolvedValue(\n Right({\n data: new Uint8Array([]),\n statusCode: new Uint8Array([0x55, 0x15]),\n }),\n );\n\n const sendSpy = vi.spyOn(mockWebSocket, \"send\");\n const events: SecureChannelEvent[] = [];\n const obs = task.run();\n obs.subscribe({\n next: (event) => {\n events.push(event);\n },\n });\n\n expect(mockWebSocket.onmessage).toBeDefined();\n mockWebSocket.onmessage!({\n data: JSON.stringify({\n ...mockMessage,\n query: \"exchange\",\n nonce: 1,\n data: \"e053000000\",\n }),\n type: \"\",\n target: {} as WebSocket,\n });\n\n await new Promise((resolve) => setTimeout(resolve, TEST_DELAY));\n\n expect(sendSpy).toHaveBeenCalledExactlyOnceWith(\n JSON.stringify({\n nonce: 1,\n response: \"error\",\n data: \"\",\n }),\n );\n expect(events).toStrictEqual([\n {\n type: SecureChannelEventType.PreExchange,\n payload: {\n nonce: 1,\n apdu: new Uint8Array([0xe0, 0x53, 0x00, 0x00, 0x00]),\n },\n },\n {\n type: SecureChannelEventType.Error,\n error: new SecureChannelError(\n {\n url: \"wss://test-host.com\",\n errorMessage: \"Device is locked\",\n },\n SecureChannelErrorType.DeviceLocked,\n ),\n },\n ]);\n });\n\n it(\"should handle incoming BULK message\", async () => {\n sendApduFn.mockResolvedValue(\n Right({\n data: new Uint8Array([0x90, 0x00]),\n statusCode: new Uint8Array([0x90, 0x00]),\n }),\n );\n const completeFn: () => void = vi.fn();\n const obs = task.run();\n const events: SecureChannelEvent[] = [];\n obs.subscribe({\n next: (event: SecureChannelEvent) => {\n events.push(event);\n },\n complete: () => completeFn(),\n });\n\n expect(mockWebSocket.onmessage).toBeDefined();\n mockWebSocket.onmessage!({\n data: JSON.stringify({\n ...mockMessage,\n query: \"bulk\",\n nonce: 1,\n data: [\"0000000100\", \"0000000200\", \"0000000300\"],\n }),\n type: \"\",\n target: {} as WebSocket,\n });\n\n await new Promise((resolve) => setTimeout(resolve, TEST_DELAY));\n\n expect(sendApduFn).toHaveBeenCalledTimes(3);\n expect(events).toStrictEqual([\n {\n type: SecureChannelEventType.Progress,\n payload: { progress: 0.33, index: 0, total: 3 },\n },\n {\n type: SecureChannelEventType.Progress,\n payload: { progress: 0.67, index: 1, total: 3 },\n },\n {\n type: SecureChannelEventType.Progress,\n payload: { progress: 1.0, index: 2, total: 3 },\n },\n ]);\n expect(completeFn).toHaveBeenCalledOnce();\n });\n\n it(\"should handle incoming BULK message with a device error\", async () => {\n sendApduFn.mockResolvedValue(\n Right({\n data: new Uint8Array([]),\n statusCode: new Uint8Array([0x55, 0x01]),\n }),\n );\n const completeFn: () => void = vi.fn();\n const obs = task.run();\n const events: SecureChannelEvent[] = [];\n obs.subscribe({\n next: (event: SecureChannelEvent) => {\n events.push(event);\n },\n complete: () => completeFn(),\n });\n\n expect(mockWebSocket.onmessage).toBeDefined();\n mockWebSocket.onmessage!({\n data: JSON.stringify({\n ...mockMessage,\n query: \"bulk\",\n nonce: 1,\n data: [\"0000000100\", \"0000000200\", \"0000000300\"],\n }),\n type: \"\",\n target: {} as WebSocket,\n });\n\n await new Promise((resolve) => setTimeout(resolve, TEST_DELAY));\n\n expect(sendApduFn).toHaveBeenCalledTimes(1);\n expect(events).toStrictEqual([\n {\n type: SecureChannelEventType.Error,\n error: new SecureChannelError(\n {\n url: \"wss://test-host.com\",\n errorMessage: \"User refused on the device\",\n },\n SecureChannelErrorType.RefusedByUser,\n ),\n },\n ]);\n expect(completeFn).toHaveBeenCalledOnce();\n });\n\n it(\"should handle incoming SUCCESS message\", () => {\n const completeFn: () => void = vi.fn();\n const events: SecureChannelEvent[] = [];\n const observable = task.run();\n observable.subscribe({\n next: (event: SecureChannelEvent) => events.push(event),\n complete: () => completeFn(),\n });\n\n mockWebSocket.onmessage!({\n data: JSON.stringify({\n ...mockMessage,\n query: \"success\",\n nonce: 1,\n result: \"success result\",\n }),\n type: \"\",\n target: {} as WebSocket,\n });\n\n expect(events).toStrictEqual([\n { type: SecureChannelEventType.Result, payload: \"success result\" },\n ]);\n expect(completeFn).toHaveBeenCalledOnce();\n });\n\n it(\"should handle incoming WARNING message\", () => {\n const events: SecureChannelEvent[] = [];\n const observable = task.run();\n observable.subscribe({\n next: (event: SecureChannelEvent) => events.push(event),\n });\n\n expect(mockWebSocket.onmessage).toBeDefined();\n mockWebSocket.onmessage!({\n data: JSON.stringify({\n ...mockMessage,\n query: \"warning\",\n nonce: 1,\n data: \"warning message\",\n }),\n type: \"\",\n target: {} as WebSocket,\n });\n\n expect(events).toStrictEqual([\n {\n type: SecureChannelEventType.Warning,\n payload: { message: \"warning message\" },\n },\n ]);\n });\n\n it(\"should handle incoming ERROR message\", () => {\n const events: SecureChannelEvent[] = [];\n const observable = task.run();\n observable.subscribe({\n next: (event: SecureChannelEvent) => events.push(event),\n });\n\n expect(mockWebSocket.onmessage).toBeDefined();\n mockWebSocket.onmessage!({\n data: JSON.stringify({\n ...mockMessage,\n query: \"error\",\n data: \"My error\",\n }),\n type: \"\",\n target: {} as WebSocket,\n });\n\n expect(events).toStrictEqual([\n {\n type: SecureChannelEventType.Error,\n error: new SecureChannelError({\n url: \"wss://test-host.com\",\n errorMessage: \"My error\",\n }),\n },\n ]);\n });\n});\n"],
5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AAc,SAAS,EAAE,YAAY,EAC5CA,EAAc,UAAW,CACvB,KAAM,KAAK,UAAU,CACnB,GAAGK,EACH,MAAO,UACP,MAAO,EACP,KAAM,iBACR,CAAC,EACD,KAAM,GACN,OAAQ,CAAC,CACX,CAAC,EAED,OAAOG,CAAM,EAAE,cAAc,CAC3B,CACE,KAAM,yBAAuB,QAC7B,QAAS,CAAE,QAAS,iBAAkB,CACxC,CACF,CAAC,CACH,CAAC,KAED,MAAG,uCAAwC,IAAM,CAC/C,MAAMA,EAA+B,CAAC,EACnBL,EAAK,IAAI,EACjB,UAAU,CACnB,KAAOQ,GAA8BH,EAAO,KAAKG,CAAK,CACxD,CAAC,EAED,OAAOX,EAAc,SAAS,EAAE,YAAY,EAC5CA,EAAc,UAAW,CACvB,KAAM,KAAK,UAAU,CACnB,GAAGK,EACH,MAAO,QACP,KAAM,UACR,CAAC,EACD,KAAM,GACN,OAAQ,CAAC,CACX,CAAC,EAED,OAAOG,CAAM,EAAE,cAAc,CAC3B,CACE,KAAM,yBAAuB,MAC7B,MAAO,IAAI,qBAAmB,CAC5B,IAAK,sBACL,aAAc,UAChB,CAAC,CACH,CACF,CAAC,CACH,CAAC,CACH,CAAC",
6
+ "names": ["import_isomorphic_ws", "import_purify_ts", "import_vitest", "import_types", "import_Errors", "import_ConnectToSecureChannelTask", "url", "TEST_DELAY", "mockWebSocket", "mockInternalApi", "taskArgs", "task", "sendApduFn", "mockMessage", "WebSocket", "_", "events", "e", "resolve", "event", "sendSpy", "completeFn", "obs"]
7
7
  }
@@ -1,2 +1,2 @@
1
- "use strict";var o=Object.defineProperty;var c=Object.getOwnPropertyDescriptor;var u=Object.getOwnPropertyNames;var x=Object.prototype.hasOwnProperty;var P=(r,e)=>{for(var t in e)o(r,t,{get:e[t],enumerable:!0})},h=(r,e,t,d)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of u(e))!x.call(r,s)&&s!==t&&o(r,s,{get:()=>e[s],enumerable:!(d=c(e,s))||d.enumerable});return r};var A=r=>h(o({},"__esModule",{value:!0}),r);var U={};P(U,{InMessageQueryEnum:()=>i,OutMessageResponseEnum:()=>g,SecureChannelEventType:()=>y,SecureChannelOperationEnum:()=>l});module.exports=A(U);var l=(a=>(a.GenuineCheck="GenuineCheck",a.ListInstalledApps="ListInstalledApps",a.UpdateMcu="UpdateMcu",a.UpdateFirmware="UpdateFirmware",a.InstallApp="InstallApp",a.UninstallApp="UninstallApp",a))(l||{}),i=(p=>(p.EXCHANGE="exchange",p.BULK="bulk",p.ERROR="error",p.WARNING="warning",p.SUCCESS="success",p))(i||{}),g=(t=>(t.SUCCESS="success",t.ERROR="error",t))(g||{}),y=(n=>(n.Opened="opened",n.Closed="closed",n.PermissionRequested="permission-requested",n.PermissionGranted="permission-granted",n.PreExchange="pre-exchange",n.Exchange="exchange",n.Progress="progress",n.Warning="warning",n.Result="result",n))(y||{});0&&(module.exports={InMessageQueryEnum,OutMessageResponseEnum,SecureChannelEventType,SecureChannelOperationEnum});
1
+ "use strict";var o=Object.defineProperty;var g=Object.getOwnPropertyDescriptor;var u=Object.getOwnPropertyNames;var x=Object.prototype.hasOwnProperty;var P=(n,r)=>{for(var t in r)o(n,t,{get:r[t],enumerable:!0})},h=(n,r,t,l)=>{if(r&&typeof r=="object"||typeof r=="function")for(let s of u(r))!x.call(n,s)&&s!==t&&o(n,s,{get:()=>r[s],enumerable:!(l=g(r,s))||l.enumerable});return n};var E=n=>h(o({},"__esModule",{value:!0}),n);var U={};P(U,{InMessageQueryEnum:()=>i,OutMessageResponseEnum:()=>y,SecureChannelEventType:()=>c,SecureChannelOperationEnum:()=>d});module.exports=E(U);var d=(a=>(a.GenuineCheck="GenuineCheck",a.ListInstalledApps="ListInstalledApps",a.UpdateMcu="UpdateMcu",a.UpdateFirmware="UpdateFirmware",a.InstallApp="InstallApp",a.UninstallApp="UninstallApp",a))(d||{}),i=(p=>(p.EXCHANGE="exchange",p.BULK="bulk",p.ERROR="error",p.WARNING="warning",p.SUCCESS="success",p))(i||{}),y=(t=>(t.SUCCESS="success",t.ERROR="error",t))(y||{}),c=(e=>(e.Opened="opened",e.Closed="closed",e.PermissionRequested="permission-requested",e.PermissionGranted="permission-granted",e.PreExchange="pre-exchange",e.Exchange="exchange",e.Progress="progress",e.Warning="warning",e.Error="error",e.Result="result",e))(c||{});0&&(module.exports={InMessageQueryEnum,OutMessageResponseEnum,SecureChannelEventType,SecureChannelOperationEnum});
2
2
  //# sourceMappingURL=types.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../../src/api/secure-channel/task/types.ts"],
4
- "sourcesContent": ["export enum SecureChannelOperationEnum {\n GenuineCheck = \"GenuineCheck\",\n ListInstalledApps = \"ListInstalledApps\",\n UpdateMcu = \"UpdateMcu\",\n UpdateFirmware = \"UpdateFirmware\",\n InstallApp = \"InstallApp\",\n UninstallApp = \"UninstallApp\",\n}\n\n/**\n * The message that will be received from the server by the secure channel.\n */\nexport type InMessageType = {\n uuid: string;\n session: string;\n query: InMessageQueryEnum;\n nonce: number;\n data: string | Array<string>;\n result?: unknown;\n};\n\nexport enum InMessageQueryEnum {\n EXCHANGE = \"exchange\",\n BULK = \"bulk\",\n ERROR = \"error\",\n WARNING = \"warning\",\n SUCCESS = \"success\",\n}\n\n/**\n * The message that will be sent to the server by the secure channel.\n */\nexport type OutMessageType = {\n nonce: number;\n response: OutMessageResponseEnum;\n data: string;\n};\n\nexport enum OutMessageResponseEnum {\n SUCCESS = \"success\",\n ERROR = \"error\",\n}\n\n/**\n * The all event types that can be emitted to the client by the secure channel.\n *\n */\nexport enum SecureChannelEventType {\n Opened = \"opened\",\n Closed = \"closed\",\n PermissionRequested = \"permission-requested\",\n PermissionGranted = \"permission-granted\",\n PreExchange = \"pre-exchange\",\n Exchange = \"exchange\",\n Progress = \"progress\",\n Warning = \"warning\",\n Result = \"result\",\n}\n\n/**\n * The possible payload that will be sent to the client when a secure channel event occurs.\n */\nexport type SecureChannelEventPayload = {\n PreExchange: { nonce: number; apdu: Uint8Array };\n Exchange: {\n nonce: number;\n apdu: Uint8Array;\n data: Uint8Array;\n status: Uint8Array;\n };\n Progress: { progress: number; index: number; total: number };\n Warning: { message: string };\n Result: unknown;\n};\n\n/**\n * The event type that will be emitted to the client when a secure channel event occurs.\n */\nexport type SecureChannelEvent =\n | {\n type: SecureChannelEventType.Opened;\n }\n | {\n type: SecureChannelEventType.Closed;\n }\n | {\n type: SecureChannelEventType.PermissionRequested;\n }\n | {\n type: SecureChannelEventType.PermissionGranted;\n }\n | {\n type: SecureChannelEventType.PreExchange;\n payload: SecureChannelEventPayload[\"PreExchange\"];\n }\n | {\n type: SecureChannelEventType.Exchange;\n payload: SecureChannelEventPayload[\"Exchange\"];\n }\n | {\n type: SecureChannelEventType.Progress;\n payload: SecureChannelEventPayload[\"Progress\"];\n }\n | {\n type: SecureChannelEventType.Warning;\n payload: SecureChannelEventPayload[\"Warning\"];\n }\n | {\n type: SecureChannelEventType.Result;\n payload: SecureChannelEventPayload[\"Result\"];\n };\n"],
5
- "mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,wBAAAE,EAAA,2BAAAC,EAAA,2BAAAC,EAAA,+BAAAC,IAAA,eAAAC,EAAAN,GAAO,IAAKK,OACVA,EAAA,aAAe,eACfA,EAAA,kBAAoB,oBACpBA,EAAA,UAAY,YACZA,EAAA,eAAiB,iBACjBA,EAAA,WAAa,aACbA,EAAA,aAAe,eANLA,OAAA,IAqBAH,OACVA,EAAA,SAAW,WACXA,EAAA,KAAO,OACPA,EAAA,MAAQ,QACRA,EAAA,QAAU,UACVA,EAAA,QAAU,UALAA,OAAA,IAiBAC,OACVA,EAAA,QAAU,UACVA,EAAA,MAAQ,QAFEA,OAAA,IASAC,OACVA,EAAA,OAAS,SACTA,EAAA,OAAS,SACTA,EAAA,oBAAsB,uBACtBA,EAAA,kBAAoB,qBACpBA,EAAA,YAAc,eACdA,EAAA,SAAW,WACXA,EAAA,SAAW,WACXA,EAAA,QAAU,UACVA,EAAA,OAAS,SATCA,OAAA",
4
+ "sourcesContent": ["import { type SecureChannelError } from \"@internal/secure-channel/model/Errors\";\n\nexport enum SecureChannelOperationEnum {\n GenuineCheck = \"GenuineCheck\",\n ListInstalledApps = \"ListInstalledApps\",\n UpdateMcu = \"UpdateMcu\",\n UpdateFirmware = \"UpdateFirmware\",\n InstallApp = \"InstallApp\",\n UninstallApp = \"UninstallApp\",\n}\n\n/**\n * The message that will be received from the server by the secure channel.\n */\nexport type InMessageType = {\n uuid: string;\n session: string;\n query: InMessageQueryEnum;\n nonce: number;\n data: unknown;\n result?: unknown;\n};\n\nexport enum InMessageQueryEnum {\n EXCHANGE = \"exchange\",\n BULK = \"bulk\",\n ERROR = \"error\",\n WARNING = \"warning\",\n SUCCESS = \"success\",\n}\n\n/**\n * The message that will be sent to the server by the secure channel.\n */\nexport type OutMessageType = {\n nonce: number;\n response: OutMessageResponseEnum;\n data: string;\n};\n\nexport enum OutMessageResponseEnum {\n SUCCESS = \"success\",\n ERROR = \"error\",\n}\n\n/**\n * The all event types that can be emitted to the client by the secure channel.\n *\n */\nexport enum SecureChannelEventType {\n Opened = \"opened\",\n Closed = \"closed\",\n PermissionRequested = \"permission-requested\",\n PermissionGranted = \"permission-granted\",\n PreExchange = \"pre-exchange\",\n Exchange = \"exchange\",\n Progress = \"progress\",\n Warning = \"warning\",\n Error = \"error\",\n Result = \"result\",\n}\n\n/**\n * The possible payload that will be sent to the client when a secure channel event occurs.\n */\nexport type SecureChannelEventPayload = {\n PreExchange: { nonce: number; apdu: Uint8Array };\n Exchange: {\n nonce: number;\n apdu: Uint8Array;\n data: Uint8Array;\n status: Uint8Array;\n };\n Progress: { progress: number; index: number; total: number };\n Warning: { message: string };\n Result: unknown;\n};\n\n/**\n * The event type that will be emitted to the client when a secure channel event occurs.\n */\nexport type SecureChannelEvent =\n | {\n type: SecureChannelEventType.Opened;\n }\n | {\n type: SecureChannelEventType.Closed;\n }\n | {\n type: SecureChannelEventType.PermissionRequested;\n }\n | {\n type: SecureChannelEventType.PermissionGranted;\n }\n | {\n type: SecureChannelEventType.PreExchange;\n payload: SecureChannelEventPayload[\"PreExchange\"];\n }\n | {\n type: SecureChannelEventType.Exchange;\n payload: SecureChannelEventPayload[\"Exchange\"];\n }\n | {\n type: SecureChannelEventType.Progress;\n payload: SecureChannelEventPayload[\"Progress\"];\n }\n | {\n type: SecureChannelEventType.Warning;\n payload: SecureChannelEventPayload[\"Warning\"];\n }\n | {\n type: SecureChannelEventType.Error;\n error: SecureChannelError;\n }\n | {\n type: SecureChannelEventType.Result;\n payload: SecureChannelEventPayload[\"Result\"];\n };\n"],
5
+ "mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,wBAAAE,EAAA,2BAAAC,EAAA,2BAAAC,EAAA,+BAAAC,IAAA,eAAAC,EAAAN,GAEO,IAAKK,OACVA,EAAA,aAAe,eACfA,EAAA,kBAAoB,oBACpBA,EAAA,UAAY,YACZA,EAAA,eAAiB,iBACjBA,EAAA,WAAa,aACbA,EAAA,aAAe,eANLA,OAAA,IAqBAH,OACVA,EAAA,SAAW,WACXA,EAAA,KAAO,OACPA,EAAA,MAAQ,QACRA,EAAA,QAAU,UACVA,EAAA,QAAU,UALAA,OAAA,IAiBAC,OACVA,EAAA,QAAU,UACVA,EAAA,MAAQ,QAFEA,OAAA,IASAC,OACVA,EAAA,OAAS,SACTA,EAAA,OAAS,SACTA,EAAA,oBAAsB,uBACtBA,EAAA,kBAAoB,qBACpBA,EAAA,YAAc,eACdA,EAAA,SAAW,WACXA,EAAA,SAAW,WACXA,EAAA,QAAU,UACVA,EAAA,MAAQ,QACRA,EAAA,OAAS,SAVCA,OAAA",
6
6
  "names": ["types_exports", "__export", "InMessageQueryEnum", "OutMessageResponseEnum", "SecureChannelEventType", "SecureChannelOperationEnum", "__toCommonJS"]
7
7
  }
@@ -1,2 +1,2 @@
1
- "use strict";var o=Object.defineProperty;var x=Object.getOwnPropertyDescriptor;var u=Object.getOwnPropertyNames;var E=Object.prototype.hasOwnProperty;var c=(e,n)=>{for(var i in n)o(e,i,{get:n[i],enumerable:!0})},f=(e,n,i,t)=>{if(n&&typeof n=="object"||typeof n=="function")for(let r of u(n))!E.call(e,r)&&r!==i&&o(e,r,{get:()=>n[r],enumerable:!(t=x(n,r))||t.enumerable});return e};var y=e=>f(o({},"__esModule",{value:!0}),e);var U={};c(U,{isDeviceGenuine:()=>p,isRefusedByUser:()=>m,willRequestPermission:()=>a});module.exports=y(U);var l=require("./constants");function a(e){return e[0]===224&&e[1]===81}function m(e){return e.length===2&&(e[0]===85&&e[1]===1||e[0]===105&&e[1]===133)}function p(e){return e===l.GENUINE_DEVICE_RESULT}0&&(module.exports={isDeviceGenuine,isRefusedByUser,willRequestPermission});
1
+ "use strict";var o=Object.defineProperty;var u=Object.getOwnPropertyDescriptor;var a=Object.getOwnPropertyNames;var E=Object.prototype.hasOwnProperty;var c=(e,n)=>{for(var t in n)o(e,t,{get:n[t],enumerable:!0})},m=(e,n,t,i)=>{if(n&&typeof n=="object"||typeof n=="function")for(let r of a(n))!E.call(e,r)&&r!==t&&o(e,r,{get:()=>n[r],enumerable:!(i=u(n,r))||i.enumerable});return e};var s=e=>m(o({},"__esModule",{value:!0}),e);var x={};c(x,{isDeviceGenuine:()=>p,willRequestPermission:()=>f});module.exports=s(x);var l=require("./constants");function f(e){return e[0]===224&&e[1]===81}function p(e){return e===l.GENUINE_DEVICE_RESULT}0&&(module.exports={isDeviceGenuine,willRequestPermission});
2
2
  //# sourceMappingURL=utils.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../src/api/secure-channel/utils.ts"],
4
- "sourcesContent": ["import { type SecureChannelEventPayload } from \"./task/types\";\nimport { GENUINE_DEVICE_RESULT } from \"./constants\";\n\n/**\n * Checks if the given APDU command will request permission.\n *\n * This method checks if the first byte of the APDU command is `0xe0` and the second byte is `0x51`.\n *\n * @param apdu - The APDU command as a Uint8Array.\n * @returns `true` if the APDU command will request permission, otherwise `false`.\n */\nexport function willRequestPermission(apdu: Uint8Array): boolean {\n return apdu[0] === 0xe0 && apdu[1] === 0x51;\n}\n\n/**\n * Checks if the user refused the permission on the device.\n *\n * The following status codes indicate a refusal:\n * - \"0x5501\": User refused the permission.\n * - \"0x6985\": Condition of use not satisfied.\n *\n * @param statusCode - The status code to check.\n * @returns `true` if the status code indicates a refusal, otherwise `false`.\n */\nexport function isRefusedByUser(statusCode: Uint8Array): boolean {\n return (\n statusCode.length === 2 &&\n ((statusCode[0] === 0x55 && statusCode[1] === 0x01) ||\n (statusCode[0] === 0x69 && statusCode[1] === 0x85))\n );\n}\n\n/**\n * Checks if the device is genuine.\n *\n * @param payload - The payload of the result secure channel event.\n * The payload has already been stringified, so that the type check is not necessary.\n * @returns `true` if the device is genuine, otherwise `false`.\n */\nexport function isDeviceGenuine(payload: SecureChannelEventPayload[\"Result\"]) {\n return payload === GENUINE_DEVICE_RESULT;\n}\n"],
5
- "mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,qBAAAE,EAAA,oBAAAC,EAAA,0BAAAC,IAAA,eAAAC,EAAAL,GACA,IAAAM,EAAsC,uBAU/B,SAASF,EAAsBG,EAA2B,CAC/D,OAAOA,EAAK,CAAC,IAAM,KAAQA,EAAK,CAAC,IAAM,EACzC,CAYO,SAASJ,EAAgBK,EAAiC,CAC/D,OACEA,EAAW,SAAW,IACpBA,EAAW,CAAC,IAAM,IAAQA,EAAW,CAAC,IAAM,GAC3CA,EAAW,CAAC,IAAM,KAAQA,EAAW,CAAC,IAAM,IAEnD,CASO,SAASN,EAAgBO,EAA8C,CAC5E,OAAOA,IAAY,uBACrB",
6
- "names": ["utils_exports", "__export", "isDeviceGenuine", "isRefusedByUser", "willRequestPermission", "__toCommonJS", "import_constants", "apdu", "statusCode", "payload"]
4
+ "sourcesContent": ["import { type SecureChannelEventPayload } from \"./task/types\";\nimport { GENUINE_DEVICE_RESULT } from \"./constants\";\n\n/**\n * Checks if the given APDU command will request permission.\n *\n * This method checks if the first byte of the APDU command is `0xe0` and the second byte is `0x51`.\n *\n * @param apdu - The APDU command as a Uint8Array.\n * @returns `true` if the APDU command will request permission, otherwise `false`.\n */\nexport function willRequestPermission(apdu: Uint8Array): boolean {\n return apdu[0] === 0xe0 && apdu[1] === 0x51;\n}\n\n/**\n * Checks if the device is genuine.\n *\n * @param payload - The payload of the result secure channel event.\n * The payload has already been stringified, so that the type check is not necessary.\n * @returns `true` if the device is genuine, otherwise `false`.\n */\nexport function isDeviceGenuine(payload: SecureChannelEventPayload[\"Result\"]) {\n return payload === GENUINE_DEVICE_RESULT;\n}\n"],
5
+ "mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,qBAAAE,EAAA,0BAAAC,IAAA,eAAAC,EAAAJ,GACA,IAAAK,EAAsC,uBAU/B,SAASF,EAAsBG,EAA2B,CAC/D,OAAOA,EAAK,CAAC,IAAM,KAAQA,EAAK,CAAC,IAAM,EACzC,CASO,SAASJ,EAAgBK,EAA8C,CAC5E,OAAOA,IAAY,uBACrB",
6
+ "names": ["utils_exports", "__export", "isDeviceGenuine", "willRequestPermission", "__toCommonJS", "import_constants", "apdu", "payload"]
7
7
  }
@@ -1,2 +1,2 @@
1
- "use strict";var t=require("./utils");describe("willRequestPermission",()=>{it("should return true if the APDU is a permission request",()=>{const e=new Uint8Array([224,81,0,0,0]);expect((0,t.willRequestPermission)(e)).toBe(!0)}),it("should return false if the APDU is not a permission request",()=>{const e=new Uint8Array([224,82,0,0,0]);expect((0,t.willRequestPermission)(e)).toBe(!1)})});describe("isRefusedByUser",()=>{it("should return true if the status code indicates a refusal",()=>{[new Uint8Array([85,1]),new Uint8Array([105,133])].forEach(e=>{expect((0,t.isRefusedByUser)(e)).toBe(!0)})}),it("should return false if the status code does not indicate a refusal",()=>{const e=new Uint8Array([144,0]);expect((0,t.isRefusedByUser)(e)).toBe(!1)})});describe("isDeviceGenuine",()=>{it("should return true if the device is genuine",()=>{expect((0,t.isDeviceGenuine)("0000")).toBe(!0)}),it("should return false if the device is not genuine",()=>{expect((0,t.isDeviceGenuine)("not genuine")).toBe(!1)})});
1
+ "use strict";var e=require("./utils");describe("willRequestPermission",()=>{it("should return true if the APDU is a permission request",()=>{const i=new Uint8Array([224,81,0,0,0]);expect((0,e.willRequestPermission)(i)).toBe(!0)}),it("should return false if the APDU is not a permission request",()=>{const i=new Uint8Array([224,82,0,0,0]);expect((0,e.willRequestPermission)(i)).toBe(!1)})});describe("isDeviceGenuine",()=>{it("should return true if the device is genuine",()=>{expect((0,e.isDeviceGenuine)("0000")).toBe(!0)}),it("should return false if the device is not genuine",()=>{expect((0,e.isDeviceGenuine)("not genuine")).toBe(!1)})});
2
2
  //# sourceMappingURL=utils.test.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../src/api/secure-channel/utils.test.ts"],
4
- "sourcesContent": ["import {\n isDeviceGenuine,\n isRefusedByUser,\n willRequestPermission,\n} from \"./utils\";\n\ndescribe(\"willRequestPermission\", () => {\n it(\"should return true if the APDU is a permission request\", () => {\n const apdu = new Uint8Array([0xe0, 0x51, 0x00, 0x00, 0x00]);\n expect(willRequestPermission(apdu)).toBe(true);\n });\n it(\"should return false if the APDU is not a permission request\", () => {\n const apdu = new Uint8Array([0xe0, 0x52, 0x00, 0x00, 0x00]);\n expect(willRequestPermission(apdu)).toBe(false);\n });\n});\n\ndescribe(\"isRefusedByUser\", () => {\n it(\"should return true if the status code indicates a refusal\", () => {\n [new Uint8Array([0x55, 0x01]), new Uint8Array([0x69, 0x85])].forEach(\n (statusCode) => {\n expect(isRefusedByUser(statusCode)).toBe(true);\n },\n );\n });\n it(\"should return false if the status code does not indicate a refusal\", () => {\n const statusCode = new Uint8Array([0x90, 0x00]);\n expect(isRefusedByUser(statusCode)).toBe(false);\n });\n});\n\ndescribe(\"isDeviceGenuine\", () => {\n it(\"should return true if the device is genuine\", () => {\n const payload = \"0000\";\n expect(isDeviceGenuine(payload)).toBe(true);\n });\n it(\"should return false if the device is not genuine\", () => {\n const payload = \"not genuine\";\n expect(isDeviceGenuine(payload)).toBe(false);\n });\n});\n"],
5
- "mappings": "aAAA,IAAAA,EAIO,mBAEP,SAAS,wBAAyB,IAAM,CACtC,GAAG,yDAA0D,IAAM,CACjE,MAAMC,EAAO,IAAI,WAAW,CAAC,IAAM,GAAM,EAAM,EAAM,CAAI,CAAC,EAC1D,UAAO,yBAAsBA,CAAI,CAAC,EAAE,KAAK,EAAI,CAC/C,CAAC,EACD,GAAG,8DAA+D,IAAM,CACtE,MAAMA,EAAO,IAAI,WAAW,CAAC,IAAM,GAAM,EAAM,EAAM,CAAI,CAAC,EAC1D,UAAO,yBAAsBA,CAAI,CAAC,EAAE,KAAK,EAAK,CAChD,CAAC,CACH,CAAC,EAED,SAAS,kBAAmB,IAAM,CAChC,GAAG,4DAA6D,IAAM,CACpE,CAAC,IAAI,WAAW,CAAC,GAAM,CAAI,CAAC,EAAG,IAAI,WAAW,CAAC,IAAM,GAAI,CAAC,CAAC,EAAE,QAC1DC,GAAe,CACd,UAAO,mBAAgBA,CAAU,CAAC,EAAE,KAAK,EAAI,CAC/C,CACF,CACF,CAAC,EACD,GAAG,qEAAsE,IAAM,CAC7E,MAAMA,EAAa,IAAI,WAAW,CAAC,IAAM,CAAI,CAAC,EAC9C,UAAO,mBAAgBA,CAAU,CAAC,EAAE,KAAK,EAAK,CAChD,CAAC,CACH,CAAC,EAED,SAAS,kBAAmB,IAAM,CAChC,GAAG,8CAA+C,IAAM,CAEtD,UAAO,mBADS,MACc,CAAC,EAAE,KAAK,EAAI,CAC5C,CAAC,EACD,GAAG,mDAAoD,IAAM,CAE3D,UAAO,mBADS,aACc,CAAC,EAAE,KAAK,EAAK,CAC7C,CAAC,CACH,CAAC",
6
- "names": ["import_utils", "apdu", "statusCode"]
4
+ "sourcesContent": ["import { isDeviceGenuine, willRequestPermission } from \"./utils\";\n\ndescribe(\"willRequestPermission\", () => {\n it(\"should return true if the APDU is a permission request\", () => {\n const apdu = new Uint8Array([0xe0, 0x51, 0x00, 0x00, 0x00]);\n expect(willRequestPermission(apdu)).toBe(true);\n });\n it(\"should return false if the APDU is not a permission request\", () => {\n const apdu = new Uint8Array([0xe0, 0x52, 0x00, 0x00, 0x00]);\n expect(willRequestPermission(apdu)).toBe(false);\n });\n});\n\ndescribe(\"isDeviceGenuine\", () => {\n it(\"should return true if the device is genuine\", () => {\n const payload = \"0000\";\n expect(isDeviceGenuine(payload)).toBe(true);\n });\n it(\"should return false if the device is not genuine\", () => {\n const payload = \"not genuine\";\n expect(isDeviceGenuine(payload)).toBe(false);\n });\n});\n"],
5
+ "mappings": "aAAA,IAAAA,EAAuD,mBAEvD,SAAS,wBAAyB,IAAM,CACtC,GAAG,yDAA0D,IAAM,CACjE,MAAMC,EAAO,IAAI,WAAW,CAAC,IAAM,GAAM,EAAM,EAAM,CAAI,CAAC,EAC1D,UAAO,yBAAsBA,CAAI,CAAC,EAAE,KAAK,EAAI,CAC/C,CAAC,EACD,GAAG,8DAA+D,IAAM,CACtE,MAAMA,EAAO,IAAI,WAAW,CAAC,IAAM,GAAM,EAAM,EAAM,CAAI,CAAC,EAC1D,UAAO,yBAAsBA,CAAI,CAAC,EAAE,KAAK,EAAK,CAChD,CAAC,CACH,CAAC,EAED,SAAS,kBAAmB,IAAM,CAChC,GAAG,8CAA+C,IAAM,CAEtD,UAAO,mBADS,MACc,CAAC,EAAE,KAAK,EAAI,CAC5C,CAAC,EACD,GAAG,mDAAoD,IAAM,CAE3D,UAAO,mBADS,aACc,CAAC,EAAE,KAAK,EAAK,CAC7C,CAAC,CACH,CAAC",
6
+ "names": ["import_utils", "apdu"]
7
7
  }
@@ -1,2 +1,2 @@
1
- "use strict";var u=Object.defineProperty;var g=Object.getOwnPropertyDescriptor;var h=Object.getOwnPropertyNames;var D=Object.prototype.hasOwnProperty;var C=(r,n)=>{for(var i in n)u(r,i,{get:n[i],enumerable:!0})},v=(r,n,i,s)=>{if(n&&typeof n=="object"||typeof n=="function")for(let o of h(n))!D.call(r,o)&&o!==i&&u(r,o,{get:()=>n[o],enumerable:!(s=g(n,o))||s.enumerable});return r};var y=r=>v(u({},"__esModule",{value:!0}),r);var S={};C(S,{DeviceConnectionStateMachine:()=>R});module.exports=y(S);var t=require("purify-ts"),c=require("xstate"),m=require("../../command/utils/CommandUtils"),l=require("../../Error"),d=require("./Errors");class R{deviceId;deviceAdpuSender;machineActor;timeoutDuration;timeout=null;startReconnectionTimeout(){this.timeout=setTimeout(()=>{this.machineActor.send({type:"ReconnectionTimedOut"})},this.timeoutDuration)}constructor(n){this.deviceId=n.deviceId,this.deviceAdpuSender=n.deviceApduSender,this.timeoutDuration=n.timeoutDuration,this.machineActor=(0,c.createActor)(T({sendApduFn:(i,s,o)=>this.sendApduToDeviceConnection(i,s,o),startReconnectionTimeout:()=>this.startReconnectionTimeout(),cancelReconnectionTimeout:()=>{this.timeout&&(clearTimeout(this.timeout),this.timeout=null)},onTerminated:n.onTerminated,closeConnection:()=>{this.deviceAdpuSender.closeConnection()}})),this.machineActor.start()}sendApduToDeviceConnection(n,i,s){this.deviceAdpuSender.sendApdu(n,i,s).then(o=>{o.caseOf({Left:e=>{this.machineActor.send({type:"ApduSendingError",error:e})},Right:e=>{this.machineActor.send({type:"ApduResponseReceived",apduResponse:e})}})}).catch(o=>{this.machineActor.send({type:"ApduSendingError",error:new l.UnknownDeviceExchangeError(o)})})}getDependencies(){return this.deviceAdpuSender.getDependencies()}setDependencies(n){this.deviceAdpuSender.setDependencies(n)}getDeviceId(){return this.deviceId}sendApdu(n,i,s){return new Promise(o=>{this.machineActor.send({type:"SendApduCalled",apdu:n,triggersDisconnection:!!i,abortTimeout:s,responseCallback:o})})}async setupConnection(){await this.deviceAdpuSender.setupConnection()}eventDeviceAttached(){this.machineActor.send({type:"DeviceAttached"})}eventDeviceDetached(){this.machineActor.send({type:"DeviceDetached"})}closeConnection(){this.machineActor.send({type:"CloseConnectionCalled"})}}function T({sendApduFn:r,startReconnectionTimeout:n,cancelReconnectionTimeout:i,onTerminated:s,closeConnection:o}){return(0,c.setup)({types:{},actions:{startTimer:()=>{n()},cancelTimer:()=>{i()},reconnectionTimeoutEvent:(0,c.emit)({type:"ReconnectionTimedOut"}),sendApdu:({context:e})=>{e.apduInProgress.map(({apdu:p,abortTimeout:a})=>{r(p,!1,a)})},sendApduResponse:({context:e},p)=>{e.apduInProgress.map(({responseCallback:a})=>a(p.response))},cleanupContext:(0,c.assign)({apduInProgress:t.Nothing}),signalTermination:()=>{s()},closeConnection:()=>{o()}},guards:{isApduThatTriggersDisconnection:({context:e},p)=>e.apduInProgress.caseOf({Just:({triggersDisconnection:a,apdu:A})=>(a||m.CommandUtils.isApduThatTriggersDisconnection(A))&&m.CommandUtils.isSuccessResponse(p.apduResponse),Nothing:()=>!1})}}).createMachine({id:"deviceConnection",initial:"Connected",context:{apduInProgress:t.Nothing},states:{Connected:{on:{DeviceDetached:{target:"WaitingForReconnection"},SendApduCalled:{target:"SendingApdu",actions:(0,c.assign)({apduInProgress:({event:e})=>t.Maybe.of({apdu:e.apdu,triggersDisconnection:e.triggersDisconnection,abortTimeout:e.abortTimeout,responseCallback:e.responseCallback})})},CloseConnectionCalled:{target:"Terminated"}}},SendingApdu:{entry:"sendApdu",on:{ApduResponseReceived:[{guard:{type:"isApduThatTriggersDisconnection",params:({event:e})=>({apduResponse:e.apduResponse})},target:"WaitingForReconnection",actions:[{type:"sendApduResponse",params:({event:e})=>({response:(0,t.Right)(e.apduResponse)})},{type:"cleanupContext"}]},{target:"Connected",actions:[{type:"sendApduResponse",params:({event:e})=>({response:(0,t.Right)(e.apduResponse)})},{type:"cleanupContext"}]}],ApduSendingError:{target:"Connected",actions:[{type:"sendApduResponse",params:({event:e})=>({response:(0,t.Left)(e.error)})},"cleanupContext"]},DeviceDetached:{target:"WaitingForReconnection",actions:[{type:"sendApduResponse",params:{response:(0,t.Left)(new d.DeviceDisconnectedWhileSendingError)}},"cleanupContext"]},CloseConnectionCalled:{target:"Terminated",actions:[{type:"sendApduResponse",params:{response:(0,t.Left)(new d.DeviceDisconnectedWhileSendingError)}},"cleanupContext"]},SendApduCalled:{actions:({event:e})=>{e.responseCallback((0,t.Left)(new d.AlreadySendingApduError))}}}},WaitingForReconnection:{entry:"startTimer",on:{DeviceAttached:{target:"Connected",actions:"cancelTimer"},SendApduCalled:{target:"WaitingForReconnectionWithQueuedSendApdu",actions:(0,c.assign)({apduInProgress:({event:e})=>t.Maybe.of({apdu:e.apdu,triggersDisconnection:e.triggersDisconnection,abortTimeout:e.abortTimeout,responseCallback:e.responseCallback})})},ReconnectionTimedOut:{target:"Terminated"},CloseConnectionCalled:{target:"Terminated"}}},WaitingForReconnectionWithQueuedSendApdu:{on:{DeviceAttached:{target:"SendingApdu",actions:"cancelTimer"},ReconnectionTimedOut:{target:"Terminated",actions:[{type:"sendApduResponse",params:{response:(0,t.Left)(new d.DeviceDisconnectedBeforeSendingApdu)}},{type:"cleanupContext"}]},CloseConnectionCalled:{target:"Terminated",actions:[{type:"sendApduResponse",params:{response:(0,t.Left)(new d.DeviceDisconnectedWhileSendingError)}},"cleanupContext"]},SendApduCalled:{actions:({event:e})=>{e.responseCallback((0,t.Left)(new d.AlreadySendingApduError))}}}},Terminated:{entry:["signalTermination","closeConnection"],type:"final"}}})}0&&(module.exports={DeviceConnectionStateMachine});
1
+ "use strict";var m=Object.defineProperty;var R=Object.getOwnPropertyDescriptor;var C=Object.getOwnPropertyNames;var v=Object.prototype.hasOwnProperty;var y=(s,n)=>{for(var i in n)m(s,i,{get:n[i],enumerable:!0})},h=(s,n,i,c)=>{if(n&&typeof n=="object"||typeof n=="function")for(let o of C(n))!v.call(s,o)&&o!==i&&m(s,o,{get:()=>n[o],enumerable:!(c=R(n,o))||c.enumerable});return s};var T=s=>h(m({},"__esModule",{value:!0}),s);var E={};y(E,{DeviceConnectionStateMachine:()=>S});module.exports=T(E);var t=require("purify-ts"),r=require("xstate"),g=require("../../command/os/GetAppAndVersionCommand"),l=require("../../command/utils/CommandUtils"),A=require("../../Error"),d=require("./Errors");class S{deviceId;deviceAdpuSender;machineActor;timeoutDuration;timeout=null;startReconnectionTimeout(){this.timeout=setTimeout(()=>{this.machineActor.send({type:"ReconnectionTimedOut"})},this.timeoutDuration)}constructor(n){this.deviceId=n.deviceId,this.deviceAdpuSender=n.deviceApduSender,this.timeoutDuration=n.timeoutDuration,this.machineActor=(0,r.createActor)(b({sendApduFn:(i,c,o)=>this.sendApduToDeviceConnection(i,c,o),startReconnectionTimeout:()=>this.startReconnectionTimeout(),cancelReconnectionTimeout:()=>{this.timeout&&(clearTimeout(this.timeout),this.timeout=null)},tryToReconnect:()=>{n.tryToReconnect(this.timeoutDuration)},onTerminated:n.onTerminated,closeConnection:()=>{this.deviceAdpuSender.closeConnection()}})),this.machineActor.start()}sendApduToDeviceConnection(n,i,c){this.deviceAdpuSender.sendApdu(n,i,c).then(o=>{o.caseOf({Left:a=>{this.machineActor.send({type:"ApduSendingError",error:a})},Right:a=>{this.machineActor.send({type:"ApduResponseReceived",apduResponse:a})}})}).catch(o=>{this.machineActor.send({type:"ApduSendingError",error:new A.UnknownDeviceExchangeError(o)})})}getDependencies(){return this.deviceAdpuSender.getDependencies()}setDependencies(n){this.deviceAdpuSender.setDependencies(n)}getDeviceId(){return this.deviceId}sendApdu(n,i,c){return new Promise(o=>{this.machineActor.send({type:"SendApduCalled",apdu:n,triggersDisconnection:!!i,abortTimeout:c,responseCallback:o})})}async setupConnection(){await this.deviceAdpuSender.setupConnection()}eventDeviceConnected(){this.machineActor.send({type:"DeviceConnected"})}eventDeviceDisconnected(){this.machineActor.send({type:"DeviceDisconnected"})}closeConnection(){this.machineActor.send({type:"CloseConnectionCalled"})}}function b({sendApduFn:s,startReconnectionTimeout:n,cancelReconnectionTimeout:i,tryToReconnect:c,onTerminated:o,closeConnection:a}){return(0,r.setup)({types:{},actions:{startTimer:()=>{n()},cancelTimer:()=>{i()},reconnectionTimeoutEvent:(0,r.emit)({type:"ReconnectionTimedOut"}),sendApdu:({context:e})=>{e.apduInProgress.map(({apdu:p,abortTimeout:u})=>{s(p,!1,u)})},sendApduResponse:({context:e},p)=>{e.apduInProgress.map(({responseCallback:u})=>u(p.response))},sendGetAppAndVersion:()=>{s(new g.GetAppAndVersionCommand().getApdu().getRawApdu(),!1)},tryToReconnect:()=>{c()},clearApduInProgress:(0,r.assign)({apduInProgress:t.Nothing}),clearApduResponse:(0,r.assign)({apduResponse:t.Nothing}),signalTermination:()=>{o()},closeConnection:()=>{a()}},guards:{isApduThatTriggersDisconnection:({context:e},p)=>e.apduInProgress.caseOf({Just:({triggersDisconnection:u,apdu:D})=>(u||l.CommandUtils.isApduThatTriggersDisconnection(D))&&l.CommandUtils.isSuccessResponse(p.apduResponse),Nothing:()=>!1})}}).createMachine({id:"deviceConnection",initial:"Connected",context:{apduInProgress:t.Nothing,apduResponse:t.Nothing},states:{Connected:{on:{DeviceDisconnected:{target:"WaitingForReconnection"},SendApduCalled:{target:"SendingApdu",actions:(0,r.assign)({apduInProgress:({event:e})=>t.Maybe.of({apdu:e.apdu,triggersDisconnection:e.triggersDisconnection,abortTimeout:e.abortTimeout,responseCallback:e.responseCallback})})},CloseConnectionCalled:{target:"Terminated"}}},SendingApdu:{entry:"sendApdu",on:{ApduResponseReceived:[{guard:{type:"isApduThatTriggersDisconnection",params:({event:e})=>({apduResponse:e.apduResponse})},target:"WaitingForDisconnection",actions:[(0,r.assign)({apduResponse:({event:e})=>t.Maybe.of(e.apduResponse)})]},{target:"Connected",actions:[{type:"sendApduResponse",params:({event:e})=>({response:(0,t.Right)(e.apduResponse)})},{type:"clearApduInProgress"}]}],ApduSendingError:{target:"Connected",actions:[{type:"sendApduResponse",params:({event:e})=>({response:(0,t.Left)(e.error)})},"clearApduInProgress"]},DeviceDisconnected:{target:"WaitingForReconnection",actions:[{type:"sendApduResponse",params:{response:(0,t.Left)(new d.DeviceDisconnectedWhileSendingError)}},"clearApduInProgress"]},CloseConnectionCalled:{target:"Terminated",actions:[{type:"sendApduResponse",params:{response:(0,t.Left)(new d.DeviceDisconnectedWhileSendingError)}},"clearApduInProgress"]},SendApduCalled:{actions:({event:e})=>{e.responseCallback((0,t.Left)(new d.AlreadySendingApduError))}}}},WaitingForDisconnection:{entry:"sendGetAppAndVersion",exit:[{type:"sendApduResponse",params:({context:e})=>({response:e.apduResponse.caseOf({Just:p=>(0,t.Right)(p),Nothing:()=>(0,t.Left)(new A.UnknownDeviceExchangeError)})})},{type:"clearApduInProgress"},{type:"clearApduResponse"}],on:{ApduResponseReceived:{target:"Connected"},ApduSendingError:{target:"WaitingForReconnection"},DeviceDisconnected:{target:"WaitingForReconnection"},CloseConnectionCalled:{target:"Terminated"}}},WaitingForReconnection:{entry:["startTimer","tryToReconnect"],on:{DeviceConnected:{target:"Connected",actions:"cancelTimer"},SendApduCalled:{target:"WaitingForReconnectionWithQueuedSendApdu",actions:(0,r.assign)({apduInProgress:({event:e})=>t.Maybe.of({apdu:e.apdu,triggersDisconnection:e.triggersDisconnection,abortTimeout:e.abortTimeout,responseCallback:e.responseCallback})})},ReconnectionTimedOut:{target:"Terminated"},CloseConnectionCalled:{target:"Terminated"}}},WaitingForReconnectionWithQueuedSendApdu:{on:{DeviceConnected:{target:"SendingApdu",actions:"cancelTimer"},ReconnectionTimedOut:{target:"Terminated",actions:[{type:"sendApduResponse",params:{response:(0,t.Left)(new d.DeviceDisconnectedBeforeSendingApdu)}},{type:"clearApduInProgress"}]},CloseConnectionCalled:{target:"Terminated",actions:[{type:"sendApduResponse",params:{response:(0,t.Left)(new d.DeviceDisconnectedWhileSendingError)}},"clearApduInProgress"]},SendApduCalled:{actions:({event:e})=>{e.responseCallback((0,t.Left)(new d.AlreadySendingApduError))}}}},Terminated:{entry:["signalTermination","closeConnection"],type:"final"}}})}0&&(module.exports={DeviceConnectionStateMachine});
2
2
  //# sourceMappingURL=DeviceConnectionStateMachine.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../../src/api/transport/model/DeviceConnectionStateMachine.ts"],
4
- "sourcesContent": ["// import { createBrowserInspector } from \"@statelyai/inspect\";\nimport { type Either, Left, Maybe, Nothing, Right } from \"purify-ts\";\nimport { type Actor, assign, createActor, emit, setup } from \"xstate\";\n\nimport { CommandUtils } from \"@api/command/utils/CommandUtils\";\nimport { type ApduResponse } from \"@api/device-session/ApduResponse\";\nimport { type DmkError, UnknownDeviceExchangeError } from \"@api/Error\";\nimport { type DeviceId } from \"@api/types\";\n\nimport { type DeviceApduSender } from \"./DeviceApduSender\";\nimport {\n AlreadySendingApduError,\n DeviceDisconnectedBeforeSendingApdu,\n DeviceDisconnectedWhileSendingError,\n} from \"./Errors\";\n\n// const { inspect } = createBrowserInspector();\n\ntype DeviceDetachedEvent = {\n type: \"DeviceDetached\";\n};\n\ntype DeviceAttachedEvent = {\n type: \"DeviceAttached\";\n};\n\ntype ApduResponseReceived = {\n type: \"ApduResponseReceived\";\n apduResponse: ApduResponse;\n};\n\ntype ApduSendingError = {\n type: \"ApduSendingError\";\n error: DmkError;\n};\n\ntype SendApduCalled = {\n type: \"SendApduCalled\";\n apdu: Uint8Array;\n triggersDisconnection: boolean;\n abortTimeout?: number;\n responseCallback: (response: Either<DmkError, ApduResponse>) => void;\n};\n\ntype ReconnectionTimedOut = {\n type: \"ReconnectionTimedOut\";\n};\n\ntype CloseConnectionCalled = {\n type: \"CloseConnectionCalled\";\n};\n\nexport type DeviceConnectionEvent =\n | DeviceDetachedEvent\n | DeviceAttachedEvent\n | ApduResponseReceived\n | ApduSendingError\n | SendApduCalled\n | CloseConnectionCalled\n | ReconnectionTimedOut;\n\nexport type DeviceConnectionStateMachineParams<Dependencies> = {\n deviceId: DeviceId;\n deviceApduSender: DeviceApduSender<Dependencies>;\n timeoutDuration: number;\n onTerminated: () => void;\n};\n\nexport class DeviceConnectionStateMachine<Dependencies> {\n private deviceId: DeviceId;\n private deviceAdpuSender: DeviceApduSender<Dependencies>;\n\n private machineActor: Actor<ReturnType<typeof makeStateMachine>>;\n\n private timeoutDuration: number;\n private timeout: ReturnType<typeof setTimeout> | null = null;\n\n startReconnectionTimeout() {\n this.timeout = setTimeout(() => {\n this.machineActor.send({ type: \"ReconnectionTimedOut\" });\n }, this.timeoutDuration);\n }\n\n constructor(params: DeviceConnectionStateMachineParams<Dependencies>) {\n this.deviceId = params.deviceId;\n this.deviceAdpuSender = params.deviceApduSender;\n this.timeoutDuration = params.timeoutDuration;\n this.machineActor = createActor(\n makeStateMachine({\n sendApduFn: (apdu, triggersDisconnection, abortTimeout) =>\n this.sendApduToDeviceConnection(\n apdu,\n triggersDisconnection,\n abortTimeout,\n ),\n startReconnectionTimeout: () => this.startReconnectionTimeout(),\n cancelReconnectionTimeout: () => {\n if (this.timeout) {\n clearTimeout(this.timeout);\n this.timeout = null;\n }\n },\n onTerminated: params.onTerminated,\n closeConnection: () => {\n this.deviceAdpuSender.closeConnection();\n },\n }),\n // {\n // // inspect,\n // },\n );\n this.machineActor.start();\n }\n\n private sendApduToDeviceConnection(\n apdu: Uint8Array,\n triggersDisconnection?: boolean,\n abortTimeout?: number,\n ) {\n this.deviceAdpuSender\n .sendApdu(apdu, triggersDisconnection, abortTimeout)\n .then((response) => {\n response.caseOf({\n Left: (error) => {\n this.machineActor.send({ type: \"ApduSendingError\", error });\n },\n Right: (apduResponse) => {\n this.machineActor.send({\n type: \"ApduResponseReceived\",\n apduResponse,\n });\n },\n });\n })\n .catch((error) => {\n this.machineActor.send({\n type: \"ApduSendingError\",\n error: new UnknownDeviceExchangeError(error),\n });\n });\n }\n\n /**\n * Called by the transport\n */\n\n public getDependencies(): Dependencies {\n return this.deviceAdpuSender.getDependencies();\n }\n\n public setDependencies(dependencies: Dependencies) {\n this.deviceAdpuSender.setDependencies(dependencies);\n }\n\n public getDeviceId() {\n return this.deviceId;\n }\n\n public sendApdu(\n apdu: Uint8Array,\n triggersDisconnection?: boolean,\n abortTimeout?: number,\n ): Promise<Either<DmkError, ApduResponse>> {\n return new Promise((responseCallback) => {\n this.machineActor.send({\n type: \"SendApduCalled\",\n apdu,\n triggersDisconnection: !!triggersDisconnection,\n abortTimeout,\n responseCallback,\n });\n });\n }\n\n public async setupConnection() {\n await this.deviceAdpuSender.setupConnection();\n }\n\n // State Machine Events\n\n public eventDeviceAttached() {\n this.machineActor.send({ type: \"DeviceAttached\" });\n }\n\n public eventDeviceDetached() {\n this.machineActor.send({ type: \"DeviceDetached\" });\n }\n\n public closeConnection() {\n this.machineActor.send({ type: \"CloseConnectionCalled\" });\n }\n}\n\nfunction makeStateMachine({\n sendApduFn,\n startReconnectionTimeout,\n cancelReconnectionTimeout,\n onTerminated,\n closeConnection,\n}: {\n sendApduFn: (\n apdu: Uint8Array,\n triggersDisconnection: boolean,\n abortTimeout?: number,\n ) => void;\n startReconnectionTimeout: () => void;\n cancelReconnectionTimeout: () => void;\n onTerminated: () => void;\n closeConnection: () => void;\n}) {\n return setup({\n types: {} as {\n context: {\n apduInProgress: Maybe<{\n apdu: Uint8Array;\n triggersDisconnection: boolean;\n abortTimeout?: number;\n responseCallback: (response: Either<DmkError, ApduResponse>) => void;\n }>;\n };\n events: DeviceConnectionEvent;\n },\n actions: {\n // event transitions\n startTimer: () => {\n startReconnectionTimeout();\n },\n cancelTimer: () => {\n cancelReconnectionTimeout();\n },\n reconnectionTimeoutEvent: emit({ type: \"ReconnectionTimedOut\" }),\n sendApdu: ({ context }) => {\n context.apduInProgress.map(({ apdu, abortTimeout }) => {\n sendApduFn(apdu, false, abortTimeout);\n });\n },\n sendApduResponse: (\n { context },\n params: { response: Either<DmkError, ApduResponse> },\n ) => {\n context.apduInProgress.map(({ responseCallback }) =>\n responseCallback(params.response),\n );\n },\n cleanupContext: assign({ apduInProgress: Nothing }),\n signalTermination: () => {\n onTerminated();\n },\n closeConnection: () => {\n closeConnection(); // ASK: how do we handle errors ?\n },\n },\n guards: {\n isApduThatTriggersDisconnection: (\n { context },\n params: { apduResponse: ApduResponse },\n ) => {\n return context.apduInProgress.caseOf({\n Just: ({ triggersDisconnection, apdu }) => {\n const res =\n (triggersDisconnection ||\n CommandUtils.isApduThatTriggersDisconnection(apdu)) &&\n CommandUtils.isSuccessResponse(params.apduResponse);\n return res;\n },\n Nothing: () => false,\n });\n },\n },\n }).createMachine({\n /** @xstate-layout N4IgpgJg5mDOIC5QTANwJYGMwGED2AdgWJgC7qEB0+RJpkAxACJpZgukCGmAFpANoAGALqJQABzyx05QmJAAPRAA4A7AGZKywQEYAnAFYATMoAsBg6fUA2ADQgAnolUnKBjUdXXVpnUb0aAL6B9igY2DTEZBQE1IRR9BAMAMpgBBAAguIQAK44nAA2BQIi8pLSsgTySgjW6oKU6uo61kbWyh06Vsr2TgjqAZR6HUaWXcrqBmrBoawR8XQxcbRkjDgFUrgL0YT5RSWiSCDlMjHVKnrWjaO6ev6qlnp6vYim1qaN9YLqGuPKOjpVDMQGE2JFFlRUul0AQoFlcgx4TkAEpwSQEWBgVHYdCoA5lKSnORHGpNVSUPwGXQDQSmNTDF4IZTWPRDJotUw+HwAnTA0HzFaVShQiAwuHZHKIiWo2DozHYsC4gQ6Q4SQmVc79TxDIzqG6eJq+VSM94NPQ6CYuUzmQGCax8uZbQVLEVipFS3Ku2EAUQATr68L6hKrjuqziTEJNNHrTG1dIIDE8jLTGVTlJQboI2i56QZeSEQY7wTtYl7xQiWOF2GAuLx8UcThqIwh-OmdBZPF0qQCBoydIJlAZKK0jP4bHntBaHVXi0Ky+71ptZzE9sUIMGCRVw6Aau2dJQ6WZlMM-D9+89HIh++mbndVHpdNYLAnp2DtnO0qLYe6RUjV-W1S3Ykd0QABac1KFpbx3kHCxumNS9ak5SDTHNax0NUDRfFMV8BQSJYAHVOFOWEADFA2xd8YmYR0MlIWs+HXUoGzDYDFEQQx90mVozABJ9BAvPo6iuFpRgtQRdDUWNcKdfCqCIkioHI31KOdQgUk-P9CjXDcWKAqpmx0dR-gpCTaXNUxvh7RkvCHWlaWM9RfC6dCZOXeTiPIMiKJIKj1NUuSCAAFXQABbSAAHkclIXTAKJAyQIQLpBHJAEXB8AS1HvdRGT0a0D2ZZpBxjSc3L82IFK8pSfMwcqGEXTF3IIf8mJDRtt3YpLLPJZMWkmTtzJyxD+1UBofifVQOm8YyWjKtSKs8sVlICiECAImQeAARRyMAdogX8JRoqs6IYgDQ30zUjJ8CkWQmYZbOsFLGWzUyzE5bssx8ObAsoSqlpq8r1tILadr2g6ERWksQvCiAopi5i4qbRKjH7Bo4N1dsvFjOxEIeIwUPQ9o9AGSYvG+1bfsW7yVN8+agZB3bIHByUGtk1aWti874s1FGJOHYy6gTLo3lMVN7wPBNVAtbRRg0IEC35NmS0pxTltpwL6e2xn9s0w7mY5hGuaRzrAWZIYBJpc0pd1E18tNMZLOMAwnOCAsCDwFB4CORWms3bnm1AozWSgrHYMsYyEL6FGKXcDleMMO5rXJ5XZ0gP3jZqB4evaLwXEeqwnJNKYDypWlzHePwcIVotyuFT83QldOOpqWNU30A8rEmrMjPcAJk6FP7qch432rY3dxnN1onlaZ9idy5NILuCxl+UEwrH7wiqeqmnarpjatbB3Xcibser3eckfmd3xOkrnpce0DMjHMeoAgLjeqCCsBfVCmFOESE+EqdSfnmNwLJjBPBSs0QwuV3CQWPN3AwT4LTtldoEIAA */\n id: \"deviceConnection\",\n initial: \"Connected\",\n context: {\n apduInProgress: Nothing,\n },\n states: {\n Connected: {\n on: {\n DeviceDetached: {\n target: \"WaitingForReconnection\",\n },\n SendApduCalled: {\n target: \"SendingApdu\",\n actions: assign({\n apduInProgress: ({ event }) => {\n return Maybe.of({\n apdu: event.apdu,\n triggersDisconnection: event.triggersDisconnection,\n abortTimeout: event.abortTimeout,\n responseCallback: event.responseCallback,\n });\n },\n }),\n },\n CloseConnectionCalled: {\n target: \"Terminated\",\n },\n },\n },\n SendingApdu: {\n entry: \"sendApdu\",\n on: {\n ApduResponseReceived: [\n {\n guard: {\n type: \"isApduThatTriggersDisconnection\",\n params: ({ event }) => ({ apduResponse: event.apduResponse }),\n },\n target: \"WaitingForReconnection\",\n actions: [\n {\n type: \"sendApduResponse\",\n // https://stately.ai/docs/actions#dynamic-action-parameters\n params: ({ event }) => {\n return {\n response: Right(event.apduResponse),\n };\n },\n },\n { type: \"cleanupContext\" },\n ],\n },\n {\n target: \"Connected\",\n actions: [\n {\n type: \"sendApduResponse\",\n // https://stately.ai/docs/actions#dynamic-action-parameters\n params: ({ event }) => {\n return {\n response: Right(event.apduResponse),\n };\n },\n },\n { type: \"cleanupContext\" },\n ],\n },\n ],\n ApduSendingError: {\n target: \"Connected\",\n actions: [\n {\n type: \"sendApduResponse\",\n // https://stately.ai/docs/actions#dynamic-action-parameters\n params: ({ event }) => {\n return {\n response: Left(event.error),\n };\n },\n },\n \"cleanupContext\",\n ],\n },\n DeviceDetached: {\n target: \"WaitingForReconnection\",\n actions: [\n {\n type: \"sendApduResponse\",\n params: {\n response: Left(new DeviceDisconnectedWhileSendingError()),\n },\n },\n \"cleanupContext\",\n ],\n },\n CloseConnectionCalled: {\n target: \"Terminated\",\n actions: [\n {\n type: \"sendApduResponse\",\n params: {\n response: Left(new DeviceDisconnectedWhileSendingError()),\n },\n },\n \"cleanupContext\",\n ],\n },\n SendApduCalled: {\n actions: ({ event }) => {\n event.responseCallback(Left(new AlreadySendingApduError()));\n },\n },\n },\n },\n WaitingForReconnection: {\n entry: \"startTimer\",\n on: {\n DeviceAttached: {\n target: \"Connected\",\n actions: \"cancelTimer\",\n },\n SendApduCalled: {\n target: \"WaitingForReconnectionWithQueuedSendApdu\",\n actions: assign({\n apduInProgress: ({ event }) => {\n return Maybe.of({\n apdu: event.apdu,\n triggersDisconnection: event.triggersDisconnection,\n abortTimeout: event.abortTimeout,\n responseCallback: event.responseCallback,\n });\n },\n }),\n },\n ReconnectionTimedOut: {\n target: \"Terminated\",\n },\n CloseConnectionCalled: {\n target: \"Terminated\",\n },\n },\n },\n WaitingForReconnectionWithQueuedSendApdu: {\n on: {\n DeviceAttached: {\n target: \"SendingApdu\",\n actions: \"cancelTimer\",\n },\n ReconnectionTimedOut: {\n target: \"Terminated\",\n actions: [\n {\n type: \"sendApduResponse\",\n params: {\n response: Left(new DeviceDisconnectedBeforeSendingApdu()),\n },\n },\n {\n type: \"cleanupContext\",\n },\n ],\n },\n CloseConnectionCalled: {\n target: \"Terminated\",\n actions: [\n {\n type: \"sendApduResponse\",\n params: {\n response: Left(new DeviceDisconnectedWhileSendingError()),\n },\n },\n \"cleanupContext\",\n ],\n },\n SendApduCalled: {\n actions: ({ event }) => {\n event.responseCallback(Left(new AlreadySendingApduError()));\n },\n },\n },\n },\n // TODO: ADD INACTIVE STATE\n Terminated: {\n entry: [\"signalTermination\", \"closeConnection\"],\n type: \"final\",\n },\n },\n });\n}\n"],
5
- "mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,kCAAAE,IAAA,eAAAC,EAAAH,GACA,IAAAI,EAAyD,qBACzDC,EAA6D,kBAE7DC,EAA6B,2CAE7BC,EAA0D,sBAI1DC,EAIO,oBAsDA,MAAMN,CAA2C,CAC9C,SACA,iBAEA,aAEA,gBACA,QAAgD,KAExD,0BAA2B,CACzB,KAAK,QAAU,WAAW,IAAM,CAC9B,KAAK,aAAa,KAAK,CAAE,KAAM,sBAAuB,CAAC,CACzD,EAAG,KAAK,eAAe,CACzB,CAEA,YAAYO,EAA0D,CACpE,KAAK,SAAWA,EAAO,SACvB,KAAK,iBAAmBA,EAAO,iBAC/B,KAAK,gBAAkBA,EAAO,gBAC9B,KAAK,gBAAe,eAClBC,EAAiB,CACf,WAAY,CAACC,EAAMC,EAAuBC,IACxC,KAAK,2BACHF,EACAC,EACAC,CACF,EACF,yBAA0B,IAAM,KAAK,yBAAyB,EAC9D,0BAA2B,IAAM,CAC3B,KAAK,UACP,aAAa,KAAK,OAAO,EACzB,KAAK,QAAU,KAEnB,EACA,aAAcJ,EAAO,aACrB,gBAAiB,IAAM,CACrB,KAAK,iBAAiB,gBAAgB,C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A,EAAM,aACpB,iBAAkBA,EAAM,gBAC1B,CAAC,CAEL,CAAC,CACH,EACA,qBAAsB,CACpB,OAAQ,YACV,EACA,sBAAuB,CACrB,OAAQ,YACV,CACF,CACF,EACA,yCAA0C,CACxC,GAAI,CACF,eAAgB,CACd,OAAQ,cACR,QAAS,aACX,EACA,qBAAsB,CACpB,OAAQ,aACR,QAAS,CACP,CACE,KAAM,mBACN,OAAQ,CACN,YAAU,QAAK,IAAI,qCAAqC,CAC1D,CACF,EACA,CACE,KAAM,gBACR,CACF,CACF,EACA,sBAAuB,CACrB,OAAQ,aACR,QAAS,CACP,CACE,KAAM,mBACN,OAAQ,CACN,YAAU,QAAK,IAAI,qCAAqC,CAC1D,CACF,EACA,gBACF,CACF,EACA,eAAgB,CACd,QAAS,CAAC,CAAE,MAAAA,CAAM,IAAM,CACtBA,EAAM,oBAAiB,QAAK,IAAI,yBAAyB,CAAC,CAC5D,CACF,CACF,CACF,EAEA,WAAY,CACV,MAAO,CAAC,oBAAqB,iBAAiB,EAC9C,KAAM,OACR,CACF,CACF,CAAC,CACH",
6
- "names": ["DeviceConnectionStateMachine_exports", "__export", "DeviceConnectionStateMachine", "__toCommonJS", "import_purify_ts", "import_xstate", "import_CommandUtils", "import_Error", "import_Errors", "params", "makeStateMachine", "apdu", "triggersDisconnection", "abortTimeout", "response", "error", "apduResponse", "dependencies", "responseCallback", "sendApduFn", "startReconnectionTimeout", "cancelReconnectionTimeout", "onTerminated", "closeConnection", "context", "event"]
4
+ "sourcesContent": ["// import { createBrowserInspector } from \"@statelyai/inspect\";\nimport { type Either, Left, Maybe, Nothing, Right } from \"purify-ts\";\nimport { type Actor, assign, createActor, emit, setup } from \"xstate\";\n\nimport { GetAppAndVersionCommand } from \"@api/command/os/GetAppAndVersionCommand\";\nimport { CommandUtils } from \"@api/command/utils/CommandUtils\";\nimport { type ApduResponse } from \"@api/device-session/ApduResponse\";\nimport { type DmkError, UnknownDeviceExchangeError } from \"@api/Error\";\nimport { type DeviceId } from \"@api/types\";\n\nimport { type DeviceApduSender } from \"./DeviceApduSender\";\nimport {\n AlreadySendingApduError,\n DeviceDisconnectedBeforeSendingApdu,\n DeviceDisconnectedWhileSendingError,\n} from \"./Errors\";\n\n// const { inspect } = createBrowserInspector();\n\ntype DeviceDisconnectedEvent = {\n type: \"DeviceDisconnected\";\n};\n\ntype DeviceConnectedEvent = {\n type: \"DeviceConnected\";\n};\n\ntype ApduResponseReceived = {\n type: \"ApduResponseReceived\";\n apduResponse: ApduResponse;\n};\n\ntype ApduSendingError = {\n type: \"ApduSendingError\";\n error: DmkError;\n};\n\ntype SendApduCalled = {\n type: \"SendApduCalled\";\n apdu: Uint8Array;\n triggersDisconnection: boolean;\n abortTimeout?: number;\n responseCallback: (response: Either<DmkError, ApduResponse>) => void;\n};\n\ntype ReconnectionTimedOut = {\n type: \"ReconnectionTimedOut\";\n};\n\ntype CloseConnectionCalled = {\n type: \"CloseConnectionCalled\";\n};\n\nexport type Events =\n | DeviceDisconnectedEvent\n | DeviceConnectedEvent\n | ApduResponseReceived\n | ApduSendingError\n | SendApduCalled\n | CloseConnectionCalled\n | ReconnectionTimedOut;\n\nexport type DeviceConnectionStateMachineParams<Dependencies> = {\n deviceId: DeviceId;\n deviceApduSender: DeviceApduSender<Dependencies>;\n timeoutDuration: number;\n tryToReconnect: (timeoutDuration: number) => void;\n onTerminated: () => void;\n};\n\nexport class DeviceConnectionStateMachine<Dependencies> {\n private deviceId: DeviceId;\n private deviceAdpuSender: DeviceApduSender<Dependencies>;\n\n private machineActor: Actor<ReturnType<typeof makeStateMachine>>;\n\n private timeoutDuration: number;\n private timeout: ReturnType<typeof setTimeout> | null = null;\n\n startReconnectionTimeout() {\n this.timeout = setTimeout(() => {\n this.machineActor.send({ type: \"ReconnectionTimedOut\" });\n }, this.timeoutDuration);\n }\n\n constructor(params: DeviceConnectionStateMachineParams<Dependencies>) {\n this.deviceId = params.deviceId;\n this.deviceAdpuSender = params.deviceApduSender;\n this.timeoutDuration = params.timeoutDuration;\n this.machineActor = createActor(\n makeStateMachine({\n sendApduFn: (apdu, triggersDisconnection, abortTimeout) =>\n this.sendApduToDeviceConnection(\n apdu,\n triggersDisconnection,\n abortTimeout,\n ),\n startReconnectionTimeout: () => this.startReconnectionTimeout(),\n cancelReconnectionTimeout: () => {\n if (this.timeout) {\n clearTimeout(this.timeout);\n this.timeout = null;\n }\n },\n tryToReconnect: () => {\n params.tryToReconnect(this.timeoutDuration);\n },\n onTerminated: params.onTerminated,\n closeConnection: () => {\n this.deviceAdpuSender.closeConnection();\n },\n }),\n // {\n // // inspect,\n // },\n );\n this.machineActor.start();\n }\n\n private sendApduToDeviceConnection(\n apdu: Uint8Array,\n triggersDisconnection?: boolean,\n abortTimeout?: number,\n ) {\n this.deviceAdpuSender\n .sendApdu(apdu, triggersDisconnection, abortTimeout)\n .then((response) => {\n response.caseOf({\n Left: (error) => {\n this.machineActor.send({ type: \"ApduSendingError\", error });\n },\n Right: (apduResponse) => {\n this.machineActor.send({\n type: \"ApduResponseReceived\",\n apduResponse,\n });\n },\n });\n })\n .catch((error) => {\n this.machineActor.send({\n type: \"ApduSendingError\",\n error: new UnknownDeviceExchangeError(error),\n });\n });\n }\n\n /**\n * Called by the transport\n */\n\n public getDependencies(): Dependencies {\n return this.deviceAdpuSender.getDependencies();\n }\n\n public setDependencies(dependencies: Dependencies) {\n this.deviceAdpuSender.setDependencies(dependencies);\n }\n\n public getDeviceId() {\n return this.deviceId;\n }\n\n public sendApdu(\n apdu: Uint8Array,\n triggersDisconnection?: boolean,\n abortTimeout?: number,\n ): Promise<Either<DmkError, ApduResponse>> {\n return new Promise((responseCallback) => {\n this.machineActor.send({\n type: \"SendApduCalled\",\n apdu,\n triggersDisconnection: !!triggersDisconnection,\n abortTimeout,\n responseCallback,\n });\n });\n }\n\n public async setupConnection() {\n await this.deviceAdpuSender.setupConnection();\n }\n\n // State Machine Events\n\n public eventDeviceConnected() {\n this.machineActor.send({ type: \"DeviceConnected\" });\n }\n\n public eventDeviceDisconnected() {\n this.machineActor.send({ type: \"DeviceDisconnected\" });\n }\n\n public closeConnection() {\n this.machineActor.send({ type: \"CloseConnectionCalled\" });\n }\n}\n\nfunction makeStateMachine({\n sendApduFn,\n startReconnectionTimeout,\n cancelReconnectionTimeout,\n tryToReconnect,\n onTerminated,\n closeConnection,\n}: {\n sendApduFn: (\n apdu: Uint8Array,\n triggersDisconnection: boolean,\n abortTimeout?: number,\n ) => void;\n startReconnectionTimeout: () => void;\n cancelReconnectionTimeout: () => void;\n tryToReconnect: () => void;\n onTerminated: () => void;\n closeConnection: () => void;\n}) {\n return setup({\n types: {} as {\n context: {\n apduInProgress: Maybe<{\n apdu: Uint8Array;\n triggersDisconnection: boolean;\n abortTimeout?: number;\n responseCallback: (response: Either<DmkError, ApduResponse>) => void;\n }>;\n apduResponse: Maybe<ApduResponse>;\n };\n events: Events;\n },\n actions: {\n // event transitions\n startTimer: () => {\n startReconnectionTimeout();\n },\n cancelTimer: () => {\n cancelReconnectionTimeout();\n },\n reconnectionTimeoutEvent: emit({ type: \"ReconnectionTimedOut\" }),\n sendApdu: ({ context }) => {\n context.apduInProgress.map(({ apdu, abortTimeout }) => {\n sendApduFn(apdu, false, abortTimeout);\n });\n },\n sendApduResponse: (\n { context },\n params: { response: Either<DmkError, ApduResponse> },\n ) => {\n context.apduInProgress.map(({ responseCallback }) =>\n responseCallback(params.response),\n );\n },\n sendGetAppAndVersion: () => {\n // TODO: not import the command like this, might cause circular dependencies\n sendApduFn(new GetAppAndVersionCommand().getApdu().getRawApdu(), false);\n },\n tryToReconnect: () => {\n tryToReconnect();\n },\n clearApduInProgress: assign({\n apduInProgress: Nothing,\n }),\n clearApduResponse: assign({\n apduResponse: Nothing,\n }),\n signalTermination: () => {\n onTerminated();\n },\n closeConnection: () => {\n closeConnection(); // ASK: how do we handle errors ?\n },\n },\n guards: {\n isApduThatTriggersDisconnection: (\n { context },\n params: { apduResponse: ApduResponse },\n ) => {\n return context.apduInProgress.caseOf({\n Just: ({ triggersDisconnection, apdu }) => {\n const res =\n (triggersDisconnection ||\n CommandUtils.isApduThatTriggersDisconnection(apdu)) &&\n CommandUtils.isSuccessResponse(params.apduResponse);\n return res;\n },\n Nothing: () => false,\n });\n },\n },\n }).createMachine({\n /** @xstate-layout N4IgpgJg5mDOIC5QTANwJYGMwGED2AdgWJgC7qEB0+RJpkAxACJpZgukCGmAFpANoAGALqJQABzyx05QmJAAPRAA4A7AGZKywQEYAnAFYATMoAsBg6fUA2ADQgAnolUnKBjUdXXVpnUb0aAL6B9igY2DTEZBQE1IRR9BAMAMpgBBAAguIQAK44nAA2BQIi8pLSsgTySgjW6oKU6uo61kbWyh06Vsr2TgjqAZR6HUaWXcrqBmrBoawR8XQxcbRkjDgFUrgL0YT5RSWiSCDlMjHVKnrWjaO6ev6qlnp6vYim1qaN9YLqGuPKOjpVDMQGE2JFFlRUul0AQoFlcgx4TkAEpwSQEWBgVHYdCoA5lKSnORHGpNVSUPwGXQDQSmNTDF4IZTWPRDJotUw+HwAnTA0HzFaVShQiAwuHZHKIiWo2DozHYsC4gQ6Q4SQmVc79TxDIzqG6eJq+VSM94NPQ6CYuUzmQGCax8uZbQVLEVipFS3Ku2EAUQATr68L6hKrjuqziTEJNNHrTG1dIIDE8jLTGVTlJQboI2i56QZeSEQY7wTtYl7xQiWOF2GAuLx8UcThqIwh-OmdBZPF0qQCBoydIJlAZKK0jP4bHntBaHVXi0Ky+71ptZzE9sUIMGCRVw6Aau2dJQ6WZlMM-D9+89HIh++mbndVHpdNYLAnp2DtnO0qLYe6RUjV-W1S3Ykd0QABac1KFpbx3kHCxumNS9ak5SDTHNax0NUDRfFMV8BQSJYAHVOFOWEADFA2xd8YmYR0MlIWs+HXUoGzDYDFEQQx90mVozABJ9BAvPo6iuFpRgtQRdDUWNcKdfCqCIkioHI31KOdQgUk-P9CjXDcWKAqpmx0dR-gpCTaXNUxvh7RkvCHWlaWM9RfC6dCZOXeTiPIMiKJIKj1NUuSCAAFXQABbSAAHkclIXTAKJAyQIQLpBHJAEXB8AS1HvdRGT0a0D2ZZpBxjSc3L82IFK8pSfMwcqGEXTF3IIf8mJDRtt3YpLLPJZMWkmTtzJyxD+1UBofifVQOm8YyWjKtSKs8sVlICiECAImQeAARRyMAdogX8JRoqs6IYgDQ30zUjJ8CkWQmYZbOsFLGWzUyzE5bssx8ObAsoSqlpq8r1tILadr2g6ERWksQvCiAopi5i4qbRKjH7Bo4N1dsvFjOxEIeIwUPQ9o9AGSYvG+1bfsW7yVN8+agZB3bIHByUGtk1aWti874s1FGJOHYy6gTLo3lMVN7wPBNVAtbRRg0IEC35NmS0pxTltpwL6e2xn9s0w7mY5hGuaRzrAWZIYBJpc0pd1E18tNMZLOMAwnOCAsCDwFB4CORWms3bnm1AozWSgrHYMsYyEL6FGKXcDleMMO5rXJ5XZ0gP3jZqB4evaLwXEeqwnJNKYDypWlzHePwcIVotyuFT83QldOOpqWNU30A8rEmrMjPcAJk6FP7qch432rY3dxnN1onlaZ9idy5NILuCxl+UEwrH7wiqeqmnarpjatbB3Xcibser3eckfmd3xOkrnpce0DMjHMeoAgLjeqCCsBfVCmFOESE+EqdSfnmNwLJjBPBSs0QwuV3CQWPN3AwT4LTtldoEIAA */\n id: \"deviceConnection\",\n initial: \"Connected\",\n context: {\n apduInProgress: Nothing,\n apduResponse: Nothing,\n },\n states: {\n Connected: {\n on: {\n DeviceDisconnected: {\n target: \"WaitingForReconnection\",\n },\n SendApduCalled: {\n target: \"SendingApdu\",\n actions: assign({\n apduInProgress: ({ event }) => {\n return Maybe.of({\n apdu: event.apdu,\n triggersDisconnection: event.triggersDisconnection,\n abortTimeout: event.abortTimeout,\n responseCallback: event.responseCallback,\n });\n },\n }),\n },\n CloseConnectionCalled: {\n target: \"Terminated\",\n },\n },\n },\n SendingApdu: {\n entry: \"sendApdu\",\n on: {\n ApduResponseReceived: [\n {\n guard: {\n type: \"isApduThatTriggersDisconnection\",\n params: ({ event }) => ({ apduResponse: event.apduResponse }),\n },\n target: \"WaitingForDisconnection\",\n actions: [\n assign({\n apduResponse: ({ event }) => Maybe.of(event.apduResponse),\n }),\n ],\n },\n {\n target: \"Connected\",\n actions: [\n {\n type: \"sendApduResponse\",\n // https://stately.ai/docs/actions#dynamic-action-parameters\n params: ({ event }) => {\n return {\n response: Right(event.apduResponse),\n };\n },\n },\n { type: \"clearApduInProgress\" },\n ],\n },\n ],\n ApduSendingError: {\n target: \"Connected\",\n actions: [\n {\n type: \"sendApduResponse\",\n // https://stately.ai/docs/actions#dynamic-action-parameters\n params: ({ event }) => {\n return {\n response: Left(event.error),\n };\n },\n },\n \"clearApduInProgress\",\n ],\n },\n DeviceDisconnected: {\n target: \"WaitingForReconnection\",\n actions: [\n {\n type: \"sendApduResponse\",\n params: {\n response: Left(new DeviceDisconnectedWhileSendingError()),\n },\n },\n \"clearApduInProgress\",\n ],\n },\n CloseConnectionCalled: {\n target: \"Terminated\",\n actions: [\n {\n type: \"sendApduResponse\",\n params: {\n response: Left(new DeviceDisconnectedWhileSendingError()),\n },\n },\n \"clearApduInProgress\",\n ],\n },\n SendApduCalled: {\n actions: ({ event }) => {\n event.responseCallback(Left(new AlreadySendingApduError()));\n },\n },\n },\n },\n WaitingForDisconnection: {\n entry: \"sendGetAppAndVersion\",\n exit: [\n {\n type: \"sendApduResponse\",\n params: ({ context }) => {\n return {\n response: context.apduResponse.caseOf({\n Just: (apduResponse) => Right(apduResponse),\n Nothing: () => Left(new UnknownDeviceExchangeError()),\n }),\n };\n },\n },\n { type: \"clearApduInProgress\" },\n { type: \"clearApduResponse\" },\n ],\n on: {\n ApduResponseReceived: {\n target: \"Connected\",\n },\n ApduSendingError: {\n target: \"WaitingForReconnection\",\n },\n DeviceDisconnected: {\n target: \"WaitingForReconnection\",\n },\n CloseConnectionCalled: {\n target: \"Terminated\",\n },\n },\n },\n WaitingForReconnection: {\n entry: [\"startTimer\", \"tryToReconnect\"],\n on: {\n DeviceConnected: {\n target: \"Connected\",\n actions: \"cancelTimer\",\n },\n SendApduCalled: {\n target: \"WaitingForReconnectionWithQueuedSendApdu\",\n actions: assign({\n apduInProgress: ({ event }) => {\n return Maybe.of({\n apdu: event.apdu,\n triggersDisconnection: event.triggersDisconnection,\n abortTimeout: event.abortTimeout,\n responseCallback: event.responseCallback,\n });\n },\n }),\n },\n ReconnectionTimedOut: {\n target: \"Terminated\",\n },\n CloseConnectionCalled: {\n target: \"Terminated\",\n },\n },\n },\n WaitingForReconnectionWithQueuedSendApdu: {\n on: {\n DeviceConnected: {\n target: \"SendingApdu\",\n actions: \"cancelTimer\",\n },\n ReconnectionTimedOut: {\n target: \"Terminated\",\n actions: [\n {\n type: \"sendApduResponse\",\n params: {\n response: Left(new DeviceDisconnectedBeforeSendingApdu()),\n },\n },\n {\n type: \"clearApduInProgress\",\n },\n ],\n },\n CloseConnectionCalled: {\n target: \"Terminated\",\n actions: [\n {\n type: \"sendApduResponse\",\n params: {\n response: Left(new DeviceDisconnectedWhileSendingError()),\n },\n },\n \"clearApduInProgress\",\n ],\n },\n SendApduCalled: {\n actions: ({ event }) => {\n event.responseCallback(Left(new AlreadySendingApduError()));\n },\n },\n },\n },\n // TODO: ADD INACTIVE STATE\n Terminated: {\n entry: [\"signalTermination\", \"closeConnection\"],\n type: \"final\",\n },\n },\n });\n}\n"],
5
+ "mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,kCAAAE,IAAA,eAAAC,EAAAH,GACA,IAAAI,EAAyD,qBACzDC,EAA6D,kBAE7DC,EAAwC,mDACxCC,EAA6B,2CAE7BC,EAA0D,sBAI1DC,EAIO,oBAuDA,MAAMP,CAA2C,CAC9C,SACA,iBAEA,aAEA,gBACA,QAAgD,KAExD,0BAA2B,CACzB,KAAK,QAAU,WAAW,IAAM,CAC9B,KAAK,aAAa,KAAK,CAAE,KAAM,sBAAuB,CAAC,CACzD,EAAG,KAAK,eAAe,CACzB,CAEA,YAAYQ,EAA0D,CACpE,KAAK,SAAWA,EAAO,SACvB,KAAK,i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,OAAQ,aACR,QAAS,CACP,CACE,KAAM,mBACN,OAAQ,CACN,YAAU,QAAK,IAAI,qCAAqC,CAC1D,CACF,EACA,CACE,KAAM,qBACR,CACF,CACF,EACA,sBAAuB,CACrB,OAAQ,aACR,QAAS,CACP,CACE,KAAM,mBACN,OAAQ,CACN,YAAU,QAAK,IAAI,qCAAqC,CAC1D,CACF,EACA,qBACF,CACF,EACA,eAAgB,CACd,QAAS,CAAC,CAAE,MAAAA,CAAM,IAAM,CACtBA,EAAM,oBAAiB,QAAK,IAAI,yBAAyB,CAAC,CAC5D,CACF,CACF,CACF,EAEA,WAAY,CACV,MAAO,CAAC,oBAAqB,iBAAiB,EAC9C,KAAM,OACR,CACF,CACF,CAAC,CACH",
6
+ "names": ["DeviceConnectionStateMachine_exports", "__export", "DeviceConnectionStateMachine", "__toCommonJS", "import_purify_ts", "import_xstate", "import_GetAppAndVersionCommand", "import_CommandUtils", "import_Error", "import_Errors", "params", "makeStateMachine", "apdu", "triggersDisconnection", "abortTimeout", "response", "error", "apduResponse", "dependencies", "responseCallback", "sendApduFn", "startReconnectionTimeout", "cancelReconnectionTimeout", "tryToReconnect", "onTerminated", "closeConnection", "context", "event"]
7
7
  }
@@ -0,0 +1,2 @@
1
+ "use strict";var t=require("purify-ts/Either"),e=require("vitest"),u=require("../../device-session/ApduResponse"),A=require("./DeviceConnectionStateMachine"),l=require("./Errors");(0,e.describe)("DeviceConnectionStateMachine",()=>{let s;const a={sendApdu:e.vi.fn(),getDependencies:e.vi.fn(),setDependencies:e.vi.fn(),closeConnection:e.vi.fn(),setupConnection:e.vi.fn()};(0,e.beforeEach)(()=>{e.vi.useFakeTimers(),s=new A.DeviceConnectionStateMachine({deviceId:"deviceId",deviceApduSender:a,timeoutDuration:1e3,tryToReconnect:e.vi.fn(),onTerminated:e.vi.fn()})}),(0,e.afterEach)(()=>{e.vi.useRealTimers(),e.vi.restoreAllMocks()}),(0,e.describe)("Send APDUs",()=>{(0,e.it)("should send APDU successfully",async()=>{const o=Uint8Array.from([1,2,3,4]),d=new u.ApduResponse({statusCode:Uint8Array.from([144,0]),data:new Uint8Array});a.sendApdu.mockResolvedValue((0,t.Right)(d));const n=await s.sendApdu(o);(0,e.expect)(a.sendApdu).toHaveBeenCalledTimes(1),(0,e.expect)(n).toStrictEqual((0,t.Right)(d))}),(0,e.it)("should send several APDUs successfully",async()=>{const o=Uint8Array.from([1,2,3,4]),d=Uint8Array.from([9,2,3,4]),n=new u.ApduResponse({statusCode:Uint8Array.from([144,0]),data:new Uint8Array});a.sendApdu.mockResolvedValue((0,t.Right)(n));const r=await s.sendApdu(o),i=await s.sendApdu(d);(0,e.expect)(a.sendApdu).toHaveBeenCalledTimes(2),(0,e.expect)(r).toStrictEqual((0,t.Right)(n)),(0,e.expect)(i).toStrictEqual((0,t.Right)(n))}),(0,e.it)("should not send several APDUs in parallel",async()=>{const o=Uint8Array.from([1,2,3,4]),d=Uint8Array.from([9,2,3,4]),n=new u.ApduResponse({statusCode:Uint8Array.from([144,0]),data:new Uint8Array});a.sendApdu.mockResolvedValue((0,t.Right)(n));const r=s.sendApdu(o),i=await s.sendApdu(d),c=await r;(0,e.expect)(a.sendApdu).toHaveBeenCalledTimes(1),(0,e.expect)(c).toStrictEqual((0,t.Right)(n)),(0,e.expect)(i).toStrictEqual((0,t.Left)(new l.AlreadySendingApduError))}),(0,e.it)("Disconnected while sending APDU",async()=>{const o=Uint8Array.from([1,2,3,4]),d=new u.ApduResponse({statusCode:Uint8Array.from([144,0]),data:new Uint8Array});a.sendApdu.mockResolvedValue((0,t.Right)(d));const n=s.sendApdu(o);s.eventDeviceDisconnected();const r=await n;(0,e.expect)(a.sendApdu).toHaveBeenCalledTimes(1),(0,e.expect)(r).toStrictEqual((0,t.Left)(new l.DeviceDisconnectedWhileSendingError))}),(0,e.it)("Request disconnection while sending APDU",async()=>{const o=Uint8Array.from([1,2,3,4]),d=new u.ApduResponse({statusCode:Uint8Array.from([144,0]),data:new Uint8Array});a.sendApdu.mockResolvedValue((0,t.Right)(d));const n=s.sendApdu(o);s.closeConnection();const r=await n;(0,e.expect)(a.sendApdu).toHaveBeenCalledTimes(1),(0,e.expect)(r).toStrictEqual((0,t.Left)(new l.DeviceDisconnectedWhileSendingError))})}),(0,e.describe)("Send APDUs triggering disconnection",()=>{(0,e.it)("should send one APDU successfully",async()=>{const o=Uint8Array.from([1,2,3,4]),d=new u.ApduResponse({statusCode:Uint8Array.from([144,0]),data:new Uint8Array});a.sendApdu.mockResolvedValue((0,t.Right)(d));const n=await s.sendApdu(o,!0);(0,e.expect)(a.sendApdu).toHaveBeenCalledTimes(2),(0,e.expect)(a.sendApdu.mock.calls).toEqual([[o,!1,void 0],[Uint8Array.from([176,1,0,0,0]),!1,void 0]]),(0,e.expect)(n).toStrictEqual((0,t.Right)(d))}),(0,e.it)("should send several APDUs successfully",async()=>{const o=Uint8Array.from([1,2,3,4]),d=Uint8Array.from([9,2,3,4]),n=new u.ApduResponse({statusCode:Uint8Array.from([144,0]),data:new Uint8Array});a.sendApdu.mockResolvedValue((0,t.Right)(n));const r=s.sendApdu(o,!0);await Promise.resolve(),s.eventDeviceDisconnected(),s.eventDeviceConnected();const i=s.sendApdu(d),c=await r,p=await i;(0,e.expect)(a.sendApdu).toHaveBeenCalledTimes(3),(0,e.expect)(a.sendApdu.mock.calls).toEqual([[o,!1,void 0],[Uint8Array.from([176,1,0,0,0]),!1,void 0],[d,!1,void 0]]),(0,e.expect)(c).toStrictEqual((0,t.Right)(n)),(0,e.expect)(p).toStrictEqual((0,t.Right)(n))}),(0,e.it)("should send a second APDU after reconnection",async()=>{const o=Uint8Array.from([1,2,3,4]),d=Uint8Array.from([9,2,3,4]),n=new u.ApduResponse({statusCode:Uint8Array.from([144,0]),data:new Uint8Array});a.sendApdu.mockResolvedValue((0,t.Right)(n));const r=await s.sendApdu(o,!0);s.eventDeviceDisconnected(),s.eventDeviceConnected();const i=await s.sendApdu(d);(0,e.expect)(a.sendApdu).toHaveBeenCalledTimes(3),(0,e.expect)(a.sendApdu.mock.calls).toEqual([[o,!1,void 0],[Uint8Array.from([176,1,0,0,0]),!1,void 0],[d,!1,void 0]]),(0,e.expect)(r).toStrictEqual((0,t.Right)(n)),(0,e.expect)(i).toStrictEqual((0,t.Right)(n))}),(0,e.it)("should not send several APDUs in parallel",async()=>{const o=Uint8Array.from([1,2,3,4]),d=Uint8Array.from([9,2,3,4]),n=new u.ApduResponse({statusCode:Uint8Array.from([144,0]),data:new Uint8Array});a.sendApdu.mockResolvedValue((0,t.Right)(n));const r=s.sendApdu(o,!0),i=await s.sendApdu(d),c=await r;(0,e.expect)(a.sendApdu).toHaveBeenCalledTimes(2),(0,e.expect)(a.sendApdu.mock.calls).toEqual([[o,!1,void 0],[Uint8Array.from([176,1,0,0,0]),!1,void 0]]),(0,e.expect)(c).toStrictEqual((0,t.Right)(n)),(0,e.expect)(i).toStrictEqual((0,t.Left)(new l.AlreadySendingApduError))}),(0,e.it)("should send another APDU in promise handler",async()=>{const o=Uint8Array.from([1,2,3,4]),d=Uint8Array.from([9,2,3,4]),n=new u.ApduResponse({statusCode:Uint8Array.from([144,0]),data:new Uint8Array});a.sendApdu.mockResolvedValue((0,t.Right)(n));let r;const i=await s.sendApdu(o,!0).then(p=>(r=s.sendApdu(d),p));s.eventDeviceDisconnected(),s.eventDeviceConnected();const c=await r;(0,e.expect)(a.sendApdu).toHaveBeenCalledTimes(3),(0,e.expect)(a.sendApdu.mock.calls).toEqual([[o,!1,void 0],[Uint8Array.from([176,1,0,0,0]),!1,void 0],[d,!1,void 0]]),(0,e.expect)(i).toStrictEqual((0,t.Right)(n)),(0,e.expect)(c).toStrictEqual((0,t.Right)(n))}),(0,e.it)("send an APDU while device is reconnecting",async()=>{const o=Uint8Array.from([1,2,3,4]),d=new u.ApduResponse({statusCode:Uint8Array.from([144,0]),data:new Uint8Array});a.sendApdu.mockResolvedValue((0,t.Right)(d)),s.eventDeviceDisconnected();const n=s.sendApdu(o,!0);s.eventDeviceConnected();const r=await n;(0,e.expect)(a.sendApdu).toHaveBeenCalledTimes(2),(0,e.expect)(a.sendApdu.mock.calls).toEqual([[o,!1,void 0],[Uint8Array.from([176,1,0,0,0]),!1,void 0]]),(0,e.expect)(r).toStrictEqual((0,t.Right)(d))}),(0,e.it)("Close while an APDU is waiting for reconnection",async()=>{const o=Uint8Array.from([1,2,3,4]),d=Uint8Array.from([9,2,3,4]),n=new u.ApduResponse({statusCode:Uint8Array.from([144,0]),data:new Uint8Array});a.sendApdu.mockResolvedValue((0,t.Right)(n));let r;const i=s.sendApdu(o,!0);await Promise.resolve(),s.eventDeviceDisconnected();const c=await i;r=s.sendApdu(d),s.closeConnection();const p=await r;(0,e.expect)(a.sendApdu.mock.calls).toEqual([[o,!1,void 0],[Uint8Array.from([176,1,0,0,0]),!1,void 0]]),(0,e.expect)(c).toStrictEqual((0,t.Right)(n)),(0,e.expect)(p).toStrictEqual((0,t.Left)(new l.DeviceDisconnectedWhileSendingError))})})});
2
+ //# sourceMappingURL=DeviceConnectionStateMachine.test.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../../../src/api/transport/model/DeviceConnectionStateMachine.test.ts"],
4
+ "sourcesContent": ["import { Left, Right } from \"purify-ts/Either\";\nimport { afterEach, beforeEach, describe, expect, it, vi } from \"vitest\";\n\nimport { ApduResponse } from \"@api/device-session/ApduResponse\";\n\nimport { type SendApduResult } from \"./DeviceConnection\";\nimport { DeviceConnectionStateMachine } from \"./DeviceConnectionStateMachine\";\nimport {\n AlreadySendingApduError,\n DeviceDisconnectedWhileSendingError,\n} from \"./Errors\";\n\ndescribe(\"DeviceConnectionStateMachine\", () => {\n let machine: DeviceConnectionStateMachine<void>;\n const mockApduSender = {\n sendApdu: vi.fn(),\n getDependencies: vi.fn(),\n setDependencies: vi.fn(),\n closeConnection: vi.fn(),\n setupConnection: vi.fn(),\n };\n\n beforeEach(() => {\n vi.useFakeTimers();\n machine = new DeviceConnectionStateMachine<void>({\n deviceId: \"deviceId\",\n deviceApduSender: mockApduSender,\n timeoutDuration: 1000,\n tryToReconnect: vi.fn(),\n onTerminated: vi.fn(),\n });\n });\n\n afterEach(() => {\n vi.useRealTimers();\n vi.restoreAllMocks();\n });\n\n describe(\"Send APDUs\", () => {\n it(\"should send APDU successfully\", async () => {\n // GIVEN\n const apdu = Uint8Array.from([1, 2, 3, 4]);\n const apduResponse = new ApduResponse({\n statusCode: Uint8Array.from([0x90, 0x00]),\n data: new Uint8Array(),\n });\n mockApduSender.sendApdu.mockResolvedValue(Right(apduResponse));\n\n // WHEN\n const result = await machine.sendApdu(apdu);\n\n // THEN\n expect(mockApduSender.sendApdu).toHaveBeenCalledTimes(1);\n expect(result).toStrictEqual(Right(apduResponse));\n });\n\n it(\"should send several APDUs successfully\", async () => {\n // GIVEN\n const apdu = Uint8Array.from([1, 2, 3, 4]);\n const apdu2 = Uint8Array.from([9, 2, 3, 4]);\n const apduResponse = new ApduResponse({\n statusCode: Uint8Array.from([0x90, 0x00]),\n data: new Uint8Array(),\n });\n mockApduSender.sendApdu.mockResolvedValue(Right(apduResponse));\n\n // WHEN\n const result = await machine.sendApdu(apdu);\n const result2 = await machine.sendApdu(apdu2);\n\n // THEN\n expect(mockApduSender.sendApdu).toHaveBeenCalledTimes(2);\n expect(result).toStrictEqual(Right(apduResponse));\n expect(result2).toStrictEqual(Right(apduResponse));\n });\n\n it(\"should not send several APDUs in parallel\", async () => {\n // GIVEN\n const apdu = Uint8Array.from([1, 2, 3, 4]);\n const apdu2 = Uint8Array.from([9, 2, 3, 4]);\n const apduResponse = new ApduResponse({\n statusCode: Uint8Array.from([0x90, 0x00]),\n data: new Uint8Array(),\n });\n mockApduSender.sendApdu.mockResolvedValue(Right(apduResponse));\n\n // WHEN\n const promise = machine.sendApdu(apdu);\n const result2 = await machine.sendApdu(apdu2);\n const result = await promise;\n\n // THEN\n expect(mockApduSender.sendApdu).toHaveBeenCalledTimes(1);\n expect(result).toStrictEqual(Right(apduResponse));\n expect(result2).toStrictEqual(Left(new AlreadySendingApduError()));\n });\n\n it(\"Disconnected while sending APDU\", async () => {\n // GIVEN\n const apdu = Uint8Array.from([1, 2, 3, 4]);\n const apduResponse = new ApduResponse({\n statusCode: Uint8Array.from([0x90, 0x00]),\n data: new Uint8Array(),\n });\n mockApduSender.sendApdu.mockResolvedValue(Right(apduResponse));\n\n // WHEN\n const promise = machine.sendApdu(apdu);\n machine.eventDeviceDisconnected();\n const result = await promise;\n\n // THEN\n expect(mockApduSender.sendApdu).toHaveBeenCalledTimes(1);\n expect(result).toStrictEqual(\n Left(new DeviceDisconnectedWhileSendingError()),\n );\n });\n\n it(\"Request disconnection while sending APDU\", async () => {\n // GIVEN\n const apdu = Uint8Array.from([1, 2, 3, 4]);\n const apduResponse = new ApduResponse({\n statusCode: Uint8Array.from([0x90, 0x00]),\n data: new Uint8Array(),\n });\n mockApduSender.sendApdu.mockResolvedValue(Right(apduResponse));\n\n // WHEN\n const promise = machine.sendApdu(apdu);\n machine.closeConnection();\n const result = await promise;\n\n // THEN\n expect(mockApduSender.sendApdu).toHaveBeenCalledTimes(1);\n expect(result).toStrictEqual(\n Left(new DeviceDisconnectedWhileSendingError()),\n );\n });\n });\n\n describe(\"Send APDUs triggering disconnection\", () => {\n it(\"should send one APDU successfully\", async () => {\n // GIVEN\n const apdu = Uint8Array.from([1, 2, 3, 4]);\n const apduResponse = new ApduResponse({\n statusCode: Uint8Array.from([0x90, 0x00]),\n data: new Uint8Array(),\n });\n mockApduSender.sendApdu.mockResolvedValue(Right(apduResponse));\n\n // WHEN\n const result = await machine.sendApdu(apdu, true);\n\n // THEN\n expect(mockApduSender.sendApdu).toHaveBeenCalledTimes(2);\n expect(mockApduSender.sendApdu.mock.calls).toEqual([\n [apdu, false, undefined],\n [Uint8Array.from([0xb0, 0x01, 0x00, 0x00, 0x00]), false, undefined], // GetAppAndVersion APDU sent after a successful result from an APDU that triggers disconnection\n ]);\n expect(result).toStrictEqual(Right(apduResponse));\n });\n\n it(\"should send several APDUs successfully\", async () => {\n // GIVEN\n const apdu = Uint8Array.from([1, 2, 3, 4]);\n const apdu2 = Uint8Array.from([9, 2, 3, 4]);\n const apduResponse = new ApduResponse({\n statusCode: Uint8Array.from([0x90, 0x00]),\n data: new Uint8Array(),\n });\n mockApduSender.sendApdu.mockResolvedValue(Right(apduResponse));\n\n // WHEN\n const promise1 = machine.sendApdu(apdu, true);\n await Promise.resolve(); // Allow the first APDU to be sent and processed before the disconnection event\n machine.eventDeviceDisconnected();\n machine.eventDeviceConnected();\n const promise2 = machine.sendApdu(apdu2);\n const result1 = await promise1;\n const result2 = await promise2;\n\n // THEN\n expect(mockApduSender.sendApdu).toHaveBeenCalledTimes(3);\n expect(mockApduSender.sendApdu.mock.calls).toEqual([\n [apdu, false, undefined],\n [Uint8Array.from([0xb0, 0x01, 0x00, 0x00, 0x00]), false, undefined], // GetAppAndVersion APDU sent after a successful result from an APDU that triggers disconnection\n [apdu2, false, undefined],\n ]);\n\n expect(result1).toStrictEqual(Right(apduResponse));\n expect(result2).toStrictEqual(Right(apduResponse));\n });\n\n it(\"should send a second APDU after reconnection\", async () => {\n // GIVEN\n const apdu = Uint8Array.from([1, 2, 3, 4]);\n const apdu2 = Uint8Array.from([9, 2, 3, 4]);\n const apduResponse = new ApduResponse({\n statusCode: Uint8Array.from([0x90, 0x00]),\n data: new Uint8Array(),\n });\n mockApduSender.sendApdu.mockResolvedValue(Right(apduResponse));\n\n // WHEN\n const result = await machine.sendApdu(apdu, true);\n machine.eventDeviceDisconnected();\n machine.eventDeviceConnected();\n const result2 = await machine.sendApdu(apdu2);\n\n // THEN\n expect(mockApduSender.sendApdu).toHaveBeenCalledTimes(3);\n expect(mockApduSender.sendApdu.mock.calls).toEqual([\n [apdu, false, undefined],\n [Uint8Array.from([0xb0, 0x01, 0x00, 0x00, 0x00]), false, undefined], // GetAppAndVersion APDU sent after a successful result from an APDU that triggers disconnection\n [apdu2, false, undefined],\n ]);\n expect(result).toStrictEqual(Right(apduResponse));\n expect(result2).toStrictEqual(Right(apduResponse));\n });\n\n it(\"should not send several APDUs in parallel\", async () => {\n // GIVEN\n const apdu = Uint8Array.from([1, 2, 3, 4]);\n const apdu2 = Uint8Array.from([9, 2, 3, 4]);\n const apduResponse = new ApduResponse({\n statusCode: Uint8Array.from([0x90, 0x00]),\n data: new Uint8Array(),\n });\n mockApduSender.sendApdu.mockResolvedValue(Right(apduResponse));\n\n // WHEN\n const promise = machine.sendApdu(apdu, true);\n const result2 = await machine.sendApdu(apdu2);\n const result = await promise;\n\n // THEN\n expect(mockApduSender.sendApdu).toHaveBeenCalledTimes(2);\n expect(mockApduSender.sendApdu.mock.calls).toEqual([\n [apdu, false, undefined],\n [Uint8Array.from([0xb0, 0x01, 0x00, 0x00, 0x00]), false, undefined], // GetAppAndVersion APDU sent after a successful result from an APDU that triggers disconnection\n ]);\n expect(result).toStrictEqual(Right(apduResponse));\n expect(result2).toStrictEqual(Left(new AlreadySendingApduError()));\n });\n\n it(\"should send another APDU in promise handler\", async () => {\n // GIVEN\n const apdu = Uint8Array.from([1, 2, 3, 4]);\n const apdu2 = Uint8Array.from([9, 2, 3, 4]);\n const apduResponse = new ApduResponse({\n statusCode: Uint8Array.from([0x90, 0x00]),\n data: new Uint8Array(),\n });\n mockApduSender.sendApdu.mockResolvedValue(Right(apduResponse));\n\n // WHEN\n let promise: Promise<SendApduResult> | undefined = undefined;\n const result = await machine.sendApdu(apdu, true).then((value) => {\n promise = machine.sendApdu(apdu2);\n return value;\n });\n machine.eventDeviceDisconnected();\n machine.eventDeviceConnected();\n const result2 = await promise!;\n\n // THEN\n expect(mockApduSender.sendApdu).toHaveBeenCalledTimes(3);\n expect(mockApduSender.sendApdu.mock.calls).toEqual([\n [apdu, false, undefined],\n [Uint8Array.from([0xb0, 0x01, 0x00, 0x00, 0x00]), false, undefined], // GetAppAndVersion APDU sent after a successful result from an APDU that triggers disconnection\n [apdu2, false, undefined],\n ]);\n expect(result).toStrictEqual(Right(apduResponse));\n expect(result2).toStrictEqual(Right(apduResponse));\n });\n\n it(\"send an APDU while device is reconnecting\", async () => {\n // GIVEN\n const apdu = Uint8Array.from([1, 2, 3, 4]);\n const apduResponse = new ApduResponse({\n statusCode: Uint8Array.from([0x90, 0x00]),\n data: new Uint8Array(),\n });\n mockApduSender.sendApdu.mockResolvedValue(Right(apduResponse));\n\n // WHEN\n machine.eventDeviceDisconnected();\n const promise = machine.sendApdu(apdu, true);\n machine.eventDeviceConnected();\n const result = await promise;\n\n // THEN\n expect(mockApduSender.sendApdu).toHaveBeenCalledTimes(2);\n expect(mockApduSender.sendApdu.mock.calls).toEqual([\n [apdu, false, undefined],\n [Uint8Array.from([0xb0, 0x01, 0x00, 0x00, 0x00]), false, undefined], // GetAppAndVersion APDU sent after a successful result from an APDU that triggers disconnection\n ]);\n expect(result).toStrictEqual(Right(apduResponse));\n });\n\n it(\"Close while an APDU is waiting for reconnection\", async () => {\n // GIVEN\n const apdu = Uint8Array.from([1, 2, 3, 4]);\n const apdu2 = Uint8Array.from([9, 2, 3, 4]);\n const apduResponse = new ApduResponse({\n statusCode: Uint8Array.from([0x90, 0x00]),\n data: new Uint8Array(),\n });\n mockApduSender.sendApdu.mockResolvedValue(Right(apduResponse));\n\n // WHEN\n let promise: Promise<SendApduResult> | undefined = undefined;\n const promise1 = machine.sendApdu(apdu, true);\n await Promise.resolve(); // Allow the first APDU promise to resolve before triggering disconnection\n machine.eventDeviceDisconnected();\n const result1 = await promise1;\n promise = machine.sendApdu(apdu2);\n machine.closeConnection();\n const result2 = await promise!;\n\n // THEN\n // expect(mockApduSender.sendApdu).toHaveBeenCalledTimes(2);\n expect(mockApduSender.sendApdu.mock.calls).toEqual([\n [apdu, false, undefined],\n [Uint8Array.from([0xb0, 0x01, 0x00, 0x00, 0x00]), false, undefined], // GetAppAndVersion APDU sent after a successful result from an APDU that triggers disconnection\n ]);\n expect(result1).toStrictEqual(Right(apduResponse));\n expect(result2).toStrictEqual(\n Left(new DeviceDisconnectedWh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UAAOA,EAAe,SAAS,KAAK,KAAK,EAAE,QAAQ,CACjD,CAACC,EAAM,GAAO,MAAS,EACvB,CAAC,WAAW,KAAK,CAAC,IAAM,EAAM,EAAM,EAAM,CAAI,CAAC,EAAG,GAAO,MAAS,CACpE,CAAC,KACD,UAAOE,CAAM,EAAE,iBAAc,SAAMD,CAAY,CAAC,CAClD,CAAC,KAED,MAAG,kDAAmD,SAAY,CAEhE,MAAMD,EAAO,WAAW,KAAK,CAAC,EAAG,EAAG,EAAG,CAAC,CAAC,EACnCG,EAAQ,WAAW,KAAK,CAAC,EAAG,EAAG,EAAG,CAAC,CAAC,EACpCF,EAAe,IAAI,eAAa,CACpC,WAAY,WAAW,KAAK,CAAC,IAAM,CAAI,CAAC,EACxC,KAAM,IAAI,UACZ,CAAC,EACDF,EAAe,SAAS,qBAAkB,SAAME,CAAY,CAAC,EAG7D,IAAII,EACJ,MAAMC,EAAWR,EAAQ,SAASE,EAAM,EAAI,EAC5C,MAAM,QAAQ,QAAQ,EACtBF,EAAQ,wBAAwB,EAChC,MAAMU,EAAU,MAAMF,EACtBD,EAAUP,EAAQ,SAASK,CAAK,EAChCL,EAAQ,gBAAgB,EACxB,MAAMM,EAAU,MAAMC,KAItB,UAAON,EAAe,SAAS,KAAK,KAAK,EAAE,QAAQ,CACjD,CAACC,EAAM,GAAO,MAAS,EACvB,CAAC,WAAW,KAAK,CAAC,IAAM,EAAM,EAAM,EAAM,CAAI,CAAC,EAAG,GAAO,MAAS,CACpE,CAAC,KACD,UAAOQ,CAAO,EAAE,iBAAc,SAAMP,CAAY,CAAC,KACjD,UAAOG,CAAO,EAAE,iBACd,QAAK,IAAI,qCAAqC,CAChD,CACF,CAAC,CACH,CAAC,CACH,CAAC",
6
+ "names": ["import_Either", "import_vitest", "import_ApduResponse", "import_DeviceConnectionStateMachine", "import_Errors", "machine", "mockApduSender", "apdu", "apduResponse", "result", "apdu2", "result2", "promise", "promise1", "promise2", "result1", "value"]
7
+ }
@@ -1,2 +1,2 @@
1
- "use strict";var s=Object.defineProperty;var c=Object.getOwnPropertyDescriptor;var a=Object.getOwnPropertyNames;var i=Object.prototype.hasOwnProperty;var l=(o,e)=>{for(var r in e)s(o,r,{get:e[r],enumerable:!0})},u=(o,e,r,d)=>{if(e&&typeof e=="object"||typeof e=="function")for(let t of a(e))!i.call(o,t)&&t!==r&&s(o,t,{get:()=>e[t],enumerable:!(d=c(e,t))||d.enumerable});return o};var p=o=>u(s({},"__esModule",{value:!0}),o);var z={};l(z,{AlreadySendingApduError:()=>f,DeviceAlreadyConnectedError:()=>E,DeviceDisconnectedBeforeSendingApdu:()=>R,DeviceDisconnectedWhileSendingError:()=>C,DeviceNotInitializedError:()=>m,DeviceNotRecognizedError:()=>y,DisconnectError:()=>_,GeneralDmkError:()=>n,NoAccessibleDeviceError:()=>x,NoTransportProvidedError:()=>h,NoTransportsProvidedError:()=>N,OpeningConnectionError:()=>v,ReconnectionFailedError:()=>S,SendApduConcurrencyError:()=>D,SendApduEmptyResponseError:()=>A,SendApduTimeoutError:()=>w,TransportAlreadyExistsError:()=>T,TransportNotSupportedError:()=>k,UnknownDeviceError:()=>g});module.exports=p(z);class n{_tag="GeneralDmkError";originalError;constructor(e){e instanceof Error?this.originalError=e:e!==void 0&&(this.originalError=new Error(String(e)))}}class E extends n{constructor(r){super(r);this.err=r}_tag="DeviceAlreadyDiscoveredError"}class y extends n{constructor(r){super(r);this.err=r}_tag="DeviceNotRecognizedError"}class x extends n{constructor(r){super(r);this.err=r}_tag="NoAccessibleDeviceError"}class v extends n{_tag="ConnectionOpeningError";constructor(e){super(e)}}class g extends n{constructor(r){super(r);this.err=r}_tag="UnknownDeviceError"}class k extends n{constructor(r){super(r);this.err=r}_tag="TransportNotSupportedError"}class D extends n{constructor(r){super(r);this.err=r}_tag="SendApduConcurrencyError"}class w extends n{constructor(r){super(r);this.err=r}_tag="SendApduTimeoutError"}class A extends n{constructor(r){super(r);this.err=r}_tag="SendApduEmptyResponseError"}class _ extends n{constructor(r){super(r);this.err=r}_tag="DisconnectError"}class S extends n{constructor(r){super(r);this.err=r}_tag="ReconnectionFailedError"}class m extends n{constructor(r){super(r);this.err=r}_tag="DeviceNotInitializedError"}class N extends n{constructor(r){super(r);this.err=r}_tag="NoTransportsProvidedError"}class T extends n{constructor(r){super(r);this.err=r}_tag="TransportAlreadyExistsError"}class C extends n{constructor(r){super(r);this.err=r}_tag="DeviceDisconnectedWhileSendingError"}class f extends n{constructor(r){super(r);this.err=r}_tag="AlreadySendingApduError"}class R extends n{constructor(r){super(r);this.err=r}_tag="DeviceDisconnectedBeforeSendingApdu"}class h extends n{constructor(r){super(r);this.err=r}_tag="NoTransportProvidedError"}0&&(module.exports={AlreadySendingApduError,DeviceAlreadyConnectedError,DeviceDisconnectedBeforeSendingApdu,DeviceDisconnectedWhileSendingError,DeviceNotInitializedError,DeviceNotRecognizedError,DisconnectError,GeneralDmkError,NoAccessibleDeviceError,NoTransportProvidedError,NoTransportsProvidedError,OpeningConnectionError,ReconnectionFailedError,SendApduConcurrencyError,SendApduEmptyResponseError,SendApduTimeoutError,TransportAlreadyExistsError,TransportNotSupportedError,UnknownDeviceError});
1
+ "use strict";var s=Object.defineProperty;var c=Object.getOwnPropertyDescriptor;var a=Object.getOwnPropertyNames;var i=Object.prototype.hasOwnProperty;var l=(o,e)=>{for(var r in e)s(o,r,{get:e[r],enumerable:!0})},u=(o,e,r,d)=>{if(e&&typeof e=="object"||typeof e=="function")for(let t of a(e))!i.call(o,t)&&t!==r&&s(o,t,{get:()=>e[t],enumerable:!(d=c(e,t))||d.enumerable});return o};var p=o=>u(s({},"__esModule",{value:!0}),o);var z={};l(z,{AlreadySendingApduError:()=>C,DeviceAlreadyConnectedError:()=>E,DeviceDisconnectedBeforeSendingApdu:()=>f,DeviceDisconnectedWhileSendingError:()=>T,DeviceNotInitializedError:()=>S,DeviceNotRecognizedError:()=>y,DisconnectError:()=>_,GeneralDmkError:()=>n,NoAccessibleDeviceError:()=>v,NoTransportProvidedError:()=>h,NoTransportsProvidedError:()=>N,OpeningConnectionError:()=>x,ReconnectionFailedError:()=>A,SendApduConcurrencyError:()=>k,SendApduTimeoutError:()=>w,TransportAlreadyExistsError:()=>m,TransportNotSupportedError:()=>D,UnknownDeviceError:()=>g});module.exports=p(z);class n{_tag="GeneralDmkError";originalError;constructor(e){e instanceof Error?this.originalError=e:e!==void 0&&(this.originalError=new Error(String(e)))}}class E extends n{constructor(r){super(r);this.err=r}_tag="DeviceAlreadyDiscoveredError"}class y extends n{constructor(r){super(r);this.err=r}_tag="DeviceNotRecognizedError"}class v extends n{constructor(r){super(r);this.err=r}_tag="NoAccessibleDeviceError"}class x extends n{_tag="ConnectionOpeningError";constructor(e){super(e)}}class g extends n{constructor(r){super(r);this.err=r}_tag="UnknownDeviceError"}class D extends n{constructor(r){super(r);this.err=r}_tag="TransportNotSupportedError"}class k extends n{constructor(r){super(r);this.err=r}_tag="SendApduConcurrencyError"}class w extends n{constructor(r){super(r);this.err=r}_tag="SendApduTimeoutError"}class _ extends n{constructor(r){super(r);this.err=r}_tag="DisconnectError"}class A extends n{constructor(r){super(r);this.err=r}_tag="ReconnectionFailedError"}class S extends n{constructor(r){super(r);this.err=r}_tag="DeviceNotInitializedError"}class N extends n{constructor(r){super(r);this.err=r}_tag="NoTransportsProvidedError"}class m extends n{constructor(r){super(r);this.err=r}_tag="TransportAlreadyExistsError"}class T extends n{constructor(r){super(r);this.err=r}_tag="DeviceDisconnectedWhileSendingError"}class C extends n{constructor(r){super(r);this.err=r}_tag="AlreadySendingApduError"}class f extends n{constructor(r){super(r);this.err=r}_tag="DeviceDisconnectedBeforeSendingApdu"}class h extends n{constructor(r){super(r);this.err=r}_tag="NoTransportProvidedError"}0&&(module.exports={AlreadySendingApduError,DeviceAlreadyConnectedError,DeviceDisconnectedBeforeSendingApdu,DeviceDisconnectedWhileSendingError,DeviceNotInitializedError,DeviceNotRecognizedError,DisconnectError,GeneralDmkError,NoAccessibleDeviceError,NoTransportProvidedError,NoTransportsProvidedError,OpeningConnectionError,ReconnectionFailedError,SendApduConcurrencyError,SendApduTimeoutError,TransportAlreadyExistsError,TransportNotSupportedError,UnknownDeviceError});
2
2
  //# sourceMappingURL=Errors.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../../src/api/transport/model/Errors.ts"],
4
- "sourcesContent": ["import { type DmkError } from \"@api/Error\";\n\nexport type ConnectError =\n | UnknownDeviceError\n | OpeningConnectionError\n | DeviceAlreadyConnectedError;\n\nexport class GeneralDmkError implements DmkError {\n _tag = \"GeneralDmkError\";\n originalError?: unknown;\n constructor(err?: unknown) {\n if (err instanceof Error) {\n this.originalError = err;\n } else if (err !== undefined) {\n this.originalError = new Error(String(err));\n }\n }\n}\n\nexport class DeviceAlreadyConnectedError extends GeneralDmkError {\n override readonly _tag = \"DeviceAlreadyDiscoveredError\";\n constructor(readonly err?: unknown) {\n super(err);\n }\n}\n\nexport class DeviceNotRecognizedError extends GeneralDmkError {\n override readonly _tag = \"DeviceNotRecognizedError\";\n constructor(readonly err?: unknown) {\n super(err);\n }\n}\n\nexport class NoAccessibleDeviceError extends GeneralDmkError {\n override readonly _tag = \"NoAccessibleDeviceError\";\n constructor(readonly err?: unknown) {\n super(err);\n }\n}\n\nexport class OpeningConnectionError extends GeneralDmkError {\n override _tag = \"ConnectionOpeningError\";\n constructor(err?: unknown) {\n super(err);\n }\n}\n\nexport class UnknownDeviceError extends GeneralDmkError {\n override readonly _tag = \"UnknownDeviceError\";\n constructor(readonly err?: unknown) {\n super(err);\n }\n}\n\nexport class TransportNotSupportedError extends GeneralDmkError {\n override readonly _tag = \"TransportNotSupportedError\";\n constructor(readonly err?: unknown) {\n super(err);\n }\n}\nexport class SendApduConcurrencyError extends GeneralDmkError {\n override readonly _tag = \"SendApduConcurrencyError\";\n constructor(readonly err?: unknown) {\n super(err);\n }\n}\n\nexport class SendApduTimeoutError extends GeneralDmkError {\n override readonly _tag = \"SendApduTimeoutError\";\n constructor(readonly err?: unknown) {\n super(err);\n }\n}\n\nexport class SendApduEmptyResponseError extends GeneralDmkError {\n override readonly _tag = \"SendApduEmptyResponseError\";\n constructor(readonly err?: unknown) {\n super(err);\n }\n}\n\nexport class DisconnectError extends GeneralDmkError {\n override readonly _tag = \"DisconnectError\";\n constructor(readonly err?: unknown) {\n super(err);\n }\n}\n\nexport class ReconnectionFailedError extends GeneralDmkError {\n override readonly _tag = \"ReconnectionFailedError\";\n constructor(readonly err?: unknown) {\n super(err);\n }\n}\n\nexport class DeviceNotInitializedError extends GeneralDmkError {\n override readonly _tag = \"DeviceNotInitializedError\";\n constructor(readonly err?: unknown) {\n super(err);\n }\n}\n\nexport class NoTransportsProvidedError extends GeneralDmkError {\n override readonly _tag = \"NoTransportsProvidedError\";\n constructor(readonly err?: unknown) {\n super(err);\n }\n}\n\nexport class TransportAlreadyExistsError extends GeneralDmkError {\n override readonly _tag = \"TransportAlreadyExistsError\";\n constructor(readonly err?: unknown) {\n super(err);\n }\n}\n\nexport class DeviceDisconnectedWhileSendingError extends GeneralDmkError {\n override readonly _tag = \"DeviceDisconnectedWhileSendingError\";\n constructor(readonly err?: unknown) {\n super(err);\n }\n}\n\nexport class AlreadySendingApduError extends GeneralDmkError {\n override readonly _tag = \"AlreadySendingApduError\";\n constructor(readonly err?: unknown) {\n super(err);\n }\n}\n\nexport class DeviceDisconnectedBeforeSendingApdu extends GeneralDmkError {\n override readonly _tag = \"DeviceDisconnectedBeforeSendingApdu\";\n constructor(readonly err?: unknown) {\n super(err);\n }\n}\n\nexport class NoTransportProvidedError extends GeneralDmkError {\n override readonly _tag = \"NoTransportProvidedError\";\n constructor(readonly err?: unknown) {\n super(err);\n }\n}\n"],
5
- "mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,6BAAAE,EAAA,gCAAAC,EAAA,wCAAAC,EAAA,wCAAAC,EAAA,8BAAAC,EAAA,6BAAAC,EAAA,oBAAAC,EAAA,oBAAAC,EAAA,4BA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AqBa,EAAe,CAClC,MAAMA,CAAG,EADU,SAAAA,CAErB,CAHkB,KAAO,4BAI3B,CAEO,MAAMd,UAAwBC,CAAgB,CAEnD,YAAqBa,EAAe,CAClC,MAAMA,CAAG,EADU,SAAAA,CAErB,CAHkB,KAAO,iBAI3B,CAEO,MAAMR,UAAgCL,CAAgB,CAE3D,YAAqBa,EAAe,CAClC,MAAMA,CAAG,EADU,SAAAA,CAErB,CAHkB,KAAO,yBAI3B,CAEO,MAAMhB,UAAkCG,CAAgB,CAE7D,YAAqBa,EAAe,CAClC,MAAMA,CAAG,EADU,SAAAA,CAErB,CAHkB,KAAO,2BAI3B,CAEO,MAAMV,UAAkCH,CAAgB,CAE7D,YAAqBa,EAAe,CAClC,MAAMA,CAAG,EADU,SAAAA,CAErB,CAHkB,KAAO,2BAI3B,CAEO,MAAMJ,UAAoCT,CAAgB,CAE/D,YAAqBa,EAAe,CAClC,MAAMA,CAAG,EADU,SAAAA,CAErB,CAHkB,KAAO,6BAI3B,CAEO,MAAMjB,UAA4CI,CAAgB,CAEvE,YAAqBa,EAAe,CAClC,MAAMA,CAAG,EADU,SAAAA,CAErB,CAHkB,KAAO,qCAI3B,CAEO,MAAMpB,UAAgCO,CAAgB,CAE3D,YAAqBa,EAAe,CAClC,MAAMA,CAAG,EADU,SAAAA,CAErB,CAHkB,KAAO,yBAI3B,CAEO,MAAMlB,UAA4CK,CAAgB,CAEvE,YAAqBa,EAAe,CAClC,MAAMA,CAAG,EADU,SAAAA,CAErB,CAHkB,KAAO,qCAI3B,CAEO,MAAMX,UAAiCF,CAAgB,CAE5D,YAAqBa,EAAe,CAClC,MAAMA,CAAG,EADU,SAAAA,CAErB,CAHkB,KAAO,0BAI3B",
6
- "names": ["Errors_exports", "__export", "AlreadySendingApduError", "DeviceAlreadyConnectedError", "DeviceDisconnectedBeforeSendingApdu", "DeviceDisconnectedWhileSendingError", "DeviceNotInitializedError", "DeviceNotRecognizedError", "DisconnectError", "GeneralDmkError", "NoAccessibleDeviceError", "NoTransportProvidedError", "NoTransportsProvidedError", "OpeningConnectionError", "ReconnectionFailedError", "SendApduConcurrencyError", "SendApduEmptyResponseError", "SendApduTimeoutError", "TransportAlreadyExistsError", "TransportNotSupportedError", "UnknownDeviceError", "__toCommonJS", "err"]
4
+ "sourcesContent": ["import { type DmkError } from \"@api/Error\";\n\nexport type ConnectError =\n | UnknownDeviceError\n | OpeningConnectionError\n | DeviceAlreadyConnectedError;\n\nexport class GeneralDmkError implements DmkError {\n _tag = \"GeneralDmkError\";\n originalError?: unknown;\n constructor(err?: unknown) {\n if (err instanceof Error) {\n this.originalError = err;\n } else if (err !== undefined) {\n this.originalError = new Error(String(err));\n }\n }\n}\n\nexport class DeviceAlreadyConnectedError extends GeneralDmkError {\n override readonly _tag = \"DeviceAlreadyDiscoveredError\";\n constructor(readonly err?: unknown) {\n super(err);\n }\n}\n\nexport class DeviceNotRecognizedError extends GeneralDmkError {\n override readonly _tag = \"DeviceNotRecognizedError\";\n constructor(readonly err?: unknown) {\n super(err);\n }\n}\n\nexport class NoAccessibleDeviceError extends GeneralDmkError {\n override readonly _tag = \"NoAccessibleDeviceError\";\n constructor(readonly err?: unknown) {\n super(err);\n }\n}\n\nexport class OpeningConnectionError extends GeneralDmkError {\n override _tag = \"ConnectionOpeningError\";\n constructor(err?: unknown) {\n super(err);\n }\n}\n\nexport class UnknownDeviceError extends GeneralDmkError {\n override readonly _tag = \"UnknownDeviceError\";\n constructor(readonly err?: unknown) {\n super(err);\n }\n}\n\nexport class TransportNotSupportedError extends GeneralDmkError {\n override readonly _tag = \"TransportNotSupportedError\";\n constructor(readonly err?: unknown) {\n super(err);\n }\n}\nexport class SendApduConcurrencyError extends GeneralDmkError {\n override readonly _tag = \"SendApduConcurrencyError\";\n constructor(readonly err?: unknown) {\n super(err);\n }\n}\n\nexport class SendApduTimeoutError extends GeneralDmkError {\n override readonly _tag = \"SendApduTimeoutError\";\n constructor(readonly err?: unknown) {\n super(err);\n }\n}\nexport class DisconnectError extends GeneralDmkError {\n override readonly _tag = \"DisconnectError\";\n constructor(readonly err?: unknown) {\n super(err);\n }\n}\n\nexport class ReconnectionFailedError extends GeneralDmkError {\n override readonly _tag = \"ReconnectionFailedError\";\n constructor(readonly err?: unknown) {\n super(err);\n }\n}\n\nexport class DeviceNotInitializedError extends GeneralDmkError {\n override readonly _tag = \"DeviceNotInitializedError\";\n constructor(readonly err?: unknown) {\n super(err);\n }\n}\n\nexport class NoTransportsProvidedError extends GeneralDmkError {\n override readonly _tag = \"NoTransportsProvidedError\";\n constructor(readonly err?: unknown) {\n super(err);\n }\n}\n\nexport class TransportAlreadyExistsError extends GeneralDmkError {\n override readonly _tag = \"TransportAlreadyExistsError\";\n constructor(readonly err?: unknown) {\n super(err);\n }\n}\n\nexport class DeviceDisconnectedWhileSendingError extends GeneralDmkError {\n override readonly _tag = \"DeviceDisconnectedWhileSendingError\";\n constructor(readonly err?: unknown) {\n super(err);\n }\n}\n\nexport class AlreadySendingApduError extends GeneralDmkError {\n override readonly _tag = \"AlreadySendingApduError\";\n constructor(readonly err?: unknown) {\n super(err);\n }\n}\n\nexport class DeviceDisconnectedBeforeSendingApdu extends GeneralDmkError {\n override readonly _tag = \"DeviceDisconnectedBeforeSendingApdu\";\n constructor(readonly err?: unknown) {\n super(err);\n }\n}\n\nexport class NoTransportProvidedError extends GeneralDmkError {\n override readonly _tag = \"NoTransportProvidedError\";\n constructor(readonly err?: unknown) {\n super(err);\n }\n}\n"],
5
+ "mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,6BAAAE,EAAA,gCAAAC,EAAA,wCAAAC,EAAA,wCAAAC,EAAA,8BAAAC,EAAA,6BAAAC,EAAA,oBAAAC,EAAA,oBAAAC,EAAA,4BAAAC,EAAA,6BAAAC,EAAA,8BAAAC,EAAA,2BAAAC,EAAA,4BAAAC,EAAA,6BAAAC,EAAA,yBAAAC,EAAA,gCAAAC,EAAA,+BAAAC,EAAA,uBAAAC,IAAA,eAAAC,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,KAAO,yBAI3B,CAEO,MAAMf,UAAkCG,CAAgB,CAE7D,YAAqBY,EAAe,CAClC,MAAMA,CAAG,EADU,SAAAA,CAErB,CAHkB,KAAO,2BAI3B,CAEO,MAAMT,UAAkCH,CAAgB,CAE7D,YAAqBY,EAAe,CAClC,MAAMA,CAAG,EADU,SAAAA,CAErB,CAHkB,KAAO,2BAI3B,CAEO,MAAMJ,UAAoCR,CAAgB,CAE/D,YAAqBY,EAAe,CAClC,MAAMA,CAAG,EADU,SAAAA,CAErB,CAHkB,KAAO,6BAI3B,CAEO,MAAMhB,UAA4CI,CAAgB,CAEvE,YAAqBY,EAAe,CAClC,MAAMA,CAAG,EADU,SAAAA,CAErB,CAHkB,KAAO,qCAI3B,CAEO,MAAMnB,UAAgCO,CAAgB,CAE3D,YAAqBY,EAAe,CAClC,MAAMA,CAAG,EADU,SAAAA,CAErB,CAHkB,KAAO,yBAI3B,CAEO,MAAMjB,UAA4CK,CAAgB,CAEvE,YAAqBY,EAAe,CAClC,MAAMA,CAAG,EADU,SAAAA,CAErB,CAHkB,KAAO,qCAI3B,CAEO,MAAMV,UAAiCF,CAAgB,CAE5D,YAAqBY,EAAe,CAClC,MAAMA,CAAG,EADU,SAAAA,CAErB,CAHkB,KAAO,0BAI3B",
6
+ "names": ["Errors_exports", "__export", "AlreadySendingApduError", "DeviceAlreadyConnectedError", "DeviceDisconnectedBeforeSendingApdu", "DeviceDisconnectedWhileSendingError", "DeviceNotInitializedError", "DeviceNotRecognizedError", "DisconnectError", "GeneralDmkError", "NoAccessibleDeviceError", "NoTransportProvidedError", "NoTransportsProvidedError", "OpeningConnectionError", "ReconnectionFailedError", "SendApduConcurrencyError", "SendApduTimeoutError", "TransportAlreadyExistsError", "TransportNotSupportedError", "UnknownDeviceError", "__toCommonJS", "err"]
7
7
  }
@@ -1,2 +1,2 @@
1
- "use strict";var t=Object.defineProperty;var c=Object.getOwnPropertyDescriptor;var l=Object.getOwnPropertyNames;var a=Object.prototype.hasOwnProperty;var E=(o,r)=>{for(var e in r)t(o,e,{get:r[e],enumerable:!0})},s=(o,r,e,i)=>{if(r&&typeof r=="object"||typeof r=="function")for(let n of l(r))!a.call(o,n)&&n!==e&&t(o,n,{get:()=>r[n],enumerable:!(i=c(r,n))||i.enumerable});return o};var u=o=>s(t({},"__esModule",{value:!0}),o);var p={};E(p,{SecureChannelError:()=>m,WebSocketConnectionError:()=>k});module.exports=u(p);class k{constructor(r){this.error=r;this.originalError=r}_tag="WebSocketConnectionError";originalError}class m{constructor(r){this.error=r;this.originalError=r}_tag="SecureChannelError";originalError}0&&(module.exports={SecureChannelError,WebSocketConnectionError});
1
+ "use strict";var l=Object.defineProperty;var u=Object.getOwnPropertyDescriptor;var i=Object.getOwnPropertyNames;var E=Object.prototype.hasOwnProperty;var p=(n,r)=>{for(var t in r)l(n,t,{get:r[t],enumerable:!0})},d=(n,r,t,a)=>{if(r&&typeof r=="object"||typeof r=="function")for(let s of i(r))!E.call(n,s)&&s!==t&&l(n,s,{get:()=>r[s],enumerable:!(a=u(r,s))||a.enumerable});return n};var D=n=>d(l({},"__esModule",{value:!0}),n);var m={};p(m,{SecureChannelError:()=>A,SecureChannelErrorType:()=>c,WebSocketConnectionError:()=>y});module.exports=D(m);var o=require("../../../api/device-action/os/Errors"),c=(e=>(e[e.AppAlreadyInstalled=0]="AppAlreadyInstalled",e[e.DeviceLocked=1]="DeviceLocked",e[e.OutOfMemory=2]="OutOfMemory",e[e.RefusedByUser=3]="RefusedByUser",e[e.Unknown=4]="Unknown",e))(c||{});class y{constructor(r){this.error=r;this.originalError=r}_tag="WebSocketConnectionError";originalError}class A{constructor(r,t=4){this.error=r;this.errorType=t;this.originalError=r}_tag="SecureChannelError";originalError;mapDAErrors(){switch(this.errorType){case 1:return new o.DeviceLockedError;case 3:return new o.RefusedByUserDAError;default:return this}}mapInstallDAErrors(){switch(this.errorType){case 1:return new o.DeviceLockedError;case 3:return new o.RefusedByUserDAError;case 0:return new o.AppAlreadyInstalledDAError;case 2:return new o.OutOfMemoryDAError;default:return this}}}0&&(module.exports={SecureChannelError,SecureChannelErrorType,WebSocketConnectionError});
2
2
  //# sourceMappingURL=Errors.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../../src/internal/secure-channel/model/Errors.ts"],
4
- "sourcesContent": ["import { type DmkError } from \"@api/Error\";\n\nexport class WebSocketConnectionError implements DmkError {\n _tag = \"WebSocketConnectionError\";\n originalError?: unknown;\n\n constructor(public readonly error: unknown) {\n this.originalError = error;\n }\n}\n\nexport class SecureChannelError implements DmkError {\n _tag = \"SecureChannelError\";\n originalError?: unknown;\n\n constructor(public readonly error: unknown) {\n this.originalError = error;\n }\n}\n"],
5
- "mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,wBAAAE,EAAA,6BAAAC,IAAA,eAAAC,EAAAJ,GAEO,MAAMG,CAA6C,CAIxD,YAA4BE,EAAgB,CAAhB,WAAAA,EAC1B,KAAK,cAAgBA,CACvB,CALA,KAAO,2BACP,aAKF,CAEO,MAAMH,CAAuC,CAIlD,YAA4BG,EAAgB,CAAhB,WAAAA,EAC1B,KAAK,cAAgBA,CACvB,CALA,KAAO,qBACP,aAKF",
6
- "names": ["Errors_exports", "__export", "SecureChannelError", "WebSocketConnectionError", "__toCommonJS", "error"]
4
+ "sourcesContent": ["import {\n AppAlreadyInstalledDAError,\n DeviceLockedError,\n OutOfMemoryDAError,\n RefusedByUserDAError,\n} from \"@api/device-action/os/Errors\";\nimport type { DmkError } from \"@api/Error\";\n\nexport enum SecureChannelErrorType {\n AppAlreadyInstalled,\n DeviceLocked,\n OutOfMemory,\n RefusedByUser,\n Unknown,\n}\n\n/**\n * Errors that can possibly occur during a secure channel operation\n */\nexport type SecureChannelDAErrors =\n | SecureChannelError\n | DeviceLockedError\n | RefusedByUserDAError;\n\n/**\n * Errors that can possibly occur during a secure channel install operation\n * such as installApp or installFirmware\n */\nexport type SecureChannelInstallDAErrors =\n | SecureChannelError\n | AppAlreadyInstalledDAError\n | OutOfMemoryDAError\n | DeviceLockedError\n | RefusedByUserDAError;\n\nexport class WebSocketConnectionError implements DmkError {\n _tag = \"WebSocketConnectionError\";\n originalError?: unknown;\n\n constructor(public readonly error: unknown) {\n this.originalError = error;\n }\n}\n\nexport class SecureChannelError implements DmkError {\n _tag = \"SecureChannelError\";\n originalError?: unknown;\n\n constructor(\n public readonly error: unknown,\n public readonly errorType: SecureChannelErrorType = SecureChannelErrorType.Unknown,\n ) {\n this.originalError = error;\n }\n\n mapDAErrors(): SecureChannelDAErrors {\n switch (this.errorType) {\n case SecureChannelErrorType.DeviceLocked:\n return new DeviceLockedError();\n case SecureChannelErrorType.RefusedByUser:\n return new RefusedByUserDAError();\n default:\n return this;\n }\n }\n\n mapInstallDAErrors(): SecureChannelInstallDAErrors {\n switch (this.errorType) {\n case SecureChannelErrorType.DeviceLocked:\n return new DeviceLockedError();\n case SecureChannelErrorType.RefusedByUser:\n return new RefusedByUserDAError();\n case SecureChannelErrorType.AppAlreadyInstalled:\n return new AppAlreadyInstalledDAError();\n case SecureChannelErrorType.OutOfMemory:\n return new OutOfMemoryDAError();\n default:\n return this;\n }\n }\n}\n"],
5
+ "mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,wBAAAE,EAAA,2BAAAC,EAAA,6BAAAC,IAAA,eAAAC,EAAAL,GAAA,IAAAM,EAKO,wCAGKH,OACVA,IAAA,6CACAA,IAAA,+BACAA,IAAA,6BACAA,IAAA,iCACAA,IAAA,qBALUA,OAAA,IA2BL,MAAMC,CAA6C,CAIxD,YAA4BG,EAAgB,CAAhB,WAAAA,EAC1B,KAAK,cAAgBA,CACvB,CALA,KAAO,2BACP,aAKF,CAEO,MAAML,CAAuC,CAIlD,YACkBK,EACAC,EAAoC,EACpD,CAFgB,WAAAD,EACA,eAAAC,EAEhB,KAAK,cAAgBD,CACvB,CARA,KAAO,qBACP,cASA,aAAqC,CACnC,OAAQ,KAAK,UAAW,CACtB,IAAK,GACH,OAAO,IAAI,oBACb,IAAK,GACH,OAAO,IAAI,uBACb,QACE,OAAO,IACX,CACF,CAEA,oBAAmD,CACjD,OAAQ,KAAK,UAAW,CACtB,IAAK,GACH,OAAO,IAAI,oBACb,IAAK,GACH,OAAO,IAAI,uBACb,IAAK,GACH,OAAO,IAAI,6BACb,IAAK,GACH,OAAO,IAAI,qBACb,QACE,OAAO,IACX,CACF,CACF",
6
+ "names": ["Errors_exports", "__export", "SecureChannelError", "SecureChannelErrorType", "WebSocketConnectionError", "__toCommonJS", "import_Errors", "error", "errorType"]
7
7
  }
@@ -1,2 +1,2 @@
1
- "use strict";var S=Object.defineProperty;var a=Object.getOwnPropertyDescriptor;var h=Object.getOwnPropertyNames;var u=Object.prototype.hasOwnProperty;var y=(s,e)=>{for(var r in e)S(s,r,{get:e[r],enumerable:!0})},f=(s,e,r,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of h(e))!u.call(s,i)&&i!==r&&S(s,i,{get:()=>e[i],enumerable:!(o=a(e,i))||o.enumerable});return s};var D=s=>f(S({},"__esModule",{value:!0}),s),d=(s,e,r,o)=>{for(var i=o>1?void 0:o?a(e,r):e,t=s.length-1,g;t>=0;t--)(g=s[t])&&(i=(o?g(e,r,i):g(i))||i);return o&&i&&S(e,r,i),i},p=(s,e)=>(r,o)=>e(r,o,s);var b={};y(b,{SendApduUseCase:()=>n});module.exports=D(b);var c=require("inversify"),m=require("../../device-session/di/deviceSessionTypes"),l=require("../../logger-publisher/di/loggerTypes");let n=class{_sessionService;_logger;constructor(e,r){this._sessionService=e,this._logger=r("SendApduUseCase")}async execute({sessionId:e,apdu:r,abortTimeout:o}){return this._sessionService.getDeviceSessionById(e).caseOf({Right:async t=>(await t.sendApdu(r,{abortTimeout:o})).caseOf({Right:v=>v,Left:v=>{throw this._logger.error("Error sending APDU",{data:{sessionId:e,apdu:r,error:v}}),v}}),Left:t=>{throw this._logger.error("Error getting deviceSession",{data:{error:t}}),t}})}};n=d([(0,c.injectable)(),p(0,(0,c.inject)(m.deviceSessionTypes.DeviceSessionService)),p(1,(0,c.inject)(l.loggerTypes.LoggerPublisherServiceFactory))],n);0&&(module.exports={SendApduUseCase});
1
+ "use strict";var S=Object.defineProperty;var a=Object.getOwnPropertyDescriptor;var h=Object.getOwnPropertyNames;var u=Object.prototype.hasOwnProperty;var y=(s,e)=>{for(var r in e)S(s,r,{get:e[r],enumerable:!0})},f=(s,e,r,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of h(e))!u.call(s,i)&&i!==r&&S(s,i,{get:()=>e[i],enumerable:!(o=a(e,i))||o.enumerable});return s};var D=s=>f(S({},"__esModule",{value:!0}),s),d=(s,e,r,o)=>{for(var i=o>1?void 0:o?a(e,r):e,g=s.length-1,t;g>=0;g--)(t=s[g])&&(i=(o?t(e,r,i):t(i))||i);return o&&i&&S(e,r,i),i},p=(s,e)=>(r,o)=>e(r,o,s);var b={};y(b,{SendApduUseCase:()=>n});module.exports=D(b);var c=require("inversify"),m=require("../../device-session/di/deviceSessionTypes"),l=require("../../logger-publisher/di/loggerTypes");let n=class{_sessionService;_logger;constructor(e,r){this._sessionService=e,this._logger=r("SendApduUseCase")}async execute({sessionId:e,apdu:r,abortTimeout:o,triggersDisconnection:i}){return this._sessionService.getDeviceSessionById(e).caseOf({Right:async t=>(await t.sendApdu(r,{abortTimeout:o,triggersDisconnection:i})).caseOf({Right:v=>v,Left:v=>{throw this._logger.error("Error sending APDU",{data:{sessionId:e,apdu:r,error:v}}),v}}),Left:t=>{throw this._logger.error("Error getting deviceSession",{data:{error:t}}),t}})}};n=d([(0,c.injectable)(),p(0,(0,c.inject)(m.deviceSessionTypes.DeviceSessionService)),p(1,(0,c.inject)(l.loggerTypes.LoggerPublisherServiceFactory))],n);0&&(module.exports={SendApduUseCase});
2
2
  //# sourceMappingURL=SendApduUseCase.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../../src/internal/send/use-case/SendApduUseCase.ts"],
4
- "sourcesContent": ["import { inject, injectable } from \"inversify\";\n\nimport { ApduResponse } from \"@api/device-session/ApduResponse\";\nimport { type LoggerPublisherService } from \"@api/logger-publisher/service/LoggerPublisherService\";\nimport { DeviceSessionId } from \"@api/types\";\nimport { deviceSessionTypes } from \"@internal/device-session/di/deviceSessionTypes\";\nimport type { DeviceSessionService } from \"@internal/device-session/service/DeviceSessionService\";\nimport { loggerTypes } from \"@internal/logger-publisher/di/loggerTypes\";\n\n/**\n * The arguments for the SendApduUseCase.\n */\nexport type SendApduUseCaseArgs = {\n /**\n * Device session identifier from `DeviceManagementKit.connect`.\n */\n sessionId: DeviceSessionId;\n /**\n * Raw APDU to send to the device.\n */\n apdu: Uint8Array;\n /**\n * The time, in milliseconds, to wait before aborting an operation.\n */\n abortTimeout?: number;\n};\n\n/**\n * Sends an APDU to a connected device.\n */\n@injectable()\nexport class SendApduUseCase {\n private readonly _sessionService: DeviceSessionService;\n private readonly _logger: LoggerPublisherService;\n\n constructor(\n @inject(deviceSessionTypes.DeviceSessionService)\n sessionService: DeviceSessionService,\n @inject(loggerTypes.LoggerPublisherServiceFactory)\n loggerFactory: (tag: string) => LoggerPublisherService,\n ) {\n this._sessionService = sessionService;\n this._logger = loggerFactory(\"SendApduUseCase\");\n }\n\n async execute({\n sessionId,\n apdu,\n abortTimeout,\n }: SendApduUseCaseArgs): Promise<ApduResponse> {\n const deviceSessionOrError =\n this._sessionService.getDeviceSessionById(sessionId);\n\n return deviceSessionOrError.caseOf({\n // Case device session found\n Right: async (deviceSession) => {\n const response = await deviceSession.sendApdu(apdu, { abortTimeout });\n return response.caseOf({\n // Case APDU sent and response received successfully\n Right: (data) => data,\n // Case error sending or receiving APDU\n Left: (error) => {\n this._logger.error(\"Error sending APDU\", {\n data: { sessionId, apdu, error },\n });\n throw error;\n },\n });\n },\n // Case device session not found\n Left: (error) => {\n this._logger.error(\"Error getting deviceSession\", {\n data: { error },\n });\n throw error;\n },\n });\n }\n}\n"],
5
- "mappings": "okBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,qBAAAE,IAAA,eAAAC,EAAAH,GAAA,IAAAI,EAAmC,qBAKnCC,EAAmC,0DAEnCC,EAA4B,qDAwBrB,IAAMC,EAAN,KAAsB,CACV,gBACA,QAEjB,YAEEC,EAEAC,EACA,CACA,KAAK,gBAAkBD,EACvB,KAAK,QAAUC,EAAc,iBAAiB,CAChD,CAEA,MAAM,QAAQ,CACZ,UAAAC,EACA,KAAAC,EACA,aAAAC,CACF,EAA+C,CAI7C,OAFE,KAAK,gBAAgB,qBAAqBF,CAAS,EAEzB,OAAO,CAEjC,MAAO,MAAOG,IACK,MAAMA,EAAc,SAASF,EAAM,CAAE,aAAAC,CAAa,CAAC,GACpD,OAAO,CAErB,MAAQE,GAASA,EAEjB,KAAOC,GAAU,CACf,WAAK,QAAQ,MAAM,qBAAsB,CACvC,KAAM,CAAE,UAAAL,EAAW,KAAAC,EAAM,MAAAI,CAAM,CACjC,CAAC,EACKA,CACR,CACF,CAAC,EAGH,KAAOA,GAAU,CACf,WAAK,QAAQ,MAAM,8BAA+B,CAChD,KAAM,CAAE,MAAAA,CAAM,CAChB,CAAC,EACKA,CACR,CACF,CAAC,CACH,CACF,EA/CaR,EAANS,EAAA,IADN,cAAW,EAMPC,EAAA,eAAO,qBAAmB,oBAAoB,GAE9CA,EAAA,eAAO,cAAY,6BAA6B,IAPxCV",
6
- "names": ["SendApduUseCase_exports", "__export", "SendApduUseCase", "__toCommonJS", "import_inversify", "import_deviceSessionTypes", "import_loggerTypes", "SendApduUseCase", "sessionService", "loggerFactory", "sessionId", "apdu", "abortTimeout", "deviceSession", "data", "error", "__decorateClass", "__decorateParam"]
4
+ "sourcesContent": ["import { inject, injectable } from \"inversify\";\n\nimport { ApduResponse } from \"@api/device-session/ApduResponse\";\nimport { type LoggerPublisherService } from \"@api/logger-publisher/service/LoggerPublisherService\";\nimport { DeviceSessionId } from \"@api/types\";\nimport { deviceSessionTypes } from \"@internal/device-session/di/deviceSessionTypes\";\nimport type { DeviceSessionService } from \"@internal/device-session/service/DeviceSessionService\";\nimport { loggerTypes } from \"@internal/logger-publisher/di/loggerTypes\";\n\n/**\n * The arguments for the SendApduUseCase.\n */\nexport type SendApduUseCaseArgs = {\n /**\n * Device session identifier from `DeviceManagementKit.connect`.\n */\n sessionId: DeviceSessionId;\n /**\n * Raw APDU to send to the device.\n */\n apdu: Uint8Array;\n /**\n * The time, in milliseconds, to wait before aborting an operation.\n */\n abortTimeout?: number;\n /**\n * Indicates if a device disconnection should be expected after sending the APDU.\n */\n triggersDisconnection?: boolean;\n};\n\n/**\n * Sends an APDU to a connected device.\n */\n@injectable()\nexport class SendApduUseCase {\n private readonly _sessionService: DeviceSessionService;\n private readonly _logger: LoggerPublisherService;\n\n constructor(\n @inject(deviceSessionTypes.DeviceSessionService)\n sessionService: DeviceSessionService,\n @inject(loggerTypes.LoggerPublisherServiceFactory)\n loggerFactory: (tag: string) => LoggerPublisherService,\n ) {\n this._sessionService = sessionService;\n this._logger = loggerFactory(\"SendApduUseCase\");\n }\n\n async execute({\n sessionId,\n apdu,\n abortTimeout,\n triggersDisconnection,\n }: SendApduUseCaseArgs): Promise<ApduResponse> {\n const deviceSessionOrError =\n this._sessionService.getDeviceSessionById(sessionId);\n\n return deviceSessionOrError.caseOf({\n // Case device session found\n Right: async (deviceSession) => {\n const response = await deviceSession.sendApdu(apdu, {\n abortTimeout,\n triggersDisconnection,\n });\n return response.caseOf({\n // Case APDU sent and response received successfully\n Right: (data) => data,\n // Case error sending or receiving APDU\n Left: (error) => {\n this._logger.error(\"Error sending APDU\", {\n data: { sessionId, apdu, error },\n });\n throw error;\n },\n });\n },\n // Case device session not found\n Left: (error) => {\n this._logger.error(\"Error getting deviceSession\", {\n data: { error },\n });\n throw error;\n },\n });\n }\n}\n"],
5
+ "mappings": "okBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,qBAAAE,IAAA,eAAAC,EAAAH,GAAA,IAAAI,EAAmC,qBAKnCC,EAAmC,0DAEnCC,EAA4B,qDA4BrB,IAAMC,EAAN,KAAsB,CACV,gBACA,QAEjB,YAEEC,EAEAC,EACA,CACA,KAAK,gBAAkBD,EACvB,KAAK,QAAUC,EAAc,iBAAiB,CAChD,CAEA,MAAM,QAAQ,CACZ,UAAAC,EACA,KAAAC,EACA,aAAAC,EACA,sBAAAC,CACF,EAA+C,CAI7C,OAFE,KAAK,gBAAgB,qBAAqBH,CAAS,EAEzB,OAAO,CAEjC,MAAO,MAAOI,IACK,MAAMA,EAAc,SAASH,EAAM,CAClD,aAAAC,EACA,sBAAAC,CACF,CAAC,GACe,OAAO,CAErB,MAAQE,GAASA,EAEjB,KAAOC,GAAU,CACf,WAAK,QAAQ,MAAM,qBAAsB,CACvC,KAAM,CAAE,UAAAN,EAAW,KAAAC,EAAM,MAAAK,CAAM,CACjC,CAAC,EACKA,CACR,CACF,CAAC,EAGH,KAAOA,GAAU,CACf,WAAK,QAAQ,MAAM,8BAA+B,CAChD,KAAM,CAAE,MAAAA,CAAM,CAChB,CAAC,EACKA,CACR,CACF,CAAC,CACH,CACF,EAnDaT,EAANU,EAAA,IADN,cAAW,EAMPC,EAAA,eAAO,qBAAmB,oBAAoB,GAE9CA,EAAA,eAAO,cAAY,6BAA6B,IAPxCX",
6
+ "names": ["SendApduUseCase_exports", "__export", "SendApduUseCase", "__toCommonJS", "import_inversify", "import_deviceSessionTypes", "import_loggerTypes", "SendApduUseCase", "sessionService", "loggerFactory", "sessionId", "apdu", "abortTimeout", "triggersDisconnection", "deviceSession", "data", "error", "__decorateClass", "__decorateParam"]
7
7
  }
@@ -1,2 +1,2 @@
1
- import{hexaStringToBuffer as h}from"../../utils/HexaString";import{DataOverflowError as a,HexaStringEncodeError as b,ValueOverflowError as u}from"./AppBuilderError";const B=4294967295;class l{constructor(r=B){this.maxPayloadSize=r}data=new Uint8Array;errors=[];build=()=>this.data;tryBuild=()=>this.hasErrors()?void 0:this.data;add8BitUIntToData=r=>this.addNumberToData(r,8n,!1,!1);add16BitUIntToData=(r,t=!0)=>this.addNumberToData(r,16n,!1,t);add32BitUIntToData=(r,t=!0)=>this.addNumberToData(r,32n,!1,t);add64BitUIntToData=(r,t=!0)=>this.addNumberToData(r,64n,!1,t);add128BitUIntToData=(r,t=!0)=>this.addNumberToData(r,128n,!1,t);add256BitUIntToData=(r,t=!0)=>this.addNumberToData(r,256n,!1,t);add16BitIntToData=(r,t=!0)=>this.addNumberToData(r,16n,!0,t);add32BitIntToData=(r,t=!0)=>this.addNumberToData(r,32n,!0,t);add64BitIntToData=(r,t=!0)=>this.addNumberToData(r,64n,!0,t);add128BitIntToData=(r,t=!0)=>this.addNumberToData(r,128n,!0,t);add256BitIntToData=(r,t=!0)=>this.addNumberToData(r,256n,!0,t);addBufferToData=r=>this.hasEnoughLengthRemaining(r)?(this.data=Uint8Array.from([...this.data,...r]),this):(this.errors.push(new a(r.toString())),this);addHexaStringToData=r=>{const t=h(r);return t===null||t.length===0?(this.errors.push(new b(r)),this):(this.addBufferToData(t),this)};addAsciiStringToData=r=>{const t=new TextEncoder().encode(r);return this.addBufferToData(t),this};encodeInLVFromHexa=r=>{const t=h(r);return t===null||t.length===0?(this.errors.push(new b(r)),this):this.hasEnoughLengthRemaining(t,!0)?(this.add8BitUIntToData(t.length),this.addBufferToData(t),this):(this.errors.push(new a(r)),this)};encodeInLVFromBuffer=r=>this.hasEnoughLengthRemaining(r,!0)?(this.add8BitUIntToData(r.length),this.addBufferToData(r),this):(this.errors.push(new a(r.toString())),this);encodeInLVFromAscii=r=>this.hasEnoughLengthRemaining(r,!0)?(this.add8BitUIntToData(r.length),this.addAsciiStringToData(r),this):(this.errors.push(new a(r)),this);getAvailablePayloadLength=()=>this.maxPayloadSize-this.data.length;getErrors=()=>this.errors;hasErrors=()=>this.errors.length!==0;hasEnoughLengthRemaining=(r,t=!1)=>this.data.length+r.length+(t?1:0)<=this.maxPayloadSize;addNumberToData(r,t,o,e){let n=this.checkBoundsAndConvert(r,t,o);if(n===void 0)return this;const d=Number(t)/8,s=new Uint8Array(d);if(e)for(let i=d-1;i>=0;i--)s[i]=Number(n&0xffn),n>>=8n;else for(let i=0;i<d;i++)s[i]=Number(n&0xffn),n>>=8n;return this.addBufferToData(s)}checkBoundsAndConvert(r,t,o){if(typeof r=="number"){if(!Number.isInteger(r)||r>Number.MAX_SAFE_INTEGER){this.errors.push(new u(r.toString()));return}r=BigInt(r)}if(o){const e=1n<<t-1n;if(r>=e||r<-e){this.errors.push(new u(r.toString(),e-1n));return}if(r<0n){const n=(1n<<t)-1n;r=-r,r=(~r&n)+1n}}else{const e=1n<<t;if(r<0||r>=e){this.errors.push(new u(r.toString(),e-1n));return}}return r}}export{l as ByteArrayBuilder};
1
+ import{hexaStringToBuffer as h}from"../../utils/HexaString";import{DataOverflowError as o,HexaStringEncodeError as B,ValueOverflowError as u}from"./AppBuilderError";const b=4294967295;class m{constructor(r=b){this.maxPayloadSize=r}data=new Uint8Array;errors=[];build=()=>this.data;tryBuild=()=>this.hasErrors()?void 0:this.data;add8BitUIntToData=r=>this.addNumberToData(r,8n,!1,!1);add16BitUIntToData=(r,t=!0)=>this.addNumberToData(r,16n,!1,t);add32BitUIntToData=(r,t=!0)=>this.addNumberToData(r,32n,!1,t);add64BitUIntToData=(r,t=!0)=>this.addNumberToData(r,64n,!1,t);add128BitUIntToData=(r,t=!0)=>this.addNumberToData(r,128n,!1,t);add256BitUIntToData=(r,t=!0)=>this.addNumberToData(r,256n,!1,t);add16BitIntToData=(r,t=!0)=>this.addNumberToData(r,16n,!0,t);add32BitIntToData=(r,t=!0)=>this.addNumberToData(r,32n,!0,t);add64BitIntToData=(r,t=!0)=>this.addNumberToData(r,64n,!0,t);add128BitIntToData=(r,t=!0)=>this.addNumberToData(r,128n,!0,t);add256BitIntToData=(r,t=!0)=>this.addNumberToData(r,256n,!0,t);addBufferToData=r=>this.hasEnoughLengthRemaining(r)?(this.data=Uint8Array.from([...this.data,...r]),this):(this.errors.push(new o(r.toString())),this);addHexaStringToData=r=>{const t=h(r);return t===null||t.length===0?(this.errors.push(new B(r)),this):(this.addBufferToData(t),this)};addAsciiStringToData=r=>{const t=new TextEncoder().encode(r);return this.addBufferToData(t),this};encodeInLVFromHexa=r=>{const t=h(r);return t===null||t.length===0?(this.errors.push(new B(r)),this):this.hasEnoughLengthRemaining(t,!0)?(this.add8BitUIntToData(t.length),this.addBufferToData(t),this):(this.errors.push(new o(r)),this)};encodeInLVFromBuffer=r=>this.hasEnoughLengthRemaining(r,!0)?(this.add8BitUIntToData(r.length),this.addBufferToData(r),this):(this.errors.push(new o(r.toString())),this);encodeInLVFromAscii=r=>this.hasEnoughLengthRemaining(r,!0)?(this.add8BitUIntToData(r.length),this.addAsciiStringToData(r),this):(this.errors.push(new o(r)),this);encodeInTLVFromHexa=(r,t)=>(this.add8BitUIntToData(r),this.encodeInLVFromHexa(t));encodeInTLVFromBuffer=(r,t)=>(this.add8BitUIntToData(r),this.encodeInLVFromBuffer(t));encodeInTLVFromUInt64=(r,t,a=!0)=>(this.add8BitUIntToData(r),this.add8BitUIntToData(8),this.add64BitUIntToData(t,a));getAvailablePayloadLength=()=>this.maxPayloadSize-this.data.length;getErrors=()=>this.errors;hasErrors=()=>this.errors.length!==0;hasEnoughLengthRemaining=(r,t=!1)=>this.data.length+r.length+(t?1:0)<=this.maxPayloadSize;addNumberToData(r,t,a,e){let n=this.checkBoundsAndConvert(r,t,a);if(n===void 0)return this;const d=Number(t)/8,s=new Uint8Array(d);if(e)for(let i=d-1;i>=0;i--)s[i]=Number(n&0xffn),n>>=8n;else for(let i=0;i<d;i++)s[i]=Number(n&0xffn),n>>=8n;return this.addBufferToData(s)}checkBoundsAndConvert(r,t,a){if(typeof r=="number"){if(!Number.isInteger(r)||r>Number.MAX_SAFE_INTEGER){this.errors.push(new u(r.toString()));return}r=BigInt(r)}if(a){const e=1n<<t-1n;if(r>=e||r<-e){this.errors.push(new u(r.toString(),e-1n));return}if(r<0n){const n=(1n<<t)-1n;r=-r,r=(~r&n)+1n}}else{const e=1n<<t;if(r<0||r>=e){this.errors.push(new u(r.toString(),e-1n));return}}return r}}export{m as ByteArrayBuilder};
2
2
  //# sourceMappingURL=ByteArrayBuilder.js.map