@ledgerhq/device-management-kit 0.0.0-rnble-transport-20250303160138 → 0.0.0-rnble-transport-20250312161847

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 (126) hide show
  1. package/lib/cjs/package.json +2 -2
  2. package/lib/cjs/src/api/device-action/model/UserInteractionRequired.js.map +1 -1
  3. package/lib/cjs/src/api/device-action/os/ListAppsWithMetadata/ListAppsWithMetadataDeviceAction.js +1 -1
  4. package/lib/cjs/src/api/device-action/os/ListAppsWithMetadata/ListAppsWithMetadataDeviceAction.js.map +3 -3
  5. package/lib/cjs/src/api/index.js +1 -1
  6. package/lib/cjs/src/api/index.js.map +3 -3
  7. package/lib/cjs/src/api/secure-channel/device-action/GenuineCheck/GenuineCheckDeviceAction.js.map +2 -2
  8. package/lib/cjs/src/api/secure-channel/device-action/GenuineCheck/types.js +1 -1
  9. package/lib/cjs/src/api/secure-channel/device-action/GenuineCheck/types.js.map +1 -1
  10. package/lib/cjs/src/api/secure-channel/device-action/ListInstalledApps/ListInstalledAppsDeviceAction.js +2 -0
  11. package/lib/cjs/src/api/secure-channel/device-action/ListInstalledApps/ListInstalledAppsDeviceAction.js.map +7 -0
  12. package/lib/cjs/src/api/secure-channel/device-action/ListInstalledApps/ListInstalledAppsDeviceAction.test.js +2 -0
  13. package/lib/cjs/src/api/secure-channel/device-action/ListInstalledApps/ListInstalledAppsDeviceAction.test.js.map +7 -0
  14. package/lib/cjs/src/api/secure-channel/device-action/ListInstalledApps/types.js +2 -0
  15. package/lib/cjs/src/api/secure-channel/device-action/ListInstalledApps/types.js.map +7 -0
  16. package/lib/cjs/src/api/secure-channel/task/ConnectToSecureChannelTask.js +1 -1
  17. package/lib/cjs/src/api/secure-channel/task/ConnectToSecureChannelTask.js.map +2 -2
  18. package/lib/cjs/src/api/secure-channel/task/types.js +1 -1
  19. package/lib/cjs/src/api/secure-channel/task/types.js.map +1 -1
  20. package/lib/cjs/src/api/secure-channel/types.js +2 -0
  21. package/lib/cjs/src/api/secure-channel/types.js.map +7 -0
  22. package/lib/cjs/src/api/transport/model/DeviceConnectionStateMachine.js +1 -1
  23. package/lib/cjs/src/api/transport/model/DeviceConnectionStateMachine.js.map +2 -2
  24. package/lib/cjs/src/api/types.js +1 -1
  25. package/lib/cjs/src/api/types.js.map +1 -1
  26. package/lib/cjs/src/internal/device-session/model/DeviceSession.js +1 -1
  27. package/lib/cjs/src/internal/device-session/model/DeviceSession.js.map +2 -2
  28. package/lib/cjs/src/internal/device-session/service/DefaultApduSenderService.js +1 -1
  29. package/lib/cjs/src/internal/device-session/service/DefaultApduSenderService.js.map +2 -2
  30. package/lib/cjs/src/internal/manager-api/data/AxiosManagerApiDataSource.js +1 -1
  31. package/lib/cjs/src/internal/manager-api/data/AxiosManagerApiDataSource.js.map +3 -3
  32. package/lib/cjs/src/internal/manager-api/data/AxiosManagerApiDataSource.test.js +1 -1
  33. package/lib/cjs/src/internal/manager-api/data/AxiosManagerApiDataSource.test.js.map +3 -3
  34. package/lib/cjs/src/internal/manager-api/data/ManagerApiDataSource.js +1 -1
  35. package/lib/cjs/src/internal/manager-api/data/ManagerApiDataSource.js.map +1 -1
  36. package/lib/cjs/src/internal/manager-api/data/ManagerApiDto.js +1 -1
  37. package/lib/cjs/src/internal/manager-api/data/ManagerApiDto.js.map +1 -1
  38. package/lib/cjs/src/internal/manager-api/data/__mocks__/AxiosManagerApiDataSource.js +1 -1
  39. package/lib/cjs/src/internal/manager-api/data/__mocks__/AxiosManagerApiDataSource.js.map +2 -2
  40. package/lib/cjs/src/internal/manager-api/model/Application.js +1 -1
  41. package/lib/cjs/src/internal/manager-api/model/Application.js.map +1 -1
  42. package/lib/cjs/src/internal/manager-api/model/Params.js +2 -0
  43. package/lib/cjs/src/internal/manager-api/model/Params.js.map +7 -0
  44. package/lib/cjs/src/internal/manager-api/service/DefaultManagerApiService.js +1 -1
  45. package/lib/cjs/src/internal/manager-api/service/DefaultManagerApiService.js.map +3 -3
  46. package/lib/cjs/src/internal/manager-api/service/DefaultManagerApiService.test.js +1 -1
  47. package/lib/cjs/src/internal/manager-api/service/DefaultManagerApiService.test.js.map +3 -3
  48. package/lib/cjs/src/internal/manager-api/service/ManagerApiService.js +1 -1
  49. package/lib/cjs/src/internal/manager-api/service/ManagerApiService.js.map +1 -1
  50. package/lib/esm/package.json +2 -2
  51. package/lib/esm/src/api/device-action/model/UserInteractionRequired.js.map +1 -1
  52. package/lib/esm/src/api/device-action/os/ListAppsWithMetadata/ListAppsWithMetadataDeviceAction.js +1 -1
  53. package/lib/esm/src/api/device-action/os/ListAppsWithMetadata/ListAppsWithMetadataDeviceAction.js.map +3 -3
  54. package/lib/esm/src/api/index.js +1 -1
  55. package/lib/esm/src/api/index.js.map +3 -3
  56. package/lib/esm/src/api/secure-channel/device-action/GenuineCheck/GenuineCheckDeviceAction.js.map +2 -2
  57. package/lib/esm/src/api/secure-channel/device-action/ListInstalledApps/ListInstalledAppsDeviceAction.js +2 -0
  58. package/lib/esm/src/api/secure-channel/device-action/ListInstalledApps/ListInstalledAppsDeviceAction.js.map +7 -0
  59. package/lib/esm/src/api/secure-channel/device-action/ListInstalledApps/ListInstalledAppsDeviceAction.test.js +2 -0
  60. package/lib/esm/src/api/secure-channel/device-action/ListInstalledApps/ListInstalledAppsDeviceAction.test.js.map +7 -0
  61. package/lib/esm/src/api/secure-channel/device-action/ListInstalledApps/types.js +2 -0
  62. package/lib/esm/src/api/secure-channel/device-action/ListInstalledApps/types.js.map +7 -0
  63. package/lib/esm/src/api/secure-channel/task/ConnectToSecureChannelTask.js +1 -1
  64. package/lib/esm/src/api/secure-channel/task/ConnectToSecureChannelTask.js.map +2 -2
  65. package/lib/esm/src/api/secure-channel/task/types.js.map +1 -1
  66. package/lib/esm/src/api/secure-channel/types.js +1 -0
  67. package/lib/esm/src/api/secure-channel/types.js.map +7 -0
  68. package/lib/esm/src/api/transport/model/DeviceConnectionStateMachine.js +1 -1
  69. package/lib/esm/src/api/transport/model/DeviceConnectionStateMachine.js.map +2 -2
  70. package/lib/esm/src/internal/device-session/model/DeviceSession.js +1 -1
  71. package/lib/esm/src/internal/device-session/model/DeviceSession.js.map +2 -2
  72. package/lib/esm/src/internal/device-session/service/DefaultApduSenderService.js +1 -1
  73. package/lib/esm/src/internal/device-session/service/DefaultApduSenderService.js.map +2 -2
  74. package/lib/esm/src/internal/manager-api/data/AxiosManagerApiDataSource.js +1 -1
  75. package/lib/esm/src/internal/manager-api/data/AxiosManagerApiDataSource.js.map +3 -3
  76. package/lib/esm/src/internal/manager-api/data/AxiosManagerApiDataSource.test.js +1 -1
  77. package/lib/esm/src/internal/manager-api/data/AxiosManagerApiDataSource.test.js.map +3 -3
  78. package/lib/esm/src/internal/manager-api/data/ManagerApiDto.js.map +1 -1
  79. package/lib/esm/src/internal/manager-api/data/__mocks__/AxiosManagerApiDataSource.js +1 -1
  80. package/lib/esm/src/internal/manager-api/data/__mocks__/AxiosManagerApiDataSource.js.map +2 -2
  81. package/lib/esm/src/internal/manager-api/model/Application.js.map +1 -1
  82. package/lib/esm/src/internal/manager-api/model/Params.js +1 -0
  83. package/lib/esm/src/internal/manager-api/model/Params.js.map +7 -0
  84. package/lib/esm/src/internal/manager-api/service/DefaultManagerApiService.js +1 -1
  85. package/lib/esm/src/internal/manager-api/service/DefaultManagerApiService.js.map +3 -3
  86. package/lib/esm/src/internal/manager-api/service/DefaultManagerApiService.test.js +1 -1
  87. package/lib/esm/src/internal/manager-api/service/DefaultManagerApiService.test.js.map +3 -3
  88. package/lib/types/src/api/device-action/model/UserInteractionRequired.d.ts +1 -1
  89. package/lib/types/src/api/device-action/os/ListAppsWithMetadata/ListAppsWithMetadataDeviceAction.d.ts.map +1 -1
  90. package/lib/types/src/api/index.d.ts +1 -0
  91. package/lib/types/src/api/index.d.ts.map +1 -1
  92. package/lib/types/src/api/secure-channel/device-action/GenuineCheck/GenuineCheckDeviceAction.d.ts.map +1 -1
  93. package/lib/types/src/api/secure-channel/device-action/GenuineCheck/types.d.ts +5 -7
  94. package/lib/types/src/api/secure-channel/device-action/GenuineCheck/types.d.ts.map +1 -1
  95. package/lib/types/src/api/secure-channel/device-action/ListInstalledApps/ListInstalledAppsDeviceAction.d.ts +8 -0
  96. package/lib/types/src/api/secure-channel/device-action/ListInstalledApps/ListInstalledAppsDeviceAction.d.ts.map +1 -0
  97. package/lib/types/src/api/secure-channel/device-action/ListInstalledApps/ListInstalledAppsDeviceAction.test.d.ts +1 -0
  98. package/lib/types/src/api/secure-channel/device-action/ListInstalledApps/ListInstalledAppsDeviceAction.test.d.ts.map +1 -0
  99. package/lib/types/src/api/secure-channel/device-action/ListInstalledApps/types.d.ts +59 -0
  100. package/lib/types/src/api/secure-channel/device-action/ListInstalledApps/types.d.ts.map +1 -0
  101. package/lib/types/src/api/secure-channel/task/types.d.ts +1 -1
  102. package/lib/types/src/api/secure-channel/task/types.d.ts.map +1 -1
  103. package/lib/types/src/api/secure-channel/types.d.ts +4 -0
  104. package/lib/types/src/api/secure-channel/types.d.ts.map +1 -0
  105. package/lib/types/src/api/transport/model/DeviceConnectionStateMachine.d.ts.map +1 -1
  106. package/lib/types/src/api/types.d.ts +2 -1
  107. package/lib/types/src/api/types.d.ts.map +1 -1
  108. package/lib/types/src/internal/device-session/model/DeviceSession.d.ts.map +1 -1
  109. package/lib/types/src/internal/manager-api/data/AxiosManagerApiDataSource.d.ts +6 -5
  110. package/lib/types/src/internal/manager-api/data/AxiosManagerApiDataSource.d.ts.map +1 -1
  111. package/lib/types/src/internal/manager-api/data/ManagerApiDataSource.d.ts +14 -9
  112. package/lib/types/src/internal/manager-api/data/ManagerApiDataSource.d.ts.map +1 -1
  113. package/lib/types/src/internal/manager-api/data/ManagerApiDto.d.ts +4 -1
  114. package/lib/types/src/internal/manager-api/data/ManagerApiDto.d.ts.map +1 -1
  115. package/lib/types/src/internal/manager-api/data/__mocks__/AxiosManagerApiDataSource.d.ts +1 -0
  116. package/lib/types/src/internal/manager-api/data/__mocks__/AxiosManagerApiDataSource.d.ts.map +1 -1
  117. package/lib/types/src/internal/manager-api/model/Application.d.ts +4 -1
  118. package/lib/types/src/internal/manager-api/model/Application.d.ts.map +1 -1
  119. package/lib/types/src/internal/manager-api/model/Params.d.ts +43 -0
  120. package/lib/types/src/internal/manager-api/model/Params.d.ts.map +1 -0
  121. package/lib/types/src/internal/manager-api/service/DefaultManagerApiService.d.ts +5 -5
  122. package/lib/types/src/internal/manager-api/service/DefaultManagerApiService.d.ts.map +1 -1
  123. package/lib/types/src/internal/manager-api/service/ManagerApiService.d.ts +33 -2
  124. package/lib/types/src/internal/manager-api/service/ManagerApiService.d.ts.map +1 -1
  125. package/lib/types/tsconfig.prod.tsbuildinfo +1 -1
  126. package/package.json +2 -2
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../../src/api/secure-channel/task/ConnectToSecureChannelTask.ts"],
4
- "sourcesContent": ["import WebSocket from \"isomorphic-ws\";\nimport { type Either } from \"purify-ts\";\nimport { Observable } from \"rxjs\";\n\nimport { CommandUtils } from \"@api/command/utils/CommandUtils\";\nimport { type InternalApi } from \"@api/device-action/DeviceAction\";\nimport { type ApduResponse } from \"@api/device-session/ApduResponse\";\nimport {\n InMessageQueryEnum,\n type InMessageType,\n OutMessageResponseEnum,\n type OutMessageType,\n type SecureChannelEvent,\n SecureChannelEventType,\n} from \"@api/secure-channel/task/types\";\nimport {\n isRefusedByUser,\n willRequestPermission,\n} from \"@api/secure-channel/utils\";\nimport { bufferToHexaString, hexaStringToBuffer } from \"@api/utils/HexaString\";\nimport {\n SecureChannelError,\n type WebSocketConnectionError,\n} from \"@internal/secure-channel/model/Errors\";\n\nexport type ConnectToSecureChannelTaskArgs = {\n connection: Either<WebSocketConnectionError, WebSocket>;\n};\n\nexport class ConnectToSecureChannelTask {\n private readonly _connection: WebSocket;\n constructor(\n private readonly _api: InternalApi,\n private readonly _args: ConnectToSecureChannelTaskArgs,\n ) {\n if (this._args.connection.isRight()) {\n this._connection = this._args.connection.extract();\n } else {\n throw new SecureChannelError(\n `Invalid WebSocket connection: ${String(this._args.connection.extract())}`,\n );\n }\n }\n\n run(): Observable<SecureChannelEvent> {\n const reenableRefresher = this._api.disableRefresher(\n \"connectToSecureChannel\",\n );\n\n const obs = new Observable<SecureChannelEvent>((subscriber) => {\n let unsubscribed: boolean = false;\n let inBulkMode = false;\n let communicationFinished = false;\n let deviceError: SecureChannelError | null = null;\n let waitingForUserAction = false;\n\n this._connection.onopen = () => {\n subscriber.next({\n type: SecureChannelEventType.Opened,\n });\n };\n\n this._connection.onerror = (error) => {\n // When the bulk sending is in progress, network error is ignored\n if (inBulkMode) {\n return;\n }\n\n subscriber.error(\n new SecureChannelError({\n url: this._connection.url,\n errorMessage: error.message,\n }),\n );\n };\n\n this._connection.onclose = () => {\n // When the bulk sending is in progress, network event is ignored\n if (inBulkMode) {\n return;\n }\n\n if (communicationFinished) {\n subscriber.next({\n type: SecureChannelEventType.Closed,\n });\n subscriber.complete();\n } else {\n subscriber.error(\n new SecureChannelError(\n deviceError ?? {\n url: this._connection.url,\n errorMessage: \"Connection closed unexpectedly\",\n },\n ),\n );\n }\n };\n\n this._connection.onmessage = async (event) => {\n // When unsubscribed, ignore the message\n if (unsubscribed) {\n return;\n }\n deviceError = null;\n\n try {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n const input: InMessageType = JSON.parse(String(event.data));\n\n switch (input.query) {\n case InMessageQueryEnum.EXCHANGE: {\n const { nonce } = input;\n\n if (Array.isArray(input.data)) {\n subscriber.error(\n new SecureChannelError(\n `${InMessageQueryEnum.EXCHANGE} data type should not be Array`,\n ),\n );\n break;\n }\n\n const apdu = hexaStringToBuffer(input.data);\n\n if (apdu === null || apdu.length < 5) {\n subscriber.error(\n new SecureChannelError(\n `Received invalid APDU data: ${input.data}`,\n ),\n );\n break;\n }\n\n subscriber.next({\n type: SecureChannelEventType.PreExchange,\n payload: { nonce, apdu },\n });\n\n if (\n willRequestPermission(apdu) &&\n !this.isSecureConnectionAllowed()\n ) {\n waitingForUserAction = true;\n subscriber.next({\n type: SecureChannelEventType.PermissionRequested,\n });\n }\n\n const response = await this._api.sendApdu(apdu);\n\n if (unsubscribed) {\n return;\n }\n\n response.caseOf({\n Left: (error) => {\n subscriber.error(new SecureChannelError(error));\n },\n Right: (apduResponse: ApduResponse) => {\n let outMessageResponse: OutMessageResponseEnum;\n /**\n * | Status Code | Description | Event Emitted |\n * |-------------|------------------------------------|------------------------------------|\n * | 0x9000 | Success | SecureChannelEventEnum.Exchange |\n * | 0x5515 | Device is locked | Error |\n * | 0x5501 | User refused on the device | Error |\n * | 0x6985 | Condition of use not satisfied | Error |\n */\n // Success response\n if (CommandUtils.isSuccessResponse(apduResponse)) {\n outMessageResponse = OutMessageResponseEnum.SUCCESS;\n // Emit event for the exchange\n subscriber.next({\n type: SecureChannelEventType.Exchange,\n payload: {\n nonce,\n apdu,\n data: apduResponse.data,\n status: apduResponse.statusCode,\n },\n });\n } else {\n outMessageResponse = OutMessageResponseEnum.ERROR;\n\n deviceError = new SecureChannelError({\n url: this._connection.url,\n errorMessage: `Invalid status code: ${bufferToHexaString(\n apduResponse.statusCode,\n )}`,\n });\n\n // Device is locked\n if (CommandUtils.isLockedDeviceResponse(apduResponse)) {\n subscriber.error(\n new SecureChannelError({\n url: this._connection.url,\n errorMessage: `Device is locked`,\n }),\n );\n return;\n }\n\n // User refused the permission\n if (\n isRefusedByUser(apduResponse.statusCode) &&\n waitingForUserAction\n ) {\n subscriber.error(\n new SecureChannelError({\n url: this._connection.url,\n errorMessage: \"User refused on the device\",\n }),\n );\n return;\n }\n }\n\n if (waitingForUserAction) {\n subscriber.next({\n type: SecureChannelEventType.PermissionGranted,\n });\n waitingForUserAction = false;\n }\n\n // Send the message back to the server\n const message: OutMessageType = {\n nonce,\n response: outMessageResponse,\n data: bufferToHexaString(apduResponse.data).slice(2),\n };\n this._connection.send(JSON.stringify(message));\n },\n });\n break;\n }\n case InMessageQueryEnum.BULK: {\n inBulkMode = true;\n this._connection.close();\n\n if (!Array.isArray(input.data) || input.data.length === 0) {\n subscriber.error(\n new SecureChannelError(\"Invalid bulk data received\"),\n );\n break;\n }\n\n const apdus = input.data.reduce(\n (acc: Array<Uint8Array>, cur: string) => {\n const apdu = hexaStringToBuffer(cur);\n return apdu === null ? acc : [...acc, apdu];\n },\n [],\n );\n\n for (let i = 0, len = apdus.length; i < len; i++) {\n await this._api.sendApdu(apdus[i]!);\n if (unsubscribed) {\n subscriber.error(\n new SecureChannelError(\n \"Bulk sending cancelled by unsubscribing\",\n ),\n );\n break;\n }\n subscriber.next({\n type: SecureChannelEventType.Progress,\n payload: {\n progress: +Number((i + 1) / len).toFixed(2),\n index: i,\n total: len,\n },\n });\n }\n communicationFinished = true;\n subscriber.complete();\n break;\n }\n case InMessageQueryEnum.SUCCESS: {\n // Ignore success message when in bulk mode\n if (inBulkMode) {\n break;\n }\n // Emit the result if there is any\n const payload = input.result ?? input.data;\n if (payload) {\n subscriber.next({\n type: SecureChannelEventType.Result,\n payload: String(payload ?? \"\"),\n });\n }\n communicationFinished = true;\n subscriber.complete();\n break;\n }\n case InMessageQueryEnum.WARNING: {\n // Ignore warning message when in bulk mode\n if (inBulkMode) {\n break;\n }\n subscriber.next({\n type: SecureChannelEventType.Warning,\n payload: { message: String(input.data) },\n });\n break;\n }\n case InMessageQueryEnum.ERROR: {\n if (inBulkMode) {\n break;\n }\n subscriber.error(\n new SecureChannelError({\n url: this._connection.url,\n errorMessage: String(input.data),\n }),\n );\n }\n }\n } catch (error) {\n deviceError = new SecureChannelError(error);\n subscriber.error(deviceError);\n }\n };\n\n return () => {\n reenableRefresher();\n unsubscribed = true;\n // Close the connection if it is open when unsubscribing\n if (this._connection.readyState === WebSocket.OPEN) {\n this._connection.close();\n }\n };\n });\n\n return obs;\n }\n\n /**\n * Determines if a secure connection is already allowed based on the current device session state.\n *\n * @returns {boolean} `true` if a secure connection is allowed, otherwise `false`.\n */\n isSecureConnectionAllowed(): boolean {\n const deviceSessionState = this._api.getDeviceSessionState();\n return (\n \"isSecureConnectionAllowed\" in deviceSessionState &&\n deviceSessionState.isSecureConnectionAllowed\n );\n }\n}\n"],
5
- "mappings": "0jBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,gCAAAE,IAAA,eAAAC,EAAAH,GAAA,IAAAI,EAAsB,4BAEtBC,EAA2B,gBAE3BC,EAA6B,2CAG7BC,EAOO,0CACPC,EAGO,qCACPC,EAAuD,iCACvDC,EAGO,iDAMA,MAAMR,CAA2B,CAEtC,YACmBS,EACAC,EACjB,CAFiB,UAAAD,EACA,WAAAC,EAEjB,GAAI,KAAK,MAAM,WAAW,QAAQ,EAChC,KAAK,YAAc,KAAK,MAAM,WAAW,QAAQ,MAEjD,OAAM,IAAI,qBACR,iCAAiC,OAAO,KAAK,MAAM,WAAW,QAAQ,CAAC,CAAC,EAC1E,CAEJ,CAZiB,YAcjB,KAAsC,CACpC,MAAMC,EAAoB,KAAK,KAAK,iBAClC,wBACF,EA+RA,OA7RY,IAAI,aAAgCC,GAAe,CAC7D,IAAIC,EAAwB,GACxBC,EAAa,GACbC,EAAwB,GACxBC,EAAyC,KACzCC,EAAuB,GAE3B,YAAK,YAAY,OAAS,IAAM,CAC9BL,EAAW,KAAK,CACd,KAAM,yBAAuB,MAC/B,CAAC,CACH,EAEA,KAAK,YAAY,QAAWM,GAAU,CAEhCJ,GAIJF,EAAW,MACT,IAAI,qBAAmB,CACrB,IAAK,KAAK,YAAY,IACtB,aAAcM,EAAM,OACtB,CAAC,CACH,CACF,EAEA,KAAK,YAAY,QAAU,IAAM,CAE3BJ,IAIAC,GACFH,EAAW,KAAK,CACd,KAAM,yBAAuB,MAC/B,CAAC,EACDA,EAAW,SAAS,GAEpBA,EAAW,MACT,IAAI,qBACFI,GAAe,CACb,IAAK,KAAK,YAAY,IACtB,aAAc,gCAChB,CACF,CACF,EAEJ,EAEA,KAAK,YAAY,UAAY,MAAOG,GAAU,CAE5C,GAA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AhB,EAAwB,GACxBH,EAAW,SAAS,EACpB,KACF,CACA,KAAK,qBAAmB,QAAS,CAE/B,GAAIE,EACF,MAGF,MAAMkB,EAAUZ,EAAM,QAAUA,EAAM,KAClCY,GACFpB,EAAW,KAAK,CACd,KAAM,yBAAuB,OAC7B,QAAS,OAAOoB,GAAW,EAAE,CAC/B,CAAC,EAEHjB,EAAwB,GACxBH,EAAW,SAAS,EACpB,KACF,CACA,KAAK,qBAAmB,QAAS,CAE/B,GAAIE,EACF,MAEFF,EAAW,KAAK,CACd,KAAM,yBAAuB,QAC7B,QAAS,CAAE,QAAS,OAAOQ,EAAM,IAAI,CAAE,CACzC,CAAC,EACD,KACF,CACA,KAAK,qBAAmB,MAAO,CAC7B,GAAIN,EACF,MAEFF,EAAW,MACT,IAAI,qBAAmB,CACrB,IAAK,KAAK,YAAY,IACtB,aAAc,OAAOQ,EAAM,IAAI,CACjC,CAAC,CACH,CACF,CACF,CACF,OAASF,EAAO,CACdF,EAAc,IAAI,qBAAmBE,CAAK,EAC1CN,EAAW,MAAMI,CAAW,CAC9B,EACF,EAEO,IAAM,CACXL,EAAkB,EAClBE,EAAe,GAEX,KAAK,YAAY,aAAe,EAAAoB,QAAU,MAC5C,KAAK,YAAY,MAAM,CAE3B,CACF,CAAC,CAGH,CAOA,2BAAqC,CACnC,MAAMC,EAAqB,KAAK,KAAK,sBAAsB,EAC3D,MACE,8BAA+BA,GAC/BA,EAAmB,yBAEvB,CACF",
4
+ "sourcesContent": ["import WebSocket from \"isomorphic-ws\";\nimport { type Either } from \"purify-ts\";\nimport { Observable } from \"rxjs\";\n\nimport { CommandUtils } from \"@api/command/utils/CommandUtils\";\nimport { type InternalApi } from \"@api/device-action/DeviceAction\";\nimport { type ApduResponse } from \"@api/device-session/ApduResponse\";\nimport {\n InMessageQueryEnum,\n type InMessageType,\n OutMessageResponseEnum,\n type OutMessageType,\n type SecureChannelEvent,\n SecureChannelEventType,\n} from \"@api/secure-channel/task/types\";\nimport {\n isRefusedByUser,\n willRequestPermission,\n} from \"@api/secure-channel/utils\";\nimport { bufferToHexaString, hexaStringToBuffer } from \"@api/utils/HexaString\";\nimport {\n SecureChannelError,\n type WebSocketConnectionError,\n} from \"@internal/secure-channel/model/Errors\";\n\nexport type ConnectToSecureChannelTaskArgs = {\n connection: Either<WebSocketConnectionError, WebSocket>;\n};\n\nexport class ConnectToSecureChannelTask {\n private readonly _connection: WebSocket;\n constructor(\n private readonly _api: InternalApi,\n private readonly _args: ConnectToSecureChannelTaskArgs,\n ) {\n if (this._args.connection.isRight()) {\n this._connection = this._args.connection.extract();\n } else {\n throw new SecureChannelError(\n `Invalid WebSocket connection: ${String(this._args.connection.extract())}`,\n );\n }\n }\n\n run(): Observable<SecureChannelEvent> {\n const reenableRefresher = this._api.disableRefresher(\n \"connectToSecureChannel\",\n );\n\n const obs = new Observable<SecureChannelEvent>((subscriber) => {\n let unsubscribed: boolean = false;\n let inBulkMode = false;\n let communicationFinished = false;\n let deviceError: SecureChannelError | null = null;\n let waitingForUserAction = false;\n\n this._connection.onopen = () => {\n subscriber.next({\n type: SecureChannelEventType.Opened,\n });\n };\n\n this._connection.onerror = (error) => {\n // When the bulk sending is in progress, network error is ignored\n if (inBulkMode) {\n return;\n }\n\n subscriber.error(\n new SecureChannelError({\n url: this._connection.url,\n errorMessage: error.message,\n }),\n );\n };\n\n this._connection.onclose = () => {\n // When the bulk sending is in progress, network event is ignored\n if (inBulkMode) {\n return;\n }\n\n if (communicationFinished) {\n subscriber.next({\n type: SecureChannelEventType.Closed,\n });\n subscriber.complete();\n } else {\n subscriber.error(\n new SecureChannelError(\n deviceError ?? {\n url: this._connection.url,\n errorMessage: \"Connection closed unexpectedly\",\n },\n ),\n );\n }\n };\n\n this._connection.onmessage = async (event) => {\n // When unsubscribed, ignore the message\n if (unsubscribed) {\n return;\n }\n deviceError = null;\n\n try {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n const input: InMessageType = JSON.parse(String(event.data));\n\n switch (input.query) {\n case InMessageQueryEnum.EXCHANGE: {\n const { nonce } = input;\n\n if (Array.isArray(input.data)) {\n subscriber.error(\n new SecureChannelError(\n `${InMessageQueryEnum.EXCHANGE} data type should not be Array`,\n ),\n );\n break;\n }\n\n const apdu = hexaStringToBuffer(input.data);\n\n if (apdu === null || apdu.length < 5) {\n subscriber.error(\n new SecureChannelError(\n `Received invalid APDU data: ${input.data}`,\n ),\n );\n break;\n }\n\n subscriber.next({\n type: SecureChannelEventType.PreExchange,\n payload: { nonce, apdu },\n });\n\n if (\n willRequestPermission(apdu) &&\n !this.isSecureConnectionAllowed()\n ) {\n waitingForUserAction = true;\n subscriber.next({\n type: SecureChannelEventType.PermissionRequested,\n });\n }\n\n const response = await this._api.sendApdu(apdu);\n\n if (unsubscribed) {\n return;\n }\n\n response.caseOf({\n Left: (error) => {\n subscriber.error(new SecureChannelError(error));\n },\n Right: (apduResponse: ApduResponse) => {\n let outMessageResponse: OutMessageResponseEnum;\n /**\n * | Status Code | Description | Event Emitted |\n * |-------------|------------------------------------|------------------------------------|\n * | 0x9000 | Success | SecureChannelEventEnum.Exchange |\n * | 0x5515 | Device is locked | Error |\n * | 0x5501 | User refused on the device | Error |\n * | 0x6985 | Condition of use not satisfied | Error |\n */\n // Success response\n if (CommandUtils.isSuccessResponse(apduResponse)) {\n outMessageResponse = OutMessageResponseEnum.SUCCESS;\n // Emit event for the exchange\n subscriber.next({\n type: SecureChannelEventType.Exchange,\n payload: {\n nonce,\n apdu,\n data: apduResponse.data,\n status: apduResponse.statusCode,\n },\n });\n } else {\n outMessageResponse = OutMessageResponseEnum.ERROR;\n\n deviceError = new SecureChannelError({\n url: this._connection.url,\n errorMessage: `Invalid status code: ${bufferToHexaString(\n apduResponse.statusCode,\n )}`,\n });\n\n // Device is locked\n if (CommandUtils.isLockedDeviceResponse(apduResponse)) {\n subscriber.error(\n new SecureChannelError({\n url: this._connection.url,\n errorMessage: `Device is locked`,\n }),\n );\n return;\n }\n\n // User refused the permission\n if (\n isRefusedByUser(apduResponse.statusCode) &&\n waitingForUserAction\n ) {\n subscriber.error(\n new SecureChannelError({\n url: this._connection.url,\n errorMessage: \"User refused on the device\",\n }),\n );\n return;\n }\n }\n\n if (waitingForUserAction) {\n subscriber.next({\n type: SecureChannelEventType.PermissionGranted,\n });\n waitingForUserAction = false;\n }\n\n // Send the message back to the server\n const message: OutMessageType = {\n nonce,\n response: outMessageResponse,\n data: bufferToHexaString(apduResponse.data).slice(2),\n };\n this._connection.send(JSON.stringify(message));\n },\n });\n break;\n }\n case InMessageQueryEnum.BULK: {\n inBulkMode = true;\n this._connection.close();\n\n if (!Array.isArray(input.data) || input.data.length === 0) {\n subscriber.error(\n new SecureChannelError(\"Invalid bulk data received\"),\n );\n break;\n }\n\n const apdus = input.data.reduce(\n (acc: Array<Uint8Array>, cur: string) => {\n const apdu = hexaStringToBuffer(cur);\n return apdu === null ? acc : [...acc, apdu];\n },\n [],\n );\n\n for (let i = 0, len = apdus.length; i < len; i++) {\n await this._api.sendApdu(apdus[i]!);\n if (unsubscribed) {\n subscriber.error(\n new SecureChannelError(\n \"Bulk sending cancelled by unsubscribing\",\n ),\n );\n break;\n }\n subscriber.next({\n type: SecureChannelEventType.Progress,\n payload: {\n progress: +Number((i + 1) / len).toFixed(2),\n index: i,\n total: len,\n },\n });\n }\n communicationFinished = true;\n subscriber.complete();\n break;\n }\n case InMessageQueryEnum.SUCCESS: {\n // Ignore success message when in bulk mode\n if (inBulkMode) {\n break;\n }\n // Emit the result if there is any\n const payload = input.result ?? input.data;\n if (payload) {\n subscriber.next({\n type: SecureChannelEventType.Result,\n payload: payload ?? \"\",\n });\n }\n communicationFinished = true;\n subscriber.complete();\n break;\n }\n case InMessageQueryEnum.WARNING: {\n // Ignore warning message when in bulk mode\n if (inBulkMode) {\n break;\n }\n subscriber.next({\n type: SecureChannelEventType.Warning,\n payload: { message: String(input.data) },\n });\n break;\n }\n case InMessageQueryEnum.ERROR: {\n if (inBulkMode) {\n break;\n }\n subscriber.error(\n new SecureChannelError({\n url: this._connection.url,\n errorMessage: String(input.data),\n }),\n );\n }\n }\n } catch (error) {\n deviceError = new SecureChannelError(error);\n subscriber.error(deviceError);\n }\n };\n\n return () => {\n reenableRefresher();\n unsubscribed = true;\n // Close the connection if it is open when unsubscribing\n if (this._connection.readyState === WebSocket.OPEN) {\n this._connection.close();\n }\n };\n });\n\n return obs;\n }\n\n /**\n * Determines if a secure connection is already allowed based on the current device session state.\n *\n * @returns {boolean} `true` if a secure connection is allowed, otherwise `false`.\n */\n isSecureConnectionAllowed(): boolean {\n const deviceSessionState = this._api.getDeviceSessionState();\n return (\n \"isSecureConnectionAllowed\" in deviceSessionState &&\n deviceSessionState.isSecureConnectionAllowed\n );\n }\n}\n"],
5
+ "mappings": "0jBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,gCAAAE,IAAA,eAAAC,EAAAH,GAAA,IAAAI,EAAsB,4BAEtBC,EAA2B,gBAE3BC,EAA6B,2CAG7BC,EAOO,0CACPC,EAGO,qCACPC,EAAuD,iCACvDC,EAGO,iDAMA,MAAMR,CAA2B,CAEtC,YACmBS,EACAC,EACjB,CAFiB,UAAAD,EACA,WAAAC,EAEjB,GAAI,KAAK,MAAM,WAAW,QAAQ,EAChC,KAAK,YAAc,KAAK,MAAM,WAAW,QAAQ,MAEjD,OAAM,IAAI,qBACR,iCAAiC,OAAO,KAAK,MAAM,WAAW,QAAQ,CAAC,CAAC,EAC1E,CAEJ,CAZiB,YAcjB,KAAsC,CACpC,MAAMC,EAAoB,KAAK,KAAK,iBAClC,wBACF,EA+RA,OA7RY,IAAI,aAAgCC,GAAe,CAC7D,IAAIC,EAAwB,GACxBC,EAAa,GACbC,EAAwB,GACxBC,EAAyC,KACzCC,EAAuB,GAE3B,YAAK,YAAY,OAAS,IAAM,CAC9BL,EAAW,KAAK,CACd,KAAM,yBAAuB,MAC/B,CAAC,CACH,EAEA,KAAK,YAAY,QAAWM,GAAU,CAEhCJ,GAIJF,EAAW,MACT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",
6
6
  "names": ["ConnectToSecureChannelTask_exports", "__export", "ConnectToSecureChannelTask", "__toCommonJS", "import_isomorphic_ws", "import_rxjs", "import_CommandUtils", "import_types", "import_utils", "import_HexaString", "import_Errors", "_api", "_args", "reenableRefresher", "subscriber", "unsubscribed", "inBulkMode", "communicationFinished", "deviceError", "waitingForUserAction", "error", "event", "input", "nonce", "apdu", "response", "apduResponse", "outMessageResponse", "message", "apdus", "acc", "cur", "i", "len", "payload", "WebSocket", "deviceSessionState"]
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 R={};P(R,{InMessageQueryEnum:()=>l,OutMessageResponseEnum:()=>g,SecureChannelEventType:()=>y,SecureChannelOperationEnum:()=>i});module.exports=A(R);var i=(a=>(a.GenuineCheck="GenuineCheck",a.ListInstalledApps="ListInstalledApps",a.UpdateMcu="UpdateMcu",a.UpdateFirmware="UpdateFirmware",a.InstallApp="InstallApp",a.UninstallApp="UninstallApp",a))(i||{}),l=(p=>(p.EXCHANGE="exchange",p.BULK="bulk",p.ERROR="error",p.WARNING="warning",p.SUCCESS="success",p))(l||{}),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 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});
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: string | Record<string, 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"],
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
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",
6
6
  "names": ["types_exports", "__export", "InMessageQueryEnum", "OutMessageResponseEnum", "SecureChannelEventType", "SecureChannelOperationEnum", "__toCommonJS"]
7
7
  }
@@ -0,0 +1,2 @@
1
+ "use strict";var u=Object.defineProperty;var i=Object.getOwnPropertyDescriptor;var o=Object.getOwnPropertyNames;var r=Object.prototype.hasOwnProperty;var x=(t,p,T,n)=>{if(p&&typeof p=="object"||typeof p=="function")for(let e of o(p))!r.call(t,e)&&e!==T&&u(t,e,{get:()=>p[e],enumerable:!(n=i(p,e))||n.enumerable});return t};var y=t=>x(u({},"__esModule",{value:!0}),t);var I={};module.exports=y(I);
2
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../../src/api/secure-channel/types.ts"],
4
+ "sourcesContent": ["export type Input<T> = { input: T };\n"],
5
+ "mappings": "+WAAA,IAAAA,EAAA,kBAAAC,EAAAD",
6
+ "names": ["types_exports", "__toCommonJS"]
7
+ }
@@ -1,2 +1,2 @@
1
- "use strict";var u=Object.defineProperty;var g=Object.getOwnPropertyDescriptor;var h=Object.getOwnPropertyNames;var C=Object.prototype.hasOwnProperty;var v=(c,n)=>{for(var o in n)u(c,o,{get:n[o],enumerable:!0})},D=(c,n,o,s)=>{if(n&&typeof n=="object"||typeof n=="function")for(let i of h(n))!C.call(c,i)&&i!==o&&u(c,i,{get:()=>n[i],enumerable:!(s=g(n,i))||s.enumerable});return c};var y=c=>D(u({},"__esModule",{value:!0}),c);var S={};v(S,{DeviceConnectionStateMachine:()=>R});module.exports=y(S);var t=require("purify-ts"),r=require("xstate"),l=require("../../command/utils/CommandUtils"),A=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,r.createActor)(T({sendApduFn:(o,s)=>this.sendApduToDeviceConnection(o,s),startReconnectionTimeout:()=>this.startReconnectionTimeout(),cancelReconnectionTimeout:()=>{this.timeout&&(clearTimeout(this.timeout),this.timeout=null)},onTerminated:n.onTerminated,closeConnection:()=>{this.deviceAdpuSender.closeConnection()}})),this.machineActor.start()}sendApduToDeviceConnection(n,o){console.log("[sendApduToDeviceConnection] called",n,o),this.deviceAdpuSender.sendApdu(n,o).then(s=>{s.caseOf({Left:i=>{console.log("[sendApduToDeviceConnection] got error response",i),this.machineActor.send({type:"ApduSendingError",error:i})},Right:i=>{console.log("[sendApduToDeviceConnection] got successful response",i),this.machineActor.send({type:"ApduResponseReceived",apduResponse:i})}})}).catch(s=>{this.machineActor.send({type:"ApduSendingError",error:new A.UnknownDeviceExchangeError(s)})})}getDependencies(){return this.deviceAdpuSender.getDependencies()}setDependencies(n){this.deviceAdpuSender.setDependencies(n)}getDeviceId(){return this.deviceId}sendApdu(n,o){return new Promise(s=>{this.machineActor.send({type:"SendApduCalled",apdu:n,triggersDisconnection:!!o,responseCallback:s})})}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:c,startReconnectionTimeout:n,cancelReconnectionTimeout:o,onTerminated:s,closeConnection:i}){return(0,r.setup)({types:{},actions:{startTimer:()=>{n()},cancelTimer:()=>{o()},reconnectionTimeoutEvent:(0,r.emit)({type:"ReconnectionTimedOut"}),sendApdu:({context:e})=>{e.apduInProgress.caseOf({Just:({apdu:p})=>{c(p,!1)},Nothing:()=>{console.error("sendApdu called while no apdu in progress")}})},sendApduResponse:({context:e},p)=>{e.apduInProgress.caseOf({Just:({responseCallback:a})=>{a(p.response)},Nothing:()=>{console.error("sendApduResponse called while no apdu in progress")}})},cleanupContext:(0,r.assign)({apduInProgress:t.Nothing}),signalTermination:()=>{s()},closeConnection:async()=>{try{await i()}catch(e){console.error("Error closing connection",e)}}},guards:{isApduThatTriggersDisconnection:({context:e},p)=>e.apduInProgress.caseOf({Just:({triggersDisconnection:a,apdu:m})=>(a||l.CommandUtils.isApduThatTriggersDisconnection(m))&&l.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,r.assign)({apduInProgress:({event:e})=>t.Maybe.of({apdu:e.apdu,triggersDisconnection:e.triggersDisconnection,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})=>{console.log("EXTRA SendApduCalled while in state: SendingApdu state"),e.responseCallback((0,t.Left)(new d.AlreadySendingApduError))}}}},WaitingForReconnection:{entry:"startTimer",on:{DeviceAttached:{target:"Connected",actions:"cancelTimer"},SendApduCalled:{target:"WaitingForReconnectionWithQueuedSendApdu",actions:(0,r.assign)({apduInProgress:({event:e})=>t.Maybe.of({apdu:e.apdu,triggersDisconnection:e.triggersDisconnection,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})=>{console.log("EXTRA SendApduCalled while in state:WaitingForReconnectionWithQueuedSendApdu"),e.responseCallback((0,t.Left)(new d.AlreadySendingApduError))}}}},Terminated:{entry:["signalTermination","closeConnection"],type:"final"}}})}0&&(module.exports={DeviceConnectionStateMachine});
1
+ "use strict";var u=Object.defineProperty;var g=Object.getOwnPropertyDescriptor;var h=Object.getOwnPropertyNames;var v=Object.prototype.hasOwnProperty;var D=(s,n)=>{for(var i in n)u(s,i,{get:n[i],enumerable:!0})},C=(s,n,i,o)=>{if(n&&typeof n=="object"||typeof n=="function")for(let r of h(n))!v.call(s,r)&&r!==i&&u(s,r,{get:()=>n[r],enumerable:!(o=g(n,r))||o.enumerable});return s};var y=s=>C(u({},"__esModule",{value:!0}),s);var S={};D(S,{DeviceConnectionStateMachine:()=>R});module.exports=y(S);var t=require("purify-ts"),c=require("xstate"),l=require("../../command/utils/CommandUtils"),m=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,o)=>this.sendApduToDeviceConnection(i,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){this.deviceAdpuSender.sendApdu(n,i).then(o=>{o.caseOf({Left:r=>{this.machineActor.send({type:"ApduSendingError",error:r})},Right:r=>{this.machineActor.send({type:"ApduResponseReceived",apduResponse:r})}})}).catch(o=>{this.machineActor.send({type:"ApduSendingError",error:new m.UnknownDeviceExchangeError(o)})})}getDependencies(){return this.deviceAdpuSender.getDependencies()}setDependencies(n){this.deviceAdpuSender.setDependencies(n)}getDeviceId(){return this.deviceId}sendApdu(n,i){return new Promise(o=>{this.machineActor.send({type:"SendApduCalled",apdu:n,triggersDisconnection:!!i,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:s,startReconnectionTimeout:n,cancelReconnectionTimeout:i,onTerminated:o,closeConnection:r}){return(0,c.setup)({types:{},actions:{startTimer:()=>{n()},cancelTimer:()=>{i()},reconnectionTimeoutEvent:(0,c.emit)({type:"ReconnectionTimedOut"}),sendApdu:({context:e})=>{e.apduInProgress.map(({apdu:p})=>{s(p,!1)})},sendApduResponse:({context:e},p)=>{e.apduInProgress.map(({responseCallback:a})=>a(p.response))},cleanupContext:(0,c.assign)({apduInProgress:t.Nothing}),signalTermination:()=>{o()},closeConnection:()=>{r()}},guards:{isApduThatTriggersDisconnection:({context:e},p)=>e.apduInProgress.caseOf({Just:({triggersDisconnection:a,apdu:A})=>(a||l.CommandUtils.isApduThatTriggersDisconnection(A))&&l.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,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,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});
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 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 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: {\n deviceId: DeviceId;\n deviceApduSender: DeviceApduSender<Dependencies>;\n timeoutDuration: number;\n onTerminated: () => void;\n }) {\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) =>\n this.sendApduToDeviceConnection(apdu, triggersDisconnection),\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 ) {\n console.log(\n \"[sendApduToDeviceConnection] called\",\n apdu,\n triggersDisconnection,\n );\n this.deviceAdpuSender\n .sendApdu(apdu, triggersDisconnection)\n .then((response) => {\n response.caseOf({\n Left: (error) => {\n console.log(\n \"[sendApduToDeviceConnection] got error response\",\n error,\n );\n this.machineActor.send({ type: \"ApduSendingError\", error });\n },\n Right: (apduResponse) => {\n console.log(\n \"[sendApduToDeviceConnection] got successful response\",\n apduResponse,\n );\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 ): Promise<Either<DmkError, ApduResponse>> {\n return new Promise((responseCallback) => {\n this.machineActor.send({\n type: \"SendApduCalled\",\n apdu,\n triggersDisconnection: !!triggersDisconnection,\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: (apdu: Uint8Array, triggersDisconnection: boolean) => 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 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.caseOf({\n Just: ({ apdu }) => {\n sendApduFn(apdu, false);\n },\n Nothing: () => {\n console.error(\"sendApdu called while no apdu in progress\");\n },\n });\n },\n sendApduResponse: (\n { context },\n params: { response: Either<DmkError, ApduResponse> },\n ) => {\n context.apduInProgress.caseOf({\n Just: ({ responseCallback }) => {\n responseCallback(params.response);\n },\n Nothing: () => {\n console.error(\"sendApduResponse called while no apdu in progress\");\n },\n });\n },\n cleanupContext: assign({ apduInProgress: Nothing }),\n signalTermination: () => {\n onTerminated();\n },\n closeConnection: async () => {\n try {\n await closeConnection(); // ASK: how do we handle errors ?\n } catch (e) {\n console.error(\"Error closing connection\", e);\n }\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 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 console.log(\n \"EXTRA SendApduCalled while in state: SendingApdu state\",\n );\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 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 console.log(\n \"EXTRA SendApduCalled while in state:WaitingForReconnectionWithQueuedSendApdu\",\n );\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,oBA8CA,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,EAKT,CACD,KAAK,SAAWA,EAAO,SACvB,KAAK,iBAAmBA,EAAO,iBAC/B,KAAK,gBAAkBA,EAAO,gBAC9B,KAAK,gBAAe,eAClBC,EAAiB,CACf,WAAY,CAACC,EA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A,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,CACtB,QAAQ,IACN,wDACF,EACAA,EAAM,oBAAiB,QAAK,IAAI,yBAAyB,CAAC,CAC5D,CACF,CACF,CACF,EACA,uBAAwB,CACtB,MAAO,aACP,GAAI,CACF,eAAgB,CACd,OAAQ,YACR,QAAS,aACX,EACA,eAAgB,CACd,OAAQ,2CACR,WAAS,UAAO,CACd,eAAgB,CAAC,CAAE,MAAAA,CAAM,IAChB,QAAM,GAAG,CACd,KAAMA,EAAM,KACZ,sBAAuBA,EAAM,sBAC7B,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,CACtB,QAAQ,IACN,8EACF,EACAA,EAAM,oBAAiB,QAAK,IAAI,yBAAyB,CAAC,CAC5D,CACF,CACF,CACF,EAEA,WAAY,CACV,MAAO,CAAC,oBAAqB,iBAAiB,EAC9C,KAAM,OACR,CACF,CACF,CAAC,CACH",
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 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 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: {\n deviceId: DeviceId;\n deviceApduSender: DeviceApduSender<Dependencies>;\n timeoutDuration: number;\n onTerminated: () => void;\n }) {\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) =>\n this.sendApduToDeviceConnection(apdu, triggersDisconnection),\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 ) {\n this.deviceAdpuSender\n .sendApdu(apdu, triggersDisconnection)\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 ): Promise<Either<DmkError, ApduResponse>> {\n return new Promise((responseCallback) => {\n this.machineActor.send({\n type: \"SendApduCalled\",\n apdu,\n triggersDisconnection: !!triggersDisconnection,\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: (apdu: Uint8Array, triggersDisconnection: boolean) => 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 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 }) => {\n sendApduFn(apdu, false);\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+RJpkAxACJpZgukCGmAFpANoAGALqJQABzyx05QmJAAPRAA4A7AGZKywQEYAnAFYATMoAsBg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SYvG+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 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 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,oBA8CA,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,EAKT,CACD,KAAK,SAAWA,EAAO,SACvB,KAAK,iBAAmBA,EAAO,iBAC/B,KAAK,gBAAkBA,EAAO,gBAC9B,KAAK,gBAAe,eAClBC,EAAiB,CACf,WAAY,CAACC,EAAMC,IACjB,KAAK,2BAA2BD,EAAMC,CAAqB,EAC7D,yBAA0B,IAAM,KAAK,yBAAyB,EAC9D,0BAA2B,IAAM,CAC3B,KAAK,UACP,aAAa,KAAK,OAAO,EACzB,KAAK,QAAU,KAEnB,EACA,aAAcH,EAAO,aACrB,gBAAiB,IAAM,CACrB,KAAK,iBAAiB,gBAAgB,CACxC,CACF,CAAC,CAIH,EACA,KAAK,aAAa,MAAM,CAC1B,CAEQ,2BACNE,EACAC,EACA,CACA,KAAK,iBACF,SAASD,EAAMC,CAAqB,EACpC,KAAMC,GAAa,CAClBA,EAAS,OAAO,CACd,KAAOC,GAAU,CACf,KAAK,aAAa,KAAK,CAAE,KAAM,mBAAoB,MAAAA,CAAM,CAAC,CAC5D,EACA,MAAQC,GAAiB,CACvB,KAAK,aAAa,KAAK,CACrB,KAAM,uBACN,aAAAA,CACF,CAAC,CACH,CACF,CAAC,CACH,CAAC,EACA,MAAOD,GAAU,CAChB,KAAK,aAAa,KAAK,CACrB,KAAM,mBAC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AAE,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
6
  "names": ["DeviceConnectionStateMachine_exports", "__export", "DeviceConnectionStateMachine", "__toCommonJS", "import_purify_ts", "import_xstate", "import_CommandUtils", "import_Error", "import_Errors", "params", "makeStateMachine", "apdu", "triggersDisconnection", "response", "error", "apduResponse", "dependencies", "responseCallback", "sendApduFn", "startReconnectionTimeout", "cancelReconnectionTimeout", "onTerminated", "closeConnection", "context", "event"]
7
7
  }
@@ -1,2 +1,2 @@
1
- "use strict";var o=Object.defineProperty;var i=Object.getOwnPropertyDescriptor;var n=Object.getOwnPropertyNames;var a=Object.prototype.hasOwnProperty;var c=(t,e,s,p)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of n(e))!a.call(t,r)&&r!==s&&o(t,r,{get:()=>e[r],enumerable:!(p=i(e,r))||p.enumerable});return t};var m=t=>c(o({},"__esModule",{value:!0}),t);var d={};module.exports=m(d);
1
+ "use strict";var o=Object.defineProperty;var i=Object.getOwnPropertyDescriptor;var n=Object.getOwnPropertyNames;var a=Object.prototype.hasOwnProperty;var c=(t,e,s,p)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of n(e))!a.call(t,r)&&r!==s&&o(t,r,{get:()=>e[r],enumerable:!(p=i(e,r))||p.enumerable});return t};var d=t=>c(o({},"__esModule",{value:!0}),t);var m={};module.exports=d(m);
2
2
  //# sourceMappingURL=types.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/api/types.ts"],
4
- "sourcesContent": ["export type { OpenAppErrorCodes } from \"./command/os/OpenAppCommand\";\nexport type { CommandErrors } from \"./command/utils/CommandErrors\";\nexport type { DeviceId } from \"./device/DeviceModel\";\nexport type { ConnectionType } from \"./discovery/ConnectionType\";\nexport type { CommandErrorArgs } from \"./Error\";\nexport type { LogSubscriberOptions } from \"./logger-subscriber/model/LogSubscriberOptions\";\nexport type { DiscoveredDevice } from \"./transport/model/DiscoveredDevice\";\nexport type {\n Transport,\n TransportArgs,\n TransportFactory,\n} from \"./transport/model/Transport\";\nexport type { TransportIdentifier } from \"./transport/model/TransportIdentifier\";\nexport type { ApduBuilderArgs } from \"@api/apdu/utils/ApduBuilder\";\nexport type { Command } from \"@api/command/Command\";\nexport type {\n CommandErrorResult,\n CommandResult,\n CommandSuccessResult,\n} from \"@api/command/model/CommandResult\";\nexport type { SendCommandUseCaseArgs } from \"@api/command/use-case/SendCommandUseCase\";\nexport type { DeviceModelId } from \"@api/device/DeviceModel\";\nexport {\n type DeviceAction,\n type DeviceActionIntermediateValue,\n type ExecuteDeviceActionReturnType,\n} from \"@api/device-action/DeviceAction\";\nexport {\n type GetDeviceStatusDAError,\n type GetDeviceStatusDAInput,\n type GetDeviceStatusDAIntermediateValue,\n type GetDeviceStatusDAOutput,\n type GetDeviceStatusDAState,\n} from \"@api/device-action/os/GetDeviceStatus/types\";\nexport {\n type GoToDashboardDAError,\n type GoToDashboardDAInput,\n type GoToDashboardDAIntermediateValue,\n type GoToDashboardDAOutput,\n type GoToDashboardDAState,\n} from \"@api/device-action/os/GoToDashboard/types\";\nexport {\n type ListAppsDAError,\n type ListAppsDAInput,\n type ListAppsDAIntermediateValue,\n type ListAppsDAOutput,\n type ListAppsDAState,\n} from \"@api/device-action/os/ListApps/types\";\nexport {\n type ListAppsWithMetadataDAError,\n type ListAppsWithMetadataDAInput,\n type ListAppsWithMetadataDAIntermediateValue,\n type ListAppsWithMetadataDAOutput,\n type ListAppsWithMetadataDAState,\n} from \"@api/device-action/os/ListAppsWithMetadata/types\";\nexport {\n type OpenAppDAError,\n type OpenAppDAInput,\n type OpenAppDAIntermediateValue,\n type OpenAppDAOutput,\n type OpenAppDARequiredInteraction,\n type OpenAppDAState,\n} from \"@api/device-action/os/OpenAppDeviceAction/types\";\nexport {\n type SendCommandInAppDAError,\n type SendCommandInAppDAInput,\n type SendCommandInAppDAIntermediateValue,\n type SendCommandInAppDAOutput,\n} from \"@api/device-action/os/SendCommandInAppDeviceAction/SendCommandInAppDeviceActionTypes\";\nexport type { ExecuteDeviceActionUseCaseArgs } from \"@api/device-action/use-case/ExecuteDeviceActionUseCase\";\nexport { type StateMachineTypes } from \"@api/device-action/xstate-utils/StateMachineTypes\";\nexport { type DeviceModelDataSource } from \"@api/device-model/data/DeviceModelDataSource\";\nexport type { DeviceSessionState } from \"@api/device-session/DeviceSessionState\";\nexport { type ApduReceiverService } from \"@api/device-session/service/ApduReceiverService\";\nexport { type ApduReceiverServiceFactory } from \"@api/device-session/service/ApduReceiverService\";\nexport { type ApduSenderServiceFactory } from \"@api/device-session/service/ApduSenderService\";\nexport { type ApduSenderService } from \"@api/device-session/service/ApduSenderService\";\nexport type { DeviceSessionId } from \"@api/device-session/types\";\nexport type { DmkConfig } from \"@api/DmkConfig\";\nexport type { DmkError } from \"@api/Error\";\nexport type { LoggerPublisherService } from \"@api/logger-publisher/service/LoggerPublisherService\";\nexport type {\n LoggerSubscriberService,\n LogParams,\n} from \"@api/logger-subscriber/service/LoggerSubscriberService\";\nexport { type DeviceApduSender } from \"@api/transport/model/DeviceApduSender\";\nexport {\n type GenuineCheckDAError,\n type GenuineCheckDAInput,\n type GenuineCheckDAIntermediateValue,\n type GenuineCheckDAOutput,\n type GenuineCheckDARequiredInteraction,\n type GenuineCheckDAState,\n} from \"@api/secure-channel/device-action/GenuineCheck/types\";\nexport {\n type DeviceConnection,\n type DisconnectHandler,\n type SendApduFnType,\n} from \"@api/transport/model/DeviceConnection\";\nexport { type TransportDiscoveredDevice } from \"@api/transport/model/TransportDiscoveredDevice\";\nexport type { HexaString } from \"@api/utils/HexaString\";\nexport type { ConnectUseCaseArgs } from \"@internal/discovery/use-case/ConnectUseCase\";\nexport type { DisconnectUseCaseArgs } from \"@internal/discovery/use-case/DisconnectUseCase\";\nexport type { GetConnectedDeviceUseCaseArgs } from \"@internal/discovery/use-case/GetConnectedDeviceUseCase\";\nexport type { StartDiscoveringUseCaseArgs } from \"@internal/discovery/use-case/StartDiscoveringUseCase\";\nexport type { SendApduUseCaseArgs } from \"@internal/send/use-case/SendApduUseCase\";\n"],
4
+ "sourcesContent": ["export type { OpenAppErrorCodes } from \"./command/os/OpenAppCommand\";\nexport type { CommandErrors } from \"./command/utils/CommandErrors\";\nexport type { DeviceId } from \"./device/DeviceModel\";\nexport type { ConnectionType } from \"./discovery/ConnectionType\";\nexport type { CommandErrorArgs } from \"./Error\";\nexport type { LogSubscriberOptions } from \"./logger-subscriber/model/LogSubscriberOptions\";\nexport type { DiscoveredDevice } from \"./transport/model/DiscoveredDevice\";\nexport type {\n Transport,\n TransportArgs,\n TransportFactory,\n} from \"./transport/model/Transport\";\nexport type { TransportIdentifier } from \"./transport/model/TransportIdentifier\";\nexport type { ApduBuilderArgs } from \"@api/apdu/utils/ApduBuilder\";\nexport type { Command } from \"@api/command/Command\";\nexport type {\n CommandErrorResult,\n CommandResult,\n CommandSuccessResult,\n} from \"@api/command/model/CommandResult\";\nexport type { SendCommandUseCaseArgs } from \"@api/command/use-case/SendCommandUseCase\";\nexport type { DeviceModelId } from \"@api/device/DeviceModel\";\nexport {\n type DeviceAction,\n type DeviceActionIntermediateValue,\n type ExecuteDeviceActionReturnType,\n} from \"@api/device-action/DeviceAction\";\nexport {\n type GetDeviceStatusDAError,\n type GetDeviceStatusDAInput,\n type GetDeviceStatusDAIntermediateValue,\n type GetDeviceStatusDAOutput,\n type GetDeviceStatusDAState,\n} from \"@api/device-action/os/GetDeviceStatus/types\";\nexport {\n type GoToDashboardDAError,\n type GoToDashboardDAInput,\n type GoToDashboardDAIntermediateValue,\n type GoToDashboardDAOutput,\n type GoToDashboardDAState,\n} from \"@api/device-action/os/GoToDashboard/types\";\nexport {\n type ListAppsDAError,\n type ListAppsDAInput,\n type ListAppsDAIntermediateValue,\n type ListAppsDAOutput,\n type ListAppsDAState,\n} from \"@api/device-action/os/ListApps/types\";\nexport {\n type ListAppsWithMetadataDAError,\n type ListAppsWithMetadataDAInput,\n type ListAppsWithMetadataDAIntermediateValue,\n type ListAppsWithMetadataDAOutput,\n type ListAppsWithMetadataDAState,\n} from \"@api/device-action/os/ListAppsWithMetadata/types\";\nexport {\n type OpenAppDAError,\n type OpenAppDAInput,\n type OpenAppDAIntermediateValue,\n type OpenAppDAOutput,\n type OpenAppDARequiredInteraction,\n type OpenAppDAState,\n} from \"@api/device-action/os/OpenAppDeviceAction/types\";\nexport {\n type SendCommandInAppDAError,\n type SendCommandInAppDAInput,\n type SendCommandInAppDAIntermediateValue,\n type SendCommandInAppDAOutput,\n} from \"@api/device-action/os/SendCommandInAppDeviceAction/SendCommandInAppDeviceActionTypes\";\nexport type { ExecuteDeviceActionUseCaseArgs } from \"@api/device-action/use-case/ExecuteDeviceActionUseCase\";\nexport { type StateMachineTypes } from \"@api/device-action/xstate-utils/StateMachineTypes\";\nexport { type DeviceModelDataSource } from \"@api/device-model/data/DeviceModelDataSource\";\nexport type { DeviceSessionState } from \"@api/device-session/DeviceSessionState\";\nexport { type ApduReceiverService } from \"@api/device-session/service/ApduReceiverService\";\nexport { type ApduReceiverServiceFactory } from \"@api/device-session/service/ApduReceiverService\";\nexport { type ApduSenderServiceFactory } from \"@api/device-session/service/ApduSenderService\";\nexport { type ApduSenderService } from \"@api/device-session/service/ApduSenderService\";\nexport type { DeviceSessionId } from \"@api/device-session/types\";\nexport type { DmkConfig } from \"@api/DmkConfig\";\nexport type { DmkError } from \"@api/Error\";\nexport type { LoggerPublisherService } from \"@api/logger-publisher/service/LoggerPublisherService\";\nexport type {\n LoggerSubscriberService,\n LogParams,\n} from \"@api/logger-subscriber/service/LoggerSubscriberService\";\nexport {\n type GenuineCheckDAError,\n type GenuineCheckDAInput,\n type GenuineCheckDAIntermediateValue,\n type GenuineCheckDAOutput,\n type GenuineCheckDARequiredInteraction,\n type GenuineCheckDAState,\n} from \"@api/secure-channel/device-action/GenuineCheck/types\";\nexport {\n type ListInstalledAppsDAError,\n type ListInstalledAppsDAInput,\n type ListInstalledAppsDAIntermediateValue,\n type ListInstalledAppsDAOutput,\n type ListInstalledAppsDARequiredInteraction,\n type ListInstalledAppsDAState,\n} from \"@api/secure-channel/device-action/ListInstalledApps/types\";\nexport { type DeviceApduSender } from \"@api/transport/model/DeviceApduSender\";\nexport {\n type DeviceConnection,\n type DisconnectHandler,\n type SendApduFnType,\n} from \"@api/transport/model/DeviceConnection\";\nexport { type TransportDiscoveredDevice } from \"@api/transport/model/TransportDiscoveredDevice\";\nexport type { HexaString } from \"@api/utils/HexaString\";\nexport type { ConnectUseCaseArgs } from \"@internal/discovery/use-case/ConnectUseCase\";\nexport type { DisconnectUseCaseArgs } from \"@internal/discovery/use-case/DisconnectUseCase\";\nexport type { GetConnectedDeviceUseCaseArgs } from \"@internal/discovery/use-case/GetConnectedDeviceUseCase\";\nexport type { StartDiscoveringUseCaseArgs } from \"@internal/discovery/use-case/StartDiscoveringUseCase\";\nexport type { SendApduUseCaseArgs } from \"@internal/send/use-case/SendApduUseCase\";\n"],
5
5
  "mappings": "+WAAA,IAAAA,EAAA,kBAAAC,EAAAD",
6
6
  "names": ["types_exports", "__toCommonJS"]
7
7
  }
@@ -1,2 +1,2 @@
1
- "use strict";var c=Object.defineProperty;var g=Object.getOwnPropertyDescriptor;var _=Object.getOwnPropertyNames;var C=Object.prototype.hasOwnProperty;var y=(n,e)=>{for(var i in e)c(n,i,{get:e[i],enumerable:!0})},A=(n,e,i,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let t of _(e))!C.call(n,t)&&t!==i&&c(n,t,{get:()=>e[t],enumerable:!(r=g(e,t))||r.enumerable});return n};var E=n=>A(c({},"__esModule",{value:!0}),n);var R={};y(R,{DeviceSession:()=>b});module.exports=E(R);var d=require("purify-ts"),p=require("rxjs"),v=require("uuid"),u=require("../../../api/command/utils/CommandUtils"),s=require("../../../api/device/DeviceStatus"),S=require("../../../api/device-session/DeviceSessionState"),l=require("../../../api/Error"),h=require("../../device-session/data/DeviceSessionRefresherConst"),m=require("../../device-session/service/RefresherService"),D=require("./DeviceSessionRefresher");class b{_id;_connectedDevice;_deviceState;_refresher;_refresherService;_managerApiService;_secureChannelService;constructor({connectedDevice:e,id:i=(0,v.v4)()},r,t,a){this._id=i,this._connectedDevice=e,this._deviceState=new p.BehaviorSubject({sessionStateType:S.DeviceSessionStateType.Connected,deviceStatus:s.DeviceStatus.CONNECTED,deviceModelId:this._connectedDevice.deviceModel.id}),this._refresher=new D.DeviceSessionRefresher({refreshInterval:h.DEVICE_SESSION_REFRESH_INTERVAL,deviceStatus:s.DeviceStatus.CONNECTED,deviceModelId:this._connectedDevice.deviceModel.id,sendApduFn:o=>this.sendApdu(o,{isPolling:!0,triggersDisconnection:!1}),updateStateFn:o=>{const f=this._deviceState.getValue();this.setDeviceSessionState(o(f))}},r("device-session-refresher")),this._refresherService=new m.RefresherService(this._refresher),this._managerApiService=t,this._secureChannelService=a}get id(){return this._id}get connectedDevice(){return this._connectedDevice}get state(){return this._deviceState.asObservable()}setDeviceSessionState(e){this._deviceState.next(e)}async sendApdu(e,i={isPolling:!1,triggersDisconnection:!1}){let r;return i.isPolling||(r=this._refresherService.disableRefresher("sendApdu"),await this.waitUntilReady()),this._deviceState.getValue().deviceStatus===s.DeviceStatus.BUSY?(0,d.Left)(new l.DeviceBusyError):(this.updateDeviceStatus(s.DeviceStatus.BUSY),(await this._connectedDevice.sendApdu(e,i.triggersDisconnection)).ifRight(o=>{u.CommandUtils.isLockedDeviceResponse(o)?this.updateDeviceStatus(s.DeviceStatus.LOCKED):this.updateDeviceStatus(s.DeviceStatus.CONNECTED),!i.isPolling&&r&&r()}).ifLeft(()=>{this.updateDeviceStatus(s.DeviceStatus.CONNECTED),!i.isPolling&&r&&r()}))}async sendCommand(e){const i=e.getApdu();return(await this.sendApdu(i.getRawApdu(),{isPolling:!1,triggersDisconnection:e.triggersDisconnection??!1})).caseOf({Left:t=>{throw t},Right:t=>e.parseResponse(t,this._connectedDevice.deviceModel.id)})}executeDeviceAction(e){const{observable:i,cancel:r}=e._execute({sendApdu:async t=>this.sendApdu(t),sendCommand:async t=>this.sendCommand(t),getDeviceSessionState:()=>this._deviceState.getValue(),getDeviceSessionStateObservable:()=>this.state,setDeviceSessionState:t=>(this.setDeviceSessionState(t),this._deviceState.getValue()),disableRefresher:t=>this._refresherService.disableRefresher(t),getManagerApiService:()=>this._managerApiService,getSecureChannelService:()=>this._secureChannelService});return{observable:i,cancel:r}}close(){this.updateDeviceStatus(s.DeviceStatus.NOT_CONNECTED),this._deviceState.complete(),this._refresher.stop()}disableRefresher(e){return this._refresherService.disableRefresher(e)}updateDeviceStatus(e){const i=this._deviceState.getValue();this._refresher.setDeviceStatus(e),this._deviceState.next({...i,deviceStatus:e})}async waitUntilReady(){let e;await new Promise(i=>{e=this._deviceState.subscribe(r=>{r.deviceStatus===s.DeviceStatus.CONNECTED&&(e?.unsubscribe(),i())})})}}0&&(module.exports={DeviceSession});
1
+ "use strict";var c=Object.defineProperty;var g=Object.getOwnPropertyDescriptor;var _=Object.getOwnPropertyNames;var C=Object.prototype.hasOwnProperty;var y=(n,e)=>{for(var i in e)c(n,i,{get:e[i],enumerable:!0})},A=(n,e,i,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let t of _(e))!C.call(n,t)&&t!==i&&c(n,t,{get:()=>e[t],enumerable:!(r=g(e,t))||r.enumerable});return n};var E=n=>A(c({},"__esModule",{value:!0}),n);var R={};y(R,{DeviceSession:()=>b});module.exports=E(R);var d=require("purify-ts"),p=require("rxjs"),v=require("uuid"),u=require("../../../api/command/utils/CommandUtils"),s=require("../../../api/device/DeviceStatus"),S=require("../../../api/device-session/DeviceSessionState"),l=require("../../../api/Error"),h=require("../../device-session/data/DeviceSessionRefresherConst"),m=require("../../device-session/service/RefresherService"),D=require("./DeviceSessionRefresher");class b{_id;_connectedDevice;_deviceState;_refresher;_refresherService;_managerApiService;_secureChannelService;constructor({connectedDevice:e,id:i=(0,v.v4)()},r,t,a){this._id=i,this._connectedDevice=e,this._deviceState=new p.BehaviorSubject({sessionStateType:S.DeviceSessionStateType.Connected,deviceStatus:s.DeviceStatus.CONNECTED,deviceModelId:this._connectedDevice.deviceModel.id}),this._refresher=new D.DeviceSessionRefresher({refreshInterval:h.DEVICE_SESSION_REFRESH_INTERVAL,deviceStatus:s.DeviceStatus.CONNECTED,deviceModelId:this._connectedDevice.deviceModel.id,sendApduFn:o=>this.sendApdu(o,{isPolling:!0,triggersDisconnection:!1}),updateStateFn:o=>{const f=this._deviceState.getValue();this.setDeviceSessionState(o(f))}},r("device-session-refresher")),this._refresherService=new m.RefresherService(this._refresher),this._managerApiService=t,this._secureChannelService=a}get id(){return this._id}get connectedDevice(){return this._connectedDevice}get state(){return this._deviceState.asObservable()}setDeviceSessionState(e){this._deviceState.next(e)}async sendApdu(e,i={isPolling:!1,triggersDisconnection:!1}){let r;return i.isPolling||(r=this._refresherService.disableRefresher("sendApdu"),await this.waitUntilReady()),this._deviceState.getValue().deviceStatus===s.DeviceStatus.BUSY?(0,d.Left)(new l.DeviceBusyError):(this.updateDeviceStatus(s.DeviceStatus.BUSY),(await this._connectedDevice.sendApdu(e,i.triggersDisconnection)).ifRight(o=>{u.CommandUtils.isLockedDeviceResponse(o)?this.updateDeviceStatus(s.DeviceStatus.LOCKED):this.updateDeviceStatus(s.DeviceStatus.CONNECTED),!i.isPolling&&r&&r()}).ifLeft(()=>{this.updateDeviceStatus(s.DeviceStatus.CONNECTED),!i.isPolling&&r&&r()}))}async sendCommand(e){const i=e.getApdu();return(await this.sendApdu(i.getRawApdu(),{isPolling:!1,triggersDisconnection:e.triggersDisconnection??!1})).caseOf({Left:t=>{throw t},Right:t=>e.parseResponse(t,this._connectedDevice.deviceModel.id)})}executeDeviceAction(e){const{observable:i,cancel:r}=e._execute({sendApdu:async t=>this.sendApdu(t),sendCommand:async t=>this.sendCommand(t),getDeviceSessionState:()=>this._deviceState.getValue(),getDeviceSessionStateObservable:()=>this.state,setDeviceSessionState:t=>(this.setDeviceSessionState(t),this._deviceState.getValue()),disableRefresher:t=>this._refresherService.disableRefresher(t),getManagerApiService:()=>this._managerApiService,getSecureChannelService:()=>this._secureChannelService});return{observable:i,cancel:r}}close(){this.updateDeviceStatus(s.DeviceStatus.NOT_CONNECTED),this._deviceState.complete(),this._refresher.stop()}disableRefresher(e){return this._refresherService.disableRefresher(e)}updateDeviceStatus(e){const i=this._deviceState.getValue();this._refresher.setDeviceStatus(e),this._deviceState.next({...i,deviceStatus:e})}async waitUntilReady(){let e;await new Promise(i=>{e=this._deviceState.subscribe(r=>{[s.DeviceStatus.LOCKED,s.DeviceStatus.CONNECTED].includes(r.deviceStatus)&&(e?.unsubscribe(),i())})})}}0&&(module.exports={DeviceSession});
2
2
  //# sourceMappingURL=DeviceSession.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../../src/internal/device-session/model/DeviceSession.ts"],
4
- "sourcesContent": ["import { type Either, Left } from \"purify-ts\";\nimport { BehaviorSubject, type Subscription } from \"rxjs\";\nimport { v4 as uuidv4 } from \"uuid\";\n\nimport { type Command } from \"@api/command/Command\";\nimport { type CommandResult } from \"@api/command/model/CommandResult\";\nimport { CommandUtils } from \"@api/command/utils/CommandUtils\";\nimport { DeviceStatus } from \"@api/device/DeviceStatus\";\nimport {\n type DeviceAction,\n type DeviceActionIntermediateValue,\n type ExecuteDeviceActionReturnType,\n} from \"@api/device-action/DeviceAction\";\nimport { type ApduResponse } from \"@api/device-session/ApduResponse\";\nimport {\n type DeviceSessionState,\n DeviceSessionStateType,\n} from \"@api/device-session/DeviceSessionState\";\nimport { type DeviceSessionId } from \"@api/device-session/types\";\nimport { DeviceBusyError, type DmkError } from \"@api/Error\";\nimport { type LoggerPublisherService } from \"@api/logger-publisher/service/LoggerPublisherService\";\nimport { type TransportConnectedDevice } from \"@api/transport/model/TransportConnectedDevice\";\nimport { DEVICE_SESSION_REFRESH_INTERVAL } from \"@internal/device-session/data/DeviceSessionRefresherConst\";\nimport { RefresherService } from \"@internal/device-session/service/RefresherService\";\nimport { type ManagerApiService } from \"@internal/manager-api/service/ManagerApiService\";\nimport { type SecureChannelService } from \"@internal/secure-channel/service/SecureChannelService\";\n\nimport { DeviceSessionRefresher } from \"./DeviceSessionRefresher\";\n\nexport type SessionConstructorArgs = {\n connectedDevice: TransportConnectedDevice;\n id?: DeviceSessionId;\n};\n\ntype SendApduOptions = {\n isPolling?: boolean;\n triggersDisconnection?: boolean;\n};\n\n/**\n * Represents a session with a device.\n */\nexport class DeviceSession {\n private readonly _id: DeviceSessionId;\n private readonly _connectedDevice: TransportConnectedDevice;\n private readonly _deviceState: BehaviorSubject<DeviceSessionState>;\n private readonly _refresher: DeviceSessionRefresher;\n private readonly _refresherService: RefresherService;\n private readonly _managerApiService: ManagerApiService;\n private readonly _secureChannelService: SecureChannelService;\n\n constructor(\n { connectedDevice, id = uuidv4() }: SessionConstructorArgs,\n loggerModuleFactory: (tag: string) => LoggerPublisherService,\n managerApiService: ManagerApiService,\n secureChannelService: SecureChannelService,\n ) {\n this._id = id;\n this._connectedDevice = connectedDevice;\n this._deviceState = new BehaviorSubject<DeviceSessionState>({\n sessionStateType: DeviceSessionStateType.Connected,\n deviceStatus: DeviceStatus.CONNECTED,\n deviceModelId: this._connectedDevice.deviceModel.id,\n });\n this._refresher = new DeviceSessionRefresher(\n {\n refreshInterval: DEVICE_SESSION_REFRESH_INTERVAL,\n deviceStatus: DeviceStatus.CONNECTED,\n deviceModelId: this._connectedDevice.deviceModel.id,\n sendApduFn: (rawApdu: Uint8Array) =>\n this.sendApdu(rawApdu, {\n isPolling: true,\n triggersDisconnection: false,\n }),\n updateStateFn: (callback) => {\n const state = this._deviceState.getValue();\n this.setDeviceSessionState(callback(state));\n },\n },\n loggerModuleFactory(\"device-session-refresher\"),\n );\n this._refresherService = new RefresherService(this._refresher);\n this._managerApiService = managerApiService;\n this._secureChannelService = secureChannelService;\n }\n\n public get id() {\n return this._id;\n }\n\n public get connectedDevice() {\n return this._connectedDevice;\n }\n\n public get state() {\n return this._deviceState.asObservable();\n }\n\n public setDeviceSessionState(state: DeviceSessionState) {\n this._deviceState.next(state);\n }\n\n public async sendApdu(\n rawApdu: Uint8Array,\n options: SendApduOptions = {\n isPolling: false,\n triggersDisconnection: false,\n },\n ): Promise<Either<DmkError, ApduResponse>> {\n let reenableRefresher: () => void;\n if (!options.isPolling) {\n reenableRefresher = this._refresherService.disableRefresher(\"sendApdu\");\n await this.waitUntilReady();\n }\n\n const sessionState = this._deviceState.getValue();\n if (sessionState.deviceStatus === DeviceStatus.BUSY) {\n return Left(new DeviceBusyError());\n }\n\n this.updateDeviceStatus(DeviceStatus.BUSY);\n\n const errorOrResponse = await this._connectedDevice.sendApdu(\n rawApdu,\n options.triggersDisconnection,\n );\n\n return errorOrResponse\n .ifRight((response: ApduResponse) => {\n if (CommandUtils.isLockedDeviceResponse(response)) {\n this.updateDeviceStatus(DeviceStatus.LOCKED);\n } else {\n this.updateDeviceStatus(DeviceStatus.CONNECTED);\n }\n\n if (!options.isPolling && reenableRefresher) {\n reenableRefresher();\n }\n })\n .ifLeft(() => {\n this.updateDeviceStatus(DeviceStatus.CONNECTED);\n\n if (!options.isPolling && reenableRefresher) {\n reenableRefresher();\n }\n });\n }\n\n public async sendCommand<Response, Args, ErrorStatusCodes>(\n command: Command<Response, Args, ErrorStatusCodes>,\n ): Promise<CommandResult<Response, ErrorStatusCodes>> {\n const apdu = command.getApdu();\n const response = await this.sendApdu(apdu.getRawApdu(), {\n isPolling: false,\n triggersDisconnection: command.triggersDisconnection ?? false,\n });\n\n return response.caseOf({\n Left: (err) => {\n throw err;\n },\n Right: (r) =>\n command.parseResponse(r, this._connectedDevice.deviceModel.id),\n });\n }\n\n public executeDeviceAction<\n Output,\n Input,\n Error extends DmkError,\n IntermediateValue extends DeviceActionIntermediateValue,\n >(\n deviceAction: DeviceAction<Output, Input, Error, IntermediateValue>,\n ): ExecuteDeviceActionReturnType<Output, Error, IntermediateValue> {\n const { observable, cancel } = deviceAction._execute({\n sendApdu: async (apdu: Uint8Array) => this.sendApdu(apdu),\n sendCommand: async <Response, ErrorStatusCodes, Args>(\n command: Command<Response, ErrorStatusCodes, Args>,\n ) => this.sendCommand(command),\n getDeviceSessionState: () => this._deviceState.getValue(),\n getDeviceSessionStateObservable: () => this.state,\n setDeviceSessionState: (state: DeviceSessionState) => {\n this.setDeviceSessionState(state);\n return this._deviceState.getValue();\n },\n disableRefresher: (blockerId: string) =>\n this._refresherService.disableRefresher(blockerId),\n getManagerApiService: () => this._managerApiService,\n getSecureChannelService: () => this._secureChannelService,\n });\n\n return {\n observable,\n cancel,\n };\n }\n\n public close() {\n this.updateDeviceStatus(DeviceStatus.NOT_CONNECTED);\n this._deviceState.complete();\n this._refresher.stop();\n }\n\n public disableRefresher(id: string): () => void {\n return this._refresherService.disableRefresher(id);\n }\n\n private updateDeviceStatus(deviceStatus: DeviceStatus) {\n const sessionState = this._deviceState.getValue();\n this._refresher.setDeviceStatus(deviceStatus);\n this._deviceState.next({\n ...sessionState,\n deviceStatus,\n });\n }\n\n private async waitUntilReady() {\n let deviceStateSub: Subscription;\n\n await new Promise<void>((resolve) => {\n deviceStateSub = this._deviceState.subscribe((state) => {\n if (state.deviceStatus === DeviceStatus.CONNECTED) {\n deviceStateSub?.unsubscribe();\n resolve();\n }\n });\n });\n }\n}\n"],
5
- "mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,mBAAAE,IAAA,eAAAC,EAAAH,GAAA,IAAAI,EAAkC,qBAClCC,EAAmD,gBACnDC,EAA6B,gBAI7BC,EAA6B,2CAC7BC,EAA6B,oCAO7BC,EAGO,kDAEPC,EAA+C,sBAG/CC,EAAgD,qEAChDC,EAAiC,6DAIjCC,EAAuC,oCAehC,MAAMX,CAAc,CACR,IACA,iBACA,aACA,WACA,kBACA,mB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aAAa,SAAS,EAChD,KAAK,WAAW,gBAAgBD,CAAY,EAC5C,KAAK,aAAa,KAAK,CACrB,GAAGC,EACH,aAAAD,CACF,CAAC,CACH,CAEA,MAAc,gBAAiB,CAC7B,IAAIE,EAEJ,MAAM,IAAI,QAAeC,GAAY,CACnCD,EAAiB,KAAK,aAAa,UAAWd,GAAU,CAClDA,EAAM,eAAiB,eAAa,YACtCc,GAAgB,YAAY,EAC5BC,EAAQ,EAEZ,CAAC,CACH,CAAC,CACH,CACF",
4
+ "sourcesContent": ["import { type Either, Left } from \"purify-ts\";\nimport { BehaviorSubject, type Subscription } from \"rxjs\";\nimport { v4 as uuidv4 } from \"uuid\";\n\nimport { type Command } from \"@api/command/Command\";\nimport { type CommandResult } from \"@api/command/model/CommandResult\";\nimport { CommandUtils } from \"@api/command/utils/CommandUtils\";\nimport { DeviceStatus } from \"@api/device/DeviceStatus\";\nimport {\n type DeviceAction,\n type DeviceActionIntermediateValue,\n type ExecuteDeviceActionReturnType,\n} from \"@api/device-action/DeviceAction\";\nimport { type ApduResponse } from \"@api/device-session/ApduResponse\";\nimport {\n type DeviceSessionState,\n DeviceSessionStateType,\n} from \"@api/device-session/DeviceSessionState\";\nimport { type DeviceSessionId } from \"@api/device-session/types\";\nimport { DeviceBusyError, type DmkError } from \"@api/Error\";\nimport { type LoggerPublisherService } from \"@api/logger-publisher/service/LoggerPublisherService\";\nimport { type TransportConnectedDevice } from \"@api/transport/model/TransportConnectedDevice\";\nimport { DEVICE_SESSION_REFRESH_INTERVAL } from \"@internal/device-session/data/DeviceSessionRefresherConst\";\nimport { RefresherService } from \"@internal/device-session/service/RefresherService\";\nimport { type ManagerApiService } from \"@internal/manager-api/service/ManagerApiService\";\nimport { type SecureChannelService } from \"@internal/secure-channel/service/SecureChannelService\";\n\nimport { DeviceSessionRefresher } from \"./DeviceSessionRefresher\";\n\nexport type SessionConstructorArgs = {\n connectedDevice: TransportConnectedDevice;\n id?: DeviceSessionId;\n};\n\ntype SendApduOptions = {\n isPolling?: boolean;\n triggersDisconnection?: boolean;\n};\n\n/**\n * Represents a session with a device.\n */\nexport class DeviceSession {\n private readonly _id: DeviceSessionId;\n private readonly _connectedDevice: TransportConnectedDevice;\n private readonly _deviceState: BehaviorSubject<DeviceSessionState>;\n private readonly _refresher: DeviceSessionRefresher;\n private readonly _refresherService: RefresherService;\n private readonly _managerApiService: ManagerApiService;\n private readonly _secureChannelService: SecureChannelService;\n\n constructor(\n { connectedDevice, id = uuidv4() }: SessionConstructorArgs,\n loggerModuleFactory: (tag: string) => LoggerPublisherService,\n managerApiService: ManagerApiService,\n secureChannelService: SecureChannelService,\n ) {\n this._id = id;\n this._connectedDevice = connectedDevice;\n this._deviceState = new BehaviorSubject<DeviceSessionState>({\n sessionStateType: DeviceSessionStateType.Connected,\n deviceStatus: DeviceStatus.CONNECTED,\n deviceModelId: this._connectedDevice.deviceModel.id,\n });\n this._refresher = new DeviceSessionRefresher(\n {\n refreshInterval: DEVICE_SESSION_REFRESH_INTERVAL,\n deviceStatus: DeviceStatus.CONNECTED,\n deviceModelId: this._connectedDevice.deviceModel.id,\n sendApduFn: (rawApdu: Uint8Array) =>\n this.sendApdu(rawApdu, {\n isPolling: true,\n triggersDisconnection: false,\n }),\n updateStateFn: (callback) => {\n const state = this._deviceState.getValue();\n this.setDeviceSessionState(callback(state));\n },\n },\n loggerModuleFactory(\"device-session-refresher\"),\n );\n this._refresherService = new RefresherService(this._refresher);\n this._managerApiService = managerApiService;\n this._secureChannelService = secureChannelService;\n }\n\n public get id() {\n return this._id;\n }\n\n public get connectedDevice() {\n return this._connectedDevice;\n }\n\n public get state() {\n return this._deviceState.asObservable();\n }\n\n public setDeviceSessionState(state: DeviceSessionState) {\n this._deviceState.next(state);\n }\n\n public async sendApdu(\n rawApdu: Uint8Array,\n options: SendApduOptions = {\n isPolling: false,\n triggersDisconnection: false,\n },\n ): Promise<Either<DmkError, ApduResponse>> {\n let reenableRefresher: () => void;\n if (!options.isPolling) {\n reenableRefresher = this._refresherService.disableRefresher(\"sendApdu\");\n await this.waitUntilReady();\n }\n\n const sessionState = this._deviceState.getValue();\n if (sessionState.deviceStatus === DeviceStatus.BUSY) {\n return Left(new DeviceBusyError());\n }\n\n this.updateDeviceStatus(DeviceStatus.BUSY);\n\n const errorOrResponse = await this._connectedDevice.sendApdu(\n rawApdu,\n options.triggersDisconnection,\n );\n\n return errorOrResponse\n .ifRight((response: ApduResponse) => {\n if (CommandUtils.isLockedDeviceResponse(response)) {\n this.updateDeviceStatus(DeviceStatus.LOCKED);\n } else {\n this.updateDeviceStatus(DeviceStatus.CONNECTED);\n }\n\n if (!options.isPolling && reenableRefresher) {\n reenableRefresher();\n }\n })\n .ifLeft(() => {\n this.updateDeviceStatus(DeviceStatus.CONNECTED);\n\n if (!options.isPolling && reenableRefresher) {\n reenableRefresher();\n }\n });\n }\n\n public async sendCommand<Response, Args, ErrorStatusCodes>(\n command: Command<Response, Args, ErrorStatusCodes>,\n ): Promise<CommandResult<Response, ErrorStatusCodes>> {\n const apdu = command.getApdu();\n const response = await this.sendApdu(apdu.getRawApdu(), {\n isPolling: false,\n triggersDisconnection: command.triggersDisconnection ?? false,\n });\n\n return response.caseOf({\n Left: (err) => {\n throw err;\n },\n Right: (r) =>\n command.parseResponse(r, this._connectedDevice.deviceModel.id),\n });\n }\n\n public executeDeviceAction<\n Output,\n Input,\n Error extends DmkError,\n IntermediateValue extends DeviceActionIntermediateValue,\n >(\n deviceAction: DeviceAction<Output, Input, Error, IntermediateValue>,\n ): ExecuteDeviceActionReturnType<Output, Error, IntermediateValue> {\n const { observable, cancel } = deviceAction._execute({\n sendApdu: async (apdu: Uint8Array) => this.sendApdu(apdu),\n sendCommand: async <Response, ErrorStatusCodes, Args>(\n command: Command<Response, ErrorStatusCodes, Args>,\n ) => this.sendCommand(command),\n getDeviceSessionState: () => this._deviceState.getValue(),\n getDeviceSessionStateObservable: () => this.state,\n setDeviceSessionState: (state: DeviceSessionState) => {\n this.setDeviceSessionState(state);\n return this._deviceState.getValue();\n },\n disableRefresher: (blockerId: string) =>\n this._refresherService.disableRefresher(blockerId),\n getManagerApiService: () => this._managerApiService,\n getSecureChannelService: () => this._secureChannelService,\n });\n\n return {\n observable,\n cancel,\n };\n }\n\n public close() {\n this.updateDeviceStatus(DeviceStatus.NOT_CONNECTED);\n this._deviceState.complete();\n this._refresher.stop();\n }\n\n public disableRefresher(id: string): () => void {\n return this._refresherService.disableRefresher(id);\n }\n\n private updateDeviceStatus(deviceStatus: DeviceStatus) {\n const sessionState = this._deviceState.getValue();\n this._refresher.setDeviceStatus(deviceStatus);\n this._deviceState.next({\n ...sessionState,\n deviceStatus,\n });\n }\n\n private async waitUntilReady() {\n let deviceStateSub: Subscription;\n\n await new Promise<void>((resolve) => {\n deviceStateSub = this._deviceState.subscribe((state) => {\n if (\n [DeviceStatus.LOCKED, DeviceStatus.CONNECTED].includes(\n state.deviceStatus,\n )\n ) {\n deviceStateSub?.unsubscribe();\n resolve();\n }\n });\n });\n }\n}\n"],
5
+ "mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,mBAAAE,IAAA,eAAAC,EAAAH,GAAA,IAAAI,EAAkC,qBAClCC,EAAmD,gBACnDC,EAA6B,gBAI7BC,EAA6B,2CAC7BC,EAA6B,oCAO7BC,EAGO,kDAEPC,EAA+C,sBAG/CC,EAAgD,qEAChDC,EAAiC,6DAIjCC,EAAuC,oCAehC,MAAMX,CAAc,CACR,IACA,iBACA,aACA,WACA,kBACA,mBACA,sBAEjB,YACE,CAAE,gBAAAY,EAAiB,GAAAC,KAAK,EAAAC,IAAO,CAAE,EACjCC,EACAC,EACAC,EACA,CACA,KAAK,IAAMJ,EACX,KAAK,iBAAmBD,EACxB,KAAK,aAAe,IAAI,kBAAoC,CAC1D,iBAAkB,yBAAuB,UACzC,aAAc,eAAa,UAC3B,cAAe,KAAK,iBAAiB,YAAY,EACnD,CAAC,EACD,KAAK,WAAa,IAAI,yBACpB,CACE,gBAAiB,kCACj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EAC5BC,EAAQ,EAEZ,CAAC,CACH,CAAC,CACH,CACF",
6
6
  "names": ["DeviceSession_exports", "__export", "DeviceSession", "__toCommonJS", "import_purify_ts", "import_rxjs", "import_uuid", "import_CommandUtils", "import_DeviceStatus", "import_DeviceSessionState", "import_Error", "import_DeviceSessionRefresherConst", "import_RefresherService", "import_DeviceSessionRefresher", "connectedDevice", "id", "uuidv4", "loggerModuleFactory", "managerApiService", "secureChannelService", "rawApdu", "callback", "state", "options", "reenableRefresher", "response", "command", "apdu", "err", "r", "deviceAction", "observable", "cancel", "blockerId", "deviceStatus", "sessionState", "deviceStateSub", "resolve"]
7
7
  }
@@ -1,2 +1,2 @@
1
- "use strict";var c=Object.defineProperty;var u=Object.getOwnPropertyDescriptor;var z=Object.getOwnPropertyNames;var y=Object.prototype.hasOwnProperty;var E=(a,e)=>{for(var t in e)c(a,t,{get:e[t],enumerable:!0})},L=(a,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of z(e))!y.call(a,i)&&i!==t&&c(a,i,{get:()=>e[i],enumerable:!(r=u(e,i))||r.enumerable});return a};var v=a=>L(c({},"__esModule",{value:!0}),a),f=(a,e,t,r)=>{for(var i=r>1?void 0:r?u(e,t):e,n=a.length-1,s;n>=0;n--)(s=a[n])&&(i=(r?s(e,t,i):s(i))||i);return r&&i&&c(e,t,i),i},F=(a,e)=>(t,r)=>e(t,r,a);var T={};E(T,{DefaultApduSenderService:()=>g});module.exports=v(T);var l=require("inversify"),o=require("purify-ts"),S=require("uuid"),m=require("../../../api/device-session/data/FramerConst"),d=require("../../../api/device-session/utils/FramerUtils"),h=require("../../device-session/model/Errors"),_=require("../../device-session/model/Frame"),A=require("../../device-session/model/FrameHeader"),b=require("../../logger-publisher/di/loggerTypes");let g=class{_frameSize;_channel;_padding;_logger;constructor({frameSize:e,channel:t=o.Maybe.zero(),padding:r=!1},i){this._frameSize=e,this._channel=t,this._padding=r,this._logger=i("framer")}getFrames(e){const t=[];let r=0,i=this.getFrameAtIndex(e,r);for(;i.isRight();)t.push(i.extract()),r+=1,i=this.getFrameAtIndex(e,r).mapLeft(n=>(n instanceof h.FramerOverflowError?this._logger.debug("Frames parsed",{data:{count:r}}):this._logger.error("Error while parsing frame",{data:{error:n}}),n));return t}getFrameAtIndex(e,t){const r=this.getFrameHeaderFrom(t,e.length),i=t*this._frameSize-this.getHeaderSizeSumFrom(t);if(i>e.length)return(0,o.Left)(new h.FramerOverflowError);if(r.getLength()>this._frameSize)return(0,o.Left)(new h.FramerApduError);const n=this._frameSize-r.getLength(),s=e.slice(t===0?0:i,t===0?n:i+this._frameSize-r.getLength()),p=this._padding?new Uint8Array(n).fill(0):new Uint8Array(s.length<n?s.length:n);p.set(s,0);const H=new _.Frame({header:r,data:p});return(0,o.Right)(H)}getFrameHeaderFrom(e,t){const r=new A.FrameHeader({uuid:(0,S.v4)(),channel:this._channel.map(i=>d.FramerUtils.getLastBytesFrom(i,m.CHANNEL_LENGTH)),headTag:new Uint8Array([m.HEAD_TAG]),index:d.FramerUtils.numberToByteArray(e,m.INDEX_LENGTH),length:this.getFrameHeaderSizeFromIndex(e),dataSize:o.Maybe.zero()});return e===0&&r.setDataSize(o.Maybe.of(d.FramerUtils.numberToByteArray(t,m.APDU_DATA_LENGTH_LENGTH))),r}getHeaderSizeSumFrom(e){let t=this.getFrameHeaderSizeFromIndex(0),r=1;for(;r<e;)t+=this.getFrameHeaderSizeFromIndex(r),r+=1;return t}getFrameHeaderSizeFromIndex(e){return this._channel.caseOf({Just:()=>m.CHANNEL_LENGTH,Nothing:()=>0})+m.INDEX_LENGTH+m.HEAD_TAG_LENGTH+(e===0?m.APDU_DATA_LENGTH_LENGTH:0)}};g=f([(0,l.injectable)(),F(1,(0,l.inject)(b.loggerTypes.LoggerPublisherServiceFactory))],g);0&&(module.exports={DefaultApduSenderService});
1
+ "use strict";var c=Object.defineProperty;var u=Object.getOwnPropertyDescriptor;var z=Object.getOwnPropertyNames;var v=Object.prototype.hasOwnProperty;var y=(a,e)=>{for(var t in e)c(a,t,{get:e[t],enumerable:!0})},E=(a,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of z(e))!v.call(a,i)&&i!==t&&c(a,i,{get:()=>e[i],enumerable:!(r=u(e,i))||r.enumerable});return a};var L=a=>E(c({},"__esModule",{value:!0}),a),f=(a,e,t,r)=>{for(var i=r>1?void 0:r?u(e,t):e,m=a.length-1,s;m>=0;m--)(s=a[m])&&(i=(r?s(e,t,i):s(i))||i);return r&&i&&c(e,t,i),i},F=(a,e)=>(t,r)=>e(t,r,a);var T={};y(T,{DefaultApduSenderService:()=>g});module.exports=L(T);var l=require("inversify"),o=require("purify-ts"),S=require("uuid"),n=require("../../../api/device-session/data/FramerConst"),d=require("../../../api/device-session/utils/FramerUtils"),h=require("../../device-session/model/Errors"),A=require("../../device-session/model/Frame"),_=require("../../device-session/model/FrameHeader"),b=require("../../logger-publisher/di/loggerTypes");let g=class{_frameSize;_channel;_padding;_logger;constructor({frameSize:e,channel:t=o.Maybe.zero(),padding:r=!1},i){this._frameSize=e,this._channel=t,this._padding=r,this._logger=i("DefaultApduSenderService")}getFrames(e){const t=[];let r=0,i=this.getFrameAtIndex(e,r);for(;i.isRight();)t.push(i.extract()),r+=1,i=this.getFrameAtIndex(e,r).mapLeft(m=>(m instanceof h.FramerOverflowError?this._logger.debug("Frames parsed",{data:{count:r}}):this._logger.error("Error while parsing frame",{data:{error:m}}),m));return t}getFrameAtIndex(e,t){const r=this.getFrameHeaderFrom(t,e.length),i=t*this._frameSize-this.getHeaderSizeSumFrom(t);if(i>e.length)return(0,o.Left)(new h.FramerOverflowError);if(r.getLength()>this._frameSize)return(0,o.Left)(new h.FramerApduError);const m=this._frameSize-r.getLength(),s=e.slice(t===0?0:i,t===0?m:i+this._frameSize-r.getLength()),p=this._padding?new Uint8Array(m).fill(0):new Uint8Array(s.length<m?s.length:m);p.set(s,0);const H=new A.Frame({header:r,data:p});return(0,o.Right)(H)}getFrameHeaderFrom(e,t){const r=new _.FrameHeader({uuid:(0,S.v4)(),channel:this._channel.map(i=>d.FramerUtils.getLastBytesFrom(i,n.CHANNEL_LENGTH)),headTag:new Uint8Array([n.HEAD_TAG]),index:d.FramerUtils.numberToByteArray(e,n.INDEX_LENGTH),length:this.getFrameHeaderSizeFromIndex(e),dataSize:o.Maybe.zero()});return e===0&&r.setDataSize(o.Maybe.of(d.FramerUtils.numberToByteArray(t,n.APDU_DATA_LENGTH_LENGTH))),r}getHeaderSizeSumFrom(e){let t=this.getFrameHeaderSizeFromIndex(0),r=1;for(;r<e;)t+=this.getFrameHeaderSizeFromIndex(r),r+=1;return t}getFrameHeaderSizeFromIndex(e){return this._channel.caseOf({Just:()=>n.CHANNEL_LENGTH,Nothing:()=>0})+n.INDEX_LENGTH+n.HEAD_TAG_LENGTH+(e===0?n.APDU_DATA_LENGTH_LENGTH:0)}};g=f([(0,l.injectable)(),F(1,(0,l.inject)(b.loggerTypes.LoggerPublisherServiceFactory))],g);0&&(module.exports={DefaultApduSenderService});
2
2
  //# sourceMappingURL=DefaultApduSenderService.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../../src/internal/device-session/service/DefaultApduSenderService.ts"],
4
- "sourcesContent": ["import { inject, injectable } from \"inversify\";\nimport { Either, Left, Maybe, Right } from \"purify-ts\";\nimport { v4 } from \"uuid\";\n\nimport {\n APDU_DATA_LENGTH_LENGTH,\n CHANNEL_LENGTH,\n HEAD_TAG,\n HEAD_TAG_LENGTH,\n INDEX_LENGTH,\n} from \"@api/device-session/data/FramerConst\";\nimport type {\n ApduSenderService,\n ApduSenderServiceConstructorArgs,\n} from \"@api/device-session/service/ApduSenderService\";\nimport { FramerUtils } from \"@api/device-session/utils/FramerUtils\";\nimport { LoggerPublisherService } from \"@api/logger-publisher/service/LoggerPublisherService\";\nimport {\n FramerApduError,\n FramerOverflowError,\n} from \"@internal/device-session/model/Errors\";\nimport { Frame } from \"@internal/device-session/model/Frame\";\nimport { FrameHeader } from \"@internal/device-session/model/FrameHeader\";\nimport { loggerTypes } from \"@internal/logger-publisher/di/loggerTypes\";\nimport { DmkError } from \"@root/src/api/Error\";\n/**\n * Default implementation of ApduSenderService\n *\n * Split APDU in an array of frames readies to send to a TransportConnectedDevice\n */\n@injectable()\nexport class DefaultApduSenderService implements ApduSenderService {\n protected _frameSize: number;\n protected _channel: Maybe<Uint8Array>;\n protected _padding: boolean;\n private _logger: LoggerPublisherService;\n\n /**\n * Constructor\n *\n * @param frameSize\n * @param channel\n * @param padding\n * @param loggerServiceFactory\n */\n constructor(\n {\n frameSize,\n channel = Maybe.zero(),\n padding = false,\n }: ApduSenderServiceConstructorArgs,\n @inject(loggerTypes.LoggerPublisherServiceFactory)\n loggerServiceFactory: (tag: string) => LoggerPublisherService,\n ) {\n this._frameSize = frameSize;\n this._channel = channel;\n this._padding = padding;\n this._logger = loggerServiceFactory(\"framer\");\n }\n\n /**\n * Get frames from apdu\n *\n * @param apdu\n */\n public getFrames(apdu: Uint8Array): Frame[] {\n const frames: Frame[] = [];\n let count = 0;\n let frame = this.getFrameAtIndex(apdu, count);\n\n while (frame.isRight()) {\n frames.push(frame.extract());\n count += 1;\n frame = this.getFrameAtIndex(apdu, count).mapLeft((error) => {\n if (error instanceof FramerOverflowError) {\n this._logger.debug(\"Frames parsed\", { data: { count } });\n } else {\n this._logger.error(\"Error while parsing frame\", { data: { error } });\n }\n return error;\n });\n }\n return frames;\n }\n\n /**\n * Get apdu frame at index\n * Split every {{PACKET_SIZE - HEADER_SIZE}} bytes of apdu\n * @param apdu\n * @param frameIndex\n * @private\n */\n private getFrameAtIndex(\n apdu: Uint8Array,\n frameIndex: number,\n ): Either<DmkError, Frame> {\n const header = this.getFrameHeaderFrom(frameIndex, apdu.length);\n const frameOffset =\n frameIndex * this._frameSize - this.getHeaderSizeSumFrom(frameIndex);\n\n if (frameOffset > apdu.length) {\n return Left(new FramerOverflowError());\n }\n if (header.getLength() > this._frameSize) {\n return Left(new FramerApduError());\n }\n const dataMaxSize = this._frameSize - header.getLength();\n const data = apdu.slice(\n frameIndex === 0 ? 0 : frameOffset,\n frameIndex === 0\n ? dataMaxSize\n : frameOffset + this._frameSize - header.getLength(),\n );\n const frameData = this._padding\n ? new Uint8Array(dataMaxSize).fill(0)\n : new Uint8Array(data.length < dataMaxSize ? data.length : dataMaxSize);\n frameData.set(data, 0);\n const frame = new Frame({\n header,\n data: frameData,\n });\n return Right(frame);\n }\n\n /**\n * Get frame header\n * @param frameIndex\n * @param apduSize\n * @private\n */\n private getFrameHeaderFrom(\n frameIndex: number,\n apduSize: number,\n ): FrameHeader {\n const header = new FrameHeader({\n uuid: v4(),\n channel: this._channel.map((channel) =>\n FramerUtils.getLastBytesFrom(channel, CHANNEL_LENGTH),\n ),\n headTag: new Uint8Array([HEAD_TAG]),\n index: FramerUtils.numberToByteArray(frameIndex, INDEX_LENGTH),\n length: this.getFrameHeaderSizeFromIndex(frameIndex),\n dataSize: Maybe.zero(),\n });\n if (frameIndex === 0) {\n header.setDataSize(\n Maybe.of(\n FramerUtils.numberToByteArray(apduSize, APDU_DATA_LENGTH_LENGTH),\n ),\n );\n }\n return header;\n }\n\n /**\n * Get frame offset\n * First frame has more bytes of header\n * Padding append means a 0 bytes is added at the end of each frame\n * @private\n * @param frameIndex\n */\n private getHeaderSizeSumFrom(frameIndex: number): number {\n let sum = this.getFrameHeaderSizeFromIndex(0);\n let i = 1;\n while (i < frameIndex) {\n sum += this.getFrameHeaderSizeFromIndex(i);\n i += 1;\n }\n return sum;\n }\n\n /**\n * Get frame header size\n * @private\n * @param frameIndex\n */\n private getFrameHeaderSizeFromIndex(frameIndex: number): number {\n return (\n this._channel.caseOf({\n Just: () => CHANNEL_LENGTH,\n Nothing: () => 0,\n }) +\n INDEX_LENGTH +\n HEAD_TAG_LENGTH +\n (frameIndex === 0 ? APDU_DATA_LENGTH_LENGTH : 0)\n );\n }\n}\n"],
5
- "mappings": "okBAAA,IAAAA,EAAA,GAAAC,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F,IAAe,EACXG,EACAD,EAAc,KAAK,WAAaD,EAAO,UAAU,CACvD,EACMI,EAAY,KAAK,SACnB,IAAI,WAAWF,CAAW,EAAE,KAAK,CAAC,EAClC,IAAI,WAAWC,EAAK,OAASD,EAAcC,EAAK,OAASD,CAAW,EACxEE,EAAU,IAAID,EAAM,CAAC,EACrB,MAAMN,EAAQ,IAAI,QAAM,CACtB,OAAAG,EACA,KAAMI,CACR,CAAC,EACD,SAAO,SAAMP,CAAK,CACpB,CAQQ,mBACNE,EACAM,EACa,CACb,MAAML,EAAS,IAAI,cAAY,CAC7B,QAAM,MAAG,EACT,QAAS,KAAK,SAAS,IAAKT,GAC1B,cAAY,iBAAiBA,EAAS,gBAAc,CACtD,EACA,QAAS,IAAI,WAAW,CAAC,UAAQ,CAAC,EAClC,MAAO,cAAY,kBAAkBQ,EAAY,cAAY,EAC7D,OAAQ,KAAK,4BAA4BA,CAAU,EACnD,SAAU,QAAM,KAAK,CACvB,CAAC,EACD,OAAIA,IAAe,GACjBC,EAAO,YACL,QAAM,GACJ,cAAY,kBAAkBK,EAAU,yBAAuB,CACjE,CACF,EAEKL,CACT,CASQ,qBAAqBD,EAA4B,CACvD,IAAIO,EAAM,KAAK,4BAA4B,CAAC,EACxCC,EAAI,EACR,KAAOA,EAAIR,GACTO,GAAO,KAAK,4BAA4BC,CAAC,EACzCA,GAAK,EAEP,OAAOD,CACT,CAOQ,4BAA4BP,EAA4B,CAC9D,OACE,KAAK,SAAS,OAAO,CACnB,KAAM,IAAM,iBACZ,QAAS,IAAM,CACjB,CAAC,EACD,eACA,mBACCA,IAAe,EAAI,0BAA0B,EAElD,CACF,EA5JaV,EAANmB,EAAA,IADN,cAAW,EAqBPC,EAAA,eAAO,cAAY,6BAA6B,IApBxCpB",
4
+ "sourcesContent": ["import { inject, injectable } from \"inversify\";\nimport { Either, Left, Maybe, Right } from \"purify-ts\";\nimport { v4 } from \"uuid\";\n\nimport {\n APDU_DATA_LENGTH_LENGTH,\n CHANNEL_LENGTH,\n HEAD_TAG,\n HEAD_TAG_LENGTH,\n INDEX_LENGTH,\n} from \"@api/device-session/data/FramerConst\";\nimport type {\n ApduSenderService,\n ApduSenderServiceConstructorArgs,\n} from \"@api/device-session/service/ApduSenderService\";\nimport { FramerUtils } from \"@api/device-session/utils/FramerUtils\";\nimport { LoggerPublisherService } from \"@api/logger-publisher/service/LoggerPublisherService\";\nimport {\n FramerApduError,\n FramerOverflowError,\n} from \"@internal/device-session/model/Errors\";\nimport { Frame } from \"@internal/device-session/model/Frame\";\nimport { FrameHeader } from \"@internal/device-session/model/FrameHeader\";\nimport { loggerTypes } from \"@internal/logger-publisher/di/loggerTypes\";\nimport { DmkError } from \"@root/src/api/Error\";\n/**\n * Default implementation of ApduSenderService\n *\n * Split APDU in an array of frames readies to send to a TransportConnectedDevice\n */\n@injectable()\nexport class DefaultApduSenderService implements ApduSenderService {\n protected _frameSize: number;\n protected _channel: Maybe<Uint8Array>;\n protected _padding: boolean;\n private _logger: LoggerPublisherService;\n\n /**\n * Constructor\n *\n * @param frameSize\n * @param channel\n * @param padding\n * @param loggerServiceFactory\n */\n constructor(\n {\n frameSize,\n channel = Maybe.zero(),\n padding = false,\n }: ApduSenderServiceConstructorArgs,\n @inject(loggerTypes.LoggerPublisherServiceFactory)\n loggerServiceFactory: (tag: string) => LoggerPublisherService,\n ) {\n this._frameSize = frameSize;\n this._channel = channel;\n this._padding = padding;\n this._logger = loggerServiceFactory(\"DefaultApduSenderService\");\n }\n\n /**\n * Get frames from apdu\n *\n * @param apdu\n */\n public getFrames(apdu: Uint8Array): Frame[] {\n const frames: Frame[] = [];\n let count = 0;\n let frame = this.getFrameAtIndex(apdu, count);\n\n while (frame.isRight()) {\n frames.push(frame.extract());\n count += 1;\n frame = this.getFrameAtIndex(apdu, count).mapLeft((error) => {\n if (error instanceof FramerOverflowError) {\n this._logger.debug(\"Frames parsed\", { data: { count } });\n } else {\n this._logger.error(\"Error while parsing frame\", { data: { error } });\n }\n return error;\n });\n }\n return frames;\n }\n\n /**\n * Get apdu frame at index\n * Split every {{PACKET_SIZE - HEADER_SIZE}} bytes of apdu\n * @param apdu\n * @param frameIndex\n * @private\n */\n private getFrameAtIndex(\n apdu: Uint8Array,\n frameIndex: number,\n ): Either<DmkError, Frame> {\n const header = this.getFrameHeaderFrom(frameIndex, apdu.length);\n const frameOffset =\n frameIndex * this._frameSize - this.getHeaderSizeSumFrom(frameIndex);\n\n if (frameOffset > apdu.length) {\n return Left(new FramerOverflowError());\n }\n if (header.getLength() > this._frameSize) {\n return Left(new FramerApduError());\n }\n const dataMaxSize = this._frameSize - header.getLength();\n const data = apdu.slice(\n frameIndex === 0 ? 0 : frameOffset,\n frameIndex === 0\n ? dataMaxSize\n : frameOffset + this._frameSize - header.getLength(),\n );\n const frameData = this._padding\n ? new Uint8Array(dataMaxSize).fill(0)\n : new Uint8Array(data.length < dataMaxSize ? data.length : dataMaxSize);\n frameData.set(data, 0);\n const frame = new Frame({\n header,\n data: frameData,\n });\n return Right(frame);\n }\n\n /**\n * Get frame header\n * @param frameIndex\n * @param apduSize\n * @private\n */\n private getFrameHeaderFrom(\n frameIndex: number,\n apduSize: number,\n ): FrameHeader {\n const header = new FrameHeader({\n uuid: v4(),\n channel: this._channel.map((channel) =>\n FramerUtils.getLastBytesFrom(channel, CHANNEL_LENGTH),\n ),\n headTag: new Uint8Array([HEAD_TAG]),\n index: FramerUtils.numberToByteArray(frameIndex, INDEX_LENGTH),\n length: this.getFrameHeaderSizeFromIndex(frameIndex),\n dataSize: Maybe.zero(),\n });\n if (frameIndex === 0) {\n header.setDataSize(\n Maybe.of(\n FramerUtils.numberToByteArray(apduSize, APDU_DATA_LENGTH_LENGTH),\n ),\n );\n }\n return header;\n }\n\n /**\n * Get frame offset\n * First frame has more bytes of header\n * Padding append means a 0 bytes is added at the end of each frame\n * @private\n * @param frameIndex\n */\n private getHeaderSizeSumFrom(frameIndex: number): number {\n let sum = this.getFrameHeaderSizeFromIndex(0);\n let i = 1;\n while (i < frameIndex) {\n sum += this.getFrameHeaderSizeFromIndex(i);\n i += 1;\n }\n return sum;\n }\n\n /**\n * Get frame header size\n * @private\n * @param frameIndex\n */\n private getFrameHeaderSizeFromIndex(frameIndex: number): number {\n return (\n this._channel.caseOf({\n Just: () => CHANNEL_LENGTH,\n Nothing: () => 0,\n }) +\n INDEX_LENGTH +\n HEAD_TAG_LENGTH +\n (frameIndex === 0 ? APDU_DATA_LENGTH_LENGTH : 0)\n );\n }\n}\n"],
5
+ "mappings": "okBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,8BAAAE,IAAA,eAAAC,EAAAH,GAAA,IAAAI,EAAmC,qBACnCC,EAA2C,qBAC3CC,EAAmB,gBAEnBC,EAMO,gDAKPC,EAA4B,iDAE5BC,EAGO,iDACPC,EAAsB,gDACtBC,EAA4B,sDAC5BC,EAA4B,qDAQrB,IAAMC,EAAN,KAA4D,CACvD,WACA,SACA,SACF,QAUR,YACE,CACE,UAAAC,EACA,QAAAC,EAAU,QAAM,KAAK,EACrB,QAAAC,EAAU,EACZ,EAEAC,EACA,CACA,KAAK,WAAaH,EAClB,KAAK,SAAWC,EAChB,KAAK,SAAWC,EAChB,KAAK,QAAUC,EAAqB,0BAA0B,CAChE,CAOO,UAAUC,EAA2B,CAC1C,MAAMC,EAAkB,CAAC,EACzB,IAAIC,EAAQ,EACRC,EAAQ,KAAK,gBAAgBH,EAAME,CAAK,EAE5C,KAAOC,EAAM,QAAQ,GACnBF,EAAO,KAAKE,EAAM,QAAQ,CAAC,EAC3BD,GAAS,EACTC,EAAQ,KAAK,gBAAgBH,EAAME,CAAK,EAAE,QAASE,IAC7CA,aAAiB,sBACnB,KAAK,QAAQ,MAAM,gBAAiB,CAAE,KAAM,CAAE,MAAAF,CAAM,CAAE,CAAC,EAEvD,KAAK,QAAQ,MAAM,4BAA6B,CAAE,KAAM,CAAE,MAAAE,CAAM,CAAE,CAAC,EAE9DA,EACR,EAEH,OAAOH,CACT,CASQ,gBACND,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AA4B,CAC9D,OACE,KAAK,SAAS,OAAO,CACnB,KAAM,IAAM,iBACZ,QAAS,IAAM,CACjB,CAAC,EACD,eACA,mBACCA,IAAe,EAAI,0BAA0B,EAElD,CACF,EA5JaV,EAANmB,EAAA,IADN,cAAW,EAqBPC,EAAA,eAAO,cAAY,6BAA6B,IApBxCpB",
6
6
  "names": ["DefaultApduSenderService_exports", "__export", "DefaultApduSenderService", "__toCommonJS", "import_inversify", "import_purify_ts", "import_uuid", "import_FramerConst", "import_FramerUtils", "import_Errors", "import_Frame", "import_FrameHeader", "import_loggerTypes", "DefaultApduSenderService", "frameSize", "channel", "padding", "loggerServiceFactory", "apdu", "frames", "count", "frame", "error", "frameIndex", "header", "frameOffset", "dataMaxSize", "data", "frameData", "apduSize", "sum", "i", "__decorateClass", "__decorateParam"]
7
7
  }
@@ -1,2 +1,2 @@
1
- "use strict";var T=Object.create;var a=Object.defineProperty;var u=Object.getOwnPropertyDescriptor;var w=Object.getOwnPropertyNames;var F=Object.getPrototypeOf,B=Object.prototype.hasOwnProperty;var d=(t,r)=>{for(var e in r)a(t,e,{get:r[e],enumerable:!0})},h=(t,r,e,i)=>{if(r&&typeof r=="object"||typeof r=="function")for(let p of w(r))!B.call(t,p)&&p!==e&&a(t,p,{get:()=>r[p],enumerable:!(i=u(r,p))||i.enumerable});return t};var E=(t,r,e)=>(e=t!=null?T(F(t)):{},h(r||!t||!t.__esModule?a(e,"default",{value:t,enumerable:!0}):e,t)),U=t=>h(a({},"__esModule",{value:!0}),t),f=(t,r,e,i)=>{for(var p=i>1?void 0:i?u(r,e):r,y=t.length-1,g;y>=0;y--)(g=t[y])&&(p=(i?g(r,e,p):g(p))||p);return i&&p&&a(r,e,p),p},v=(t,r)=>(e,i)=>r(e,i,t);var b={};d(b,{AxiosManagerApiDataSource:()=>m});module.exports=U(b);var s=E(require("axios")),A=require("inversify"),l=require("purify-ts"),D=require("../../manager-api/di/managerApiTypes"),o=require("../../manager-api/model/Application"),c=require("../../manager-api/model/Errors"),n=require("./ManagerApiDto");let m=class{managerApiBaseUrl;webSocketBaseUrl;constructor({managerApiUrl:r,webSocketUrl:e}){this.managerApiBaseUrl=r,this.webSocketBaseUrl=e,console.log(this.webSocketBaseUrl)}getDeviceVersion(r,e){return(0,l.EitherAsync)(()=>s.default.get(`${this.managerApiBaseUrl}/get_device_version`,{params:{target_id:r,provider:e}})).map(i=>i.data).mapLeft(i=>new c.HttpFetchApiError(i))}getFirmwareVersion(r,e,i){return(0,l.EitherAsync)(()=>s.default.get(`${this.managerApiBaseUrl}/get_firmware_version`,{params:{device_version:e,version_name:r,provider:i}})).map(p=>p.data).mapLeft(p=>new c.HttpFetchApiError(p))}getAppsByHash(r){return(0,l.EitherAsync)(()=>s.default.post(`${this.managerApiBaseUrl}/v2/apps/hash`,r)).map(e=>e.data).map(e=>this.mapApplicationDtoToApplication(e)).mapLeft(e=>new c.HttpFetchApiError(e))}mapAppTypeDtoToAppType(r){switch(r){case n.AppTypeDto.currency:return o.AppType.currency;case n.AppTypeDto.plugin:return o.AppType.plugin;case n.AppTypeDto.tool:return o.AppType.tool;case n.AppTypeDto.swap:return o.AppType.swap}}mapApplicationDtoToApplication(r){return r.map(e=>{if(e===null)return null;const{applicationType:i,...p}=e;return{...p,applicationType:this.mapAppTypeDtoToAppType(i)}})}};m=f([(0,A.injectable)(),v(0,(0,A.inject)(D.managerApiTypes.DmkConfig))],m);0&&(module.exports={AxiosManagerApiDataSource});
1
+ "use strict";var d=Object.create;var o=Object.defineProperty;var h=Object.getOwnPropertyDescriptor;var w=Object.getOwnPropertyNames;var T=Object.getPrototypeOf,F=Object.prototype.hasOwnProperty;var E=(i,r)=>{for(var e in r)o(i,e,{get:r[e],enumerable:!0})},f=(i,r,e,t)=>{if(r&&typeof r=="object"||typeof r=="function")for(let p of w(r))!F.call(i,p)&&p!==e&&o(i,p,{get:()=>r[p],enumerable:!(t=h(r,p))||t.enumerable});return i};var V=(i,r,e)=>(e=i!=null?d(T(i)):{},f(r||!i||!i.__esModule?o(e,"default",{value:i,enumerable:!0}):e,i)),_=i=>f(o({},"__esModule",{value:!0}),i),v=(i,r,e,t)=>{for(var p=t>1?void 0:t?h(r,e):r,a=i.length-1,g;a>=0;a--)(g=i[a])&&(p=(t?g(r,e,p):g(p))||p);return t&&p&&o(r,e,p),p},u=(i,r)=>(e,t)=>r(e,t,i);var B={};E(B,{AxiosManagerApiDataSource:()=>A});module.exports=_(B);var n=V(require("axios")),y=require("inversify"),s=require("purify-ts"),D=require("../../manager-api/di/managerApiTypes"),m=require("../../manager-api/model/Application"),c=require("../../manager-api/model/Errors"),l=require("./ManagerApiDto");let A=class{managerApiBaseUrl;constructor({managerApiUrl:r}){this.managerApiBaseUrl=r}getAppList(r){const{targetId:e,provider:t,firmwareVersionName:p}=r;return(0,s.EitherAsync)(()=>n.default.get(`${this.managerApiBaseUrl}/v2/apps/by-target`,{params:{target_id:e,provider:t,firmware_version_name:p}})).map(a=>a.data).mapLeft(a=>new c.HttpFetchApiError(a))}getDeviceVersion(r){const{targetId:e,provider:t}=r;return(0,s.EitherAsync)(()=>n.default.get(`${this.managerApiBaseUrl}/get_device_version`,{params:{target_id:e,provider:t}})).map(p=>p.data).mapLeft(p=>new c.HttpFetchApiError(p))}getFirmwareVersion(r){const{deviceId:e,version:t,provider:p}=r;return(0,s.EitherAsync)(()=>n.default.get(`${this.managerApiBaseUrl}/get_firmware_version`,{params:{device_version:e,version_name:t,provider:p}})).map(a=>a.data).mapLeft(a=>new c.HttpFetchApiError(a))}getAppsByHash(r){const{hashes:e}=r;return(0,s.EitherAsync)(()=>n.default.post(`${this.managerApiBaseUrl}/v2/apps/hash`,e)).map(t=>t.data).map(t=>this.mapApplicationDtoToApplication(t)).mapLeft(t=>new c.HttpFetchApiError(t))}mapAppTypeDtoToAppType(r){switch(r){case l.AppTypeDto.currency:return m.AppType.currency;case l.AppTypeDto.plugin:return m.AppType.plugin;case l.AppTypeDto.tool:return m.AppType.tool;case l.AppTypeDto.swap:return m.AppType.swap}}mapApplicationDtoToApplication(r){return r.map(e=>{if(e===null)return null;const{applicationType:t,...p}=e;return{...p,applicationType:this.mapAppTypeDtoToAppType(t)}})}};A=v([(0,y.injectable)(),u(0,(0,y.inject)(D.managerApiTypes.DmkConfig))],A);0&&(module.exports={AxiosManagerApiDataSource});
2
2
  //# sourceMappingURL=AxiosManagerApiDataSource.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../../src/internal/manager-api/data/AxiosManagerApiDataSource.ts"],
4
- "sourcesContent": ["import axios from \"axios\";\nimport { inject, injectable } from \"inversify\";\nimport { EitherAsync } from \"purify-ts\";\n\nimport { type DmkConfig } from \"@api/DmkConfig\";\nimport { managerApiTypes } from \"@internal/manager-api/di/managerApiTypes\";\nimport {\n type Application,\n AppType,\n} from \"@internal/manager-api/model/Application\";\nimport { type DeviceVersion } from \"@internal/manager-api/model/Device\";\nimport { HttpFetchApiError } from \"@internal/manager-api/model/Errors\";\nimport { type FinalFirmware } from \"@internal/manager-api/model/Firmware\";\n\nimport { ManagerApiDataSource } from \"./ManagerApiDataSource\";\nimport { ApplicationDto, AppTypeDto } from \"./ManagerApiDto\";\n\n@injectable()\nexport class AxiosManagerApiDataSource implements ManagerApiDataSource {\n private readonly managerApiBaseUrl: string;\n private readonly webSocketBaseUrl: string;\n\n constructor(\n @inject(managerApiTypes.DmkConfig)\n { managerApiUrl, webSocketUrl }: DmkConfig,\n ) {\n this.managerApiBaseUrl = managerApiUrl;\n this.webSocketBaseUrl = webSocketUrl;\n console.log(this.webSocketBaseUrl);\n }\n\n getDeviceVersion(\n targetId: string,\n provider: number,\n ): EitherAsync<HttpFetchApiError, DeviceVersion> {\n return EitherAsync(() =>\n axios.get<DeviceVersion>(`${this.managerApiBaseUrl}/get_device_version`, {\n params: {\n target_id: targetId,\n provider,\n },\n }),\n )\n .map((res) => res.data)\n .mapLeft((error) => new HttpFetchApiError(error));\n }\n\n getFirmwareVersion(\n version: string,\n deviceId: number,\n provider: number,\n ): EitherAsync<HttpFetchApiError, FinalFirmware> {\n return EitherAsync(() =>\n axios.get<FinalFirmware>(\n `${this.managerApiBaseUrl}/get_firmware_version`,\n {\n params: {\n device_version: deviceId,\n version_name: version,\n provider,\n },\n },\n ),\n )\n .map((res) => res.data)\n .mapLeft((error) => new HttpFetchApiError(error));\n }\n\n getAppsByHash(\n hashes: string[],\n ): EitherAsync<HttpFetchApiError, Array<Application | null>> {\n return EitherAsync(() =>\n axios.post<Array<ApplicationDto | null>>(\n `${this.managerApiBaseUrl}/v2/apps/hash`,\n hashes,\n ),\n )\n .map((res) => res.data)\n .map((apps) => this.mapApplicationDtoToApplication(apps))\n .mapLeft((error) => new HttpFetchApiError(error));\n }\n\n private mapAppTypeDtoToAppType(appType: AppTypeDto): AppType {\n switch (appType) {\n case AppTypeDto.currency:\n return AppType.currency;\n case AppTypeDto.plugin:\n return AppType.plugin;\n case AppTypeDto.tool:\n return AppType.tool;\n case AppTypeDto.swap:\n return AppType.swap;\n }\n }\n\n private mapApplicationDtoToApplication(\n apps: Array<ApplicationDto | null>,\n ): Array<Application | null> {\n return apps.map((app) => {\n if (app === null) {\n return null;\n }\n\n const { applicationType, ...rest } = app;\n\n return {\n ...rest,\n applicationType: this.mapAppTypeDtoToAppType(applicationType),\n };\n });\n }\n}\n"],
5
- "mappings": "qtBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,+BAAAE,IAAA,eAAAC,EAAAH,GAAA,IAAAI,EAAkB,oBAClBC,EAAmC,qBACnCC,EAA4B,qBAG5BC,EAAgC,oDAChCC,EAGO,mDAEPC,EAAkC,8CAIlCC,EAA2C,2BAGpC,IAAMC,EAAN,KAAgE,CACpD,kBACA,iBAEjB,YAEE,CAAE,cAAAC,EAAe,aAAAC,CAAa,EAC9B,CACA,KAAK,kBAAoBD,EACzB,KAAK,iBAAmBC,EACxB,QAAQ,IAAI,KAAK,gBAAgB,CACnC,CAEA,iBACEC,EACAC,EAC+C,C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Source_exports", "__export", "AxiosManagerApiDataSource", "__toCommonJS", "import_axios", "import_inversify", "import_purify_ts", "import_managerApiTypes", "import_Application", "import_Errors", "import_ManagerApiDto", "AxiosManagerApiDataSource", "managerApiUrl", "webSocketUrl", "targetId", "provider", "axios", "res", "error", "version", "deviceId", "hashes", "apps", "appType", "app", "applicationType", "rest", "__decorateClass", "__decorateParam"]
4
+ "sourcesContent": ["import axios from \"axios\";\nimport { inject, injectable } from \"inversify\";\nimport { EitherAsync } from \"purify-ts\";\n\nimport { type DmkConfig } from \"@api/DmkConfig\";\nimport { managerApiTypes } from \"@internal/manager-api/di/managerApiTypes\";\nimport {\n type Application,\n AppType,\n} from \"@internal/manager-api/model/Application\";\nimport { type DeviceVersion } from \"@internal/manager-api/model/Device\";\nimport { HttpFetchApiError } from \"@internal/manager-api/model/Errors\";\nimport { type FinalFirmware } from \"@internal/manager-api/model/Firmware\";\nimport {\n type GetAppByHashParams,\n type GetAppListParams,\n type GetDeviceVersionParams,\n type GetFirmwareVersionParams,\n} from \"@internal/manager-api/model/Params\";\n\nimport { ManagerApiDataSource } from \"./ManagerApiDataSource\";\nimport { ApplicationDto, AppTypeDto } from \"./ManagerApiDto\";\n\n@injectable()\nexport class AxiosManagerApiDataSource implements ManagerApiDataSource {\n private readonly managerApiBaseUrl: string;\n\n constructor(\n @inject(managerApiTypes.DmkConfig)\n { managerApiUrl }: DmkConfig,\n ) {\n this.managerApiBaseUrl = managerApiUrl;\n }\n\n getAppList(\n params: GetAppListParams,\n ): EitherAsync<HttpFetchApiError, Application[]> {\n const { targetId, provider, firmwareVersionName } = params;\n return EitherAsync(() =>\n axios.get<Application[]>(`${this.managerApiBaseUrl}/v2/apps/by-target`, {\n params: {\n target_id: targetId,\n provider,\n firmware_version_name: firmwareVersionName,\n },\n }),\n )\n .map((res) => res.data)\n .mapLeft((error) => new HttpFetchApiError(error));\n }\n\n getDeviceVersion(\n params: GetDeviceVersionParams,\n ): EitherAsync<HttpFetchApiError, DeviceVersion> {\n const { targetId, provider } = params;\n return EitherAsync(() =>\n axios.get<DeviceVersion>(`${this.managerApiBaseUrl}/get_device_version`, {\n params: {\n target_id: targetId,\n provider,\n },\n }),\n )\n .map((res) => res.data)\n .mapLeft((error) => new HttpFetchApiError(error));\n }\n\n getFirmwareVersion(\n params: GetFirmwareVersionParams,\n ): EitherAsync<HttpFetchApiError, FinalFirmware> {\n const { deviceId, version, provider } = params;\n return EitherAsync(() =>\n axios.get<FinalFirmware>(\n `${this.managerApiBaseUrl}/get_firmware_version`,\n {\n params: {\n device_version: deviceId,\n version_name: version,\n provider,\n },\n },\n ),\n )\n .map((res) => res.data)\n .mapLeft((error) => new HttpFetchApiError(error));\n }\n\n getAppsByHash(\n params: GetAppByHashParams,\n ): EitherAsync<HttpFetchApiError, Array<Application | null>> {\n const { hashes } = params;\n return EitherAsync(() =>\n axios.post<Array<ApplicationDto | null>>(\n `${this.managerApiBaseUrl}/v2/apps/hash`,\n hashes,\n ),\n )\n .map((res) => res.data)\n .map((apps) => this.mapApplicationDtoToApplication(apps))\n .mapLeft((error) => new HttpFetchApiError(error));\n }\n\n private mapAppTypeDtoToAppType(appType: AppTypeDto): AppType {\n switch (appType) {\n case AppTypeDto.currency:\n return AppType.currency;\n case AppTypeDto.plugin:\n return AppType.plugin;\n case AppTypeDto.tool:\n return AppType.tool;\n case AppTypeDto.swap:\n return AppType.swap;\n }\n }\n\n private mapApplicationDtoToApplication(\n apps: Array<ApplicationDto | null>,\n ): Array<Application | null> {\n return apps.map((app) => {\n if (app === null) {\n return null;\n }\n const { applicationType, ...rest } = app;\n return {\n ...rest,\n applicationType: this.mapAppTypeDtoToAppType(applicationType),\n };\n });\n }\n}\n"],
5
+ "mappings": "qtBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,+BAAAE,IAAA,eAAAC,EAAAH,GAAA,IAAAI,EAAkB,oBAClBC,EAAmC,qBACnCC,EAA4B,qBAG5BC,EAAgC,oDAChCC,EAGO,mDAEPC,EAAkC,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K,+BAA+BA,CAAI,CAAC,EACvD,QAASJ,GAAU,IAAI,oBAAkBA,CAAK,CAAC,CACpD,CAEQ,uBAAuBK,EAA8B,CAC3D,OAAQA,EAAS,CACf,KAAK,aAAW,SACd,OAAO,UAAQ,SACjB,KAAK,aAAW,OACd,OAAO,UAAQ,OACjB,KAAK,aAAW,KACd,OAAO,UAAQ,KACjB,KAAK,aAAW,KACd,OAAO,UAAQ,IACnB,CACF,CAEQ,+BACND,EAC2B,CAC3B,OAAOA,EAAK,IAAKE,GAAQ,CACvB,GAAIA,IAAQ,KACV,OAAO,KAET,KAAM,CAAE,gBAAAC,EAAiB,GAAGC,CAAK,EAAIF,EACrC,MAAO,CACL,GAAGE,EACH,gBAAiB,KAAK,uBAAuBD,CAAe,CAC9D,CACF,CAAC,CACH,CACF,EAzGaf,EAANiB,EAAA,IADN,cAAW,EAKPC,EAAA,eAAO,kBAAgB,SAAS,IAJxBlB",
6
+ "names": ["AxiosManagerApiDataSource_exports", "__export", "AxiosManagerApiDataSource", "__toCommonJS", "import_axios", "import_inversify", "import_purify_ts", "import_managerApiTypes", "import_Application", "import_Errors", "import_ManagerApiDto", "AxiosManagerApiDataSource", "managerApiUrl", "params", "targetId", "provider", "firmwareVersionName", "axios", "res", "error", "deviceId", "version", "hashes", "apps", "appType", "app", "applicationType", "rest", "__decorateClass", "__decorateParam"]
7
7
  }
@@ -1,2 +1,2 @@
1
- "use strict";var m=Object.create;var l=Object.defineProperty;var d=Object.getOwnPropertyDescriptor;var v=Object.getOwnPropertyNames;var g=Object.getPrototypeOf,f=Object.prototype.hasOwnProperty;var A=(r,e,s,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of v(e))!f.call(r,i)&&i!==s&&l(r,i,{get:()=>e[i],enumerable:!(n=d(e,i))||n.enumerable});return r};var E=(r,e,s)=>(s=r!=null?m(g(r)):{},A(e||!r||!r.__esModule?l(s,"default",{value:r,enumerable:!0}):s,r));var o=E(require("axios")),a=require("purify-ts"),t=require("../../../api/device-action/__test-utils__/data"),p=require("../../manager-api/model/Errors"),c=require("./AxiosManagerApiDataSource");vi.mock("axios");const h={id:17,target_id:"857735172"},u={id:361,perso:"perso_11"};describe("AxiosManagerApiDataSource",()=>{describe("getAppsByHash",()=>{describe("success cases",()=>{let r;beforeEach(()=>{r=new c.AxiosManagerApiDataSource({})}),afterEach(()=>{vi.clearAllMocks()}),it("with BTC app, should return the metadata",async()=>{vi.spyOn(o.default,"post").mockResolvedValue({data:[t.BTC_APP_METADATA]});const e=[t.BTC_APP.appFullHash],s=await r.getAppsByHash(e);expect(s).toEqual((0,a.Right)([t.BTC_APP_METADATA]))}),it("with no apps, should return an empty list",async()=>{vi.spyOn(o.default,"post").mockResolvedValue({data:[]});const e=[],s=await r.getAppsByHash(e);expect(s).toEqual((0,a.Right)([]))}),it("with BTC app and custom lock screen, should return the metadata",async()=>{vi.spyOn(o.default,"post").mockResolvedValue({data:[t.BTC_APP_METADATA,t.CUSTOM_LOCK_SCREEN_APP_METADATA]});const e=[t.BTC_APP.appFullHash,t.CUSTOM_LOCK_SCREEN_APP.appFullHash],s=await r.getAppsByHash(e);expect(s).toEqual((0,a.Right)([t.BTC_APP_METADATA,t.CUSTOM_LOCK_SCREEN_APP_METADATA]))})}),describe("error cases",()=>{afterEach(()=>{vi.clearAllMocks()}),it("should throw an error if the request fails",()=>{const r=new c.AxiosManagerApiDataSource({}),e=new Error("fetch error");vi.spyOn(o.default,"post").mockRejectedValue(e);const s=[t.BTC_APP.appFullHash],n=r.getAppsByHash(s);expect(n).resolves.toEqual((0,a.Left)(new p.HttpFetchApiError(e)))})})}),describe("getDeviceVersion",()=>{let r;beforeEach(()=>{r=new c.AxiosManagerApiDataSource({})}),afterEach(()=>{vi.clearAllMocks()}),it("should return a complete device version",()=>{vi.spyOn(o.default,"get").mockResolvedValue({data:h});const e=r.getDeviceVersion("targetId",42);expect(e).resolves.toEqual((0,a.Right)(h))}),it("should return an error if the request fails",()=>{const e=new Error("fetch error");vi.spyOn(o.default,"get").mockRejectedValue(e);const s=r.getDeviceVersion("targetId",42);expect(s).resolves.toEqual((0,a.Left)(new p.HttpFetchApiError(e)))})}),describe("getFirmwareVersion",()=>{let r;beforeEach(()=>{r=new c.AxiosManagerApiDataSource({})}),afterEach(()=>{vi.clearAllMocks()}),it("should return a complete firmware version",()=>{vi.spyOn(o.default,"get").mockResolvedValue({data:u});const e=r.getFirmwareVersion("versionName",42,21);expect(e).resolves.toEqual((0,a.Right)(u))}),it("should return an error if the request fails",()=>{const e=new Error("fetch error");vi.spyOn(o.default,"get").mockRejectedValue(e);const s=r.getFirmwareVersion("versionName",42,21);expect(s).resolves.toEqual((0,a.Left)(new p.HttpFetchApiError(e)))})})});
1
+ "use strict";var m=Object.create;var l=Object.defineProperty;var h=Object.getOwnPropertyDescriptor;var v=Object.getOwnPropertyNames;var g=Object.getPrototypeOf,f=Object.prototype.hasOwnProperty;var A=(r,e,t,p)=>{if(e&&typeof e=="object"||typeof e=="function")for(let c of v(e))!f.call(r,c)&&c!==t&&l(r,c,{get:()=>e[c],enumerable:!(p=h(e,c))||p.enumerable});return r};var E=(r,e,t)=>(t=r!=null?m(g(r)):{},A(e||!r||!r.__esModule?l(t,"default",{value:r,enumerable:!0}):t,r));var o=E(require("axios")),a=require("purify-ts"),s=require("../../../api/device-action/__test-utils__/data"),n=require("../../manager-api/model/Errors"),i=require("./AxiosManagerApiDataSource");vi.mock("axios");const d={id:17,target_id:"857735172"},u={id:361,perso:"perso_11"};describe("AxiosManagerApiDataSource",()=>{describe("getAppList",()=>{let r;beforeEach(()=>{r=new i.AxiosManagerApiDataSource({})}),afterEach(()=>{vi.clearAllMocks()}),it("should return a list of applications",()=>{const e=[s.BTC_APP_METADATA,s.CUSTOM_LOCK_SCREEN_APP_METADATA];vi.spyOn(o.default,"get").mockResolvedValue({data:e});const t=r.getAppList({targetId:"targetId",provider:42,firmwareVersionName:"firmwareVersionName"});expect(t).resolves.toEqual((0,a.Right)(e))}),it("should return an error if the request fails",()=>{const e=new Error("fetch error");vi.spyOn(o.default,"get").mockRejectedValue(e);const t=r.getAppList({targetId:"targetId",provider:42,firmwareVersionName:"firmwareVersionName"});expect(t).resolves.toEqual((0,a.Left)(new n.HttpFetchApiError(e)))})}),describe("getAppsByHash",()=>{describe("success cases",()=>{let r;beforeEach(()=>{r=new i.AxiosManagerApiDataSource({})}),afterEach(()=>{vi.clearAllMocks()}),it("with BTC app, should return the metadata",async()=>{vi.spyOn(o.default,"post").mockResolvedValue({data:[s.BTC_APP_METADATA]});const e=[s.BTC_APP.appFullHash],t=await r.getAppsByHash({hashes:e});expect(t).toEqual((0,a.Right)([s.BTC_APP_METADATA]))}),it("with no apps, should return an empty list",async()=>{vi.spyOn(o.default,"post").mockResolvedValue({data:[]});const e=[],t=await r.getAppsByHash({hashes:e});expect(t).toEqual((0,a.Right)([]))}),it("with BTC app and custom lock screen, should return the metadata",async()=>{vi.spyOn(o.default,"post").mockResolvedValue({data:[s.BTC_APP_METADATA,s.CUSTOM_LOCK_SCREEN_APP_METADATA]});const e=[s.BTC_APP.appFullHash,s.CUSTOM_LOCK_SCREEN_APP.appFullHash],t=await r.getAppsByHash({hashes:e});expect(t).toEqual((0,a.Right)([s.BTC_APP_METADATA,s.CUSTOM_LOCK_SCREEN_APP_METADATA]))})}),describe("error cases",()=>{afterEach(()=>{vi.clearAllMocks()}),it("should throw an error if the request fails",()=>{const r=new i.AxiosManagerApiDataSource({}),e=new Error("fetch error");vi.spyOn(o.default,"post").mockRejectedValue(e);const t=[s.BTC_APP.appFullHash],p=r.getAppsByHash({hashes:t});expect(p).resolves.toEqual((0,a.Left)(new n.HttpFetchApiError(e)))})})}),describe("getDeviceVersion",()=>{let r;beforeEach(()=>{r=new i.AxiosManagerApiDataSource({})}),afterEach(()=>{vi.clearAllMocks()}),it("should return a complete device version",()=>{vi.spyOn(o.default,"get").mockResolvedValue({data:d});const e=r.getDeviceVersion({targetId:"targetId",provider:42});expect(e).resolves.toEqual((0,a.Right)(d))}),it("should return an error if the request fails",()=>{const e=new Error("fetch error");vi.spyOn(o.default,"get").mockRejectedValue(e);const t=r.getDeviceVersion({targetId:"targetId",provider:42});expect(t).resolves.toEqual((0,a.Left)(new n.HttpFetchApiError(e)))})}),describe("getFirmwareVersion",()=>{let r;beforeEach(()=>{r=new i.AxiosManagerApiDataSource({})}),afterEach(()=>{vi.clearAllMocks()}),it("should return a complete firmware version",()=>{vi.spyOn(o.default,"get").mockResolvedValue({data:u});const e=r.getFirmwareVersion({version:"versionName",deviceId:42,provider:21});expect(e).resolves.toEqual((0,a.Right)(u))}),it("should return an error if the request fails",()=>{const e=new Error("fetch error");vi.spyOn(o.default,"get").mockRejectedValue(e);const t=r.getFirmwareVersion({version:"versionName",deviceId:42,provider:21});expect(t).resolves.toEqual((0,a.Left)(new n.HttpFetchApiError(e)))})})});
2
2
  //# sourceMappingURL=AxiosManagerApiDataSource.test.js.map