@tma.js/sdk 2.7.0 → 3.0.1

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 (310) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +9 -9
  3. package/dist/dts/composables/AsyncMountable.d.ts +44 -0
  4. package/dist/dts/composables/Button.d.ts +140 -0
  5. package/dist/dts/composables/Mountable.d.ts +43 -0
  6. package/dist/dts/composables/Stateful.d.ts +35 -0
  7. package/dist/dts/errors.d.ts +41 -0
  8. package/dist/dts/features/BackButton/BackButton.d.ts +96 -0
  9. package/dist/dts/features/BackButton/exports.d.ts +2 -0
  10. package/dist/dts/features/BackButton/instance.d.ts +2 -0
  11. package/dist/dts/features/Biometry/Biometry.d.ts +122 -0
  12. package/dist/dts/features/Biometry/exports.d.ts +3 -0
  13. package/dist/dts/features/Biometry/instance.d.ts +2 -0
  14. package/dist/dts/features/Biometry/types.d.ts +84 -0
  15. package/dist/dts/features/ClosingBehavior/ClosingBehavior.d.ts +51 -0
  16. package/dist/dts/features/ClosingBehavior/exports.d.ts +2 -0
  17. package/dist/dts/features/ClosingBehavior/instance.d.ts +2 -0
  18. package/dist/dts/features/CloudStorage/CloudStorage.d.ts +90 -0
  19. package/dist/dts/features/CloudStorage/exports.d.ts +2 -0
  20. package/dist/dts/features/CloudStorage/instance.d.ts +2 -0
  21. package/dist/dts/features/HapticFeedback/HapticFeedback.d.ts +57 -0
  22. package/dist/dts/features/HapticFeedback/exports.d.ts +2 -0
  23. package/dist/dts/features/HapticFeedback/instance.d.ts +2 -0
  24. package/dist/dts/features/InitData/InitData.d.ts +84 -0
  25. package/dist/dts/features/InitData/exports.d.ts +2 -0
  26. package/dist/dts/features/InitData/instance.d.ts +2 -0
  27. package/dist/dts/features/Invoice/Invoice.d.ts +54 -0
  28. package/dist/dts/features/Invoice/exports.d.ts +2 -0
  29. package/dist/dts/features/Invoice/instance.d.ts +2 -0
  30. package/dist/dts/features/LocationManager/LocationManager.d.ts +74 -0
  31. package/dist/dts/features/LocationManager/exports.d.ts +3 -0
  32. package/dist/dts/features/LocationManager/instance.d.ts +2 -0
  33. package/dist/dts/features/LocationManager/types.d.ts +65 -0
  34. package/dist/dts/features/MainButton/MainButton.d.ts +214 -0
  35. package/dist/dts/features/MainButton/exports.d.ts +2 -0
  36. package/dist/dts/features/MainButton/instance.d.ts +2 -0
  37. package/dist/dts/features/MiniApp/MiniApp.d.ts +192 -0
  38. package/dist/dts/features/MiniApp/exports.d.ts +2 -0
  39. package/dist/dts/features/MiniApp/instance.d.ts +2 -0
  40. package/dist/dts/features/Popup/Popup.d.ts +56 -0
  41. package/dist/dts/features/Popup/exports.d.ts +3 -0
  42. package/dist/dts/features/Popup/instance.d.ts +2 -0
  43. package/dist/dts/features/Popup/prepareParams.d.ts +9 -0
  44. package/dist/dts/{components → features}/Popup/types.d.ts +5 -12
  45. package/dist/dts/features/QrScanner/QrScanner.d.ts +132 -0
  46. package/dist/dts/features/QrScanner/exports.d.ts +2 -0
  47. package/dist/dts/features/QrScanner/instance.d.ts +2 -0
  48. package/dist/dts/features/SecondaryButton/SecondaryButton.d.ts +253 -0
  49. package/dist/dts/features/SecondaryButton/exports.d.ts +2 -0
  50. package/dist/dts/features/SecondaryButton/instance.d.ts +2 -0
  51. package/dist/dts/features/SettingsButton/SettingsButton.d.ts +96 -0
  52. package/dist/dts/features/SettingsButton/exports.d.ts +2 -0
  53. package/dist/dts/features/SettingsButton/instance.d.ts +2 -0
  54. package/dist/dts/features/SwipeBehavior/SwipeBehavior.d.ts +62 -0
  55. package/dist/dts/features/SwipeBehavior/exports.d.ts +2 -0
  56. package/dist/dts/features/SwipeBehavior/instance.d.ts +2 -0
  57. package/dist/dts/features/ThemeParams/ThemeParams.d.ts +127 -0
  58. package/dist/dts/features/ThemeParams/exports.d.ts +2 -0
  59. package/dist/dts/features/ThemeParams/instance.d.ts +2 -0
  60. package/dist/dts/features/Viewport/Viewport.d.ts +220 -0
  61. package/dist/dts/features/Viewport/exports.d.ts +2 -0
  62. package/dist/dts/features/Viewport/instance.d.ts +2 -0
  63. package/dist/dts/features/emoji-status/exports.d.ts +2 -0
  64. package/dist/dts/features/emoji-status/requestEmojiStatusAccess.d.ts +16 -0
  65. package/dist/dts/features/emoji-status/setEmojiStatus.d.ts +28 -0
  66. package/dist/dts/features/home-screen/addToHomeScreen.d.ts +11 -0
  67. package/dist/dts/features/home-screen/checkHomeScreenStatus.d.ts +14 -0
  68. package/dist/dts/features/home-screen/exports.d.ts +2 -0
  69. package/dist/dts/features/links/exports.d.ts +3 -0
  70. package/dist/dts/features/links/openLink.d.ts +31 -0
  71. package/dist/dts/features/links/openTelegramLink.d.ts +18 -0
  72. package/dist/dts/features/links/shareURL.d.ts +18 -0
  73. package/dist/dts/features/privacy/exports.d.ts +3 -0
  74. package/dist/dts/features/privacy/requestContact.d.ts +59 -0
  75. package/dist/dts/features/privacy/requestPhoneAccess.d.ts +19 -0
  76. package/dist/dts/features/privacy/requestWriteAccess.d.ts +14 -0
  77. package/dist/dts/features/uncategorized/copyTextToClipboard.d.ts +5 -0
  78. package/dist/dts/features/uncategorized/downloadFile.d.ts +21 -0
  79. package/dist/dts/features/uncategorized/exports.d.ts +11 -0
  80. package/dist/dts/features/uncategorized/getCurrentTime.d.ts +15 -0
  81. package/dist/dts/features/uncategorized/hideKeyboard.d.ts +13 -0
  82. package/dist/dts/features/uncategorized/readTextFromClipboard.d.ts +13 -0
  83. package/dist/dts/features/uncategorized/retrieveAndroidDeviceData.d.ts +6 -0
  84. package/dist/dts/features/uncategorized/retrieveAndroidDeviceDataFrom.d.ts +14 -0
  85. package/dist/dts/features/uncategorized/sendData.d.ts +20 -0
  86. package/dist/dts/features/uncategorized/shareMessage.d.ts +14 -0
  87. package/dist/dts/features/uncategorized/shareStory.d.ts +50 -0
  88. package/dist/dts/features/uncategorized/switchInlineQuery.d.ts +28 -0
  89. package/dist/dts/fn-options/bottomButtonOptions.d.ts +11 -0
  90. package/dist/dts/fn-options/buttonOptions.d.ts +10 -0
  91. package/dist/dts/fn-options/createFnOption.d.ts +2 -0
  92. package/dist/dts/fn-options/sharedFeatureOptions.d.ts +8 -0
  93. package/dist/dts/fn-options/withInvokeCustomMethod.d.ts +11 -0
  94. package/dist/dts/fn-options/withPostEvent.d.ts +8 -0
  95. package/dist/dts/fn-options/withRequest.d.ts +8 -0
  96. package/dist/dts/fn-options/withStateRestore.d.ts +13 -0
  97. package/dist/dts/fn-options/withVersion.d.ts +9 -0
  98. package/dist/dts/globals/createRequestId.d.ts +4 -0
  99. package/dist/dts/globals/inline-mode.d.ts +4 -0
  100. package/dist/dts/globals/invokeCustomMethod.d.ts +16 -0
  101. package/dist/dts/globals/post-event.d.ts +4 -0
  102. package/dist/dts/globals/request.d.ts +3 -0
  103. package/dist/dts/globals/resetGlobals.d.ts +4 -0
  104. package/dist/dts/globals/signals-registry.d.ts +39 -0
  105. package/dist/dts/globals/themeParams.d.ts +4 -0
  106. package/dist/dts/globals/version.d.ts +4 -0
  107. package/dist/dts/helpers/access.d.ts +2 -0
  108. package/dist/dts/helpers/component-storage.d.ts +9 -0
  109. package/dist/dts/helpers/createIsSupportedSignal.d.ts +5 -0
  110. package/dist/dts/helpers/css-vars.d.ts +11 -0
  111. package/dist/dts/helpers/isColorDark.d.ts +11 -0
  112. package/dist/dts/{navigation/isPageReload.d.ts → helpers/navigation.d.ts} +1 -1
  113. package/dist/dts/helpers/removeUndefined.d.ts +10 -0
  114. package/dist/dts/helpers/shallowEqual.d.ts +1 -0
  115. package/dist/dts/index.d.ts +33 -168
  116. package/dist/dts/init.d.ts +42 -0
  117. package/dist/dts/types.d.ts +6 -0
  118. package/dist/dts/with-checks/throwifyWithChecksFp.d.ts +3 -0
  119. package/dist/dts/with-checks/withChecksFp.d.ts +172 -0
  120. package/dist/index.cjs +1 -3
  121. package/dist/index.cjs.map +1 -1
  122. package/dist/index.iife.js +3 -3
  123. package/dist/index.iife.js.map +1 -1
  124. package/dist/index.js +3811 -2897
  125. package/dist/index.js.map +1 -1
  126. package/package.json +15 -5
  127. package/dist/dts/bridge/captureSameReq.d.ts +0 -10
  128. package/dist/dts/bridge/events/event-emitter/createMiniAppsEventEmitter.d.ts +0 -15
  129. package/dist/dts/bridge/events/event-emitter/singleton.d.ts +0 -8
  130. package/dist/dts/bridge/events/event-handlers/cleanupEventHandlers.d.ts +0 -4
  131. package/dist/dts/bridge/events/event-handlers/defineEventHandlers.d.ts +0 -6
  132. package/dist/dts/bridge/events/event-handlers/emitMiniAppsEvent.d.ts +0 -9
  133. package/dist/dts/bridge/events/listening/off.d.ts +0 -8
  134. package/dist/dts/bridge/events/listening/on.d.ts +0 -12
  135. package/dist/dts/bridge/events/listening/subscribe.d.ts +0 -9
  136. package/dist/dts/bridge/events/listening/unsubscribe.d.ts +0 -7
  137. package/dist/dts/bridge/events/types.d.ts +0 -302
  138. package/dist/dts/bridge/invokeCustomMethod.d.ts +0 -23
  139. package/dist/dts/bridge/methods/createPostEvent.d.ts +0 -14
  140. package/dist/dts/bridge/methods/postEvent.d.ts +0 -40
  141. package/dist/dts/bridge/methods/types/custom-methods.d.ts +0 -57
  142. package/dist/dts/bridge/methods/types/haptic.d.ts +0 -40
  143. package/dist/dts/bridge/methods/types/index.d.ts +0 -4
  144. package/dist/dts/bridge/methods/types/methods.d.ts +0 -392
  145. package/dist/dts/bridge/methods/types/popup.d.ts +0 -49
  146. package/dist/dts/bridge/parseMessage.d.ts +0 -18
  147. package/dist/dts/bridge/request.d.ts +0 -53
  148. package/dist/dts/bridge/target-origin.d.ts +0 -18
  149. package/dist/dts/classes/State/State.d.ts +0 -46
  150. package/dist/dts/classes/State/types.d.ts +0 -29
  151. package/dist/dts/classes/WithStateUtils.d.ts +0 -18
  152. package/dist/dts/classes/WithSupports.d.ts +0 -19
  153. package/dist/dts/classes/WithSupportsAndStateUtils.d.ts +0 -24
  154. package/dist/dts/classes/WithSupportsAndTrackableState.d.ts +0 -16
  155. package/dist/dts/classes/WithTrackableState.d.ts +0 -16
  156. package/dist/dts/classnames/classNames.d.ts +0 -12
  157. package/dist/dts/classnames/mergeClassNames.d.ts +0 -14
  158. package/dist/dts/colors/isColorDark.d.ts +0 -6
  159. package/dist/dts/colors/isRGB.d.ts +0 -7
  160. package/dist/dts/colors/isRGBShort.d.ts +0 -7
  161. package/dist/dts/colors/toRGB.d.ts +0 -12
  162. package/dist/dts/colors/types.d.ts +0 -8
  163. package/dist/dts/components/BackButton/BackButton.d.ts +0 -41
  164. package/dist/dts/components/BackButton/initBackButton.d.ts +0 -7
  165. package/dist/dts/components/BackButton/types.d.ts +0 -25
  166. package/dist/dts/components/BiometryManager/BiometryManager.d.ts +0 -61
  167. package/dist/dts/components/BiometryManager/formatEvent.d.ts +0 -34
  168. package/dist/dts/components/BiometryManager/initBiometryManager.d.ts +0 -7
  169. package/dist/dts/components/BiometryManager/requestBiometryInfo.d.ts +0 -8
  170. package/dist/dts/components/BiometryManager/types.d.ts +0 -40
  171. package/dist/dts/components/ClosingBehavior/ClosingBehavior.d.ts +0 -26
  172. package/dist/dts/components/ClosingBehavior/initClosingBehavior.d.ts +0 -7
  173. package/dist/dts/components/ClosingBehavior/types.d.ts +0 -20
  174. package/dist/dts/components/CloudStorage/CloudStorage.d.ts +0 -47
  175. package/dist/dts/components/CloudStorage/initCloudStorage.d.ts +0 -7
  176. package/dist/dts/components/HapticFeedback/HapticFeedback.d.ts +0 -34
  177. package/dist/dts/components/HapticFeedback/initHapticFeedback.d.ts +0 -7
  178. package/dist/dts/components/InitData/InitData.d.ts +0 -55
  179. package/dist/dts/components/InitData/initInitData.d.ts +0 -7
  180. package/dist/dts/components/InitData/parseInitData.d.ts +0 -7
  181. package/dist/dts/components/InitData/parsers/chat.d.ts +0 -3
  182. package/dist/dts/components/InitData/parsers/initData.d.ts +0 -7
  183. package/dist/dts/components/InitData/parsers/user.d.ts +0 -3
  184. package/dist/dts/components/InitData/types.d.ts +0 -132
  185. package/dist/dts/components/Invoice/Invoice.d.ts +0 -31
  186. package/dist/dts/components/Invoice/initInvoice.d.ts +0 -7
  187. package/dist/dts/components/Invoice/types.d.ts +0 -20
  188. package/dist/dts/components/MainButton/MainButton.d.ts +0 -106
  189. package/dist/dts/components/MainButton/initMainButton.d.ts +0 -7
  190. package/dist/dts/components/MainButton/types.d.ts +0 -40
  191. package/dist/dts/components/MiniApp/MiniApp.d.ts +0 -121
  192. package/dist/dts/components/MiniApp/initMiniApp.d.ts +0 -7
  193. package/dist/dts/components/MiniApp/parsing/contact.d.ts +0 -7
  194. package/dist/dts/components/MiniApp/types.d.ts +0 -53
  195. package/dist/dts/components/Popup/Popup.d.ts +0 -30
  196. package/dist/dts/components/Popup/initPopup.d.ts +0 -7
  197. package/dist/dts/components/Popup/preparePopupParams.d.ts +0 -8
  198. package/dist/dts/components/QRScanner/QRScanner.d.ts +0 -33
  199. package/dist/dts/components/QRScanner/initQRScanner.d.ts +0 -7
  200. package/dist/dts/components/QRScanner/types.d.ts +0 -31
  201. package/dist/dts/components/SettingsButton/SettingsButton.d.ts +0 -37
  202. package/dist/dts/components/SettingsButton/initSettingsButton.d.ts +0 -7
  203. package/dist/dts/components/SettingsButton/types.d.ts +0 -25
  204. package/dist/dts/components/ThemeParams/ThemeParams.d.ts +0 -57
  205. package/dist/dts/components/ThemeParams/initThemeParams.d.ts +0 -7
  206. package/dist/dts/components/ThemeParams/keys.d.ts +0 -11
  207. package/dist/dts/components/ThemeParams/parsing/parseThemeParams.d.ts +0 -7
  208. package/dist/dts/components/ThemeParams/parsing/serializeThemeParams.d.ts +0 -6
  209. package/dist/dts/components/ThemeParams/parsing/themeParams.d.ts +0 -4
  210. package/dist/dts/components/ThemeParams/requestThemeParams.d.ts +0 -8
  211. package/dist/dts/components/ThemeParams/types.d.ts +0 -29
  212. package/dist/dts/components/Utils/Utils.d.ts +0 -77
  213. package/dist/dts/components/Utils/initUtils.d.ts +0 -7
  214. package/dist/dts/components/Viewport/Viewport.d.ts +0 -77
  215. package/dist/dts/components/Viewport/initViewport.d.ts +0 -7
  216. package/dist/dts/components/Viewport/requestViewport.d.ts +0 -13
  217. package/dist/dts/components/Viewport/types.d.ts +0 -35
  218. package/dist/dts/css-vars/bindMiniAppCSSVars.d.ts +0 -29
  219. package/dist/dts/css-vars/bindThemeParamsCSSVars.d.ts +0 -29
  220. package/dist/dts/css-vars/bindViewportCSSVars.d.ts +0 -32
  221. package/dist/dts/css-vars/setCSSVar.d.ts +0 -6
  222. package/dist/dts/debug/debug.d.ts +0 -14
  223. package/dist/dts/env/hasExternalNotify.d.ts +0 -10
  224. package/dist/dts/env/hasWebviewProxy.d.ts +0 -10
  225. package/dist/dts/env/initWeb.d.ts +0 -11
  226. package/dist/dts/env/isIframe.d.ts +0 -5
  227. package/dist/dts/env/isSSR.d.ts +0 -4
  228. package/dist/dts/env/isTMA.d.ts +0 -4
  229. package/dist/dts/env/mockTelegramEnv.d.ts +0 -7
  230. package/dist/dts/errors/SDKError.d.ts +0 -9
  231. package/dist/dts/errors/createError.d.ts +0 -10
  232. package/dist/dts/errors/errors.d.ts +0 -49
  233. package/dist/dts/errors/isSDKError.d.ts +0 -7
  234. package/dist/dts/errors/isSDKErrorOfType.d.ts +0 -8
  235. package/dist/dts/events/event-emitter/EventEmitter.d.ts +0 -54
  236. package/dist/dts/events/event-emitter/types.d.ts +0 -45
  237. package/dist/dts/events/onWindow.d.ts +0 -10
  238. package/dist/dts/events/types.d.ts +0 -6
  239. package/dist/dts/index.low-level.d.ts +0 -41
  240. package/dist/dts/launch-params/parseLaunchParams.d.ts +0 -7
  241. package/dist/dts/launch-params/retrieveFromLocation.d.ts +0 -7
  242. package/dist/dts/launch-params/retrieveFromPerformance.d.ts +0 -7
  243. package/dist/dts/launch-params/retrieveFromStorage.d.ts +0 -7
  244. package/dist/dts/launch-params/retrieveFromUrl.d.ts +0 -8
  245. package/dist/dts/launch-params/retrieveLaunchParams.d.ts +0 -7
  246. package/dist/dts/launch-params/saveToStorage.d.ts +0 -7
  247. package/dist/dts/launch-params/serializeLaunchParams.d.ts +0 -7
  248. package/dist/dts/launch-params/types.d.ts +0 -51
  249. package/dist/dts/logger/Logger.d.ts +0 -29
  250. package/dist/dts/misc/createCleanup.d.ts +0 -11
  251. package/dist/dts/misc/createComponentInitFn/createComponentInitFn.d.ts +0 -16
  252. package/dist/dts/misc/createComponentInitFn/types.d.ts +0 -54
  253. package/dist/dts/misc/createSingleton.d.ts +0 -15
  254. package/dist/dts/misc/isRecord.d.ts +0 -5
  255. package/dist/dts/misc/objectFromKeys.d.ts +0 -6
  256. package/dist/dts/navigation/BasicNavigator/BasicNavigator.d.ts +0 -118
  257. package/dist/dts/navigation/BasicNavigator/prepareItem.d.ts +0 -8
  258. package/dist/dts/navigation/BasicNavigator/types.d.ts +0 -37
  259. package/dist/dts/navigation/BrowserNavigator/BrowserNavigator.d.ts +0 -198
  260. package/dist/dts/navigation/BrowserNavigator/basicItemToBrowser.d.ts +0 -7
  261. package/dist/dts/navigation/BrowserNavigator/createBrowserNavigatorFromLocation.d.ts +0 -4
  262. package/dist/dts/navigation/BrowserNavigator/prepareItem.d.ts +0 -25
  263. package/dist/dts/navigation/BrowserNavigator/types.d.ts +0 -64
  264. package/dist/dts/navigation/createSafeURL.d.ts +0 -7
  265. package/dist/dts/navigation/drop.d.ts +0 -4
  266. package/dist/dts/navigation/ensurePrefix.d.ts +0 -7
  267. package/dist/dts/navigation/getFirstNavigationEntry.d.ts +0 -6
  268. package/dist/dts/navigation/getHash.d.ts +0 -15
  269. package/dist/dts/navigation/getPathname.d.ts +0 -7
  270. package/dist/dts/navigation/go.d.ts +0 -5
  271. package/dist/dts/navigation/initNavigator.d.ts +0 -9
  272. package/dist/dts/navigation/urlToPath.d.ts +0 -7
  273. package/dist/dts/parsing/ArrayParser/ArrayParser.d.ts +0 -17
  274. package/dist/dts/parsing/ArrayParser/types.d.ts +0 -12
  275. package/dist/dts/parsing/ValueParser/ValueParser.d.ts +0 -17
  276. package/dist/dts/parsing/ValueParser/types.d.ts +0 -28
  277. package/dist/dts/parsing/createTypeError.d.ts +0 -6
  278. package/dist/dts/parsing/createValueParserGenerator.d.ts +0 -10
  279. package/dist/dts/parsing/parseBySchema.d.ts +0 -9
  280. package/dist/dts/parsing/parsers/array.d.ts +0 -7
  281. package/dist/dts/parsing/parsers/boolean.d.ts +0 -6
  282. package/dist/dts/parsing/parsers/date.d.ts +0 -6
  283. package/dist/dts/parsing/parsers/json.d.ts +0 -9
  284. package/dist/dts/parsing/parsers/number.d.ts +0 -6
  285. package/dist/dts/parsing/parsers/rgb.d.ts +0 -7
  286. package/dist/dts/parsing/parsers/searchParams.d.ts +0 -9
  287. package/dist/dts/parsing/parsers/string.d.ts +0 -6
  288. package/dist/dts/parsing/toRecord.d.ts +0 -7
  289. package/dist/dts/parsing/types.d.ts +0 -30
  290. package/dist/dts/request-id/createRequestIdGenerator.d.ts +0 -6
  291. package/dist/dts/request-id/types.d.ts +0 -9
  292. package/dist/dts/storage/storage.d.ts +0 -42
  293. package/dist/dts/supports/createSupportsFn.d.ts +0 -12
  294. package/dist/dts/supports/createSupportsParamFn.d.ts +0 -16
  295. package/dist/dts/supports/supports.d.ts +0 -16
  296. package/dist/dts/supports/types.d.ts +0 -4
  297. package/dist/dts/timeout/createTimeoutError.d.ts +0 -7
  298. package/dist/dts/timeout/sleep.d.ts +0 -5
  299. package/dist/dts/timeout/withTimeout.d.ts +0 -6
  300. package/dist/dts/types/index.d.ts +0 -6
  301. package/dist/dts/types/logical.d.ts +0 -16
  302. package/dist/dts/types/methods.d.ts +0 -16
  303. package/dist/dts/types/misc.d.ts +0 -12
  304. package/dist/dts/types/platform.d.ts +0 -4
  305. package/dist/dts/types/unions.d.ts +0 -20
  306. package/dist/dts/types/utils.d.ts +0 -24
  307. package/dist/dts/version/compareVersions.d.ts +0 -10
  308. package/dist/dts/version/types.d.ts +0 -5
  309. package/dist/index.low-level.iife.js +0 -4
  310. package/dist/index.low-level.iife.js.map +0 -1
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":["../src/misc/createSingleton.ts","../src/bridge/events/listening/unsubscribe.ts","../src/bridge/events/listening/subscribe.ts","../src/logger/Logger.ts","../src/debug/debug.ts","../src/events/event-emitter/EventEmitter.ts","../src/events/onWindow.ts","../src/misc/createCleanup.ts","../src/errors/SDKError.ts","../src/errors/createError.ts","../src/errors/errors.ts","../src/parsing/createTypeError.ts","../src/parsing/ValueParser/ValueParser.ts","../src/parsing/createValueParserGenerator.ts","../src/parsing/parsers/boolean.ts","../src/parsing/parseBySchema.ts","../src/parsing/toRecord.ts","../src/parsing/parsers/json.ts","../src/parsing/parsers/number.ts","../src/parsing/parsers/string.ts","../src/bridge/parseMessage.ts","../src/bridge/events/event-handlers/cleanupEventHandlers.ts","../src/bridge/events/event-handlers/emitMiniAppsEvent.ts","../src/bridge/events/event-handlers/defineEventHandlers.ts","../src/bridge/events/event-emitter/createMiniAppsEventEmitter.ts","../src/bridge/events/event-emitter/singleton.ts","../src/bridge/events/listening/off.ts","../src/bridge/events/listening/on.ts","../src/misc/isRecord.ts","../src/version/compareVersions.ts","../src/supports/supports.ts","../src/env/hasExternalNotify.ts","../src/env/hasWebviewProxy.ts","../src/env/isIframe.ts","../src/bridge/target-origin.ts","../src/bridge/methods/postEvent.ts","../src/bridge/methods/createPostEvent.ts","../src/bridge/captureSameReq.ts","../src/timeout/createTimeoutError.ts","../src/timeout/withTimeout.ts","../src/bridge/request.ts","../src/bridge/invokeCustomMethod.ts","../src/classnames/classNames.ts","../src/classnames/mergeClassNames.ts","../src/colors/isRGB.ts","../src/colors/isRGBShort.ts","../src/colors/toRGB.ts","../src/colors/isColorDark.ts","../src/classes/State/State.ts","../src/classes/WithStateUtils.ts","../src/supports/createSupportsFn.ts","../src/classes/WithSupportsAndStateUtils.ts","../src/components/BackButton/BackButton.ts","../src/parsing/parsers/date.ts","../src/parsing/parsers/searchParams.ts","../src/components/InitData/parsers/chat.ts","../src/components/InitData/parsers/user.ts","../src/components/InitData/parsers/initData.ts","../src/parsing/parsers/rgb.ts","../src/components/ThemeParams/keys.ts","../src/components/ThemeParams/parsing/themeParams.ts","../src/launch-params/parseLaunchParams.ts","../src/launch-params/retrieveFromUrl.ts","../src/launch-params/retrieveFromLocation.ts","../src/navigation/getFirstNavigationEntry.ts","../src/launch-params/retrieveFromPerformance.ts","../src/storage/storage.ts","../src/launch-params/retrieveFromStorage.ts","../src/components/ThemeParams/parsing/serializeThemeParams.ts","../src/launch-params/serializeLaunchParams.ts","../src/launch-params/saveToStorage.ts","../src/launch-params/retrieveLaunchParams.ts","../src/navigation/isPageReload.ts","../src/request-id/createRequestIdGenerator.ts","../src/misc/createComponentInitFn/createComponentInitFn.ts","../src/components/BackButton/initBackButton.ts","../src/classes/WithSupportsAndTrackableState.ts","../src/components/BiometryManager/formatEvent.ts","../src/components/BiometryManager/BiometryManager.ts","../src/components/BiometryManager/requestBiometryInfo.ts","../src/components/BiometryManager/initBiometryManager.ts","../src/classes/WithTrackableState.ts","../src/components/ClosingBehavior/ClosingBehavior.ts","../src/components/ClosingBehavior/initClosingBehavior.ts","../src/classes/WithSupports.ts","../src/parsing/ArrayParser/ArrayParser.ts","../src/parsing/parsers/array.ts","../src/components/CloudStorage/CloudStorage.ts","../src/components/CloudStorage/initCloudStorage.ts","../src/components/HapticFeedback/HapticFeedback.ts","../src/components/HapticFeedback/initHapticFeedback.ts","../src/components/InitData/InitData.ts","../src/components/InitData/initInitData.ts","../src/components/InitData/parseInitData.ts","../src/components/Invoice/Invoice.ts","../src/components/Invoice/initInvoice.ts","../src/components/MainButton/MainButton.ts","../src/components/MainButton/initMainButton.ts","../src/components/MiniApp/parsing/contact.ts","../src/supports/createSupportsParamFn.ts","../src/timeout/sleep.ts","../src/components/MiniApp/MiniApp.ts","../src/components/MiniApp/initMiniApp.ts","../src/components/Popup/preparePopupParams.ts","../src/components/Popup/Popup.ts","../src/components/Popup/initPopup.ts","../src/components/QRScanner/QRScanner.ts","../src/components/QRScanner/initQRScanner.ts","../src/components/SettingsButton/SettingsButton.ts","../src/components/SettingsButton/initSettingsButton.ts","../src/components/ThemeParams/parsing/parseThemeParams.ts","../src/components/ThemeParams/ThemeParams.ts","../src/components/ThemeParams/initThemeParams.ts","../src/components/ThemeParams/requestThemeParams.ts","../src/navigation/ensurePrefix.ts","../src/navigation/createSafeURL.ts","../src/components/Utils/Utils.ts","../src/components/Utils/initUtils.ts","../src/components/Viewport/requestViewport.ts","../src/components/Viewport/Viewport.ts","../src/components/Viewport/initViewport.ts","../src/css-vars/setCSSVar.ts","../src/css-vars/bindMiniAppCSSVars.ts","../src/css-vars/bindThemeParamsCSSVars.ts","../src/css-vars/bindViewportCSSVars.ts","../src/env/initWeb.ts","../src/env/isSSR.ts","../src/env/isTMA.ts","../src/env/mockTelegramEnv.ts","../src/errors/isSDKError.ts","../src/errors/isSDKErrorOfType.ts","../src/navigation/BasicNavigator/prepareItem.ts","../src/navigation/BasicNavigator/BasicNavigator.ts","../src/navigation/BrowserNavigator/basicItemToBrowser.ts","../src/navigation/urlToPath.ts","../src/navigation/BrowserNavigator/prepareItem.ts","../src/navigation/go.ts","../src/navigation/drop.ts","../src/navigation/getPathname.ts","../src/navigation/BrowserNavigator/BrowserNavigator.ts","../src/navigation/BrowserNavigator/createBrowserNavigatorFromLocation.ts","../src/navigation/getHash.ts","../src/navigation/initNavigator.ts"],"sourcesContent":["/**\n * Creates resettable singleton. We mostly need it for test purposes.\n * @param create - function which creates singleton entity.\n * @param onReset - function which will be called in case, singleton was reset.\n */\nexport function createSingleton<T>(\n create: (reset: () => void) => T,\n onReset?: (entity: T) => void,\n): [\n /**\n * Returns singleton entity.\n */\n get: () => T,\n /**\n * Resets last stored entity.\n */\n reset: () => void,\n] {\n let cached: T | undefined;\n const reset = () => {\n cached !== undefined && onReset && onReset(cached);\n cached = undefined;\n };\n\n return [() => (cached === undefined ? cached = create(reset) : cached), reset];\n}\n","import { miniAppsEventEmitter, resetMiniAppsEventEmitter } from '../event-emitter/singleton.js';\nimport type { MiniAppsSubscribeListener } from '../types.js';\n\n/**\n * Removes global event listener.\n * @param listener - event listener.\n */\nexport function unsubscribe(listener: MiniAppsSubscribeListener): void {\n const ee = miniAppsEventEmitter();\n const { count } = ee;\n ee.unsubscribe(listener);\n\n // If event emitter now has no listeners, we can make a cleanup.\n if (count && !ee.count) {\n resetMiniAppsEventEmitter();\n }\n}\n","import type { RemoveEventListenerFn } from '@/events/types.js';\n\nimport { miniAppsEventEmitter } from '../event-emitter/singleton.js';\nimport { unsubscribe } from '../listening/unsubscribe.js';\nimport type { MiniAppsSubscribeListener } from '../types.js';\n\n/**\n * Subscribes to all events sent from the native Telegram application.\n * @param listener - event listener to bind.\n * @returns Function to remove bound event listener.\n */\nexport function subscribe(listener: MiniAppsSubscribeListener): RemoveEventListenerFn {\n miniAppsEventEmitter().subscribe(listener);\n return () => unsubscribe(listener);\n}\n","/**\n * Message log level.\n */\nexport type LogLevel = 'log' | 'error';\n\nexport interface LoggerOptions {\n bgColor?: string;\n textColor?: string;\n}\n\nexport class Logger implements Pick<Console, 'log' | 'error'> {\n constructor(\n private readonly scope: string,\n private readonly options: LoggerOptions = {},\n ) {\n }\n\n /**\n * Prints message into a console in case, logger is currently enabled.\n * @param level - log level.\n * @param args - arguments.\n */\n private print(level: LogLevel, ...args: any[]): void {\n const now = new Date();\n const date = Intl\n .DateTimeFormat('en-GB', {\n hour: '2-digit',\n minute: '2-digit',\n second: '2-digit',\n fractionalSecondDigits: 3,\n timeZone: 'UTC',\n })\n .format(now);\n\n const { textColor, bgColor } = this.options;\n const commonCss = 'font-weight: bold;padding: 0 5px;border-radius:5px';\n\n console[level](\n `%c${date}%c / %c${this.scope}`,\n `${commonCss};background-color: lightblue;color:black`,\n '',\n `${commonCss};${textColor ? `color:${textColor};` : ''}${bgColor ? `background-color:${bgColor}` : ''}`,\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n ...args,\n );\n }\n\n /**\n * Prints error message into a console.\n * @param args\n */\n error(...args: any[]): void {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n this.print('error', ...args);\n }\n\n /**\n * Prints log message into a console.\n * @param args\n */\n log(...args: any[]): void {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n this.print('log', ...args);\n }\n}\n","import { subscribe } from '@/bridge/events/listening/subscribe.js';\nimport { unsubscribe } from '@/bridge/events/listening/unsubscribe.js';\nimport { Logger } from '@/logger/Logger.js';\nimport type { MiniAppsSubscribeListener } from '@/bridge/events/types.js';\n\nexport const logger = new Logger('SDK', {\n bgColor: 'forestgreen',\n textColor: 'white',\n});\n\nlet debugEnabled = false;\n\nconst onEvent: MiniAppsSubscribeListener = ({ name, payload }) => {\n logger.log('Event received:', payload ? { name, payload } : { name });\n};\n\n/**\n * Sets new debug mode. Enabling debug mode leads to printing additional messages in the console,\n * related to the processes inside the package.\n * @param enable - should debug be enabled.\n */\nexport function setDebug(enable: boolean): void {\n if (debugEnabled !== enable) {\n debugEnabled = enable;\n enable ? subscribe(onEvent) : unsubscribe(onEvent);\n }\n}\n\n/**\n * Logs info message into the console.\n * @param args - additional arguments.\n */\nexport function log(...args: any[]): void {\n if (debugEnabled) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n logger.log(...args);\n }\n}\n","import type { RemoveEventListenerFn } from '../types.js';\nimport type {\n EmptyEventName,\n EventListener,\n EventName,\n EventParams,\n NonEmptyEventName,\n SubscribeListener,\n} from './types.js';\n\nexport class EventEmitter<Schema> {\n private readonly listeners: Map<\n string,\n [listener: EventListener<any>, once?: boolean][]\n > = new Map();\n\n private listenersCount = 0;\n\n private subscribeListeners: SubscribeListener<Schema>[] = [];\n\n /**\n * Removes all event listeners.\n */\n clear() {\n this.listeners.clear();\n this.subscribeListeners = [];\n }\n\n /**\n * Returns count of bound listeners.\n */\n get count(): number {\n return this.listenersCount + this.subscribeListeners.length;\n }\n\n /**\n * Emits known event which has no parameters.\n * @param event - event name.\n */\n emit<E extends EmptyEventName<Schema>>(event: E): void;\n\n /**\n * Emits known event which has parameters.\n * @param event - event name.\n * @param args - list of event listener arguments.\n */\n emit<E extends NonEmptyEventName<Schema>>(event: E, ...args: EventParams<Schema[E]>): void;\n\n emit(event: EventName<Schema>, ...args: any[]): void {\n this.subscribeListeners.forEach((l) => l({\n event,\n args: args as EventParams<Schema[EventName<Schema>]>,\n }));\n\n const listeners = this.listeners.get(event) || [];\n\n listeners.forEach(([listener, once]) => {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n listener(...args);\n if (once) {\n this.off(event, listener);\n }\n });\n }\n\n /**\n * Adds new event listener.\n * @param event - event name.\n * @param listener - event listener.\n * @param once - should listener be called only once.\n * @returns Function to remove bound event listener.\n */\n on<E extends EventName<Schema>>(\n event: E,\n listener: EventListener<Schema[E]>,\n once?: boolean,\n ): RemoveEventListenerFn {\n let listeners = this.listeners.get(event);\n if (!listeners) {\n this.listeners.set(event, listeners = []);\n }\n\n listeners.push([listener, once]);\n this.listenersCount += 1;\n\n return () => this.off(event, listener);\n }\n\n /**\n * Removes event listener. In case, specified listener was bound several times, it removes\n * only a single one.\n * @param event - event name.\n * @param listener - event listener.\n */\n off<E extends EventName<Schema>>(event: E, listener: EventListener<Schema[E]>): void {\n const listeners = this.listeners.get(event) || [];\n for (let i = 0; i < listeners.length; i += 1) {\n if (listener === listeners[i][0]) {\n listeners.splice(i, 1);\n this.listenersCount -= 1;\n return;\n }\n }\n }\n\n /**\n * Adds a new event listener for all events.\n * @param listener - event listener.\n * @returns Function to remove event listener.\n */\n subscribe(listener: SubscribeListener<Schema>): RemoveEventListenerFn {\n this.subscribeListeners.push(listener);\n return () => this.unsubscribe(listener);\n }\n\n /**\n * Removes global event listener. In case, specified listener was bound several times, it removes\n * only a single one.\n * @param listener - event listener.\n */\n unsubscribe(listener: SubscribeListener<Schema>): void {\n for (let i = 0; i < this.subscribeListeners.length; i += 1) {\n if (this.subscribeListeners[i] === listener) {\n this.subscribeListeners.splice(i, 1);\n return;\n }\n }\n }\n}\n","import type { RemoveEventListenerFn } from './types.js';\n\n/**\n * Adds new event listener using window.addEventListener.\n * @param type - event name.\n * @param listener - event listener.\n * @param options - listening options.\n * @returns Function to remove event listener.\n */\nexport function onWindow<K extends keyof WindowEventMap>(\n type: K,\n listener: (this: Window, ev: WindowEventMap[K]) => any,\n options?: boolean | AddEventListenerOptions,\n): RemoveEventListenerFn {\n window.addEventListener(type, listener, options);\n return () => window.removeEventListener(type, listener, options);\n}\n","import { CleanupFn } from '@/types/index.js';\n\n/**\n * Returns a tuple, containing function to add cleanup, call cleanup, and flag showing whether\n * cleanup was called. Cleanup will not be performed in case, it was done before.\n */\nexport function createCleanup(...fns: (CleanupFn | CleanupFn[])[]): [\n add: (fn: CleanupFn) => void,\n cleanup: () => void,\n cleanedUp: boolean,\n] {\n let cleanedUp = false;\n const cache = fns.flat(1);\n\n return [\n (fn) => !cleanedUp && cache.push(fn),\n () => {\n if (!cleanedUp) {\n cleanedUp = true;\n cache.forEach(clean => clean());\n }\n },\n cleanedUp,\n ];\n}","import type { ErrorType } from './errors.js';\n\n/**\n * Error used across the SDK.\n */\nexport class SDKError extends Error {\n constructor(public readonly type: ErrorType, message?: string, cause?: unknown) {\n super(message, { cause });\n Object.setPrototypeOf(this, SDKError.prototype);\n }\n}\n","import { SDKError } from './SDKError.js';\nimport type { ErrorType } from './errors.js';\n\n/**\n * Creates new error using specified type and message.\n * @param type - error code.\n * @param message - error message.\n * @param cause - original error.\n */\nexport function createError(type: ErrorType, message: string, cause?: unknown): SDKError {\n return new SDKError(type, message, cause);\n}\n","/**\n * Specified Mini Apps method is unsupported.\n */\nexport const ERR_METHOD_UNSUPPORTED = 'ERR_METHOD_UNSUPPORTED';\n\n/**\n * Specified Mini Apps method parameter is unsupported.\n */\nexport const ERR_METHOD_PARAMETER_UNSUPPORTED = 'ERR_METHOD_PARAMETER_UNSUPPORTED';\n\n/**\n * Current environment is not Telegram application.\n */\nexport const ERR_UNKNOWN_ENV = 'ERR_UNKNOWN_ENV';\n\n/**\n * Telegram application returned and error while invoking custom method.\n */\nexport const ERR_INVOKE_CUSTOM_METHOD_RESPONSE = 'ERR_INVOKE_CUSTOM_METHOD_RESPONSE';\n\n/**\n * Timeout reached.\n */\nexport const ERR_TIMED_OUT = 'ERR_TIMED_OUT';\n\n/**\n * Value has unexpected type.\n */\nexport const ERR_UNEXPECTED_TYPE = 'ERR_UNEXPECTED_TYPE';\n\n/**\n * Something went wrong during value parsing.\n */\nexport const ERR_PARSE = 'ERR_PARSE';\n\n/**\n * Navigation entries list is empty.\n */\nexport const ERR_NAVIGATION_HISTORY_EMPTY = 'ERR_NAVIGATION_LIST_EMPTY';\n\n/**\n * Navigation entries cursor is invalid.\n */\nexport const ERR_NAVIGATION_INDEX_INVALID = 'ERR_NAVIGATION_CURSOR_INVALID';\n\n/**\n * Navigation entries item is invalid.\n */\nexport const ERR_NAVIGATION_ITEM_INVALID = 'ERR_NAVIGATION_ITEM_INVALID';\n\n/**\n * SSR component initialization failed.\n */\nexport const ERR_SSR_INIT = 'ERR_SSR_INIT';\n\n/**\n * Path starts from the invalid base.\n */\nexport const ERR_INVALID_PATH_BASE = 'ERR_INVALID_PATH_BASE';\n\nexport type ErrorType =\n | typeof ERR_METHOD_UNSUPPORTED\n | typeof ERR_METHOD_PARAMETER_UNSUPPORTED\n | typeof ERR_UNKNOWN_ENV\n | typeof ERR_INVOKE_CUSTOM_METHOD_RESPONSE\n | typeof ERR_TIMED_OUT\n | typeof ERR_PARSE\n | typeof ERR_UNEXPECTED_TYPE\n | typeof ERR_NAVIGATION_HISTORY_EMPTY\n | typeof ERR_NAVIGATION_INDEX_INVALID\n | typeof ERR_NAVIGATION_ITEM_INVALID\n | typeof ERR_SSR_INIT\n | typeof ERR_INVALID_PATH_BASE;\n","import { createError } from '@/errors/createError.js';\nimport { ERR_UNEXPECTED_TYPE } from '@/errors/errors.js';\nimport type { SDKError } from '@/errors/SDKError.js';\n\n/**\n * Creates instance of TypeError stating, that value has unexpected type.\n */\nexport function createTypeError(): SDKError {\n return createError(ERR_UNEXPECTED_TYPE, 'Value has unexpected type');\n}\n","import { createError } from '@/errors/createError.js';\nimport { ERR_PARSE } from '@/errors/errors.js';\n\nimport type { Parser } from '../types.js';\nimport type { ValueParserOptionalResult, ValueParserParseResult } from './types.js';\n\nexport class ValueParser<ResultType, IsOptional extends boolean> {\n constructor(\n protected parser: Parser<ResultType>,\n protected isOptional: IsOptional,\n protected type?: string,\n ) {\n }\n\n /**\n * Attempts to parse passed value\n * @param value - value to parse.\n * @throws {SDKError} ERR_PARSE\n * @see ERR_PARSE\n */\n parse(value: unknown): ValueParserParseResult<ResultType, IsOptional> {\n // In case, parsing result is specified as optional, and passed value is considered as empty,\n // we can return undefined. Otherwise, pass to parser.\n if (this.isOptional && value === undefined) {\n return undefined as ValueParserParseResult<ResultType, IsOptional>;\n }\n\n try {\n return this.parser(value) as ValueParserParseResult<ResultType, IsOptional>;\n } catch (cause) {\n throw createError(\n ERR_PARSE,\n `Unable to parse value${this.type ? ` as ${this.type}` : ''}`,\n cause,\n );\n }\n }\n\n optional(): ValueParserOptionalResult<this, ResultType> {\n this.isOptional = true as IsOptional;\n return this as ValueParserOptionalResult<this, ResultType>;\n }\n}\n","import { ValueParser } from './ValueParser/ValueParser.js';\nimport type { Parser } from './types.js';\n\nexport type ValueParserGenerator<T> = () => ValueParser<T, false>;\n\n/**\n * Creates function which generates new scalar value parser based on the specified one.\n * @param parser - parser to use as basic.\n * @param type - type name.\n */\nexport function createValueParserGenerator<T>(\n parser: Parser<T>,\n type?: string,\n): ValueParserGenerator<T> {\n return () => new ValueParser(parser, false, type);\n}\n","import { createTypeError } from '../createTypeError.js';\nimport { createValueParserGenerator } from '../createValueParserGenerator.js';\nimport type { ValueParserGenerator } from '../createValueParserGenerator.js';\n\n/**\n * Returns parser to parse value as boolean.\n */\nexport const boolean: ValueParserGenerator<boolean> = createValueParserGenerator((value) => {\n if (typeof value === 'boolean') {\n return value;\n }\n const asString = String(value);\n\n if (asString === '1' || asString === 'true') {\n return true;\n }\n\n if (asString === '0' || asString === 'false') {\n return false;\n }\n\n throw createTypeError();\n}, 'boolean');\n","import { createError } from '@/errors/createError.js';\nimport { ERR_PARSE } from '@/errors/errors.js';\n\nimport type { Parser, Schema } from './types.js';\n\n/**\n * Parses external value by specified schema. Functions iterates over each schema field\n * and uses getField function to get its value from the external source.\n * @param schema - object schema.\n * @param getField - function which gets external value by its field name.\n */\nexport function parseBySchema<T>(\n schema: Schema<T>,\n getField: (field: string) => unknown,\n): T {\n const result = {} as T;\n\n for (const field in schema) {\n const definition = schema[field];\n if (!definition) {\n continue;\n }\n\n let from: string;\n let parser: Parser<any>;\n\n // In case, definition has \"type\" property, then SchemaFieldDetailed was passed.\n if (typeof definition === 'function' || 'parse' in definition) {\n // Otherwise we are working with either parser function or instance.\n from = field;\n parser = typeof definition === 'function' ? definition : definition.parse.bind(definition);\n } else {\n const { type: definitionType } = definition;\n\n from = definition.from || field;\n parser = typeof definitionType === 'function'\n ? definitionType\n : definitionType.parse.bind(definitionType);\n }\n\n try {\n const parsedValue = parser(getField(from));\n if (parsedValue !== undefined) {\n (result as any)[field] = parsedValue;\n }\n } catch (error) {\n throw createError(ERR_PARSE, `Unable to parse field \"${field}\"`, error);\n }\n }\n\n return result;\n}\n","import { createTypeError } from './createTypeError.js';\n\n/**\n * Converts value to record.\n * @param value - value to convert.\n * @throws {Error} Value passed as a string does not represent JSON object.\n * @throws {Error} Value is not convertable.\n */\nexport function toRecord(value: unknown): Record<string, unknown> {\n let formattedValue: any = value;\n\n // Convert value to JSON in case, it is string. We expect value to be JSON string.\n if (typeof formattedValue === 'string') {\n formattedValue = JSON.parse(formattedValue);\n }\n\n // We expect json to be usual object.\n if (\n typeof formattedValue !== 'object'\n || formattedValue === null\n || Array.isArray(formattedValue)\n ) {\n throw createTypeError();\n }\n\n return formattedValue as Record<string, unknown>;\n}\n","import { parseBySchema } from '../parseBySchema.js';\nimport { toRecord } from '../toRecord.js';\nimport { ValueParser } from '../ValueParser/ValueParser.js';\nimport type { Schema } from '../types.js';\n\n/**\n * Creates new Json parser according to passed schema.\n * @param schema - object schema.\n * @param type - parser type name.\n */\nexport function json<T>(schema: Schema<T>, type?: string): ValueParser<T, false> {\n return new ValueParser((value) => {\n const record = toRecord(value);\n return parseBySchema(schema, (field) => record[field]);\n }, false, type);\n}\n","import { createTypeError } from '../createTypeError.js';\nimport { createValueParserGenerator } from '../createValueParserGenerator.js';\nimport type { ValueParserGenerator } from '../createValueParserGenerator.js';\n\n/**\n * Returns parser to parse value as number.\n */\nexport const number: ValueParserGenerator<number> = createValueParserGenerator((value) => {\n if (typeof value === 'number') {\n return value;\n }\n\n if (typeof value === 'string') {\n const num = Number(value);\n\n if (!Number.isNaN(num)) {\n return num;\n }\n }\n\n throw createTypeError();\n}, 'number');\n","import { createTypeError } from '../createTypeError.js';\nimport { createValueParserGenerator } from '../createValueParserGenerator.js';\nimport type { ValueParserGenerator } from '../createValueParserGenerator.js';\n\n/**\n * Returns parser to parse value as string.\n */\nexport const string: ValueParserGenerator<string> = createValueParserGenerator((value) => {\n if (typeof value === 'string' || typeof value === 'number') {\n return value.toString();\n }\n throw createTypeError();\n}, 'string');\n","import { json } from '@/parsing/parsers/json.js';\nimport { string } from '@/parsing/parsers/string.js';\n\n/**\n * Message format used in communication between client and Telegram applications.\n */\nexport interface MiniAppsMessage {\n /**\n * Event name.\n */\n eventType: string;\n /**\n * Event parameters.\n */\n eventData?: unknown;\n}\n\n/**\n * Parses value as a message between client and Telegram applications.\n * @param value - value to parse.\n */\nexport function parseMessage(value: unknown): MiniAppsMessage {\n return json({\n eventType: string(),\n eventData: (v) => v,\n }).parse(value);\n}\n","/**\n * Removes global event handlers, used by the package.\n */\nexport function cleanupEventHandlers(): void {\n ['TelegramGameProxy_receiveEvent', 'TelegramGameProxy', 'Telegram'].forEach((prop) => {\n delete window[prop as keyof Window];\n });\n}\n","/**\n * Emits event sent from Telegram native application like it was sent in\n * default web environment between 2 iframes. It dispatches new MessageEvent\n * and expects it to be handled via `window.addEventListener('message', ...)`\n * as developer would do it to handle messages sent from the parent iframe.\n * @param eventType - event name.\n * @param eventData - event payload.\n */\nexport function emitMiniAppsEvent(eventType: string, eventData: unknown): void {\n window.dispatchEvent(new MessageEvent('message', {\n data: JSON.stringify({ eventType, eventData }),\n // We specify window.parent to imitate the case, the parent iframe sent us this event.\n source: window.parent,\n }));\n}\n","import { emitMiniAppsEvent } from './emitMiniAppsEvent.js';\n\n/**\n * Defines special handlers by known paths, which are recognized by\n * Telegram as ports to receive events. This function also sets special\n * function in global window object to prevent duplicate declaration.\n */\nexport function defineEventHandlers() {\n // Iterate over each path, where \"receiveEvent\" function should be\n // defined. This function is called by external environment in case,\n // it wants to emit some event.\n [\n ['TelegramGameProxy_receiveEvent'], // Windows Phone.\n ['TelegramGameProxy', 'receiveEvent'], // Desktop.\n ['Telegram', 'WebView', 'receiveEvent'], // Android and iOS.\n ].forEach((path) => {\n // Path starts from the \"window\" object.\n let pointer = window as any;\n\n path.forEach((item, idx, arr) => {\n // We are on the last iteration, where function property name is passed.\n if (idx === arr.length - 1) {\n pointer[item] = emitMiniAppsEvent;\n return;\n }\n\n if (!(item in pointer)) {\n pointer[item] = {};\n }\n pointer = pointer[item];\n });\n });\n}\n","import { logger } from '@/debug/debug.js';\nimport { EventEmitter } from '@/events/event-emitter/EventEmitter.js';\nimport { onWindow } from '@/events/onWindow.js';\nimport { createCleanup } from '@/misc/createCleanup.js';\nimport { boolean } from '@/parsing/parsers/boolean.js';\nimport { json } from '@/parsing/parsers/json.js';\nimport { number } from '@/parsing/parsers/number.js';\nimport { string } from '@/parsing/parsers/string.js';\n\nimport { type MiniAppsMessage, parseMessage } from '../../parseMessage.js';\nimport { cleanupEventHandlers } from '../event-handlers/cleanupEventHandlers.js';\nimport { defineEventHandlers } from '../event-handlers/defineEventHandlers.js';\nimport type {\n MiniAppsEventName,\n MiniAppsEventPayload,\n MiniAppsEventEmitter,\n MiniAppsEvents,\n} from '../types.js';\n\n/**\n * Parsers for problematic Mini Apps events.\n */\nconst parsers: {\n [E in MiniAppsEventName]?: {\n parse(value: unknown): MiniAppsEventPayload<E>;\n }\n} = {\n clipboard_text_received: json({\n req_id: string(),\n data: (value) => (value === null ? value : string().optional().parse(value)),\n }),\n custom_method_invoked: json({\n req_id: string(),\n result: (value) => value,\n error: string().optional(),\n }),\n popup_closed: {\n parse(value) {\n return json({\n button_id: (value) => (\n value === null || value === undefined\n ? undefined\n : string().parse(value)\n ),\n }).parse(value ?? {});\n },\n },\n viewport_changed: json({\n height: number(),\n width: (value) => (\n value === null || value === undefined\n ? window.innerWidth\n : number().parse(value)\n ),\n is_state_stable: boolean(),\n is_expanded: boolean(),\n }),\n};\n\n/**\n * Creates new event emitter, which handles events from the Telegram application.\n */\nexport function createMiniAppsEventEmitter(): [\n /**\n * Created event emitter.\n */\n emitter: MiniAppsEventEmitter,\n /**\n * Function to dispose created emitter.\n */\n dispose: () => void,\n] {\n // We use this event emitter for better developer experience, using the subscribe method.\n const subEmitter = new EventEmitter<{ event: any[] }>();\n\n // Event emitter processing all the incoming events.\n const mainEmitter = new EventEmitter<MiniAppsEvents>();\n\n mainEmitter.subscribe(event => {\n subEmitter.emit('event', { name: event.event, payload: event.args[0] });\n });\n\n // Define event handles, which will proxy native method calls to their web version.\n defineEventHandlers();\n\n // List of cleanup functions, which should be called on dispose.\n const [, cleanup] = createCleanup(\n // Don't forget to remove created handlers.\n cleanupEventHandlers,\n // Add \"resize\" event listener to make sure, we always have fresh viewport information.\n // Desktop version of Telegram is sometimes not sending the viewport_changed\n // event. For example, when the MainButton is shown. That's why we should\n // add our own listener to make sure, viewport information is always fresh.\n // Issue: https://github.com/Telegram-Mini-Apps/tma.js/issues/10\n onWindow('resize', () => {\n mainEmitter.emit('viewport_changed', {\n width: window.innerWidth,\n height: window.innerHeight,\n is_state_stable: true,\n is_expanded: true,\n });\n }),\n // Add listener, which handles events sent from the Telegram web application and also events\n // generated by the local emitEvent function.\n onWindow('message', (event) => {\n // Ignore non-parent window messages.\n if (event.source !== window.parent) {\n return;\n }\n\n // Parse incoming event data.\n let message: MiniAppsMessage;\n try {\n message = parseMessage(event.data);\n } catch {\n // We ignore incorrect messages as they could be generated by any other code.\n return;\n }\n\n const { eventType, eventData } = message;\n const parser = parsers[eventType as keyof typeof parsers];\n\n try {\n const data = parser ? parser.parse(eventData) : eventData;\n mainEmitter.emit(...(data ? [eventType, data] : [eventType]) as [any, any]);\n } catch (cause) {\n logger.error(\n `An error occurred processing the \"${eventType}\" event from the Telegram application.\\nPlease, file an issue here:\\nhttps://github.com/Telegram-Mini-Apps/tma.js/issues/new/choose`,\n message,\n cause,\n );\n }\n }),\n // Clear emitters.\n () => subEmitter.clear(),\n () => mainEmitter.clear(),\n );\n\n return [{\n on: mainEmitter.on.bind(mainEmitter),\n off: mainEmitter.off.bind(mainEmitter),\n subscribe(listener) {\n return subEmitter.on('event', listener);\n },\n unsubscribe(listener) {\n subEmitter.off('event', listener);\n },\n get count() {\n return mainEmitter.count + subEmitter.count;\n },\n }, cleanup];\n}\n","import { createSingleton } from '@/misc/createSingleton.js';\n\nimport { createMiniAppsEventEmitter } from './createMiniAppsEventEmitter.js';\nimport type { MiniAppsEventEmitter } from '../types.js';\n\nconst [get, resetMiniAppsEventEmitter] = createSingleton(\n (reset) => {\n const [emitter, cleanup] = createMiniAppsEventEmitter();\n\n // Rewire \"off\" method and make it reset singleton if no event listeners left.\n const off = emitter.off.bind(emitter);\n emitter.off = (event, listener) => {\n const { count } = emitter;\n off(event, listener);\n\n // If event emitter now has no listeners, we can perform a reset.\n if (count && !emitter.count) {\n reset();\n }\n };\n\n return [emitter, cleanup] as const;\n },\n ([, cleanup]) => cleanup(),\n);\n\n/**\n * Returns Mini Apps event emitter singleton.\n */\nexport function miniAppsEventEmitter(): MiniAppsEventEmitter {\n return get()[0];\n}\n\nexport { resetMiniAppsEventEmitter };\n","import { miniAppsEventEmitter } from '../event-emitter/singleton.js';\nimport type { MiniAppsEventListener, MiniAppsEventName } from '../types.js';\n\n/**\n * Removes listener from specified event.\n * @param event - event to listen.\n * @param listener - event listener to remove.\n */\nexport function off<E extends MiniAppsEventName>(\n event: E,\n listener: MiniAppsEventListener<E>,\n): void {\n miniAppsEventEmitter().off(event, listener);\n}\n","import type { RemoveEventListenerFn } from '@/events/types.js';\n\nimport { miniAppsEventEmitter } from '../event-emitter/singleton.js';\nimport type { MiniAppsEventListener, MiniAppsEventName } from '../types.js';\n\n/**\n * Adds new listener to the specified event. Returns handler\n * which allows to stop listening to event.\n * @param event - event name.\n * @param listener - event listener.\n * @param once - should listener be called only once.\n * @returns Function to remove bound event listener.\n */\nexport function on<E extends MiniAppsEventName>(\n event: E,\n listener: MiniAppsEventListener<E>,\n once?: boolean,\n): RemoveEventListenerFn {\n return miniAppsEventEmitter().on(event, listener, once);\n}\n","/**\n * States that passed value is Record and not Array.\n * @param value - value to check.\n */\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n","import type { Version } from './types.js';\n\n/**\n * Returns 1 in case, version \"a\" is greater than \"b\".\n * Returns 0 in case, version \"a\" equal to \"b\".\n * Returns -1 in case, version \"a\" is lower than \"b\".\n * @param a - first version.\n * @param b - second version.\n */\nexport function compareVersions(a: Version, b: Version): number {\n // Split both of the version by dot.\n const aParts = a.split('.');\n const bParts = b.split('.');\n\n // Compute maximum length.\n const len = Math.max(aParts.length, bParts.length);\n\n // Iterate over each part of version and compare them. In case, part is\n // missing, assume its value is equal to 0.\n for (let i = 0; i < len; i += 1) {\n const aVal = parseInt(aParts[i] || '0', 10);\n const bVal = parseInt(bParts[i] || '0', 10);\n\n if (aVal === bVal) {\n continue;\n }\n return aVal > bVal ? 1 : -1;\n }\n return 0;\n}\n","import { compareVersions } from '@/version/compareVersions.js';\nimport type {\n MiniAppsMethodName,\n MiniAppsMethodVersionedParams,\n MiniAppsMethodWithVersionedParams,\n} from '@/bridge/methods/types/methods.js';\nimport type { Version } from '@/version/types.js';\n\n/**\n * Returns true if \"a\" version is less than or equal to \"b\" version.\n * @param a\n * @param b\n */\nfunction versionLessOrEqual(a: Version, b: Version): boolean {\n return compareVersions(a, b) <= 0;\n}\n\n/**\n * Returns true in case, passed parameter in specified method is supported.\n * @param method - method name\n * @param param - method parameter\n * @param inVersion - platform version.\n */\nexport function supports<M extends MiniAppsMethodWithVersionedParams>(\n method: M,\n param: MiniAppsMethodVersionedParams<M>,\n inVersion: Version,\n): boolean;\n\n/**\n * Returns true in case, specified method is supported in passed version.\n * @param method - method name.\n * @param inVersion - platform version.\n */\nexport function supports(method: MiniAppsMethodName, inVersion: Version): boolean;\n\nexport function supports(\n method: MiniAppsMethodName,\n paramOrVersion: Version | string,\n inVersion?: string,\n): boolean {\n // Method name, parameter, target version.\n if (typeof inVersion === 'string') {\n if (method === 'web_app_open_link') {\n if (paramOrVersion === 'try_instant_view') {\n return versionLessOrEqual('6.4', inVersion);\n }\n if (paramOrVersion === 'try_browser') {\n return versionLessOrEqual('7.6', inVersion);\n }\n }\n\n if (method === 'web_app_set_header_color') {\n if (paramOrVersion === 'color') {\n return versionLessOrEqual('6.9', inVersion);\n }\n }\n\n if (method === 'web_app_close' && paramOrVersion === 'return_back') {\n return versionLessOrEqual('7.6', inVersion);\n }\n }\n\n switch (method) {\n case 'web_app_open_tg_link':\n case 'web_app_open_invoice':\n case 'web_app_setup_back_button':\n case 'web_app_set_background_color':\n case 'web_app_set_header_color':\n case 'web_app_trigger_haptic_feedback':\n return versionLessOrEqual('6.1', paramOrVersion);\n case 'web_app_open_popup':\n return versionLessOrEqual('6.2', paramOrVersion);\n case 'web_app_close_scan_qr_popup':\n case 'web_app_open_scan_qr_popup':\n case 'web_app_read_text_from_clipboard':\n return versionLessOrEqual('6.4', paramOrVersion);\n case 'web_app_switch_inline_query':\n return versionLessOrEqual('6.7', paramOrVersion);\n case 'web_app_invoke_custom_method':\n case 'web_app_request_write_access':\n case 'web_app_request_phone':\n return versionLessOrEqual('6.9', paramOrVersion);\n case 'web_app_setup_settings_button':\n return versionLessOrEqual('6.10', paramOrVersion);\n case 'web_app_biometry_get_info':\n case 'web_app_biometry_open_settings':\n case 'web_app_biometry_request_access':\n case 'web_app_biometry_request_auth':\n case 'web_app_biometry_update_token':\n return versionLessOrEqual('7.2', paramOrVersion);\n default:\n return [\n 'iframe_ready',\n 'iframe_will_reload',\n 'web_app_close',\n 'web_app_data_send',\n 'web_app_expand',\n 'web_app_open_link',\n 'web_app_ready',\n 'web_app_request_theme',\n 'web_app_request_viewport',\n 'web_app_setup_main_button',\n 'web_app_setup_closing_behavior',\n ].includes(method);\n }\n}\n","import { isRecord } from '@/misc/isRecord.js';\n\n/**\n * Returns true in case, passed value contains path `external.notify` property and `notify` is a\n * function.\n * @param value - value to check.\n */\nexport function hasExternalNotify<T extends object>(value: T): value is (\n T & {\n external: {\n notify: (...args: any) => any;\n };\n}) {\n return 'external' in value\n && isRecord(value.external)\n && 'notify' in value.external\n && typeof value.external.notify === 'function';\n}\n","import { isRecord } from '@/misc/isRecord.js';\n\n/**\n * Returns true in case, passed value contains path `TelegramWebviewProxy.postEvent` property and\n * `postEvent` is a function.\n * @param value - value to check.\n */\nexport function hasWebviewProxy<T extends {}>(value: T): value is (\n T & {\n TelegramWebviewProxy: {\n postEvent: (...args: unknown[]) => unknown;\n }\n}) {\n return 'TelegramWebviewProxy' in value\n && isRecord(value.TelegramWebviewProxy)\n && 'postEvent' in value.TelegramWebviewProxy\n && typeof value.TelegramWebviewProxy.postEvent === 'function';\n}\n","/**\n * @see https://stackoverflow.com/a/326076\n * @returns True, if current environment is iframe.\n */\nexport function isIframe(): boolean {\n try {\n return window.self !== window.top;\n } catch {\n return true;\n }\n}\n","const INITIAL_TARGET_ORIGIN = 'https://web.telegram.org'\n\nlet currentTargetOrigin = INITIAL_TARGET_ORIGIN;\n\n/**\n * Sets a new global targetOrigin, used by the `postEvent` method.\n * The default value is \"https://web.telegram.org\".\n * You don't need to use this method until you know what you are doing.\n *\n * This method could be used for test purposes.\n * @param value - new target origin.\n * @see postEvent\n */\nexport function setTargetOrigin(value: string): void {\n currentTargetOrigin = value;\n}\n\n/**\n * Sets the initial target origin.\n */\nexport function resetTargetOrigin(): void {\n setTargetOrigin(INITIAL_TARGET_ORIGIN);\n}\n\n/**\n * Returns current global target origin.\n */\nexport function targetOrigin(): string {\n return currentTargetOrigin;\n}\n","import { log } from '@/debug/debug.js';\nimport { hasExternalNotify } from '@/env/hasExternalNotify.js';\nimport { hasWebviewProxy } from '@/env/hasWebviewProxy.js';\nimport { isIframe } from '@/env/isIframe.js';\nimport { createError } from '@/errors/createError.js';\nimport { ERR_UNKNOWN_ENV } from '@/errors/errors.js';\n\nimport { targetOrigin as targetOriginFn } from '../target-origin.js';\nimport type {\n MiniAppsMethodName,\n MiniAppsMethodParams,\n MiniAppsMethodWithOptionalParams,\n MiniAppsMethodWithoutParams,\n MiniAppsMethodWithRequiredParams,\n} from './types/methods.js';\n\ninterface PostEventOptions {\n /**\n * Origin used while posting a message.\n *\n * This option is only used if the current environment is browser (Web version of Telegram)\n * and could be used for test purposes.\n * @default 'https://web.telegram.org'\n */\n targetOrigin?: string;\n}\n\nexport type PostEvent = typeof postEvent;\n\n/**\n * Calls Mini Apps method with optional parameters.\n * @param method - method name.\n * @param params - method parameters.\n * @param options - posting options.\n * @throws {SDKError} ERR_UNKNOWN_ENV\n * @see ERR_UNKNOWN_ENV\n */\nexport function postEvent<Method extends MiniAppsMethodWithOptionalParams>(\n method: Method,\n params?: MiniAppsMethodParams<Method>,\n options?: PostEventOptions,\n): void;\n\n/**\n * Calls Mini Apps method without parameters.\n * @param method - method name.\n * @param options - posting options.\n * @throws {SDKError} ERR_UNKNOWN_ENV\n * @see ERR_UNKNOWN_ENV\n */\nexport function postEvent(\n method: MiniAppsMethodWithoutParams | MiniAppsMethodWithOptionalParams,\n options?: PostEventOptions,\n): void;\n\n/**\n * Calls Mini Apps method with parameters.\n * @param method - method name.\n * @param params - method parameters.\n * @param options - posting options.\n * @throws {SDKError} ERR_UNKNOWN_ENV\n * @see ERR_UNKNOWN_ENV\n */\nexport function postEvent<Method extends MiniAppsMethodWithRequiredParams>(\n method: Method,\n params: MiniAppsMethodParams<Method>,\n options?: PostEventOptions,\n): void;\n\nexport function postEvent(\n eventType: MiniAppsMethodName,\n paramsOrOptions?: MiniAppsMethodParams<MiniAppsMethodName> | PostEventOptions,\n options?: PostEventOptions,\n): void {\n let postOptions: PostEventOptions = {};\n let eventData: any;\n\n if (!paramsOrOptions && !options) {\n // Parameters and options were not passed.\n postOptions = {};\n } else if (paramsOrOptions && options) {\n // Both parameters and options passed.\n postOptions = options;\n eventData = paramsOrOptions;\n } else if (paramsOrOptions) {\n // Only parameters were passed.\n if ('targetOrigin' in paramsOrOptions) {\n postOptions = paramsOrOptions;\n } else {\n eventData = paramsOrOptions;\n }\n }\n\n log('Posting event:', eventData\n ? { event: eventType, data: eventData }\n : { event: eventType });\n\n // Telegram Web.\n if (isIframe()) {\n return window.parent.postMessage(\n JSON.stringify({ eventType, eventData }),\n postOptions.targetOrigin || targetOriginFn(),\n );\n }\n\n // Telegram for Windows Phone or Android.\n if (hasExternalNotify(window)) {\n window.external.notify(JSON.stringify({ eventType, eventData }));\n return;\n }\n\n // Telegram for iOS and macOS.\n if (hasWebviewProxy(window)) {\n window.TelegramWebviewProxy.postEvent(eventType, JSON.stringify(eventData));\n return;\n }\n\n // Otherwise current environment is unknown, and we are not able to send event.\n throw createError(\n ERR_UNKNOWN_ENV,\n 'Unable to determine current environment and possible way to send event. You are probably trying to use Mini Apps method outside the Telegram application environment.',\n );\n}\n","import { createError } from '@/errors/createError.js';\nimport { ERR_METHOD_PARAMETER_UNSUPPORTED, ERR_METHOD_UNSUPPORTED } from '@/errors/errors.js';\nimport { isRecord } from '@/misc/isRecord.js';\nimport { supports } from '@/supports/supports.js';\nimport type { Version } from '@/version/types.js';\n\nimport { type PostEvent, postEvent } from './postEvent.js';\n\n/**\n * Creates a function which checks if specified method and parameters are supported.\n *\n * If method or parameters are unsupported, an error will be thrown.\n * @param version - Telegram Mini Apps version.\n * @throws {SDKError} ERR_METHOD_UNSUPPORTED\n * @throws {SDKError} ERR_METHOD_PARAMETER_UNSUPPORTED\n * @see ERR_METHOD_UNSUPPORTED\n * @see ERR_METHOD_PARAMETER_UNSUPPORTED\n */\nexport function createPostEvent(version: Version): PostEvent {\n return (method: any, params: any) => {\n // Firstly, check if a method is supported.\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n if (!supports(method, version)) {\n throw createError(ERR_METHOD_UNSUPPORTED, `Method \"${method}\" is unsupported in Mini Apps version ${version}`);\n }\n\n // Method could use parameters, which are supported only in specific\n // versions of Mini Apps.\n // We are validating only those parameters, which are not backward compatible.\n if (\n isRecord(params)\n && method === 'web_app_set_header_color'\n && 'color' in params\n && !supports(method, 'color', version)\n ) {\n throw createError(\n ERR_METHOD_PARAMETER_UNSUPPORTED,\n `Parameter \"color\" of \"${method}\" method is unsupported in Mini Apps version ${version}`,\n );\n }\n\n return postEvent(method, params);\n };\n}\n","type CaptureSameReqFn = (payload: { req_id: string }) => boolean;\n\n/**\n * Returns a function which can be used in `request` function `capture` property to capture\n * the event with the same request identifier.\n * @param reqId - request identifier.\n */\nexport function captureSameReq(reqId: string): CaptureSameReqFn {\n return ({ req_id }) => req_id === reqId;\n}\n","import { createError } from '@/errors/createError.js';\nimport { ERR_TIMED_OUT } from '@/errors/errors.js';\nimport type { SDKError } from '@/errors/SDKError.js';\n\n/**\n * Creates new timeout error.\n * @param timeout - timeout in ms.\n */\nexport function createTimeoutError(timeout: number): SDKError {\n return createError(ERR_TIMED_OUT, `Timeout reached: ${timeout}ms`);\n}\n","import { createTimeoutError } from '@/timeout/createTimeoutError.js';\n\n/**\n * Runs passed function or promise with specified deadline presented via timeout argument.\n * @param funcOrPromise - function to execute or pending promise.\n * @param timeout - completion timeout.\n */\nexport function withTimeout<T>(\n funcOrPromise: Promise<T> | (() => Promise<T>),\n timeout: number,\n): Promise<T> {\n return Promise.race([\n typeof funcOrPromise === 'function' ? funcOrPromise() : funcOrPromise,\n new Promise<never>((_, rej) => {\n setTimeout(() => {\n rej(createTimeoutError(timeout));\n }, timeout);\n }),\n ]);\n}\n","import { withTimeout } from '@/timeout/withTimeout.js';\nimport type { ExecuteWithOptions, If, IsNever } from '@/types/index.js';\n\nimport { on } from './events/listening/on.js';\nimport { postEvent as defaultPostEvent } from './methods/postEvent.js';\nimport type { MiniAppsEventName, MiniAppsEventPayload } from './events/types.js';\nimport type { MiniAppsMethodName, MiniAppsMethodParams } from './methods/types/index.js';\nimport { createCleanup } from '@/misc/createCleanup.js';\n\n/**\n * Returns all possible payloads for the specified events array.\n */\nexport type RequestEventsPayloads<E extends MiniAppsEventName[]> =\n E extends (infer U extends MiniAppsEventName)[]\n ? MiniAppsEventPayload<U>\n : never;\n\nexport type RequestCaptureEventsFn<E extends MiniAppsEventName[]> =\n E extends (infer U extends MiniAppsEventName)[]\n ? (payload: {\n [K in U]: If<\n IsNever<MiniAppsEventPayload<K>>,\n { event: K },\n { event: K; payload: MiniAppsEventPayload<K> }\n >\n }[U]) => boolean\n : never;\n\nexport type RequestCaptureEventFn<E extends MiniAppsEventName> = If<\n IsNever<MiniAppsEventPayload<E>>,\n () => boolean,\n (payload: MiniAppsEventPayload<E>) => boolean\n>;\n\n/**\n * `request` method options.\n * @see request\n */\nexport type RequestOptions<M extends MiniAppsMethodName, E, C> = {\n /**\n * Mini Apps method name.\n */\n method: M;\n /**\n * Tracked Mini Apps events.\n */\n event: E;\n /**\n * Should return true if this event should be captured.\n * A request will be captured if this property is omitted.\n */\n capture?: C;\n }\n & ExecuteWithOptions\n & If<IsNever<MiniAppsMethodParams<M>>, {}, {\n /**\n * List of method parameters.\n */\n params: MiniAppsMethodParams<M>\n}>;\n\ntype AnyRequestResult =\n | MiniAppsEventPayload<MiniAppsEventName>\n | RequestEventsPayloads<MiniAppsEventName[]>;\n\n/**\n * Calls specified Mini Apps method and captures specified event.\n * @param options - method options.\n * @returns Promise which will be resolved with data of the captured event.\n */\nexport async function request<M extends MiniAppsMethodName, E extends MiniAppsEventName>(\n options: RequestOptions<M, E, RequestCaptureEventFn<E>>,\n): Promise<MiniAppsEventPayload<E>>;\n\n/**\n * Calls specified Mini Apps method and captures one of the specified events.\n * @param options - method options.\n * @returns Promise which will be resolved with data of the first captured event.\n */\nexport async function request<M extends MiniAppsMethodName, E extends MiniAppsEventName[]>(\n options: RequestOptions<M, E, RequestCaptureEventsFn<E>>,\n): Promise<RequestEventsPayloads<E>>;\n\nexport async function request<M extends MiniAppsMethodName>(\n options:\n | RequestOptions<M, MiniAppsEventName, RequestCaptureEventFn<MiniAppsEventName>>\n | RequestOptions<M, MiniAppsEventName[], RequestCaptureEventsFn<MiniAppsEventName[]>>,\n): Promise<AnyRequestResult> {\n let resolve: (payload: AnyRequestResult) => void;\n const promise = new Promise<AnyRequestResult>(res => resolve = res);\n\n const { event, capture, timeout } = options;\n const [, cleanup] = createCleanup(\n // We need to iterate over all tracked events, and create their event listeners.\n (Array.isArray(event) ? event : [event]).map((ev) => {\n // Each event listener waits for the event to occur.\n // Then, if the capture function was passed, we should check if the event should be captured.\n // If the function is omitted, we instantly capture the event.\n return on(ev, (payload) => {\n if (!capture || (\n Array.isArray(event)\n ? (capture as RequestCaptureEventsFn<MiniAppsEventName[]>)({\n event: ev,\n payload: payload as any,\n })\n : (capture as RequestCaptureEventFn<MiniAppsEventName>)(payload)\n )) {\n resolve(payload);\n }\n });\n }),\n );\n\n try {\n (options.postEvent || defaultPostEvent)(options.method as any, (options as any).params);\n return await (timeout ? withTimeout(promise, timeout) : promise);\n } finally {\n // After promise execution was completed, don't forget to remove all the listeners.\n cleanup();\n }\n}\n","import { createError } from '@/errors/createError.js';\nimport { ERR_INVOKE_CUSTOM_METHOD_RESPONSE } from '@/errors/errors.js';\nimport type { ExecuteWithOptions } from '@/types/index.js';\n\nimport { captureSameReq } from './captureSameReq.js';\nimport { request } from './request.js';\nimport type { CustomMethodName, CustomMethodParams } from './methods/types/custom-methods.js';\n\n/**\n * Invokes known custom method. Returns method execution result.\n * @param method - method name.\n * @param params - method parameters.\n * @param requestId - request identifier.\n * @param options - additional options.\n * @throws {SDKError} ERR_INVOKE_CUSTOM_METHOD_RESPONSE\n * @see ERR_INVOKE_CUSTOM_METHOD_RESPONSE\n */\nexport async function invokeCustomMethod<M extends CustomMethodName>(\n method: M,\n params: CustomMethodParams<M>,\n requestId: string,\n options?: ExecuteWithOptions,\n): Promise<unknown>;\n\n/**\n * Invokes unknown custom method. Returns method execution result.\n * @param method - method name.\n * @param params - method parameters.\n * @param requestId - request identifier.\n * @param options - additional options.\n * @throws {SDKError} ERR_INVOKE_CUSTOM_METHOD_RESPONSE\n * @see ERR_INVOKE_CUSTOM_METHOD_RESPONSE\n */\nexport function invokeCustomMethod(\n method: string,\n params: object,\n requestId: string,\n options?: ExecuteWithOptions,\n): Promise<unknown>;\n\nexport async function invokeCustomMethod(\n method: string,\n params: object,\n requestId: string,\n options: ExecuteWithOptions = {},\n): Promise<unknown> {\n const {\n result,\n error,\n } = await request({\n ...options,\n method: 'web_app_invoke_custom_method',\n event: 'custom_method_invoked',\n params: {\n method,\n params,\n req_id: requestId,\n },\n capture: captureSameReq(requestId),\n });\n\n if (error) {\n throw createError(ERR_INVOKE_CUSTOM_METHOD_RESPONSE, error);\n }\n\n return result;\n}\n","import { isRecord } from '@/misc/isRecord.js';\n\n/**\n * Function which joins passed values with space following these rules:\n * 1. If value is non-empty string, it will be added to output.\n * 2. If value is object, only those keys will be added, which values are truthy.\n * 3. If value is array, classNames will be called with this value spread.\n * 4. All other values are ignored.\n *\n * You can find this function to similar one from the package {@link https://www.npmjs.com/package/classnames|classnames}.\n * @param values - values array.\n * @returns Final class name.\n */\nexport function classNames(...values: any[]): string {\n return values\n .map((value) => {\n if (typeof value === 'string') {\n return value;\n }\n\n if (isRecord(value)) {\n return classNames(Object.entries(value).map((entry) => entry[1] && entry[0]));\n }\n\n if (Array.isArray(value)) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n return classNames(...value);\n }\n })\n .filter(Boolean)\n .join(' ');\n}\n","import { isRecord } from '@/misc/isRecord.js';\nimport type { UnionOptionalKeys, UnionRequiredKeys } from '@/types/unions.js';\n\nimport { classNames } from './classNames.js';\n\nexport type MergeClassNames<Tuple extends any[]> =\n // Removes all types from union which will be ignored by the mergeClassNames function.\n Exclude<Tuple[number], number | string | null | undefined | any[] | boolean> extends infer Union\n ? {\n [K in UnionRequiredKeys<Union>]: string;\n } & {\n [K in UnionOptionalKeys<Union>]?: string;\n }\n : never;\n\n/**\n * Merges 2 sets of parameters. Function expects passing an array of objects with values, which\n * could be passed to `classNames` function. As the result, it returns an object with keys\n * from all objects with merged values.\n * @see classNames\n */\nexport function mergeClassNames<T extends any[]>(...partials: T): MergeClassNames<T> {\n return partials.reduce<MergeClassNames<T>>((acc, partial) => {\n if (!isRecord(partial)) {\n return acc;\n }\n\n Object.entries(partial).forEach(([key, value]) => {\n const className = classNames((acc as any)[key], value);\n\n if (className.length) {\n (acc as any)[key] = className;\n }\n });\n\n return acc;\n }, {} as MergeClassNames<T>);\n}\n","import type { RGB } from './types.js';\n\n/**\n * Returns true in case, passed value has #RRGGBB format.\n * @param value - value to check.\n */\nexport function isRGB(value: string): value is RGB {\n return /^#[\\da-f]{6}$/i.test(value);\n}\n","import type { RGBShort } from './types.js';\n\n/**\n * Returns true in case, passed value has #RGB format.\n * @param value - value to check.\n */\nexport function isRGBShort(value: string): value is RGBShort {\n return /^#[\\da-f]{3}$/i.test(value);\n}\n","import { isRGB } from './isRGB.js';\nimport { isRGBShort } from './isRGBShort.js';\nimport type { RGB } from './types.js';\n\n/**\n * Converts passed value to #RRGGBB format. Accepts following color formats:\n * - `#RGB`\n * - `#RRGGBB`\n * - `rgb(1,2,3)`\n * - `rgba(1,2,3,4)`\n * @param value - value to convert.\n * @throws {Error} Passed value does not satisfy any of known RGB formats.\n */\nexport function toRGB(value: string): RGB {\n // Remove all spaces.\n const clean = value.replace(/\\s/g, '').toLowerCase();\n\n // Value already has required format.\n if (isRGB(clean)) {\n return clean;\n }\n\n // Convert from #RGB.\n if (isRGBShort(clean)) {\n let color: RGB = '#';\n for (let i = 0; i < 3; i += 1) {\n color += clean[1 + i].repeat(2);\n }\n return color;\n }\n\n // Example valid values: rgb(0,3,10) rgba(32,114,8,0)\n const match = clean.match(/^rgb\\((\\d{1,3}),(\\d{1,3}),(\\d{1,3})\\)$/)\n || clean.match(/^rgba\\((\\d{1,3}),(\\d{1,3}),(\\d{1,3}),\\d{1,3}\\)$/);\n\n // In case, this didn't work as well, we can't extract RGB color from passed\n // text.\n if (!match) {\n throw new Error(`Value \"${value}\" does not satisfy any of known RGB formats.`);\n }\n\n // Otherwise, take R, G and B components, convert to hex and create #RRGGBB\n // string.\n return match.slice(1).reduce((acc, component) => {\n const formatted = parseInt(component, 10).toString(16);\n return acc + (formatted.length === 1 ? '0' : '') + formatted;\n }, '#') as RGB;\n}\n","import { toRGB } from './toRGB.js';\n\n/**\n * Returns true in case, the color is recognized as dark.\n * @param color - color in any format acceptable by toRGB function.\n * @see toRGB\n */\nexport function isColorDark(color: string): boolean {\n // Convert color to RGB.\n const rgb = toRGB(color);\n\n // Real formula: hsp = Math.sqrt(0.299 * r * r + 0.587 * g * g + 0.114 * b * b)\n // See: https://stackoverflow.com/a/596243\n return Math.sqrt(\n [0.299, 0.587, 0.114].reduce<number>((acc, modifier, idx) => {\n // Extract part of #RRGGBB pattern and convert it to DEC.\n const dec = parseInt(rgb.slice(1 + idx * 2, 1 + (idx + 1) * 2), 16);\n return acc + dec * dec * modifier;\n }, 0),\n ) < 120;\n}\n","import { EventEmitter } from '@/events/event-emitter/EventEmitter.js';\nimport type { StateEvents } from '@/classes/State/types.js';\nimport type { StringKeys } from '@/types/utils.js';\n\ntype Emitter<State extends object> = EventEmitter<StateEvents<State>>;\n\nexport class State<State extends object> {\n private readonly ee: Emitter<State> = new EventEmitter();\n\n constructor(\n /**\n * Initial state.\n */\n private readonly state: State,\n ) {\n }\n\n /**\n * Clones current state and returns its copy.\n */\n clone(): State {\n return { ...this.state };\n }\n\n /**\n * Sets value by key.\n * @param key - state key.\n * @param value - value to set.\n */\n set<K extends StringKeys<State>>(key: K, value: State[K]): void;\n /**\n * Sets several values simultaneously.\n * @param state - partial state.\n */\n set(state: Partial<State>): void;\n set(keyOrState: StringKeys<State> | Partial<State>, keyValue?: State[keyof State]): void {\n const didChange = Object\n .entries(typeof keyOrState === 'string' ? { [keyOrState]: keyValue } : keyOrState)\n .reduce((acc, [key, value]) => {\n // If value is the same or missing at all, we skip it.\n if (this.state[key as keyof State] === value || value === undefined) {\n return acc;\n }\n\n // Otherwise set new value and emit change event.\n this.state[key as keyof State] = value;\n // eslint-disable-next-line @typescript-eslint/no-unsafe-call\n (this.ee as any).emit(`change:${key}`, value);\n\n return true;\n }, false);\n\n if (didChange) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-call\n (this.ee as any).emit('change', this.state);\n }\n }\n\n /**\n * Returns value by specified key.\n * @param key - state key.\n */\n get<K extends StringKeys<State>>(key: K): State[K] {\n return this.state[key];\n }\n\n /**\n * Adds new event listener.\n */\n on: Emitter<State>['on'] = this.ee.on.bind(this.ee);\n\n /**\n * Removes event listener.\n */\n off: Emitter<State>['off'] = this.ee.off.bind(this.ee);\n}\n","import { State } from '@/classes/State/State.js';\n\nexport class WithStateUtils<Shape extends object> {\n protected state: State<Shape>;\n\n constructor(shape: Shape) {\n this.state = new State(shape);\n this.set = this.state.set.bind(this.state);\n this.get = this.state.get.bind(this.state);\n this.clone = this.state.clone.bind(this.state);\n }\n\n /**\n * Gets the state value.\n */\n protected get: State<Shape>['get'];\n\n /**\n * Sets the state value.\n */\n protected set: State<Shape>['set'];\n\n /**\n * Clones the current state.\n */\n protected clone: State<Shape>['clone'];\n}\n","import { supports } from '@/supports/supports.js';\nimport type { MiniAppsMethodName } from '@/bridge/methods/types/methods.js';\nimport type { SupportsFn } from '@/supports/types.js';\nimport type { Version } from '@/version/types.js';\n\nexport type SupportsSchema<Method extends string> = Record<Method, MiniAppsMethodName>;\n\n/**\n * Returns function, which accepts predefined method name and checks if it is supported\n * via passed schema and version.\n * @param schema - object which contains methods names and TWA method as a dependency.\n * @param version - platform version.\n */\nexport function createSupportsFn<Method extends string>(\n version: Version,\n schema: SupportsSchema<Method>,\n): SupportsFn<Method> {\n return (method) => supports(schema[method], version);\n}\n","import { WithStateUtils } from '@/classes/WithStateUtils.js';\nimport { createSupportsFn } from '@/supports/createSupportsFn.js';\nimport type { MiniAppsMethodName } from '@/bridge/methods/types/methods.js';\nimport type { SupportsFn } from '@/supports/types.js';\nimport type { Version } from '@/version/types.js';\n\nexport class WithSupportsAndStateUtils<StateShape extends object, SupportsMethod extends string>\nextends WithStateUtils<StateShape> {\n constructor(\n /**\n * Initial state.\n */\n stateShape: StateShape,\n /**\n * Mini Apps version.\n */\n version: Version,\n /**\n * Supports method schema.\n */\n supportsSchema: Record<SupportsMethod, MiniAppsMethodName>,\n ) {\n super(stateShape);\n this.supports = createSupportsFn(version, supportsSchema);\n }\n\n /**\n * @returns True, if specified method is supported by the current component.\n */\n supports: SupportsFn<SupportsMethod>;\n}\n","import { off } from '@/bridge/events/listening/off.js';\nimport { on } from '@/bridge/events/listening/on.js';\nimport { WithSupportsAndStateUtils } from '@/classes/WithSupportsAndStateUtils.js';\nimport type { PostEvent } from '@/bridge/methods/postEvent.js';\nimport type { BackButtonEvents, BackButtonState } from '@/components/BackButton/types.js';\nimport type { EventEmitter } from '@/events/event-emitter/EventEmitter.js';\nimport type { Version } from '@/version/types.js';\n\ntype Emitter = EventEmitter<BackButtonEvents>;\n\n/**\n * @see Usage: https://docs.telegram-mini-apps.com/platform/back-button\n * @see API: https://docs.telegram-mini-apps.com/packages/tma-js-sdk/components/back-button\n */\nexport class BackButton extends WithSupportsAndStateUtils<BackButtonState, 'show' | 'hide'> {\n constructor(isVisible: boolean, version: Version, private readonly postEvent: PostEvent) {\n super({ isVisible }, version, {\n show: 'web_app_setup_back_button',\n hide: 'web_app_setup_back_button',\n });\n }\n\n private set isVisible(visible: boolean) {\n this.set('isVisible', visible);\n this.postEvent('web_app_setup_back_button', { is_visible: visible });\n }\n\n /**\n * True if BackButton is currently visible.\n */\n get isVisible(): boolean {\n return this.get('isVisible');\n }\n\n /**\n * Hides the BackButton.\n */\n hide(): void {\n this.isVisible = false;\n }\n\n /**\n * Adds a new event listener.\n * @param event - event to listen.\n * @param listener - listener to add.\n */\n on: Emitter['on'] = (event, listener) => (\n event === 'click'\n ? on('back_button_pressed', listener)\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n : this.state.on(event, listener as any)\n );\n\n /**\n * Removes the event listener.\n * @param event - event to listen.\n * @param listener - listener to remove.\n */\n off: Emitter['off'] = (event, listener) => (\n event === 'click'\n ? off('back_button_pressed', listener)\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n : this.state.off(event, listener as any)\n );\n\n /**\n * Shows the BackButton.\n */\n show(): void {\n this.isVisible = true;\n }\n}\n","import { createValueParserGenerator } from '../createValueParserGenerator.js';\nimport { number } from './number.js';\nimport type { ValueParserGenerator } from '../createValueParserGenerator.js';\n\n/**\n * Returns parser to parse value as Date.\n */\nexport const date: ValueParserGenerator<Date> = createValueParserGenerator((value) => (\n value instanceof Date\n ? value\n : new Date(number().parse(value) * 1000)\n), 'Date');\n","import { createTypeError } from '../createTypeError.js';\nimport { parseBySchema } from '../parseBySchema.js';\nimport { ValueParser } from '../ValueParser/ValueParser.js';\nimport type { Schema } from '../types.js';\n\n/**\n * Creates new search params parser according to passed schema.\n * @param schema - object schema.\n * @param type - parser type name.\n */\nexport function searchParams<T>(schema: Schema<T>, type?: string): ValueParser<T, false> {\n return new ValueParser((value) => {\n if (typeof value !== 'string' && !(value instanceof URLSearchParams)) {\n throw createTypeError();\n }\n\n const params = typeof value === 'string' ? new URLSearchParams(value) : value;\n\n return parseBySchema(schema, (field) => {\n const paramValue = params.get(field);\n return paramValue === null ? undefined : paramValue;\n });\n }, false, type);\n}\n","import { json } from '@/parsing/parsers/json.js';\nimport { number } from '@/parsing/parsers/number.js';\nimport { string } from '@/parsing/parsers/string.js';\n\nimport type { Chat } from '../types.js';\n\nexport const chat = json<Chat>({\n id: number(),\n type: string(),\n title: string(),\n photoUrl: {\n type: string().optional(),\n from: 'photo_url',\n },\n username: string().optional(),\n}, 'Chat')\n .optional();\n","import { boolean } from '@/parsing/parsers/boolean.js';\nimport { json } from '@/parsing/parsers/json.js';\nimport { number } from '@/parsing/parsers/number.js';\nimport { string } from '@/parsing/parsers/string.js';\n\nimport type { User } from '../types.js';\n\nexport const user = json<User>({\n addedToAttachmentMenu: {\n type: boolean().optional(),\n from: 'added_to_attachment_menu',\n },\n allowsWriteToPm: {\n type: boolean().optional(),\n from: 'allows_write_to_pm',\n },\n firstName: {\n type: string(),\n from: 'first_name',\n },\n id: number(),\n isBot: {\n type: boolean().optional(),\n from: 'is_bot',\n },\n isPremium: {\n type: boolean().optional(),\n from: 'is_premium',\n },\n languageCode: {\n type: string().optional(),\n from: 'language_code',\n },\n lastName: {\n type: string().optional(),\n from: 'last_name',\n },\n photoUrl: {\n type: string().optional(),\n from: 'photo_url',\n },\n username: string().optional(),\n}, 'User')\n .optional();\n","import { date } from '@/parsing/parsers/date.js';\nimport { number } from '@/parsing/parsers/number.js';\nimport { searchParams } from '@/parsing/parsers/searchParams.js';\nimport { string } from '@/parsing/parsers/string.js';\nimport type { ValueParser } from '@/parsing/ValueParser/ValueParser.js';\n\nimport { chat } from './chat.js';\nimport { user } from './user.js';\nimport type { InitDataParsed } from '../types.js';\n\n/**\n * Returns parser used to parse init data, presented as search params.\n */\nexport function initData(): ValueParser<InitDataParsed, false> {\n return searchParams<InitDataParsed>({\n authDate: {\n type: date(),\n from: 'auth_date',\n },\n canSendAfter: {\n type: number().optional(),\n from: 'can_send_after',\n },\n chat,\n chatInstance: {\n type: string().optional(),\n from: 'chat_instance',\n },\n chatType: {\n type: string().optional(),\n from: 'chat_type',\n },\n hash: string(),\n queryId: {\n type: string().optional(),\n from: 'query_id',\n },\n receiver: user,\n startParam: {\n type: string().optional(),\n from: 'start_param',\n },\n user,\n }, 'InitData');\n}\n","import { toRGB } from '@/colors/toRGB.js';\nimport type { RGB } from '@/colors/types.js';\n\nimport { createValueParserGenerator } from '../createValueParserGenerator.js';\nimport { string } from './string.js';\nimport type { ValueParserGenerator } from '../createValueParserGenerator.js';\n\n/**\n * Returns parser to parse value as RGB color.\n */\nexport const rgb: ValueParserGenerator<RGB> = createValueParserGenerator((value) => toRGB(string().parse(value)), 'rgb');\n","/**\n * Converts a palette key from the Telegram application to the representation used by the package.\n * @param key - palette key.\n */\nexport function keyToLocal(key: string): string {\n return key.replace(/_[a-z]/g, (match) => match[1].toUpperCase());\n}\n\n/**\n * Converts palette key from the local representation to the representation sent from the\n * Telegram application.\n * @param key - palette key.\n */\nexport function keyToExternal(key: string): string {\n return key.replace(/[A-Z]/g, (match) => `_${match.toLowerCase()}`);\n}\n","import { createValueParserGenerator, type ValueParserGenerator } from '@/parsing/createValueParserGenerator.js';\nimport { rgb } from '@/parsing/parsers/rgb.js';\nimport { toRecord } from '@/parsing/toRecord.js';\n\nimport { keyToLocal } from '../keys.js';\nimport type { ThemeParamsParsed } from '../types.js';\n\nexport const themeParams: ValueParserGenerator<ThemeParamsParsed> = createValueParserGenerator(\n (value) => {\n const rgbOptional = rgb().optional();\n\n return Object\n .entries(toRecord(value))\n .reduce<ThemeParamsParsed>((acc, [k, v]) => {\n acc[keyToLocal(k)] = rgbOptional.parse(v);\n return acc;\n }, {});\n },\n 'ThemeParams',\n);\n","import { initData } from '@/components/InitData/parsers/initData.js';\nimport { themeParams } from '@/components/ThemeParams/parsing/themeParams.js';\nimport { boolean } from '@/parsing/parsers/boolean.js';\nimport { searchParams } from '@/parsing/parsers/searchParams.js';\nimport { string } from '@/parsing/parsers/string.js';\n\nimport type { LaunchParams } from './types.js';\n\n/**\n * Parses value as launch parameters.\n * @param value - value to parse.\n */\nexport function parseLaunchParams(value: unknown): LaunchParams {\n return searchParams({\n botInline: {\n type: boolean().optional(),\n from: 'tgWebAppBotInline',\n },\n initData: {\n type: initData().optional(),\n from: 'tgWebAppData',\n },\n initDataRaw: {\n type: string().optional(),\n from: 'tgWebAppData',\n },\n platform: {\n type: string(),\n from: 'tgWebAppPlatform',\n },\n showSettings: {\n type: boolean().optional(),\n from: 'tgWebAppShowSettings',\n },\n startParam: {\n type: string().optional(),\n from: 'tgWebAppStartParam',\n },\n themeParams: {\n type: themeParams(),\n from: 'tgWebAppThemeParams',\n },\n version: {\n type: string(),\n from: 'tgWebAppVersion',\n },\n }).parse(value);\n}\n","import { parseLaunchParams } from './parseLaunchParams.js';\nimport type { LaunchParams } from './types.js';\n\n/**\n * @param urlString - URL to extract launch parameters from.\n * @returns Launch parameters from the specified URL.\n * @throws Error if function was unable to extract launch parameters from the passed URL.\n */\nexport function retrieveFromUrl(urlString: string): LaunchParams {\n return parseLaunchParams(\n urlString\n // Replace everything before this first hashtag or question sign.\n .replace(/^[^?#]*[?#]/, '')\n // Replace all hashtags and question signs to make it look like some search params.\n .replace(/[?#]/g, '&'),\n );\n}\n","import { retrieveFromUrl } from './retrieveFromUrl.js';\nimport type { LaunchParams } from './types.js';\n\n/**\n * @returns Launch parameters from the current window location hash.\n * @throws Error if function was unable to extract launch parameters from the window location hash.\n */\nexport function retrieveFromLocation(): LaunchParams {\n return retrieveFromUrl(window.location.href);\n}\n","/**\n * Returns the first navigation entry from window.performance.\n * @returns First navigation entry or null, in case performance functionality is not supported\n * or navigation entry was not found.\n */\nexport function getFirstNavigationEntry(): PerformanceNavigationTiming | undefined {\n return performance.getEntriesByType('navigation')[0] as PerformanceNavigationTiming | undefined;\n}\n","import { getFirstNavigationEntry } from '@/navigation/getFirstNavigationEntry.js';\n\nimport { retrieveFromUrl } from './retrieveFromUrl.js';\nimport type { LaunchParams } from './types.js';\n\n/**\n * @returns Launch parameters based on the first navigation entry.\n * @throws Error if function was unable to extract launch parameters from the navigation entry.\n */\nexport function retrieveFromPerformance(): LaunchParams {\n const navigationEntry = getFirstNavigationEntry();\n if (!navigationEntry) {\n throw new Error('Unable to get first navigation entry.');\n }\n\n return retrieveFromUrl(navigationEntry.name);\n}\n","import type { BackButtonState } from '@/components/BackButton/types.js';\nimport type { BiometryManagerState } from '@/components/BiometryManager/types.js';\nimport type { ClosingBehaviorState } from '@/components/ClosingBehavior/types.js';\nimport type { MainButtonState } from '@/components/MainButton/types.js';\nimport type { MiniAppState } from '@/components/MiniApp/types.js';\nimport type { SettingsButtonState } from '@/components/SettingsButton/types.js';\nimport type { ThemeParamsParsed } from '@/components/ThemeParams/types.js';\nimport type { ViewportState } from '@/components/Viewport/types.js';\n\n/**\n * Describes storage keys and according values.\n */\nexport interface StorageParams {\n backButton: BackButtonState;\n biometryManager: BiometryManagerState;\n closingBehavior: ClosingBehaviorState;\n launchParams: string;\n mainButton: MainButtonState;\n miniApp: MiniAppState;\n settingsButton: SettingsButtonState;\n themeParams: ThemeParamsParsed;\n viewport: ViewportState;\n}\n\n/**\n * Key which could be used to store data in the storage.\n */\nexport type StorageKey = keyof StorageParams;\n\n/**\n * Type specific to the specified storage key.\n */\nexport type StorageValue<K extends StorageKey> = StorageParams[K];\n\n/**\n * Converts passed storage key to the formatted state.\n * @param key - storage key.\n */\nfunction formatKey(key: StorageKey): string {\n return `tma.js/${key.replace(/[A-Z]/g, (m) => `-${m.toLowerCase()}`)}`;\n}\n\n/**\n * Saves value in the storage.\n * @param key - storage key.\n * @param value - storage value.\n */\nexport function setStorageValue<K extends StorageKey>(key: K, value: StorageValue<K>): void {\n sessionStorage.setItem(formatKey(key), JSON.stringify(value));\n}\n\n/**\n * Extracts value from the storage.\n * @param key - storage key.\n */\nexport function getStorageValue<K extends StorageKey>(key: K): StorageValue<K> | undefined {\n const value = sessionStorage.getItem(formatKey(key));\n try {\n return value ? JSON.parse(value) as StorageValue<K> : undefined;\n } catch { /* empty */ }\n}\n","import { parseLaunchParams } from '@/launch-params/parseLaunchParams.js';\nimport { getStorageValue } from '@/storage/storage.js';\nimport type { LaunchParams } from '@/launch-params/types.js';\n\n/**\n * @returns Launch parameters stored in the session storage.\n * @throws Error if function was unable to extract launch parameters from the window location hash.\n */\nexport function retrieveFromStorage(): LaunchParams {\n return parseLaunchParams(getStorageValue('launchParams') || '');\n}\n","import { keyToExternal } from '../keys.js';\nimport type { ThemeParamsParsed } from '../types.js';\n\n/**\n * Serializes theme parameters to representation sent from the Telegram application.\n */\nexport function serializeThemeParams(themeParams: ThemeParamsParsed): string {\n return JSON.stringify(\n Object.fromEntries(\n Object\n .entries(themeParams)\n .map(([key, value]) => [keyToExternal(key), value]),\n ),\n );\n}\n","import { serializeThemeParams } from '@/components/ThemeParams/parsing/serializeThemeParams.js';\n\nimport type { LaunchParams } from './types.js';\n\n/**\n * Converts launch parameters to its initial representation.\n * @param value - launch parameters.\n */\nexport function serializeLaunchParams(value: LaunchParams): string {\n const {\n initDataRaw,\n themeParams,\n platform,\n version,\n showSettings,\n startParam,\n botInline,\n } = value;\n\n const params = new URLSearchParams();\n\n params.set('tgWebAppPlatform', platform);\n params.set('tgWebAppThemeParams', serializeThemeParams(themeParams));\n params.set('tgWebAppVersion', version);\n\n if (initDataRaw) {\n params.set('tgWebAppData', initDataRaw);\n }\n\n if (startParam) {\n params.set('tgWebAppStartParam', startParam);\n }\n\n if (typeof showSettings === 'boolean') {\n params.set('tgWebAppShowSettings', showSettings ? '1' : '0');\n }\n\n if (typeof botInline === 'boolean') {\n params.set('tgWebAppBotInline', botInline ? '1' : '0');\n }\n\n return params.toString();\n}\n","import { setStorageValue } from '@/storage/storage.js';\n\nimport { serializeLaunchParams } from './serializeLaunchParams.js';\nimport type { LaunchParams } from './types.js';\n\n/**\n * Saves specified launch parameters in the session storage.\n * @param value - launch params to save.\n */\nexport function saveToStorage(value: LaunchParams): void {\n setStorageValue('launchParams', serializeLaunchParams(value));\n}\n","import { retrieveFromLocation } from './retrieveFromLocation.js';\nimport { retrieveFromPerformance } from './retrieveFromPerformance.js';\nimport { retrieveFromStorage } from './retrieveFromStorage.js';\nimport { saveToStorage } from './saveToStorage.js';\nimport type { LaunchParams } from './types.js';\n\n/**\n * @returns Launch parameters from any known source.\n * @throws Error if extraction was unsuccessful.\n */\nexport function retrieveLaunchParams(): LaunchParams {\n const errors: unknown[] = [];\n\n for (const retrieve of [\n // Try to retrieve launch parameters from the current location. This method can return\n // nothing in case, location was changed and then page was reloaded.\n retrieveFromLocation,\n // Then, try using the lower level API - window.performance.\n retrieveFromPerformance,\n // Finally, try to extract launch parameters from the session storage.\n retrieveFromStorage,\n ]) {\n try {\n const lp = retrieve();\n saveToStorage(lp);\n return lp;\n } catch (e) {\n errors.push(e);\n }\n }\n\n throw new Error('Unable to retrieve launch parameters from any known source.');\n}\n","import { getFirstNavigationEntry } from './getFirstNavigationEntry.js';\n\n/**\n * @returns True, if current page was reloaded.\n * @see https://stackoverflow.com/a/36444134/11894710\n */\nexport function isPageReload(): boolean {\n const entry = getFirstNavigationEntry();\n return !!(entry && entry.type === 'reload');\n}\n","import type { CreateRequestIdFn } from './types.js';\n\n/**\n * Creates function which generated request identifiers.\n */\nexport function createRequestIdGenerator(): CreateRequestIdFn {\n let requestId = 0;\n return () => (requestId += 1).toString();\n}\n","import { createPostEvent } from '@/bridge/methods/createPostEvent.js';\nimport { retrieveLaunchParams } from '@/launch-params/retrieveLaunchParams.js';\nimport { createSingleton } from '@/misc/createSingleton.js';\nimport { isPageReload } from '@/navigation/isPageReload.js';\nimport { createRequestIdGenerator } from '@/request-id/createRequestIdGenerator.js';\nimport type { StorageKey, StorageValue } from '@/storage/storage.js';\nimport { getStorageValue, setStorageValue } from '@/storage/storage.js';\nimport { createCleanup } from '@/misc/createCleanup.js';\n\nimport {\n FactoryDynamic,\n FactoryStatic,\n InitStaticComponentFn,\n InitDynamicComponentFn,\n WithOnChange,\n} from './types.js';\n\nconst [createReqId] = createSingleton(createRequestIdGenerator);\n\n/**\n * Creates a new init function based on factory, creating a component, not synchronizing its\n * state with the session storage.\n * @param factory - function creating new component instance.\n */\nexport function createComponentInitFn<R>(factory: FactoryStatic<R>): InitStaticComponentFn<R>;\n\n/**\n * Creates a new init function based on factory, creating a component, synchronizing its\n * state with the session storage.\n * @param factory - function creating new component instance.\n * @param storageKey - storage key to restore component from.\n */\nexport function createComponentInitFn<\n SK extends StorageKey,\n R extends WithOnChange<StorageValue<SK>> | Promise<WithOnChange<StorageValue<SK>>>,\n>(\n storageKey: SK,\n factory: FactoryDynamic<R, SK>,\n): InitDynamicComponentFn<R>;\n\nexport function createComponentInitFn<\n R extends WithOnChange<StorageValue<SK>> | Promise<WithOnChange<StorageValue<SK>>>,\n SK extends StorageKey,\n>(\n factoryStaticOrSK: FactoryStatic<R> | SK,\n factoryDynamic?: FactoryDynamic<R, SK>,\n): InitStaticComponentFn<R> | InitDynamicComponentFn<R> {\n return () => {\n const lp = retrieveLaunchParams();\n const factoryOptions = {\n ...lp,\n postEvent: createPostEvent(lp.version),\n createRequestId: createReqId(),\n };\n\n // In static init mode we have no reason to use the storage to restore the state. In this\n // case we should just call the factory.\n if (typeof factoryStaticOrSK === 'function') {\n return factoryStaticOrSK(factoryOptions);\n }\n\n // Otherwise, we create a new component instance from the storage if possible and add\n // required change listeners.\n const [addCleanup, cleanup, cleanedUp] = createCleanup();\n\n const result = factoryDynamic!({\n ...factoryOptions,\n // State should only be passed only in case, current page was reloaded. If we don't add\n // this check, state restoration will work improperly in the web version of Telegram,\n // when we are always working in the same \"session\" (tab).\n state: isPageReload() ? getStorageValue(factoryStaticOrSK) : undefined,\n addCleanup,\n });\n\n const bindChange = (value: WithOnChange<StorageValue<SK>>) => {\n if (!cleanedUp) {\n addCleanup(\n value.on('change', (state) => {\n setStorageValue(factoryStaticOrSK, state);\n }),\n );\n }\n return value;\n };\n\n return [\n result instanceof Promise ? result.then(bindChange) : bindChange(result),\n cleanup,\n ] as unknown as R;\n };\n}\n","import { createComponentInitFn } from '@/misc/createComponentInitFn/createComponentInitFn.js';\n\nimport { BackButton } from './BackButton.js';\n\n/**\n * @returns A new initialized instance of the `BackButton` class.\n * @see BackButton\n */\nexport const initBackButton = createComponentInitFn('backButton', ({\n postEvent,\n version,\n state = { isVisible: false },\n}) => new BackButton(state.isVisible, version, postEvent));\n","import { WithSupportsAndStateUtils } from '@/classes/WithSupportsAndStateUtils.js';\nimport type { StateEvents } from '@/classes/State/types.js';\nimport type { EventEmitter } from '@/events/event-emitter/EventEmitter.js';\n\ntype Emitter<StateShape extends object> = EventEmitter<StateEvents<StateShape>>;\n\nexport class WithSupportsAndTrackableState<StateShape extends object, SupportsMethod extends string>\n extends WithSupportsAndStateUtils<StateShape, SupportsMethod> {\n /**\n * Adds a new event listener.\n */\n on: Emitter<StateShape>['on'] = this.state.on.bind(this.state);\n\n /**\n * Removes the event listener.\n */\n off: Emitter<StateShape>['off'] = this.state.off.bind(this.state);\n}\n","import type { BiometryType, MiniAppsEventPayload } from '@/bridge/events/types.js';\n\nexport interface FormatBiometryInfoResult {\n /**\n * Shows whether biometry is available.\n */\n available: boolean;\n /**\n * Shows whether permission to use biometrics has been requested.\n */\n accessRequested: boolean;\n /**\n * Shows whether permission to use biometrics has been granted.\n */\n accessGranted: boolean;\n /**\n * A unique device identifier that can be used to match the token to the device.\n */\n deviceId: string;\n /**\n * Show whether local storage contains previously saved token.\n */\n tokenSaved: boolean;\n /**\n * The type of biometrics currently available on the device.\n */\n type: BiometryType;\n}\n\n/**\n * Converts `biometry_info_received` to some common shape.\n * @param event - event payload.\n * @see biometry_info_received\n */\nexport function formatEvent(\n event: MiniAppsEventPayload<'biometry_info_received'>,\n): FormatBiometryInfoResult {\n const data = event.available ? event : {\n available: false,\n device_id: '',\n token_saved: false,\n access_requested: false,\n access_granted: false,\n type: '',\n };\n\n return {\n available: true,\n type: data.type,\n deviceId: data.device_id,\n tokenSaved: data.token_saved,\n accessRequested: data.access_requested,\n accessGranted: data.access_granted,\n };\n}\n","import { request } from '@/bridge/request.js';\nimport { WithSupportsAndTrackableState } from '@/classes/WithSupportsAndTrackableState.js';\nimport { formatEvent } from '@/components/BiometryManager/formatEvent.js';\nimport type { BiometryType } from '@/bridge/events/types.js';\nimport type { PostEvent } from '@/bridge/methods/postEvent.js';\nimport type {\n BiometryManagerAuthenticateOptions,\n BiometryManagerProps,\n BiometryManagerRequestAccessOptions,\n BiometryManagerState,\n BiometryManagerUpdateTokenOptions,\n} from '@/components/BiometryManager/types.js';\n\nexport class BiometryManager extends WithSupportsAndTrackableState<BiometryManagerState,\n | 'auth'\n | 'openSettings'\n | 'requestAccess'\n | 'updateToken'\n> {\n private readonly postEvent: PostEvent;\n\n private authPromise?: Promise<string | undefined>;\n\n private accessPromise?: Promise<boolean>;\n\n constructor({ postEvent, version, ...rest }: BiometryManagerProps) {\n super(rest, version, {\n auth: 'web_app_biometry_request_auth',\n openSettings: 'web_app_biometry_open_settings',\n requestAccess: 'web_app_biometry_request_access',\n updateToken: 'web_app_biometry_update_token',\n });\n this.postEvent = postEvent;\n }\n\n /**\n * Shows whether biometry is available.\n */\n get available(): boolean {\n return this.get('available');\n }\n\n /**\n * Shows whether permission to use biometrics has been granted.\n */\n get accessGranted(): boolean {\n return this.get('accessGranted');\n }\n\n /**\n * Shows whether if permission to use biometrics has been requested.\n */\n get accessRequested(): boolean {\n return this.get('accessRequested');\n }\n\n /**\n * Authenticates the user using biometrics.\n * @param options - method options.\n * @since 7.2\n * @returns Token from the local secure storage, if authentication was successful.\n */\n async authenticate({\n reason,\n ...rest\n }: BiometryManagerAuthenticateOptions): Promise<string | undefined> {\n if (!this.authPromise) {\n this.authPromise = request({\n ...rest,\n method: 'web_app_biometry_request_auth',\n event: 'biometry_auth_requested',\n postEvent: this.postEvent,\n params: {\n // TODO: Check if reason is empty works fine.\n reason: (reason || '').trim(),\n },\n })\n .then(({ token }) => token)\n .finally(() => this.authPromise = undefined);\n }\n return this.authPromise;\n }\n\n /**\n * A unique device identifier that can be used to match the token to the device.\n */\n get deviceId(): string {\n return this.get('deviceId');\n }\n\n /**\n * Opens the biometric access settings for bots. Useful when you need to request biometrics\n * access to users who haven't granted it yet.\n *\n * _Note that this method can be called only in response to user interaction with the Mini App\n * interface (e.g. a click inside the Mini App or on the main button)_.\n * @since 7.2\n */\n openSettings(): void {\n this.postEvent('web_app_biometry_open_settings');\n }\n\n /**\n * Requests permission to use biometrics.\n * @since 7.2\n * @returns Promise with true, if access was granted.\n */\n requestAccess({ reason, ...rest }: BiometryManagerRequestAccessOptions = {}): Promise<boolean> {\n if (!this.accessPromise) {\n this.accessPromise = request({\n ...rest,\n postEvent: this.postEvent,\n method: 'web_app_biometry_request_access',\n event: 'biometry_info_received',\n params: { reason: reason || '' },\n })\n .then((response) => {\n // Actualize local state.\n const formatted = formatEvent(response);\n this.set(formatted);\n\n return formatted.accessGranted;\n })\n .finally(() => this.accessPromise = undefined);\n }\n return this.accessPromise;\n }\n\n /**\n * The type of biometrics currently available on the device.\n */\n get biometryType(): BiometryType | undefined {\n return this.get('biometryType');\n }\n\n /**\n * Shows whether token was saved previously in the local secure storage.\n */\n get tokenSaved(): boolean {\n return this.get('tokenSaved');\n }\n\n /**\n * Updates the biometric token in a secure storage on the device.\n * @returns Promise with `true`, if token was updated.\n */\n async updateToken({ token, ...rest }: BiometryManagerUpdateTokenOptions = {}): Promise<boolean> {\n return ['removed', 'updated'].includes(\n (\n await request({\n ...rest,\n postEvent: this.postEvent,\n method: 'web_app_biometry_update_token',\n event: 'biometry_token_updated',\n params: { token: token || '' },\n })\n ).status,\n );\n }\n}\n","import { request } from '@/bridge/request.js';\nimport type { ExecuteWithOptions } from '@/types/index.js';\n\nimport { formatEvent } from './formatEvent.js';\nimport type { FormatBiometryInfoResult } from './formatEvent.js';\n\n/**\n * Requests biometry information.\n * @param options - additional execution options.\n */\nexport async function requestBiometryInfo(\n options?: ExecuteWithOptions,\n): Promise<FormatBiometryInfoResult> {\n return formatEvent(\n await request({\n ...(options || {}),\n method: 'web_app_biometry_get_info',\n event: 'biometry_info_received',\n }),\n );\n}\n","import { createComponentInitFn } from '@/misc/createComponentInitFn/createComponentInitFn.js';\nimport { supports } from '@/supports/supports.js';\n\nimport { BiometryManager } from './BiometryManager.js';\nimport { requestBiometryInfo } from './requestBiometryInfo.js';\n\n/**\n * @returns A promise with a new initialized instance of the `BiometryManager` class.\n * @see BiometryManager\n */\nexport const initBiometryManager = createComponentInitFn(\n 'biometryManager',\n async ({ postEvent, version, state }) => {\n return new BiometryManager({\n ...(state || supports('web_app_biometry_get_info', version)\n ? state || await requestBiometryInfo({ timeout: 1000 })\n : {\n available: false,\n accessGranted: false,\n accessRequested: false,\n tokenSaved: false,\n deviceId: '',\n }),\n version,\n postEvent,\n });\n },\n);\n","import { WithStateUtils } from '@/classes/WithStateUtils.js';\nimport type { StateEvents } from '@/classes/State/types.js';\nimport type { EventEmitter } from '@/events/event-emitter/EventEmitter.js';\n\ntype Emitter<StateShape extends object> = EventEmitter<StateEvents<StateShape>>;\n\nexport class WithTrackableState<StateShape extends object>\n extends WithStateUtils<StateShape> {\n /**\n * Adds a new event listener.\n */\n on: Emitter<StateShape>['on'] = this.state.on.bind(this.state);\n\n /**\n * Removes the event listener.\n */\n off: Emitter<StateShape>['off'] = this.state.off.bind(this.state);\n}\n","import { WithTrackableState } from '@/classes/WithTrackableState.js';\nimport type { PostEvent } from '@/bridge/methods/postEvent.js';\nimport type { ClosingBehaviorState } from '@/components/ClosingBehavior/types.js';\n\n/**\n * @see Usage: https://docs.telegram-mini-apps.com/platform/closing-behavior\n * @see API: https://docs.telegram-mini-apps.com/packages/tma-js-sdk/components/closing-behavior\n */\nexport class ClosingBehavior extends WithTrackableState<ClosingBehaviorState> {\n constructor(isConfirmationNeeded: boolean, private readonly postEvent: PostEvent) {\n super({ isConfirmationNeeded });\n }\n\n private set isConfirmationNeeded(value: boolean) {\n this.set('isConfirmationNeeded', value);\n this.postEvent('web_app_setup_closing_behavior', { need_confirmation: value });\n }\n\n /**\n * True, if the confirmation dialog should be shown while the user is trying to close\n * the Mini App.\n */\n get isConfirmationNeeded(): boolean {\n return this.get('isConfirmationNeeded');\n }\n\n /**\n * Disables the confirmation dialog when closing the Mini App.\n */\n disableConfirmation(): void {\n this.isConfirmationNeeded = false;\n }\n\n /**\n * Enables the confirmation dialog when closing the Mini App.\n */\n enableConfirmation(): void {\n this.isConfirmationNeeded = true;\n }\n}\n","import { createComponentInitFn } from '@/misc/createComponentInitFn/createComponentInitFn.js';\n\nimport { ClosingBehavior } from './ClosingBehavior.js';\n\n/**\n * @returns A new initialized instance of the `ClosingBehavior` class.\n * @see ClosingBehavior\n */\nexport const initClosingBehavior = createComponentInitFn(\n 'closingBehavior',\n ({\n postEvent,\n state = { isConfirmationNeeded: false },\n }) => new ClosingBehavior(state.isConfirmationNeeded, postEvent),\n);\n","import { createSupportsFn } from '@/supports/createSupportsFn.js';\nimport type { MiniAppsMethodName } from '@/bridge/methods/types/methods.js';\nimport type { SupportsFn } from '@/supports/types.js';\nimport type { Version } from '@/version/types.js';\n\nexport class WithSupports<SupportsMethod extends string> {\n constructor(\n /**\n * Mini Apps version.\n */\n version: Version,\n /**\n * Supports method schema.\n */\n supportsSchema: Record<SupportsMethod, MiniAppsMethodName>,\n ) {\n this.supports = createSupportsFn(version, supportsSchema);\n }\n\n /**\n * @returns True, if specified method is supported by the current component.\n */\n supports: SupportsFn<SupportsMethod>;\n}\n","import { createTypeError } from '../createTypeError.js';\nimport { ValueParser } from '../ValueParser/ValueParser.js';\nimport type { ArrayParserOfResult } from '../ArrayParser/types.js';\nimport type { AnyParser, Parser } from '../types.js';\nimport type { ValueParserParseResult } from '../ValueParser/types.js';\n\n/**\n * Parses incoming value as array.\n * @param value - value to parse.\n */\nfunction parseArray(value: unknown): unknown[] {\n if (Array.isArray(value)) {\n return value;\n }\n\n if (typeof value === 'string') {\n try {\n const json = JSON.parse(value);\n\n if (Array.isArray(json)) {\n return json;\n }\n } catch {}\n }\n throw createTypeError();\n}\n\nexport class ArrayParser<ItemType, IsOptional extends boolean>\n extends ValueParser<unknown[], IsOptional> {\n private itemParser: Parser<any>;\n\n constructor(\n itemParser: AnyParser<ItemType>,\n isOptional: IsOptional,\n type?: string,\n ) {\n super(parseArray, isOptional, type);\n\n this.itemParser = typeof itemParser === 'function'\n ? itemParser\n : itemParser.parse.bind(itemParser);\n }\n\n /**\n * Attempts to parse passed value\n * @param value - value to parse.\n * @throws {SDKError} ERR_PARSE\n * @see ERR_PARSE\n */\n override parse(value: unknown): ValueParserParseResult<ItemType[], IsOptional> {\n const arr = super.parse(value);\n return arr === undefined ? arr : arr.map(this.itemParser);\n }\n\n of<Item>(itemParser: AnyParser<Item>): ArrayParserOfResult<this, Item, IsOptional> {\n this.itemParser = typeof itemParser === 'function'\n ? itemParser\n : itemParser.parse.bind(itemParser);\n\n return this as ArrayParserOfResult<this, Item, IsOptional>;\n }\n}\n","import { ArrayParser } from '@/parsing/ArrayParser/ArrayParser.js';\n\n/**\n * Parses incoming value as an array.\n * @param parserTypeName - parser type name.\n */\nexport function array(parserTypeName?: string): ArrayParser<unknown, false> {\n return new ArrayParser((value) => value, false, parserTypeName);\n}\n","import { invokeCustomMethod } from '@/bridge/invokeCustomMethod.js';\nimport { WithSupports } from '@/classes/WithSupports.js';\nimport { array } from '@/parsing/parsers/array.js';\nimport { json } from '@/parsing/parsers/json.js';\nimport { string } from '@/parsing/parsers/string.js';\nimport type { PostEvent } from '@/bridge/methods/postEvent.js';\nimport type { CreateRequestIdFn } from '@/request-id/types.js';\nimport type { ExecuteWithTimeout } from '@/types/methods.js';\nimport type { Version } from '@/version/types.js';\n\nfunction objectFromKeys<K extends string, V>(keys: K[], value: V): Record<K, V> {\n return Object.fromEntries(keys.map((k) => [k, value])) as Record<K, V>;\n}\n\n// TODO: Usage.\n\n/**\n * @see API: https://docs.telegram-mini-apps.com/packages/tma-js-sdk/components/cloud-storage\n */\nexport class CloudStorage extends WithSupports<'delete' | 'get' | 'getKeys' | 'set'> {\n constructor(\n version: Version,\n private readonly createRequestId: CreateRequestIdFn,\n private readonly postEvent: PostEvent,\n ) {\n super(version, {\n delete: 'web_app_invoke_custom_method',\n get: 'web_app_invoke_custom_method',\n getKeys: 'web_app_invoke_custom_method',\n set: 'web_app_invoke_custom_method',\n });\n }\n\n /**\n * Deletes specified key or keys from the cloud storage.\n * @param keyOrKeys - key or keys to delete.\n * @param options - request execution options.\n */\n async delete(keyOrKeys: string | string[], options: ExecuteWithTimeout = {}): Promise<void> {\n const keys = Array.isArray(keyOrKeys) ? keyOrKeys : [keyOrKeys];\n if (keys.length) {\n await invokeCustomMethod(\n 'deleteStorageValues',\n { keys },\n this.createRequestId(),\n { ...options, postEvent: this.postEvent },\n );\n }\n }\n\n /**\n * Returns list of all keys presented in the cloud storage.\n * @param options - request execution options.\n */\n async getKeys(options: ExecuteWithTimeout = {}): Promise<string[]> {\n return array().of(string()).parse(\n await invokeCustomMethod(\n 'getStorageKeys',\n {},\n this.createRequestId(),\n { ...options, postEvent: this.postEvent },\n ),\n );\n }\n\n /**\n * Returns map, where key is one of the specified in keys argument, and value is according\n * storage value.\n * @param keys - keys list.\n * @param options - request execution options.\n */\n get<K extends string>(keys: K[], options?: ExecuteWithTimeout): Promise<Record<K, string>>;\n\n /**\n * Returns value of the specified key.\n * @param key - cloud storage key.\n * @param options - request execution options.\n * @return Value of the specified key. In case, key was not created previously, function\n * will return empty string.\n */\n get(key: string, options?: ExecuteWithTimeout): Promise<string>;\n\n async get(\n keyOrKeys: string | string[],\n options: ExecuteWithTimeout = {},\n ): Promise<string | Record<string, string>> {\n const keys = Array.isArray(keyOrKeys) ? keyOrKeys : [keyOrKeys];\n if (!keys.length) {\n return objectFromKeys(keys, '');\n }\n\n const data = await invokeCustomMethod(\n 'getStorageValues',\n { keys },\n this.createRequestId(),\n { ...options, postEvent: this.postEvent },\n );\n const result = json(objectFromKeys(keys, string()), 'CloudStorageData').parse(data);\n\n return Array.isArray(keyOrKeys) ? result : result[keyOrKeys];\n }\n\n /**\n * Saves specified value by key.\n * @param key - storage key.\n * @param value - storage value.\n * @param options - request execution options.\n */\n async set(key: string, value: string, options: ExecuteWithTimeout = {}): Promise<void> {\n await invokeCustomMethod(\n 'saveStorageValue',\n { key, value },\n this.createRequestId(),\n { ...options, postEvent: this.postEvent },\n );\n }\n}\n","import { createComponentInitFn } from '@/misc/createComponentInitFn/createComponentInitFn.js';\n\nimport { CloudStorage } from './CloudStorage.js';\n\n/**\n * @returns A new initialized instance of the `CloudStorage` class.\n * @see CloudStorage\n */\nexport const initCloudStorage = createComponentInitFn(\n ({ createRequestId, postEvent, version }) => {\n return new CloudStorage(version, createRequestId, postEvent);\n },\n);\n","import { WithSupports } from '@/classes/WithSupports.js';\nimport type { PostEvent } from '@/bridge/methods/postEvent.js';\nimport type {\n ImpactHapticFeedbackStyle,\n NotificationHapticFeedbackType,\n} from '@/bridge/methods/types/haptic.js';\nimport type { Version } from '@/version/types.js';\n\n/**\n * @see Usage: https://docs.telegram-mini-apps.com/platform/haptic-feedback\n * @see API: https://docs.telegram-mini-apps.com/packages/tma-js-sdk/components/haptic-feedback\n */\nexport class HapticFeedback\n extends WithSupports<'impactOccurred' | 'notificationOccurred' | 'selectionChanged'> {\n constructor(version: Version, private readonly postEvent: PostEvent) {\n super(version, {\n impactOccurred: 'web_app_trigger_haptic_feedback',\n notificationOccurred: 'web_app_trigger_haptic_feedback',\n selectionChanged: 'web_app_trigger_haptic_feedback',\n });\n }\n\n /**\n * A method tells that an impact occurred. The Telegram app may play the\n * appropriate haptics based on style value passed.\n * @param style - impact style.\n */\n impactOccurred(style: ImpactHapticFeedbackStyle): void {\n this.postEvent('web_app_trigger_haptic_feedback', {\n type: 'impact',\n impact_style: style,\n });\n }\n\n /**\n * A method tells that a task or action has succeeded, failed, or produced\n * a warning. The Telegram app may play the appropriate haptics based on\n * type value passed.\n * @param type - notification type.\n */\n notificationOccurred(type: NotificationHapticFeedbackType): void {\n this.postEvent('web_app_trigger_haptic_feedback', {\n type: 'notification',\n notification_type: type,\n });\n }\n\n /**\n * A method tells that the user has changed a selection. The Telegram app\n * may play the appropriate haptics.\n *\n * Do not use this feedback when the user makes or confirms a selection;\n * use it only when the selection changes.\n */\n selectionChanged(): void {\n this.postEvent('web_app_trigger_haptic_feedback', { type: 'selection_change' });\n }\n}\n","import { createComponentInitFn } from '@/misc/createComponentInitFn/createComponentInitFn.js';\n\nimport { HapticFeedback } from './HapticFeedback.js';\n\n/**\n * @returns A new initialized instance of the `HapticFeedback` class.\n * @see HapticFeedback\n */\nexport const initHapticFeedback = createComponentInitFn(\n ({ version, postEvent }) => new HapticFeedback(version, postEvent),\n);\n","import type {\n Chat,\n ChatType,\n InitDataParsed,\n User,\n} from './types.js';\n\n/**\n * @see Usage: https://docs.telegram-mini-apps.com/platform/init-data\n * @see API: https://docs.telegram-mini-apps.com/packages/tma-js-sdk/init-data\n */\nexport class InitData {\n constructor(private readonly initData: InitDataParsed) {\n }\n\n /**\n * @see InitDataParsed.authDate\n */\n get authDate(): Date {\n return this.initData.authDate;\n }\n\n /**\n * @see InitDataParsed.canSendAfter\n */\n get canSendAfter(): number | undefined {\n return this.initData.canSendAfter;\n }\n\n /**\n * Date after which it is allowed to call\n * the [answerWebAppQuery](https://core.telegram.org/bots/api#answerwebappquery) method.\n */\n get canSendAfterDate(): Date | undefined {\n const { canSendAfter } = this;\n\n return canSendAfter\n ? new Date(this.authDate.getTime() + canSendAfter * 1000)\n : undefined;\n }\n\n /**\n * @see InitDataParsed.chat\n */\n get chat(): Chat | undefined {\n return this.initData.chat;\n }\n\n /**\n * @see InitDataParsed.chatType\n */\n get chatType(): ChatType | undefined {\n return this.initData.chatType;\n }\n\n /**\n * @see InitDataParsed.chatInstance\n */\n get chatInstance(): string | undefined {\n return this.initData.chatInstance;\n }\n\n /**\n * @see InitDataParsed.hash\n */\n get hash(): string {\n return this.initData.hash;\n }\n\n /**\n * @see InitDataParsed.queryId\n */\n get queryId(): string | undefined {\n return this.initData.queryId;\n }\n\n /**\n * @see InitDataParsed.receiver\n */\n get receiver(): User | undefined {\n return this.initData.receiver;\n }\n\n /**\n * @see InitDataParsed.startParam\n */\n get startParam(): string | undefined {\n return this.initData.startParam;\n }\n\n /**\n * @see InitDataParsed.user\n */\n get user(): User | undefined {\n return this.initData.user;\n }\n}\n","import { createComponentInitFn } from '@/misc/createComponentInitFn/createComponentInitFn.js';\n\nimport { InitData } from './InitData.js';\n\n/**\n * @returns A new initialized instance of the `InitData` class or undefined.\n * @see InitData\n */\nexport const initInitData = createComponentInitFn(\n ({ initData }) => (initData ? new InitData(initData) : undefined),\n);\n","import { initData } from './parsers/initData.js';\nimport type { InitDataParsed } from './types.js';\n\n/**\n * Parses incoming value as init data.\n * @param value - value to parse.\n */\nexport function parseInitData(value: unknown): InitDataParsed {\n return initData().parse(value);\n}\n","import { request } from '@/bridge/request.js';\nimport { WithSupportsAndTrackableState } from '@/classes/WithSupportsAndTrackableState.js';\nimport type { InvoiceStatus } from '@/bridge/events/types.js';\nimport type { PostEvent } from '@/bridge/methods/postEvent.js';\nimport type { Version } from '@/version/types.js';\n\nimport type { InvoiceState } from './types.js';\n\n// TODO: Usage.\n\n/**\n * @see API: https://docs.telegram-mini-apps.com/packages/tma-js-sdk/components/invoice\n */\nexport class Invoice extends WithSupportsAndTrackableState<InvoiceState, 'open'> {\n constructor(\n isOpened: boolean,\n version: Version,\n private readonly postEvent: PostEvent,\n ) {\n super({ isOpened }, version, { open: 'web_app_open_invoice' });\n }\n\n private set isOpened(value) {\n this.set('isOpened', value);\n }\n\n /**\n * True if invoice is currently opened.\n */\n get isOpened(): boolean {\n return this.get('isOpened');\n }\n\n /**\n * Opens an invoice using its slug.\n * @param slug - invoice slug.\n * @throws {Error} Invoice is already opened.\n */\n open(slug: string): Promise<InvoiceStatus>;\n\n /**\n * Opens an invoice using its url. It expects passing link in full format, with hostname \"t.me\".\n * @param url - invoice URL.\n * @param type - value type.\n * @throws {Error} Invoice is already opened.\n */\n open(url: string, type: 'url'): Promise<InvoiceStatus>;\n\n async open(urlOrSlug: string, type?: 'url'): Promise<InvoiceStatus> {\n if (this.isOpened) {\n throw new Error('Invoice is already opened');\n }\n\n let slug: string;\n if (!type) {\n slug = urlOrSlug;\n } else {\n const { hostname, pathname } = new URL(urlOrSlug, window.location.href);\n if (hostname !== 't.me') {\n throw new Error(`Incorrect hostname: ${hostname}`);\n }\n\n // Valid examples:\n // \"/invoice/my-slug\"\n // \"/$my-slug\"\n const match = pathname.match(/^\\/(\\$|invoice\\/)([A-Za-z0-9\\-_=]+)$/);\n if (!match) {\n throw new Error('Link pathname has incorrect format. Expected to receive \"/invoice/{slug}\" or \"/${slug}\"');\n }\n [, , slug] = match;\n }\n\n this.isOpened = true;\n\n try {\n const result = await request({\n method: 'web_app_open_invoice',\n event: 'invoice_closed',\n params: { slug },\n postEvent: this.postEvent,\n capture(data) {\n return slug === data.slug;\n },\n });\n\n return result.status;\n } finally {\n this.isOpened = false;\n }\n }\n}\n","import { createComponentInitFn } from '@/misc/createComponentInitFn/createComponentInitFn.js';\n\nimport { Invoice } from './Invoice.js';\n\n/**\n * @returns A new initialized instance of the `Invoice` class.\n * @see Invoice\n */\nexport const initInvoice = createComponentInitFn(\n ({ version, postEvent }) => new Invoice(false, version, postEvent),\n);\n","import { off } from '@/bridge/events/listening/off.js';\nimport { on } from '@/bridge/events/listening/on.js';\nimport { WithStateUtils } from '@/classes/WithStateUtils.js';\nimport type { PostEvent } from '@/bridge/methods/postEvent.js';\nimport type { RGB } from '@/colors/types.js';\nimport type {\n MainButtonEvents,\n MainButtonParams,\n MainButtonProps,\n MainButtonState,\n} from '@/components/MainButton/types.js';\nimport type { EventEmitter } from '@/events/event-emitter/EventEmitter.js';\n\ntype Emitter = EventEmitter<MainButtonEvents>;\n\n/**\n * @see Usage: https://docs.telegram-mini-apps.com/platform/main-button\n * @see API: https://docs.telegram-mini-apps.com/packages/tma-js-sdk/components/main-button\n */\nexport class MainButton extends WithStateUtils<MainButtonState> {\n private readonly postEvent: PostEvent;\n\n constructor({ postEvent, ...rest }: MainButtonProps) {\n super(rest);\n this.postEvent = postEvent;\n }\n\n /**\n * The MainButton background color.\n */\n get bgColor(): RGB {\n return this.get('bgColor');\n }\n\n /**\n * Sends current local state to the Telegram application.\n */\n private commit(): void {\n // We should not commit changes until payload is correct. We could\n // have some invalid values in case, button instance was created\n // with empty values. Otherwise, an unexpected behavior could be received.\n if (this.text === '') {\n return;\n }\n\n this.postEvent('web_app_setup_main_button', {\n is_visible: this.isVisible,\n is_active: this.isEnabled,\n is_progress_visible: this.isLoaderVisible,\n text: this.text,\n color: this.bgColor,\n text_color: this.textColor,\n });\n }\n\n /**\n * Disables the MainButton.\n * @see Does not work on Android: https://github.com/Telegram-Mini-Apps/issues/issues/1\n */\n disable(): this {\n this.isEnabled = false;\n return this;\n }\n\n /**\n * Enables the MainButton.\n */\n enable(): this {\n this.isEnabled = true;\n return this;\n }\n\n /**\n * Hides the MainButton.\n */\n hide(): this {\n this.isVisible = false;\n return this;\n }\n\n /**\n * Hides the MainButton loading indicator.\n */\n hideLoader(): this {\n this.isLoaderVisible = false;\n return this;\n }\n\n private set isEnabled(isEnabled: boolean) {\n this.setParams({ isEnabled });\n }\n\n /**\n * True if the MainButton is enabled.\n */\n get isEnabled(): boolean {\n return this.get('isEnabled');\n }\n\n private set isLoaderVisible(isLoaderVisible: boolean) {\n this.setParams({ isLoaderVisible });\n }\n\n /**\n * True if the MainButton loader is visible.\n */\n get isLoaderVisible(): boolean {\n return this.get('isLoaderVisible');\n }\n\n private set isVisible(isVisible: boolean) {\n this.setParams({ isVisible });\n }\n\n /**\n * True if the MainButton is visible.\n */\n get isVisible(): boolean {\n return this.get('isVisible');\n }\n\n /**\n * Adds a new event listener.\n * @param event - event to listen.\n * @param listener - listener to add.\n */\n on: Emitter['on'] = (event, listener) => (\n event === 'click'\n ? on('main_button_pressed', listener)\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n : this.state.on(event, listener as any)\n );\n\n /**\n * Removes the event listener.\n * @param event - event to listen.\n * @param listener - listener to remove.\n */\n off: Emitter['off'] = (event, listener) => (\n event === 'click'\n ? off('main_button_pressed', listener)\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n : this.state.off(event, listener as any)\n );\n\n /**\n * Shows the MainButton.\n *\n * Note that opening the Mini App from the attachment menu hides the main button until the\n * user interacts with the Mini App interface.\n */\n show(): this {\n this.isVisible = true;\n return this;\n }\n\n /**\n * Shows a loading indicator on the Main Button.\n */\n showLoader(): this {\n this.isLoaderVisible = true;\n return this;\n }\n\n /**\n * Sets a new MainButton text. Minimal length for the text is 1 symbol, and maximum is 64 symbols.\n * @param text - a new text.\n */\n setText(text: string): this {\n return this.setParams({ text });\n }\n\n /**\n * Sets a new Main Button text color.\n * @param textColor - new text color.\n */\n setTextColor(textColor: RGB): this {\n return this.setParams({ textColor });\n }\n\n /**\n * Updates current Main Button color.\n * @param bgColor - color to set.\n */\n setBgColor(bgColor: RGB): this {\n return this.setParams({ bgColor });\n }\n\n /**\n * Allows setting multiple Main Button parameters.\n * @param params - Main Button parameters.\n */\n setParams(params: Partial<MainButtonParams>): this {\n this.set(params);\n this.commit();\n return this;\n }\n\n /**\n * The MainButton text.\n */\n get text(): string {\n return this.get('text');\n }\n\n /**\n * The MainButton text color.\n */\n get textColor(): RGB {\n return this.get('textColor');\n }\n}\n","import { createComponentInitFn } from '@/misc/createComponentInitFn/createComponentInitFn.js';\n\nimport { MainButton } from './MainButton.js';\n\n/**\n * @returns A new initialized instance of the `MainButton` class.\n * @see MainButton\n */\nexport const initMainButton = createComponentInitFn(\n 'mainButton',\n ({\n postEvent,\n themeParams,\n state = {\n isVisible: false,\n isEnabled: false,\n text: '',\n isLoaderVisible: false,\n textColor: themeParams.buttonTextColor || '#ffffff',\n bgColor: themeParams.buttonColor || '#000000',\n },\n }) => new MainButton({ ...state, postEvent }),\n);\n","import { date } from '@/parsing/parsers/date.js';\nimport { json } from '@/parsing/parsers/json.js';\nimport { number } from '@/parsing/parsers/number.js';\nimport { searchParams } from '@/parsing/parsers/searchParams.js';\nimport { string } from '@/parsing/parsers/string.js';\nimport type { ValueParser } from '@/parsing/ValueParser/ValueParser.js';\n\nimport type { RequestedContact } from '../types.js';\n\n/**\n * Returns function which parses incoming value as a contact information.\n */\nexport function contact(): ValueParser<RequestedContact, false> {\n return searchParams({\n contact: json({\n userId: {\n type: number(),\n from: 'user_id',\n },\n phoneNumber: {\n type: string(),\n from: 'phone_number',\n },\n firstName: {\n type: string(),\n from: 'first_name',\n },\n lastName: {\n type: string().optional(),\n from: 'last_name',\n },\n }),\n authDate: {\n type: date(),\n from: 'auth_date',\n },\n hash: string(),\n }, 'RequestedContact');\n}\n","import { supports } from '@/supports/supports.js';\nimport type {\n MiniAppsMethodVersionedParams,\n MiniAppsMethodWithVersionedParams,\n} from '@/bridge/methods/types/methods.js';\nimport type { SupportsFn } from '@/supports/types.js';\nimport type { Version } from '@/version/types.js';\n\ntype HasCheckSupportMethodTuple = {\n [M in MiniAppsMethodWithVersionedParams]: [M, MiniAppsMethodVersionedParams<M>]\n}[MiniAppsMethodWithVersionedParams];\n\n/**\n * Returns function, which accepts predefined method name and checks if it is supported\n * via passed schema and version.\n * @param schema - object which contains methods names and TWA methods with specified parameter\n * as a dependency.\n * @param version - platform version.\n */\nexport function createSupportsParamFn<Method extends string>(\n version: Version,\n schema: Record<Method, HasCheckSupportMethodTuple>,\n): SupportsFn<Method> {\n return (method) => {\n const [tmaMethod, param] = schema[method];\n\n return supports(tmaMethod, param, version);\n };\n}\n","/**\n * Awaits for specified amount of time.\n * @param duration - duration in ms to await.\n */\nexport function sleep(duration: number): Promise<void> {\n return new Promise((res) => {\n setTimeout(res, duration);\n });\n}\n","import { invokeCustomMethod } from '@/bridge/invokeCustomMethod.js';\nimport { request } from '@/bridge/request.js';\nimport { WithSupportsAndTrackableState } from '@/classes/WithSupportsAndTrackableState.js';\nimport { isColorDark } from '@/colors/isColorDark.js';\nimport { isRGB } from '@/colors/isRGB.js';\nimport { contact } from '@/components/MiniApp/parsing/contact.js';\nimport { createSupportsParamFn } from '@/supports/createSupportsParamFn.js';\nimport { createTimeoutError } from '@/timeout/createTimeoutError.js';\nimport { sleep } from '@/timeout/sleep.js';\nimport { withTimeout } from '@/timeout/withTimeout.js';\nimport type { PhoneRequestedStatus, WriteAccessRequestedStatus } from '@/bridge/events/types.js';\nimport type { PostEvent } from '@/bridge/methods/postEvent.js';\nimport type { SwitchInlineQueryChatType } from '@/bridge/methods/types/methods.js';\nimport type { RGB } from '@/colors/types.js';\nimport type {\n MiniAppHeaderColor,\n MiniAppProps,\n MiniAppState,\n RequestedContact,\n} from '@/components/MiniApp/types.js';\nimport type { CreateRequestIdFn } from '@/request-id/types.js';\nimport type { SupportsFn } from '@/supports/types.js';\nimport type { ExecuteWithTimeout } from '@/types/methods.js';\n\n/**\n * Provides common Mini Apps functionality not covered by other system components.\n */\nexport class MiniApp extends WithSupportsAndTrackableState<\n MiniAppState,\n | 'requestPhoneAccess'\n | 'requestWriteAccess'\n | 'switchInlineQuery'\n | 'setHeaderColor'\n | 'setBackgroundColor'\n> {\n private readonly botInline: boolean;\n\n private readonly postEvent: PostEvent;\n\n private readonly createRequestId: CreateRequestIdFn;\n\n private requestPhoneAccessPromise: Promise<PhoneRequestedStatus> | undefined;\n\n private requestWriteAccessPromise: Promise<WriteAccessRequestedStatus> | undefined;\n\n constructor({ postEvent, createRequestId, version, botInline, ...rest }: MiniAppProps) {\n super(rest, version, {\n requestPhoneAccess: 'web_app_request_phone',\n requestWriteAccess: 'web_app_request_write_access',\n switchInlineQuery: 'web_app_switch_inline_query',\n setHeaderColor: 'web_app_set_header_color',\n setBackgroundColor: 'web_app_set_background_color',\n });\n\n this.createRequestId = createRequestId;\n this.postEvent = postEvent;\n this.botInline = botInline;\n\n const supportsOriginal = this.supports.bind(this);\n this.supports = (method) => {\n if (!supportsOriginal(method)) {\n return false;\n }\n\n // web_app_switch_inline_query requires a Mini App to be in inline mode, that's why we\n // add 1 more check here.\n return method !== 'switchInlineQuery' || botInline;\n };\n\n this.supportsParam = createSupportsParamFn(version, {\n 'setHeaderColor.color': ['web_app_set_header_color', 'color'],\n });\n }\n\n /**\n * Attempts to get requested contact.\n * @param timeout - request timeout.\n */\n private async getRequestedContact({\n timeout = 10000,\n }: ExecuteWithTimeout = {}): Promise<RequestedContact> {\n return contact().parse(\n await invokeCustomMethod(\n 'getRequestedContact',\n {},\n this.createRequestId(),\n { postEvent: this.postEvent, timeout },\n ),\n );\n }\n\n /**\n * The Mini App background color.\n * @example \"#ffaabb\"\n */\n get bgColor(): RGB {\n return this.get('bgColor');\n }\n\n /**\n * Closes the Mini App.\n * @param returnBack - should the application be wrapped into the bottom bar.\n */\n close(returnBack?: boolean): void {\n this.postEvent('web_app_close', { return_back: returnBack });\n }\n\n /**\n * The Mini App header color.\n * @example \"#ffaabb\"\n * @example \"bg_color\"\n */\n get headerColor(): MiniAppHeaderColor {\n return this.get('headerColor');\n }\n\n /**\n * True if the Mini App is currently launched in bot inline mode.\n */\n get isBotInline(): boolean {\n return this.botInline;\n }\n\n /**\n * True if the current Mini App background color is recognized as dark.\n */\n get isDark(): boolean {\n return isColorDark(this.bgColor);\n }\n\n /**\n * Informs the Telegram app that the Mini App is ready to be displayed.\n *\n * It is recommended to call this method as early as possible, as soon as all essential\n * interface elements loaded. Once this method called, the loading placeholder is hidden\n * and the Mini App shown.\n *\n * If the method not called, the placeholder will be hidden only when the page fully loaded.\n */\n ready(): void {\n this.postEvent('web_app_ready');\n }\n\n /**\n * Requests current user contact information. In contrary to requestPhoneAccess, this method\n * returns promise with contact information that rejects in case, user denied access, or request\n * failed.\n * @param options - additional options.\n */\n async requestContact({ timeout = 5000 }: ExecuteWithTimeout = {}): Promise<RequestedContact> {\n // First of all, let's try to get the requested contact. Probably, we already requested\n // it before.\n try {\n return await this.getRequestedContact();\n } catch { /* empty */\n }\n\n // Then, request access to user's phone.\n const status = await this.requestPhoneAccess();\n if (status !== 'sent') {\n throw new Error('Access denied.');\n }\n\n // Expected deadline.\n const deadlineAt = Date.now() + timeout;\n\n // Time to wait before executing the next request.\n let sleepTime = 50;\n\n // We are trying to retrieve the requested contact until deadline was reached.\n return withTimeout(async () => {\n while (Date.now() < deadlineAt) {\n try {\n return await this.getRequestedContact();\n } catch {}\n\n // Sleep for some time.\n await sleep(sleepTime);\n\n // Increase the sleep time not to kill the backend service.\n sleepTime += 50;\n }\n\n throw createTimeoutError(timeout);\n }, timeout);\n }\n\n /**\n * Requests current user phone access. Method returns promise, which resolves\n * status of the request. In case, user accepted the request, Mini App bot will receive\n * the according notification.\n *\n * To obtain the retrieved information instead, utilize the `requestContact` method.\n * @param options - additional options.\n * @see requestContact\n */\n async requestPhoneAccess(options: ExecuteWithTimeout = {}): Promise<PhoneRequestedStatus> {\n if (!this.requestPhoneAccessPromise) {\n this.requestPhoneAccessPromise = request({\n ...options,\n method: 'web_app_request_phone',\n event: 'phone_requested',\n postEvent: this.postEvent,\n })\n .then(({ status }) => status)\n .finally(() => this.requestPhoneAccessPromise = undefined);\n }\n return this.requestPhoneAccessPromise;\n }\n\n /**\n * Requests write message access to current user.\n * @param options - additional options.\n */\n async requestWriteAccess(options: ExecuteWithTimeout = {}): Promise<WriteAccessRequestedStatus> {\n if (!this.requestWriteAccessPromise) {\n this.requestWriteAccessPromise = request({\n ...options,\n method: 'web_app_request_write_access',\n event: 'write_access_requested',\n postEvent: this.postEvent,\n })\n .then(({ status }) => status)\n .finally(() => this.requestWriteAccessPromise = undefined);\n }\n return this.requestWriteAccessPromise;\n }\n\n /**\n * A method used to send data to the bot. When this method called, a service message sent to\n * the bot containing the data of the length up to 4096 bytes, and the Mini App closed. See the\n * field `web_app_data` in the class [Message](https://core.telegram.org/bots/api#message).\n *\n * This method is only available for Mini Apps launched via a Keyboard button.\n * @param data - data to send to bot.\n * @throws {Error} data has incorrect size.\n */\n sendData(data: string): void {\n const { size } = new Blob([data]);\n if (!size || size > 4096) {\n throw new Error(`Passed data has incorrect size: ${size}`);\n }\n this.postEvent('web_app_data_send', { data });\n }\n\n /**\n * Updates current Mini App header color.\n *\n * @see No effect on desktop: https://github.com/Telegram-Mini-Apps/tma.js/issues/9\n * @see Works incorrectly in Android: https://github.com/Telegram-Mini-Apps/tma.js/issues/8\n * @param color - color key or RGB color.\n */\n setHeaderColor(color: MiniAppHeaderColor): void {\n this.postEvent('web_app_set_header_color', isRGB(color) ? { color } : { color_key: color });\n this.set('headerColor', color);\n }\n\n /**\n * Updates current Mini App background color.\n *\n * @see No effect on desktop: https://github.com/Telegram-Mini-Apps/tma.js/issues/9\n * @see Works incorrectly in Android: https://github.com/Telegram-Mini-Apps/tma.js/issues/8\n * @param color - RGB color.\n */\n setBgColor(color: RGB): void {\n this.postEvent('web_app_set_background_color', { color });\n this.set('bgColor', color);\n }\n\n /**\n * Checks if specified method parameter is supported by current component.\n */\n supportsParam: SupportsFn<'setHeaderColor.color'>;\n\n /**\n * Inserts the bot's username and the specified inline query in the current chat's input field.\n * Query may be empty, in which case only the bot's username will be inserted. The client prompts\n * the user to choose a specific chat, then opens that chat and inserts the bot's username and\n * the specified inline query in the input field.\n * @param text - text which should be inserted in the input after the current bot name. Max\n * length is 256 symbols.\n * @param chatTypes - List of chat types which could be chosen to send the message. Could be\n * empty list.\n */\n switchInlineQuery(text: string, chatTypes: SwitchInlineQueryChatType[] = []): void {\n if (!this.supports('switchInlineQuery') && !this.isBotInline) {\n throw new Error('Method is unsupported because Mini App should be launched in inline mode.');\n }\n this.postEvent('web_app_switch_inline_query', { query: text, chat_types: chatTypes });\n }\n}\n","import { createComponentInitFn } from '@/misc/createComponentInitFn/createComponentInitFn.js';\n\nimport { MiniApp } from './MiniApp.js';\n\n/**\n * @returns A new initialized instance of the `MiniApp` class.\n * @see MiniApp\n */\nexport const initMiniApp = createComponentInitFn(\n 'miniApp',\n ({\n themeParams,\n botInline = false,\n state = {\n bgColor: themeParams.bgColor || '#ffffff',\n headerColor: themeParams.headerBgColor || '#000000',\n },\n ...rest\n }) => new MiniApp({ ...rest, ...state, botInline }),\n);\n","import type { PopupButton, PopupParams as BridgePopupParams } from '@/bridge/methods/types/popup.js';\n\nimport type { OpenPopupOptions } from './types.js';\n\n/**\n * Prepares popup parameters before sending them to native app.\n * @param params - popup parameters.\n */\nexport function preparePopupParams(params: OpenPopupOptions): BridgePopupParams {\n const message = params.message.trim();\n const title = (params.title || '').trim();\n const buttons = params.buttons || [];\n let preparedButtons: PopupButton[];\n\n // Check title.\n if (title.length > 64) {\n throw new Error(`Title has incorrect size: ${title.length}`);\n }\n\n // Check message.\n if (!message.length || message.length > 256) {\n throw new Error(`Message has incorrect size: ${message.length}`);\n }\n\n // Check buttons.\n if (buttons.length > 3) {\n throw new Error(`Buttons have incorrect size: ${buttons.length}`);\n }\n\n // Append button in case, there are no buttons passed.\n if (!buttons.length) {\n preparedButtons = [{ type: 'close', id: '' }];\n } else {\n // Otherwise, check all the buttons.\n preparedButtons = buttons.map((b) => {\n const { id = '' } = b;\n\n // Check button ID.\n if (id.length > 64) {\n throw new Error(`Button ID has incorrect size: ${id}`);\n }\n\n if (!b.type || b.type === 'default' || b.type === 'destructive') {\n const text = b.text.trim();\n\n if (!text.length || text.length > 64) {\n const type = b.type || 'default';\n\n throw new Error(`Button text with type \"${type}\" has incorrect size: ${b.text.length}`);\n }\n\n return { ...b, text, id };\n }\n\n return { ...b, id };\n });\n }\n return { title, message, buttons: preparedButtons };\n}\n","import { request } from '@/bridge/request.js';\nimport { WithSupportsAndTrackableState } from '@/classes/WithSupportsAndTrackableState.js';\nimport { preparePopupParams } from '@/components/Popup/preparePopupParams.js';\nimport type { PostEvent } from '@/bridge/methods/postEvent.js';\nimport type { OpenPopupOptions, PopupState } from '@/components/Popup/types.js';\nimport type { Version } from '@/version/types.js';\n\n/**\n * @see Usage: https://docs.telegram-mini-apps.com/platform/popup\n * @see API: https://docs.telegram-mini-apps.com/packages/tma-js-sdk/components/popup\n */\nexport class Popup extends WithSupportsAndTrackableState<PopupState, 'open'> {\n constructor(isOpened: boolean, version: Version, private readonly postEvent: PostEvent) {\n super({ isOpened }, version, { open: 'web_app_open_popup' });\n }\n\n private set isOpened(value) {\n this.set('isOpened', value);\n }\n\n /**\n * True if the Popup is opened.\n */\n get isOpened(): boolean {\n return this.get('isOpened');\n }\n\n /**\n * A method that shows a native popup described by the `params` argument.\n * Promise will be resolved when popup is closed. Resolved value will have\n * an identifier of pressed button.\n *\n * In case, user clicked outside the popup or clicked top right popup close\n * button, null will be returned.\n *\n * @param options - popup parameters.\n * @throws {Error} Popup is already opened.\n */\n async open(options: OpenPopupOptions): Promise<string | null> {\n if (this.isOpened) {\n throw new Error('Popup is already opened.');\n }\n\n this.isOpened = true;\n\n try {\n const { button_id: buttonId = null } = await request({\n event: 'popup_closed',\n method: 'web_app_open_popup',\n postEvent: this.postEvent,\n params: preparePopupParams(options),\n });\n return buttonId;\n } finally {\n this.isOpened = false;\n }\n }\n}\n","import { createComponentInitFn } from '@/misc/createComponentInitFn/createComponentInitFn.js';\n\nimport { Popup } from './Popup.js';\n\n/**\n * @returns A new initialized instance of the `Popup` class.\n * @see Popup\n */\nexport const initPopup = createComponentInitFn(\n ({ postEvent, version }) => new Popup(false, version, postEvent),\n);\n","import { request } from '@/bridge/request.js';\nimport { WithSupportsAndTrackableState } from '@/classes/WithSupportsAndTrackableState.js';\nimport type { PostEvent } from '@/bridge/methods/postEvent.js';\nimport type { Version } from '@/version/types.js';\n\nimport { QRScannerOpenOptions, QRScannerState } from './types.js';\n\n// TODO: Usage\n\n/**\n * @see API: https://docs.telegram-mini-apps.com/packages/tma-js-sdk/components/qr-scanner\n */\nexport class QRScanner extends WithSupportsAndTrackableState<QRScannerState, 'close' | 'open'> {\n constructor(isOpened: boolean, version: Version, private readonly postEvent: PostEvent) {\n super({ isOpened }, version, {\n close: 'web_app_close_scan_qr_popup',\n open: 'web_app_open_scan_qr_popup',\n });\n }\n\n /**\n * Closes the scanner.\n */\n close(): void {\n this.postEvent('web_app_close_scan_qr_popup');\n this.isOpened = false;\n }\n\n private set isOpened(value) {\n this.set('isOpened', value);\n }\n\n /**\n * Returns true if the scanner is currently opened.\n */\n get isOpened(): boolean {\n return this.get('isOpened');\n }\n\n /**\n * Opens the scanner with the specified title shown to user.\n * The method returns a promise with a scanned QR content and null if the scanner was closed.\n * @param options - method options.\n */\n async open(options?: QRScannerOpenOptions): Promise<string | null>;\n /**\n * Opens the scanner with the specified title shown to user.\n * The method returns a promise with a scanned QR content and null if the scanner was closed.\n * @param text - title to display.\n */\n async open(text?: string): Promise<string | null>;\n async open(textOrOptions?: QRScannerOpenOptions | string): Promise<string | null> {\n if (this.isOpened) {\n throw new Error('The scanner is already opened');\n }\n\n const { text, capture }: QRScannerOpenOptions = (\n typeof textOrOptions === 'string'\n ? { text: textOrOptions }\n : textOrOptions\n ) || {};\n this.isOpened = true;\n\n try {\n const result = await request({\n method: 'web_app_open_scan_qr_popup',\n event: ['qr_text_received', 'scan_qr_popup_closed'],\n postEvent: this.postEvent,\n params: { text },\n capture(ev) {\n return ev.event === 'scan_qr_popup_closed' || !capture || capture(ev.payload);\n },\n }) || {};\n\n const qr = result.data || null;\n if (qr) {\n this.close();\n }\n return qr;\n } finally {\n this.isOpened = false;\n }\n }\n\n // TODO: Streaming mode, allowing to scan several QRs until closed.\n}\n","import { createComponentInitFn } from '@/misc/createComponentInitFn/createComponentInitFn.js';\n\nimport { QRScanner } from './QRScanner.js';\n\n/**\n * @returns A new initialized instance of the `QRScanner` class.\n * @see QRScanner\n */\nexport const initQRScanner = createComponentInitFn(\n ({ version, postEvent }) => new QRScanner(false, version, postEvent),\n);\n","import { off } from '@/bridge/events/listening/off.js';\nimport { on } from '@/bridge/events/listening/on.js';\nimport { WithSupportsAndStateUtils } from '@/classes/WithSupportsAndStateUtils.js';\nimport type { PostEvent } from '@/bridge/methods/postEvent.js';\nimport type {\n SettingsButtonEvents,\n SettingsButtonState,\n} from '@/components/SettingsButton/types.js';\nimport type { EventEmitter } from '@/events/event-emitter/EventEmitter.js';\nimport type { Version } from '@/version/types.js';\n\ntype Emitter = EventEmitter<SettingsButtonEvents>;\n\nexport class SettingsButton extends WithSupportsAndStateUtils<SettingsButtonState, 'show' | 'hide'> {\n constructor(isVisible: boolean, version: Version, private readonly postEvent: PostEvent) {\n super({ isVisible }, version, {\n show: 'web_app_setup_settings_button',\n hide: 'web_app_setup_settings_button',\n });\n }\n\n private set isVisible(visible: boolean) {\n this.set('isVisible', visible);\n this.postEvent('web_app_setup_settings_button', { is_visible: visible });\n }\n\n /**\n * True if the SettingsButton is visible.\n */\n get isVisible(): boolean {\n return this.get('isVisible');\n }\n\n /**\n * Hides the SettingsButton.\n */\n hide(): void {\n this.isVisible = false;\n }\n\n /**\n * Adds a new event listener.\n * @param event - event to listen.\n * @param listener - listener to add.\n */\n on: Emitter['on'] = (event, listener) => (\n event === 'click'\n ? on('settings_button_pressed', listener)\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n : this.state.on(event, listener as any)\n );\n\n /**\n * Removes the event listener.\n * @param event - event to listen.\n * @param listener - listener to remove.\n */\n off: Emitter['off'] = (event, listener) => (\n event === 'click'\n ? off('settings_button_pressed', listener)\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n : this.state.off(event, listener as any)\n );\n\n /**\n * Shows the SettingsButton.\n */\n show(): void {\n this.isVisible = true;\n }\n}\n","import { createComponentInitFn } from '@/misc/createComponentInitFn/createComponentInitFn.js';\n\nimport { SettingsButton } from './SettingsButton.js';\n\n/**\n * @returns A new initialized instance of the `SettingsButton` class.\n * @see SettingsButton\n */\nexport const initSettingsButton = createComponentInitFn(\n 'settingsButton',\n ({\n version,\n postEvent,\n state = { isVisible: false },\n }) => new SettingsButton(state.isVisible, version, postEvent),\n);\n","import { themeParams } from '@/components/ThemeParams/parsing/themeParams.js';\n\nimport type { ThemeParamsParsed } from '../types.js';\n\n/**\n * Parses incoming value as theme parameters.\n * @param value - value to parse.\n */\nexport function parseThemeParams(value: unknown): ThemeParamsParsed {\n return themeParams().parse(value);\n}\n","import { on } from '@/bridge/events/listening/on.js';\nimport { WithTrackableState } from '@/classes/WithTrackableState.js';\nimport { isColorDark } from '@/colors/isColorDark.js';\nimport type { RGB } from '@/colors/types.js';\nimport type { RemoveEventListenerFn } from '@/events/types.js';\n\nimport { parseThemeParams } from './parsing/parseThemeParams.js';\nimport type { ThemeParamsParsed, ThemeParamsState } from './types.js';\n\n/**\n * @see Usage: https://docs.telegram-mini-apps.com/platform/theming\n * @see API: https://docs.telegram-mini-apps.com/packages/tma-js-sdk/components/theme-params\n */\nexport class ThemeParams extends WithTrackableState<ThemeParamsState> {\n /**\n * @since v6.10\n */\n get accentTextColor(): RGB | undefined {\n return this.get('accentTextColor');\n }\n\n get bgColor(): RGB | undefined {\n return this.get('bgColor');\n }\n\n get buttonColor(): RGB | undefined {\n return this.get('buttonColor');\n }\n\n get buttonTextColor(): RGB | undefined {\n return this.get('buttonTextColor');\n }\n\n get destructiveTextColor(): RGB | undefined {\n return this.get('destructiveTextColor');\n }\n\n /**\n * Returns the copy of the internal state of the current component instance.\n */\n getState(): ThemeParamsParsed {\n return this.clone();\n }\n\n /**\n * @since v6.10\n */\n get headerBgColor(): RGB | undefined {\n return this.get('headerBgColor');\n }\n\n get hintColor(): RGB | undefined {\n return this.get('hintColor');\n }\n\n /**\n * @returns True in case, current color scheme is recognized as dark. This\n * value is calculated according to theme bg color.\n */\n get isDark(): boolean {\n return !this.bgColor || isColorDark(this.bgColor);\n }\n\n get linkColor(): RGB | undefined {\n return this.get('linkColor');\n }\n\n get secondaryBgColor(): RGB | undefined {\n return this.get('secondaryBgColor');\n }\n\n /**\n * @since v6.10\n */\n get sectionBgColor(): RGB | undefined {\n return this.get('sectionBgColor');\n }\n\n /**\n * @since v6.10\n */\n get sectionHeaderTextColor(): RGB | undefined {\n return this.get('sectionHeaderTextColor');\n }\n\n /**\n * @since v7.6\n */\n get sectionSeparatorColor(): RGB | undefined {\n return this.get('sectionHeaderTextColor');\n }\n\n /**\n * Starts listening to the external theme changes and applies them.\n * @returns Function to stop listening.\n */\n listen(): RemoveEventListenerFn {\n return on('theme_changed', (event) => {\n this.set(parseThemeParams(event.theme_params));\n });\n }\n\n /**\n * @since v6.10\n */\n get subtitleTextColor(): RGB | undefined {\n return this.get('subtitleTextColor');\n }\n\n get textColor(): RGB | undefined {\n return this.get('textColor');\n }\n}\n","import { ThemeParams } from '@/components/ThemeParams/ThemeParams.js';\nimport { createComponentInitFn } from '@/misc/createComponentInitFn/createComponentInitFn.js';\n\n/**\n * @returns A new initialized instance of the `ThemeParams` class.\n * @see ThemeParams\n */\nexport const initThemeParams = createComponentInitFn(\n 'themeParams',\n ({ themeParams, state = themeParams, addCleanup }) => {\n const tp = new ThemeParams(state);\n addCleanup(tp.listen());\n return tp;\n },\n);\n","import { request } from '@/bridge/request.js';\nimport type { ExecuteWithOptions } from '@/types/index.js';\n\nimport { parseThemeParams } from './parsing/parseThemeParams.js';\nimport type { ThemeParamsParsed } from './types.js';\n\n/**\n * Requests current theme parameters from the Telegram application.\n * @param options - request options.\n */\nexport function requestThemeParams(options: ExecuteWithOptions = {}): Promise<ThemeParamsParsed> {\n return request({\n ...options,\n method: 'web_app_request_theme',\n event: 'theme_changed',\n }).then(parseThemeParams);\n}\n","/**\n * Ensures, that specified value starts with the specified prefix. If it doesn't, function appends\n * prefix.\n * @param value - value to check.\n * @param prefix - prefix to add.\n */\nexport function ensurePrefix(value: string, prefix: string): string {\n return value.startsWith(prefix) ? value : `${prefix}${value}`;\n}\n","import { ensurePrefix } from '@/navigation/ensurePrefix.js';\nimport type { URLLike } from '@/navigation/BrowserNavigator/types.js';\n\n/**\n * Safely creates new instance of URL with some predefined protocol and hostname.\n * @param urlOrPath - URL instance or path.\n */\nexport function createSafeURL(urlOrPath: string | Partial<URLLike>): URL {\n return new URL(\n typeof urlOrPath === 'string'\n ? urlOrPath\n : `${urlOrPath.pathname || ''}${ensurePrefix(urlOrPath.search || '', '?')}${ensurePrefix(urlOrPath.hash || '', '#')}`,\n 'http://a',\n );\n}\n","import { captureSameReq } from '@/bridge/captureSameReq.js';\nimport { request } from '@/bridge/request.js';\nimport { WithSupports } from '@/classes/WithSupports.js';\nimport { createSupportsParamFn } from '@/supports/createSupportsParamFn.js';\nimport { supports } from '@/supports/supports.js';\nimport { createSafeURL } from '@/navigation/createSafeURL.js';\nimport type { PostEvent } from '@/bridge/methods/postEvent.js';\nimport type { CreateRequestIdFn } from '@/request-id/types.js';\nimport type { SupportsFn } from '@/supports/types.js';\nimport type { Version } from '@/version/types.js';\n\nexport interface UtilsOpenLinkOptions {\n /**\n * Attempts to use the instant view mode.\n */\n tryInstantView?: boolean;\n /**\n * Attempts to use user preferred browser.\n */\n tryBrowser?: boolean;\n}\n\n/**\n * @see API: https://docs.telegram-mini-apps.com/packages/tma-js-sdk/components/utils\n */\nexport class Utils extends WithSupports<'readTextFromClipboard'> {\n constructor(\n private readonly version: Version,\n private readonly createRequestId: CreateRequestIdFn,\n private readonly postEvent: PostEvent,\n ) {\n super(version, { readTextFromClipboard: 'web_app_read_text_from_clipboard' });\n\n this.supportsParam = createSupportsParamFn(version, {\n 'openLink.tryInstantView': ['web_app_open_link', 'try_instant_view'],\n });\n }\n\n /**\n * Opens a link.\n *\n * The Mini App will not be closed.\n *\n * Note that this method can be called only in response to the user\n * interaction with the Mini App interface (e.g. click inside the Mini App or on the main button).\n * @param url - URL to be opened.\n * @param options - additional options.\n */\n openLink(url: string, options?: UtilsOpenLinkOptions): void;\n\n /**\n * Opens a link.\n *\n * The Mini App will not be closed.\n *\n * Note that this method can be called only in response to the user\n * interaction with the Mini App interface (e.g. click inside the Mini App or on the main button).\n * @param url - URL to be opened.\n * @param tryInstantView - try to use the instant view.\n * @deprecated Use the second argument as an object.\n */\n openLink(url: string, tryInstantView?: boolean): void\n\n openLink(url: string, instantOrOptions?: boolean | UtilsOpenLinkOptions): void {\n const formattedUrl = createSafeURL(url).toString();\n\n // If the method is not supported, we are doing it in legacy way.\n if (!supports('web_app_open_link', this.version)) {\n window.open(formattedUrl, '_blank');\n return;\n }\n\n const options: UtilsOpenLinkOptions = typeof instantOrOptions === 'boolean'\n ? { tryInstantView: instantOrOptions }\n : instantOrOptions || {};\n\n // Otherwise, do it normally.\n this.postEvent('web_app_open_link', {\n url: formattedUrl,\n try_browser: options.tryBrowser,\n try_instant_view: options.tryInstantView,\n });\n }\n\n /**\n * Opens a Telegram link inside Telegram app. The Mini App will be closed. It expects passing\n * link in full format, with hostname \"t.me\".\n * @param url - URL to be opened.\n * @throws {Error} URL has not allowed hostname.\n */\n openTelegramLink(url: string): void {\n const { hostname, pathname, search } = new URL(url, 'https://t.me');\n if (hostname !== 't.me') {\n throw new Error(`URL has not allowed hostname: ${hostname}. Only \"t.me\" is allowed`);\n }\n\n if (!supports('web_app_open_tg_link', this.version)) {\n window.location.href = url;\n return;\n }\n\n this.postEvent('web_app_open_tg_link', { path_full: pathname + search });\n }\n\n /**\n * Reads text from clipboard and returns string or null. null is returned\n * in cases:\n * - Value in clipboard is not text\n * - Access to clipboard is not allowed\n */\n async readTextFromClipboard(): Promise<string | null> {\n const reqId = this.createRequestId();\n const {\n data = null,\n } = await request({\n method: 'web_app_read_text_from_clipboard',\n event: 'clipboard_text_received',\n postEvent: this.postEvent,\n params: { req_id: reqId },\n capture: captureSameReq(reqId),\n });\n\n return data;\n }\n\n /**\n * Shares specified URL with the passed to the chats, selected by user. After being called,\n * it closes the mini application.\n *\n * This method uses Telegram's Share Links.\n * @param url - URL to share.\n * @param text - text to append after the URL.\n * @see https://core.telegram.org/api/links#share-links\n * @see https://core.telegram.org/widgets/share#custom-buttons\n */\n shareURL(url: string, text?: string): void {\n this.openTelegramLink(\n `https://t.me/share/url?` + new URLSearchParams({ url, text: text || '' })\n .toString()\n // By default, URL search params encode spaces with \"+\".\n // We are replacing them with \"%20\", because plus symbols are working incorrectly\n // in Telegram.\n .replace(/\\+/g, '%20'),\n );\n }\n\n /**\n * Checks if specified method parameter is supported by current component.\n */\n supportsParam: SupportsFn<'openLink.tryInstantView'>;\n}\n","import { Utils } from '@/components/Utils/Utils.js';\nimport { createComponentInitFn } from '@/misc/createComponentInitFn/createComponentInitFn.js';\n\n/**\n * @returns A new initialized instance of the `Utils` class.\n * @see Utils\n */\nexport const initUtils = createComponentInitFn(\n ({ version, postEvent, createRequestId }) => {\n return new Utils(version, createRequestId, postEvent);\n },\n);\n","import { request } from '@/bridge/request.js';\nimport type { ExecuteWithOptions } from '@/types/index.js';\n\nexport interface RequestViewportResult {\n height: number;\n isStateStable: boolean;\n isExpanded: boolean;\n width: number;\n}\n\n/**\n * Requests viewport actual information from the Telegram application.\n * @param options - request options.\n */\nexport async function requestViewport(\n options: ExecuteWithOptions = {},\n): Promise<RequestViewportResult> {\n const {\n is_expanded: isExpanded,\n is_state_stable: isStateStable,\n ...rest\n } = await request({\n ...options,\n method: 'web_app_request_viewport',\n event: 'viewport_changed',\n });\n\n return { ...rest, isExpanded, isStateStable };\n}\n","import { on } from '@/bridge/events/listening/on.js';\nimport { WithTrackableState } from '@/classes/WithTrackableState.js';\nimport type { PostEvent } from '@/bridge/methods/postEvent.js';\nimport type { RemoveEventListenerFn } from '@/events/types.js';\nimport type { ExecuteWithOptions } from '@/types/index.js';\n\nimport { requestViewport } from './requestViewport.js';\nimport type { ViewportProps, ViewportState } from './types.js';\n\n/**\n * Formats value to make it stay in bounds [0, +Inf).\n * @param value - value to format.\n */\nfunction truncate(value: number): number {\n return value < 0 ? 0 : value;\n}\n\n/**\n * @see Usage: https://docs.telegram-mini-apps.com/platform/viewport\n * @see API: https://docs.telegram-mini-apps.com/packages/tma-js-sdk/components/viewport\n */\nexport class Viewport extends WithTrackableState<ViewportState> {\n private readonly postEvent: PostEvent;\n\n constructor({ postEvent, stableHeight, height, width, isExpanded }: ViewportProps) {\n super({\n height: truncate(height),\n isExpanded,\n stableHeight: truncate(stableHeight),\n width: truncate(width),\n });\n this.postEvent = postEvent;\n }\n\n /**\n * Requests viewport information from the Telegram application and updates current Viewport\n * instance.\n * @param options - options to request fresh data.\n */\n async sync(options?: ExecuteWithOptions): Promise<void> {\n const { isStateStable, ...rest } = await requestViewport(options);\n this.set({\n ...rest,\n stableHeight: isStateStable ? rest.height : this.get('stableHeight'),\n });\n }\n\n /**\n * The current height of the **visible area** of the Mini App.\n *\n * The application can display just the top part of the Mini App, with its lower part remaining\n * outside the screen area. From this position, the user can \"pull\" the Mini App to its\n * maximum height, while the bot can do the same by calling `expand` method. As the position of\n * the Mini App changes, the current height value of the visible area will be updated in real\n * time.\n *\n * Please note that the refresh rate of this value is not sufficient to smoothly follow the\n * lower border of the window. It should not be used to pin interface elements to the bottom\n * of the visible area. It's more appropriate to use the value of the `stableHeight`\n * field for this purpose.\n *\n * @see stableHeight\n */\n get height(): number {\n return this.get('height');\n }\n\n /**\n * The height of the visible area of the Mini App in its last stable state.\n *\n * The application can display just the top part of the Mini App, with its lower part remaining\n * outside the screen area. From this position, the user can \"pull\" the Mini App to its\n * maximum height, while the application can do the same by calling `expand` method.\n *\n * Unlike the value of `height`, the value of `stableHeight` does not change as the position\n * of the Mini App changes with user gestures or during animations. The value of `stableHeight`\n * will be updated after all gestures and animations are completed and\n * the Mini App reaches its final size.\n *\n * @see height\n */\n get stableHeight(): number {\n return this.get('stableHeight');\n }\n\n /**\n * Starts listening to viewport changes and applies them.\n * @returns Function to stop listening.\n */\n listen(): RemoveEventListenerFn {\n return on('viewport_changed', (event) => {\n const {\n height,\n width,\n is_expanded: isExpanded,\n is_state_stable: isStateStable,\n } = event;\n const truncatedHeight = truncate(height);\n\n this.set({\n height: truncatedHeight,\n isExpanded,\n width: truncate(width),\n ...(isStateStable ? { stableHeight: truncatedHeight } : {}),\n });\n });\n }\n\n /**\n * True if the Mini App is expanded to the maximum available height. Otherwise, if\n * the Mini App occupies part of the screen and can be expanded to the full height using\n * `expand` method.\n * @see expand\n */\n get isExpanded(): boolean {\n return this.get('isExpanded');\n }\n\n /**\n * Current visible area width.\n */\n get width(): number {\n return this.get('width');\n }\n\n /**\n * A method that expands the Mini App to the maximum available height. To find out if the Mini\n * App is expanded to the maximum height, refer to the value of the `isExpanded`.\n * @see isExpanded\n */\n expand(): void {\n this.postEvent('web_app_expand');\n this.set('isExpanded', true);\n }\n\n /**\n * True if the current viewport height is stable and is not going to change in the next moment.\n */\n get isStable(): boolean {\n return this.stableHeight === this.height;\n }\n}\n","import { createComponentInitFn } from '@/misc/createComponentInitFn/createComponentInitFn.js';\n\nimport { Viewport } from './Viewport.js';\nimport { requestViewport } from '@/components/Viewport/requestViewport.js';\n\n/**\n * @returns A promise with a new initialized instance of the `Viewport` class.\n * @see Viewport\n */\nexport const initViewport = createComponentInitFn(\n 'viewport',\n async ({ state, platform, postEvent, addCleanup }) => {\n let isExpanded = false;\n let height = 0;\n let width = 0;\n let stableHeight = 0;\n\n // State was saved previously, we restore the Viewport from this state.\n if (state) {\n isExpanded = state.isExpanded;\n height = state.height;\n width = state.width;\n stableHeight = state.stableHeight;\n } else if (['macos', 'tdesktop', 'unigram', 'webk', 'weba', 'web'].includes(platform)) {\n // If platform has a stable viewport, it means we could instantiate Viewport using\n // the window global object properties.\n isExpanded = true;\n height = window.innerHeight;\n width = window.innerWidth;\n stableHeight = window.innerHeight;\n } else {\n // We were unable to retrieve data locally. In this case we are sending a request returning\n // a viewport information.\n const response = await requestViewport({ timeout: 1000, postEvent });\n isExpanded = response.isExpanded;\n height = response.height;\n width = response.width;\n stableHeight = response.isStateStable ? height : 0;\n }\n\n // Otherwise, Viewport instance will be created using zero values.\n const viewport = new Viewport({\n postEvent,\n height,\n width,\n stableHeight,\n isExpanded,\n });\n\n // Listen to the viewport external changes and actualize local instance.\n addCleanup(viewport.listen());\n\n return viewport;\n },\n);\n","/**\n * Sets CSS variable globally.\n * @param name - variable name.\n * @param value - variable value.\n */\nexport function setCSSVar(name: string, value: string): void {\n document.documentElement.style.setProperty(name, value);\n}\n","import { isRGB } from '@/colors/isRGB.js';\nimport { setCSSVar } from '@/css-vars/setCSSVar.js';\nimport type { ThemeParams } from '@/components/ThemeParams/ThemeParams.js';\nimport type { MiniApp } from '@/components/MiniApp/MiniApp.js';\nimport type { CleanupFn } from '@/types/index.js';\n\nexport interface GetMiniAppCSSVarNameFn {\n /**\n * @param property - MiniApp property.\n * @returns Computed complete CSS variable name.\n */\n (property: 'bg' | 'header'): string;\n}\n\n/**\n * Creates CSS variables connected with the MiniApps class instance background and header colors\n * based on the passed MiniApp and ThemeParams instances.\n *\n * Created variables by default:\n * - `--tg-bg-color`\n * - `--tg-header-color`\n *\n * Variables are being automatically updated in case, corresponding MiniApp and ThemeParams\n * properties were updated.\n *\n * @param miniApp - MiniApp instance.\n * @param themeParams - ThemeParams instance.\n * @param getVarName - function, returning complete CSS variable name for the specified\n * MiniApp property.\n * @returns Function to stop updating variables.\n */\nexport function bindMiniAppCSSVars(\n miniApp: MiniApp,\n themeParams: ThemeParams,\n getVarName?: GetMiniAppCSSVarNameFn,\n): CleanupFn {\n getVarName ||= (property) => `--tg-${property}-color`;\n\n const headerVar = getVarName('header');\n const bgVar = getVarName('bg');\n\n const actualize = () => {\n const { headerColor } = miniApp;\n\n if (isRGB(headerColor)) {\n setCSSVar(headerVar, headerColor);\n } else {\n const { bgColor, secondaryBgColor } = themeParams;\n\n if (headerColor === 'bg_color' && bgColor) {\n setCSSVar(headerVar, bgColor);\n } else if (headerColor === 'secondary_bg_color' && secondaryBgColor) {\n setCSSVar(headerVar, secondaryBgColor);\n }\n }\n\n setCSSVar(bgVar, miniApp.bgColor)\n };\n\n const listeners = [\n themeParams.on('change', actualize),\n miniApp.on('change', actualize),\n ];\n\n actualize();\n\n return () => listeners.forEach(off => off());\n}\n","import { setCSSVar } from '@/css-vars/setCSSVar.js';\nimport type { ThemeParams } from '@/components/ThemeParams/ThemeParams.js';\nimport type { CleanupFn } from '@/types/index.js';\n\nexport interface GetThemeParamsCSSVarNameFn {\n /**\n * @param property - ThemeParams property.\n * @returns Computed complete CSS variable name.\n */\n (property: string): string;\n}\n\n/**\n * Creates CSS variables connected with the passed instance of the ThemeParams class.\n *\n * By default, created CSS variables names are following the pattern \"--tg-theme-{name}\", where\n * {name} is a theme parameters key name converted from camel case to kebab case.\n *\n * Example:\n * --tg-theme-bg-color\n * --tg-theme-secondary-text-color\n *\n * Variables are being automatically updated in case, corresponding properties updated in\n * the passed ThemeParams instance.\n *\n * @param themeParams - ThemeParams instance.\n * @param getCSSVarName - function, returning complete CSS variable name for the specified\n * ThemeParams property.\n * @returns Function to stop updating variables.\n */\nexport function bindThemeParamsCSSVars(\n themeParams: ThemeParams,\n getCSSVarName?: GetThemeParamsCSSVarNameFn,\n): CleanupFn {\n getCSSVarName ||= (property) => {\n return `--tg-theme-${property.replace(/[A-Z]/g, (m) => `-${m.toLowerCase()}`)}`;\n };\n\n const actualize = () => {\n Object.entries(themeParams.getState()).forEach(([k, v]) => {\n if (v) {\n setCSSVar(getCSSVarName(k), v);\n }\n });\n };\n\n actualize();\n\n return themeParams.on('change', actualize);\n}\n","import { setCSSVar } from '@/css-vars/setCSSVar.js';\nimport type { Viewport } from '@/components/Viewport/Viewport.js';\nimport type { CleanupFn } from '@/types/index.js';\n\nexport interface GetViewportCSSVarNameFn {\n /**\n * @param property - Viewport property.\n * @returns Computed complete CSS variable name.\n */\n (property: 'width' | 'height' | 'stable-height'): string;\n}\n\n/**\n * Accepts Viewport instance and sets CSS variables connected with viewport\n * sizes.\n *\n * Be careful using this function as long as it can impact application\n * performance. Viewport size is changing rather often, this makes CSS\n * variables update, which leads to possible layout redraw.\n *\n * Variables:\n * - `--tg-viewport-height`\n * - `--tg-viewport-width`\n * - `--tg-viewport-stable-height`\n *\n * Variables are being automatically updated in case, corresponding properties\n * updated in passed Viewport instance.\n *\n * @param viewport - Viewport instance.\n * @param getCSSVarName - function, returning complete CSS variable name for the specified\n * Viewport property.\n * @returns Function to stop updating variables.\n */\nexport function bindViewportCSSVars(\n viewport: Viewport,\n getCSSVarName?: GetViewportCSSVarNameFn,\n): CleanupFn {\n getCSSVarName ||= (property) => `--tg-viewport-${property}`;\n const [\n heightVar,\n widthVar,\n stableHeightVar,\n ] = (['height', 'width', 'stable-height'] as const).map((prop) => getCSSVarName(prop));\n const setHeight = () => setCSSVar(heightVar, `${viewport.height}px`);\n const setWidth = () => setCSSVar(widthVar, `${viewport.width}px`);\n const setStableHeight = () => setCSSVar(stableHeightVar, `${viewport.stableHeight}px`);\n\n // TODO: Should probably add debounce or throttle.\n const listeners = [\n viewport.on('change:height', setHeight),\n viewport.on('change:width', setWidth),\n viewport.on('change:stableHeight', setStableHeight),\n ];\n\n setHeight();\n setWidth();\n setStableHeight();\n\n return () => listeners.forEach(off => off());\n}\n","import { on } from '@/bridge/events/listening/on.js';\nimport { postEvent } from '@/bridge/methods/postEvent.js';\n\ninterface CleanupFn {\n (): void;\n}\n\n/**\n * Performs initialization process in the web version of Telegram.\n * @returns Function, which performs cleanup removing all created elements and listeners.\n * @param acceptCustomStyles - true if SDK should accept styles sent from the Telegram web\n * application. This option is only used in web versions of Telegram. Default: false.\n */\nexport function initWeb(acceptCustomStyles = true): CleanupFn {\n const listeners: CleanupFn[] = [\n on('reload_iframe', () => {\n postEvent('iframe_will_reload');\n window.location.reload();\n }),\n ];\n const cleanup: CleanupFn = () => listeners.forEach((l) => l());\n\n if (acceptCustomStyles) {\n const style = document.createElement('style');\n style.id = 'telegram-custom-styles';\n document.head.appendChild(style);\n\n listeners.push(\n on('set_custom_style', (html) => {\n // It is safe to use innerHTML here as long as style tag has a special behavior related\n // to the specified content. In case, any script will be passed here, it will not be\n // executed.\n style.innerHTML = html;\n }),\n () => document.head.removeChild(style),\n );\n }\n\n // Notify Telegram, iframe is ready. This will result in sending style tag html from native\n // application which is used in catchCustomStyles function. We should call this method also\n // to start receiving \"reload_iframe\" events from the Telegram application.\n postEvent('iframe_ready', { reload_supported: true });\n\n return cleanup;\n}\n","/**\n * @returns True, if current environment is server.\n */\nexport function isSSR(): boolean {\n return typeof window === 'undefined';\n}\n","import { request } from '@/bridge/request.js';\nimport { hasWebviewProxy } from '@/env/hasWebviewProxy.js';\n\n/**\n * Returns true in case, current environment is Telegram Mini Apps.\n */\nexport async function isTMA(): Promise<boolean> {\n if (hasWebviewProxy(window)) {\n return true;\n }\n try {\n await request({ method: 'web_app_request_theme', event: 'theme_changed', timeout: 100 });\n return true;\n } catch {\n return false;\n }\n}\n","import { saveToStorage } from '@/launch-params/saveToStorage.js';\nimport { parseMessage } from '@/bridge/parseMessage.js';\nimport { isIframe } from '@/env/isIframe.js';\nimport { hasExternalNotify } from '@/env/hasExternalNotify.js';\nimport { emitMiniAppsEvent } from '@/bridge/events/event-handlers/emitMiniAppsEvent.js';\nimport { serializeThemeParams } from '@/components/ThemeParams/parsing/serializeThemeParams.js';\nimport { parseLaunchParams } from '@/launch-params/parseLaunchParams.js';\nimport type { LaunchParams } from '@/launch-params/types.js';\nimport type { MiniAppsEventPayload } from '@/bridge/events/types.js';\n\n/**\n * Mocks a Telegram application environment.\n * @param launchParamsRaw - launch parameters presented as a string or query parameters.\n */\nexport function mockTelegramEnv(launchParamsRaw: LaunchParams | string): void {\n const lp = typeof launchParamsRaw === 'string'\n ? parseLaunchParams(launchParamsRaw)\n : launchParamsRaw;\n\n // Save launch params in the storage, so retrieveLaunchParams will return them.\n saveToStorage(lp);\n\n function wiredPostMessage(data: unknown): void {\n if (typeof data !== 'string') {\n return;\n }\n try {\n const { eventType } = parseMessage(data);\n\n if (eventType === 'web_app_request_theme') {\n emitMiniAppsEvent('theme_changed', {\n theme_params: JSON.parse(serializeThemeParams(lp.themeParams)),\n } satisfies MiniAppsEventPayload<'theme_changed'>);\n }\n\n if (eventType === 'web_app_request_viewport') {\n emitMiniAppsEvent('viewport_changed', {\n width: window.innerWidth,\n height: window.innerHeight,\n is_state_stable: true,\n is_expanded: true,\n } satisfies MiniAppsEventPayload<'viewport_changed'>);\n }\n } catch {\n }\n }\n\n // Override all possible ways of calling a Mini Apps method.\n if (isIframe()) {\n const postMessage = window.parent.postMessage.bind(window.parent);\n window.parent.postMessage = data => {\n void wiredPostMessage(data);\n postMessage(data);\n };\n return;\n }\n\n if (hasExternalNotify(window)) {\n const notify = window.external.notify.bind(window.external);\n window.external.notify = data => {\n void wiredPostMessage(data);\n notify(data);\n };\n return;\n }\n\n const proxy = (window as any).TelegramWebviewProxy;\n (window as any).TelegramWebviewProxy = {\n ...(proxy || {}),\n postEvent(...args: any) {\n void wiredPostMessage(JSON.stringify({ eventType: args[0], eventData: args[1] }));\n // eslint-disable-next-line @typescript-eslint/no-unsafe-call\n proxy && proxy.postEvent(...args);\n },\n };\n}\n","import { SDKError } from './SDKError.js';\n\n/**\n * @returns True, if passed value is an instance of SDKError.\n * @param value - value to check.\n */\nexport function isSDKError(value: unknown): value is SDKError {\n return value instanceof SDKError;\n}\n","import { isSDKError } from './isSDKError.js';\nimport type { ErrorType } from './errors.js';\n\n/**\n * Returns true if passed value is an SDK error of specified type.\n * @param value - value to check.\n * @param type - error type.\n */\nexport function isSDKErrorOfType(value: unknown, type: ErrorType): boolean {\n return isSDKError(value) && value.type === type;\n}\n","import type {\n BasicNavigatorAnyHistoryItem,\n BasicNavigatorHistoryItem,\n} from '@/navigation/BasicNavigator/types.js';\n\n/**\n * Converts any known history item type to the local one.\n * @param item - history item presented as a string or an object.\n * @param relativePathname - relative pathname.\n */\nexport function prepareItem<Params>(\n item: BasicNavigatorAnyHistoryItem<Params>,\n relativePathname: string,\n): Readonly<BasicNavigatorHistoryItem<Params>> {\n let pathname: string;\n let params: Params | undefined;\n let id: string | undefined;\n\n if (typeof item === 'string') {\n pathname = item;\n } else {\n pathname = item.pathname === undefined\n ? relativePathname\n : item.pathname;\n params = item.params;\n id = item.id;\n }\n\n return Object.freeze({\n id: id || ((Math.random() * 2 ** 14) | 0).toString(16),\n pathname,\n params,\n });\n}\n","import { off } from '@/bridge/events/listening/off.js';\nimport { on } from '@/bridge/events/listening/on.js';\nimport { type PostEvent, postEvent as defaultPostEvent } from '@/bridge/methods/postEvent.js';\nimport { createError } from '@/errors/createError.js';\nimport {\n ERR_NAVIGATION_HISTORY_EMPTY,\n ERR_NAVIGATION_INDEX_INVALID,\n} from '@/errors/errors.js';\nimport { EventEmitter } from '@/events/event-emitter/EventEmitter.js';\nimport { prepareItem } from '@/navigation/BasicNavigator/prepareItem.js';\nimport type {\n BasicNavigatorAnyHistoryItem,\n BasicNavigatorEvents,\n BasicNavigatorHistoryItem,\n} from '@/navigation/BasicNavigator/types.js';\n\ntype Emitter<Params> = EventEmitter<BasicNavigatorEvents<Params>>;\n\nexport class BasicNavigator<Params = {}> {\n /**\n * Navigation history.\n */\n readonly history: Readonly<BasicNavigatorHistoryItem<Params>>[];\n\n private readonly ee: Emitter<Params> = new EventEmitter();\n\n constructor(\n /**\n * Navigation history.\n */\n history: readonly BasicNavigatorAnyHistoryItem<Params>[],\n /**\n * Currently active history item.\n */\n private _index: number,\n /**\n * Function to call Mini Apps methods.\n * @default Global `postEvent` function.\n */\n private readonly postEvent: PostEvent = defaultPostEvent,\n ) {\n if (history.length === 0) {\n throw createError(ERR_NAVIGATION_HISTORY_EMPTY, 'History should not be empty.');\n }\n\n if (_index < 0 || _index >= history.length) {\n throw createError(\n ERR_NAVIGATION_INDEX_INVALID,\n 'Index should not be zero and higher or equal than history size.',\n );\n }\n this.history = history.map((item) => prepareItem(item, ''));\n }\n\n /**\n * True, if current navigator is currently attached.\n */\n private attached = false;\n\n /**\n * Allows this navigator to control the `BackButton` visibility state. It also tracks the\n * `BackButton` clicks and calls the `back` method.\n */\n attach(): void {\n if (!this.attached) {\n this.attached = true;\n this.sync();\n on('back_button_pressed', this.back);\n }\n }\n\n /**\n * Goes to the previous history item.\n */\n back = (): void => this.go(-1);\n\n /**\n * Currently active history item.\n */\n get current(): Readonly<BasicNavigatorHistoryItem<Params>> {\n return this.history[this.index];\n }\n\n /**\n * Prevents current navigator from controlling the BackButton visibility state.\n */\n detach(): void {\n this.attached = false;\n off('back_button_pressed', this.back);\n }\n\n /**\n * Goes to the next history item.\n */\n forward(): void {\n this.go(1);\n }\n\n /**\n * Changes currently active history item index by the specified delta. This method doesn't\n * change index in case, the updated index points to the non-existing history item. This behavior\n * is preserved until the `fit` argument is specified.\n * @param delta - index delta.\n * @param fit - cuts the delta argument to fit the bounds `[0, history.length - 1]`.\n */\n go(delta: number, fit?: boolean): void {\n // Compute the next index.\n const index = this.index + delta;\n\n // Cut the index to be in bounds [0, history.length - 1].\n const fitIndex = Math.min(\n Math.max(0, index),\n this.history.length - 1,\n );\n\n // We perform \"go\" only in case, computed and cut indexes are equal or \"fit\" option was\n // specified.\n if (index === fitIndex || fit) {\n // We are just calling setter to update the index and emit all related events.\n this.replaceAndMove(fitIndex, this.history[fitIndex]);\n }\n }\n\n /**\n * Goes to the specified index. Method does nothing in case, passed index is out of bounds.\n *\n * If \"fit\" option was specified and index is out of bounds, it will be cut to the nearest\n * bound.\n * @param index - target index.\n * @param fit - cuts the index argument to fit the bounds `[0, history.length - 1]`.\n */\n goTo(index: number, fit?: boolean): void {\n this.go(index - this.index, fit);\n }\n\n /**\n * True if navigator has items before the current item.\n */\n get hasPrev(): boolean {\n return this.index > 0;\n }\n\n /**\n * True if navigator has items after the current item.\n */\n get hasNext(): boolean {\n return this.index !== this.history.length - 1;\n }\n\n /**\n * Currently active history item index.\n */\n get index(): number {\n return this._index;\n }\n\n /**\n * Adds new event listener.\n */\n on: Emitter<Params>['on'] = this.ee.on.bind(this.ee);\n\n /**\n * Removes event listener.\n */\n off: Emitter<Params>['off'] = this.ee.off.bind(this.ee);\n\n /**\n * Adds a new history item removing all after the current one.\n * @param item - item to add.\n */\n push(item: BasicNavigatorAnyHistoryItem<Params>): void {\n if (this.hasNext) {\n this.history.splice(this.index + 1);\n }\n this.replaceAndMove(this.index + 1, prepareItem(item, this.current.pathname));\n }\n\n /**\n * Replaces the current history item.\n * @param item - item to replace the current item with.\n */\n replace(item: BasicNavigatorAnyHistoryItem<Params>): void {\n this.replaceAndMove(this.index, prepareItem(item, this.current.pathname));\n }\n\n /**\n * Sets history item by the specified index.\n * @param index - history item index to replace.\n * @param historyItem - history item to set.\n */\n private replaceAndMove(index: number, historyItem: BasicNavigatorHistoryItem<Params>): void {\n const delta = index - this.index;\n if (!delta && this.current === historyItem) {\n // Nothing changed.\n return;\n }\n\n const from = this.current;\n\n if (this.index !== index) {\n const prevIndex = this._index;\n this._index = index;\n\n // If navigator is attached and back button local visibility state changed, we should\n // notify Telegram app about it.\n if (this.attached && prevIndex > 0 !== index > 0) {\n this.sync();\n }\n }\n\n this.history[index] = historyItem;\n this.ee.emit('change', {\n navigator: this,\n from,\n to: this.current,\n delta,\n });\n }\n\n /**\n * Actualizes the `BackButton` visibility state.\n */\n private sync(): void {\n this.postEvent('web_app_setup_back_button', { is_visible: !!this.index });\n }\n}\n","import type { BasicNavigatorHistoryItem } from '@/navigation/BasicNavigator/types.js';\nimport type {\n BrowserNavigatorHistoryItem,\n BrowserNavigatorHistoryItemParams,\n} from '@/navigation/BrowserNavigator/types.js';\n\n/**\n * Converts basic navigator entry to browser navigator entry.\n */\nexport function basicItemToBrowser<State>(\n {\n params,\n ...rest\n }: BasicNavigatorHistoryItem<BrowserNavigatorHistoryItemParams<State>>,\n): BrowserNavigatorHistoryItem<State> {\n return { ...(params || { hash: '', search: '' }), ...rest };\n}\n","import { createSafeURL } from '@/navigation/createSafeURL.js';\nimport type { URLLike } from '@/navigation/BrowserNavigator/types.js';\n\n/**\n * Extracts path part from a URL.\n * @param urlOrPath - URL instance or path.\n */\nexport function urlToPath(urlOrPath: string | Partial<URLLike>): string {\n const isAbsolute = typeof urlOrPath === 'string'\n ? urlOrPath.startsWith('/')\n : !!(urlOrPath.pathname && urlOrPath.pathname.startsWith('/'));\n const url = createSafeURL(urlOrPath);\n\n return `${isAbsolute ? url.pathname : url.pathname.slice(1)}${url.search}${url.hash}`;\n}\n","import { ensurePrefix } from '@/navigation/ensurePrefix.js';\nimport { urlToPath } from '@/navigation/urlToPath.js';\nimport type { BrowserNavigatorAnyHistoryItem } from '@/navigation/BrowserNavigator/types.js';\n\ninterface PrepareItemResult<State> {\n id?: string;\n pathname: string;\n params: {\n hash: string;\n search: string;\n state?: State;\n };\n}\n\n/**\n * Converts a path, presented as a string to a basic navigator appropriate form.\n * @param path - full path.\n * @param relativePath - relative path.\n * @param state - history item state.\n */\nexport function prepareItem<State>(\n path: string,\n relativePath: string,\n state?: State,\n): PrepareItemResult<State>;\n\n/**\n * Converts a path, presented as an object to a basic navigator appropriate form.\n * @param item - history item data.\n * @param relativePath - relative path.\n */\nexport function prepareItem<State>(\n item: BrowserNavigatorAnyHistoryItem<State>,\n relativePath: string,\n): PrepareItemResult<State>;\n\nexport function prepareItem<State>(\n itemOrPath: string | BrowserNavigatorAnyHistoryItem<State>,\n relativePath: string,\n state?: State,\n): PrepareItemResult<State> {\n let path: string;\n let id: string | undefined;\n\n if (typeof itemOrPath === 'string') {\n path = itemOrPath;\n } else {\n path = urlToPath(itemOrPath);\n state = itemOrPath.state;\n id = itemOrPath.id;\n }\n\n const { pathname, search, hash } = new URL(path, `http://a${ensurePrefix(relativePath, '/')}`);\n return { id, pathname, params: { hash, search, state } };\n}\n","import { onWindow } from '@/events/onWindow.js';\n\n/**\n * Performs window.history.go operation waiting for it to be completed.\n * @param delta - history change delta.\n */\nexport async function go(delta: number): Promise<boolean> {\n if (delta === 0) {\n return true;\n }\n\n // We expect popstate event to occur during some time. Yeah, this seems tricky and not stable,\n // but it seems like we have no other way out. Waiting for Navigation API to be implemented in\n // browsers.\n return Promise.race<boolean>([\n new Promise((res) => {\n const remove = onWindow('popstate', () => {\n remove();\n res(true);\n });\n\n window.history.go(delta);\n }),\n\n // Usually, it takes about 1ms to emit this event, but we use some buffer.\n new Promise((res) => {\n setTimeout(res, 50, false);\n }),\n ]);\n}\n","import { go } from '@/navigation/go.js';\n\n/**\n * Drops current browser history switching browser history cursor to the first one entry.\n */\nexport async function drop(): Promise<void> {\n if (window.history.length <= 1) {\n return;\n }\n\n // Push empty state to cut states we have no access to, placed after the current one.\n window.history.pushState(null, '');\n\n // By this line of code we cover the most recent case, when application is opened in WebView,\n // but not in iframe. Applications opened in WebView have simple browser history containing\n // only entries belonging to the current web application.\n const goPerformed = await go(1 - window.history.length);\n if (goPerformed) {\n return;\n }\n\n // Nevertheless, iframe works a bit different in context of browser history. Calling\n // window.history.length in iframe will return browser history information related to the\n // external web environment too (e.g. browser tab). So, iframe shares the browser history with\n // the external application, but has no access to its history entries. Calling window.history.go\n // pointing out to the entry belonging to the external application will have no impact, so the\n // previous idea with go(1 - ...) will not work.\n //\n // This is the reason why we iteratively call go(-1) to meet the entry which is recognized as\n // the initial one for the current iframe.\n let shouldGoBack = await go(-1);\n while (shouldGoBack) {\n shouldGoBack = await go(-1);\n }\n}\n","import { createSafeURL } from '@/navigation/createSafeURL.js';\nimport type { URLLike } from '@/navigation/BrowserNavigator/types.js';\n\n/**\n * Extracts pathname from the value.\n * @param value - source value.\n */\nexport function getPathname(value: string | Partial<URLLike>): string {\n return createSafeURL(value).pathname;\n}\n","import { EventEmitter } from '@/events/event-emitter/EventEmitter.js';\nimport { BasicNavigator } from '@/navigation/BasicNavigator/BasicNavigator.js';\nimport { basicItemToBrowser } from '@/navigation/BrowserNavigator/basicItemToBrowser.js';\nimport { prepareItem } from '@/navigation/BrowserNavigator/prepareItem.js';\nimport { createSafeURL } from '@/navigation/createSafeURL.js';\nimport { drop } from '@/navigation/drop.js';\nimport { ensurePrefix } from '@/navigation/ensurePrefix.js';\nimport { getPathname } from '@/navigation/getPathname.js';\nimport { go } from '@/navigation/go.js';\nimport { urlToPath } from '@/navigation/urlToPath.js';\nimport type { BasicNavigatorEvents } from '@/navigation/BasicNavigator/types.js';\nimport type {\n BrowserNavigatorAnyHistoryItem,\n BrowserNavigatorConOptions,\n BrowserNavigatorEvents,\n BrowserNavigatorHashMode,\n BrowserNavigatorHistoryItem,\n BrowserNavigatorHistoryItemParams,\n URLLike,\n} from '@/navigation/BrowserNavigator/types.js';\n\nconst CURSOR_VOID = 0;\nconst CURSOR_BACK = 1;\nconst CURSOR_FORWARD = 2;\n\ntype Navigator<State> = BasicNavigator<BrowserNavigatorHistoryItemParams<State>>;\ntype Emitter<State> = EventEmitter<BrowserNavigatorEvents<State>>;\n\nexport class BrowserNavigator<State = {}> {\n private readonly navigator: Navigator<State>;\n\n private readonly ee: Emitter<State> = new EventEmitter();\n\n readonly hashMode: BrowserNavigatorHashMode | null;\n\n readonly base: string;\n\n constructor(\n /**\n * Navigation history.\n */\n history: readonly BrowserNavigatorAnyHistoryItem<State>[],\n /**\n * Currently active history item index.\n */\n index: number,\n { postEvent, hashMode = 'classic', base }: BrowserNavigatorConOptions = {},\n ) {\n this.navigator = new BasicNavigator(\n history.map((item) => prepareItem(item, '/')),\n index,\n postEvent,\n );\n this.navigator.on('change', (e) => {\n void this.onNavigatorChange(e);\n });\n this.hashMode = hashMode;\n this.base = getPathname(base || '');\n }\n\n /**\n * Shows whether the navigator is currently attached to the browser history.\n */\n private attached = false;\n\n /**\n * Attaches current navigator to the browser history allowing navigator to manipulate it.\n */\n async attach(): Promise<void> {\n if (!this.attached) {\n this.attached = true;\n this.navigator.attach();\n window.addEventListener('popstate', this.onPopState);\n await this.syncHistory();\n }\n }\n\n /**\n * Goes back in history by 1.\n */\n back(): void {\n this.navigator.back();\n }\n\n /**\n * Detaches current navigator from the browser history.\n */\n detach() {\n this.attached = false;\n this.navigator.detach();\n window.removeEventListener('popstate', this.onPopState);\n }\n\n /**\n * Goes forward in history.\n */\n forward(): void {\n return this.navigator.forward();\n }\n\n /**\n * Current history cursor.\n */\n get index(): number {\n return this.navigator.index;\n }\n\n /**\n * Current history item identifier.\n */\n get id(): string {\n return this.navigator.current.id;\n }\n\n /**\n * Changes currently active history item index by the specified delta. This method doesn't\n * change index in case, the updated index points to the non-existing history item. This behavior\n * is preserved until the `fit` argument is specified.\n * @param delta - index delta.\n * @param fit - cuts the delta argument to fit the bounds `[0, history.length - 1]`.\n */\n go(delta: number, fit?: boolean): void {\n return this.navigator.go(delta, fit);\n }\n\n /**\n * Goes to the specified index. Method does nothing in case, passed index is out of bounds.\n *\n * If \"fit\" option was specified and index is out of bounds, it will be cut to the nearest\n * bound.\n * @param index - target index.\n * @param fit - cuts the index argument to fit the bounds `[0, history.length - 1]`.\n */\n goTo(index: number, fit?: boolean): void {\n this.navigator.goTo(index, fit);\n }\n\n /**\n * Current history item hash.\n * @see URL.hash\n * @example\n * \"\", \"#my-hash\"\n */\n get hash(): string {\n return (this.navigator.current.params || {}).hash || '';\n }\n\n /**\n * True if navigator has items before the current item.\n */\n get hasPrev(): boolean {\n return this.navigator.hasPrev;\n }\n\n /**\n * True if navigator has items after the current item.\n */\n get hasNext(): boolean {\n return this.navigator.hasNext;\n }\n\n /**\n * Navigation history.\n */\n get history(): BrowserNavigatorHistoryItem<State>[] {\n return this.navigator.history.map(basicItemToBrowser);\n }\n\n /**\n * Handles the window \"popstate\" event.\n * @param state - event state.\n */\n private onPopState = ({ state }: PopStateEvent) => {\n // In case state is null, we recognize current event as occurring whenever user clicks\n // any anchor.\n // TODO: Should we do it?\n if (state === null) {\n return this.push(this.parsePath(window.location.href));\n }\n\n // There is only one case when state can be CURSOR_VOID - when history contains\n // only one element. In this case, we should return user to the current history element.\n if (state === CURSOR_VOID) {\n window.history.forward();\n } else if (state === CURSOR_BACK) {\n this.back();\n }\n if (state === CURSOR_FORWARD) {\n this.forward();\n }\n };\n\n /**\n * Underlying navigator change event listener.\n */\n private onNavigatorChange = async ({\n to,\n from,\n delta,\n }: BasicNavigatorEvents<BrowserNavigatorHistoryItemParams<State>>['change']) => {\n // If this navigator is attached to the browser history, we should synchronize.\n if (this.attached) {\n await this.syncHistory();\n }\n this.ee.emit('change', {\n delta,\n from: basicItemToBrowser(from),\n to: basicItemToBrowser(to),\n navigator: this,\n });\n };\n\n /**\n * Adds new event listener.\n */\n on: Emitter<State>['on'] = this.ee.on.bind(this.ee);\n\n /**\n * Removes event listener.\n */\n off: Emitter<State>['off'] = this.ee.off.bind(this.ee);\n\n /**\n * Path, including pathname, search and hash.\n * @example Pathname only.\n * \"/pathname\"\n * @example Pathname + search.\n * \"/pathname?search\"\n * @example Pathname + hash.\n * \"/pathname#hash\"\n * @example Pathname + search + hash.\n * \"/pathname?search#hash\"\n */\n get path(): string {\n return urlToPath(this);\n }\n\n /**\n * Current pathname. Always starts with the slash.\n * @see URL.pathname\n * @example\n * \"/\", \"/abc\"\n */\n get pathname(): string {\n return this.navigator.current.pathname;\n }\n\n /**\n * Depending on the current navigation type, parses incoming path and returns it presented as\n * an object. In other words, this method parses the passed path and returns object, describing\n * how the navigator \"sees\" it.\n *\n * @example Hash mode is omitted.\n * parsePath('/abc?a=1#hash');\n * // { pathname: '/abc', search: '?a=1', hash: '#hash' }\n * parsePath('http://example.com/abc?a=1#hash');\n * // { pathname: '/abc', search: '?a=1', hash: '#hash' }\n *\n * @example Hash mode is enabled.\n * parsePath('/abc?a=1#tma?is=cool#yeah');\n * // { pathname: '/tma', search: '?is=cool', hash: '#yeah' }\n * parsePath('http://example.com/abc?a=1#tma?is=cool#yeah');\n * // { pathname: '/tma', search: '?is=cool', hash: '#yeah' }\n */\n parsePath(path: string | URL): URLLike {\n let url = createSafeURL(path);\n if (this.hashMode) {\n url = createSafeURL(url.hash.slice(1));\n }\n\n return {\n pathname: url.pathname,\n search: url.search,\n hash: url.hash,\n };\n }\n\n /**\n * Pushes new history item. Method replaces all entries after the current one with the one\n * being pushed. Take a note, that passed item is always relative. In case, you want to use\n * it as an absolute one, use the \"/\" prefix. Example: \"/absolute\", { pathname: \"/absolute\" }.\n *\n * To create a final path, navigator uses a method, used in the URL class constructor, resolving\n * a path based on the current one.\n * @param path - entry path.\n * @param state - entry state.\n *\n * @example Pushing an absolute path.\n * push(\"/absolute\"); // \"/absolute\"\n *\n * @example Pushing a relative path.\n * push(\"relative\"); // \"/home/root\" -> \"/home/relative\"\n *\n * @example Pushing query parameters.\n * push(\"/absolute?my-param=1\"); // \"/home/root\" -> \"/absolute?my-param=1\"\n * push(\"relative?my-param=1\"); // \"/home/root\" -> \"/home/relative?my-param=1\"\n * push(\"?my-param=1\"); // \"/home\" -> \"/home?my-param=1\"\n *\n * @example Pushing hash.\n * push(\"#my-hash\"); // \"/home\" -> \"/home#my-hash\"\n * push(\"relative#my-hash\"); // \"/home/root\" -> \"/home/relative#my-hash\"\n *\n * @example Pushing state.\n * push(\"\", { state: 'my-state' }); \"/home/root\" -> \"/home/root\"\n * push({ state: 'my-state' }); \"/home/root\" -> \"/home/root\"\n */\n push(path: string, state?: State): void;\n push(item: BrowserNavigatorAnyHistoryItem<State>): void;\n push(itemOrPath: string | BrowserNavigatorAnyHistoryItem<State>, fnState?: State): void {\n const item = prepareItem(itemOrPath, this.path);\n const { state = fnState } = item.params;\n this.navigator.push({ ...item, params: { ...item.params, state } });\n }\n\n /**\n * Replaces the current history item. Has the same logic as the `push` method.\n * @param path - entry path.\n * @param state - entry state.\n * @see push\n */\n replace(path: string, state?: State): void;\n replace(item: BrowserNavigatorAnyHistoryItem<State>): void;\n replace(itemOrPath: string | BrowserNavigatorAnyHistoryItem<State>, fnState?: State): void {\n const item = prepareItem(itemOrPath, this.path);\n const { state = fnState } = item.params;\n this.navigator.replace({ ...item, params: { ...item.params, state } });\n }\n\n /**\n * Combines the navigator `base` property with the passed path data applying the navigator\n * navigation mode.\n * @param value - path presented as string or URLLike.\n */\n renderPath(value: string | URLLike): string {\n const path = (this.base.length === 1 ? '' : this.base)\n + ensurePrefix(urlToPath(value), '/');\n\n return this.hashMode\n ? ensurePrefix(path.slice(1), this.hashMode === 'classic' ? '#' : '#/')\n : path;\n }\n\n /**\n * Synchronizes current navigator state with browser history.\n */\n private async syncHistory(): Promise<void> {\n // Remove history change event listener to get rid of side effects related to the possible\n // future calls of history.go.\n window.removeEventListener('popstate', this.onPopState);\n\n const { state } = this;\n const path = this.renderPath(this);\n\n // Drop the browser history and work with the clean one.\n await drop();\n\n if (this.hasPrev && this.hasNext) {\n // We have both previous and next elements. History should be:\n // [back, *current*, forward]\n window.history.replaceState(CURSOR_BACK, '');\n window.history.pushState(state, '', path);\n window.history.pushState(CURSOR_FORWARD, '');\n\n await go(-1);\n } else if (this.hasPrev) {\n // We have only previous element. History should be:\n // [back, *current*]\n window.history.replaceState(CURSOR_BACK, '');\n window.history.pushState(state, '', path);\n } else if (this.hasNext) {\n // We have only next element. History should be:\n // [*current*, forward]\n window.history.replaceState(state, path);\n window.history.pushState(CURSOR_FORWARD, '');\n\n await go(-1);\n } else {\n // We have no back and next elements. History should be:\n // [void, *current*]\n window.history.replaceState(CURSOR_VOID, '');\n window.history.pushState(state, '', path);\n }\n\n window.addEventListener('popstate', this.onPopState);\n }\n\n /**\n * Current query parameters.\n * @see URL.search\n * @example\n * \"\", \"?\", \"?a=1\"\n */\n get search(): string {\n return (this.navigator.current.params || {}).search || '';\n }\n\n /**\n * Current history item state.\n */\n get state(): State | undefined {\n return (this.navigator.current.params || {}).state;\n }\n}\n","import { createError } from '@/errors/createError.js';\nimport { ERR_INVALID_PATH_BASE } from '@/errors/errors.js';\nimport { BrowserNavigator } from '@/navigation/BrowserNavigator/BrowserNavigator.js';\nimport { getPathname } from '@/navigation/getPathname.js';\nimport { urlToPath } from '@/navigation/urlToPath.js';\nimport type { BrowserNavigatorConOptions } from '@/navigation/BrowserNavigator/types.js';\n\nexport function createBrowserNavigatorFromLocation<State>(\n options?: BrowserNavigatorConOptions,\n): BrowserNavigator<State> {\n options ||= {};\n const { href, hash } = window.location;\n\n let path = urlToPath(\n options.hashMode === null\n // Hash mode is explicitly disabled. We are working with the usual location path.\n ? href\n // If hash mode is enabled, we should create a navigator based on the location's hash.\n // In this case we have 2 possible situations:\n // 1. Hash contains only launch parameters. Example:\n // #tgWebAppData=...&tgWebAppPlatform=...&...\n // Here we should mark the launch parameters as query parameters and have pathname \"/\" as\n // the initial one.\n //\n // 2. Hash contains value, passed from above and launch parameters as query parameters.\n // For instance, we could have such a URL:\n // https://t.me/mybot/myapp#my-hash\n // In this case, the Mini App will be opened with this URL:\n // https://example.com/#my-hash?tgWebAppData=...&tgWebAppPlatform=...&...\n : hash.includes('?') ? hash.slice(1) : `?${hash.slice(1)}`,\n );\n\n // If some base was specified, we should check if computed path starts with this base. In\n // case it does, it should be removed from the path. Otherwise, an error must be thrown.\n const base = options.base ? getPathname(options.base) : undefined;\n if (base) {\n if (!path.startsWith(base)) {\n throw createError(\n ERR_INVALID_PATH_BASE,\n `Path \"${path}\" expected to be starting with \"${base}\"`,\n );\n }\n path = path.slice(base.length);\n }\n\n return new BrowserNavigator<State>([path], 0, options);\n}\n","/**\n * @param value - string to take hash part from.\n * @returns String after the first met \"#\" symbol. In case, value doesn't contain hashtag, the\n * function will return null.\n *\n * @example No hash.\n * getHash('/path'); // null\n *\n * @example Has hash.\n * getHash('/path#abc'); // 'abc'\n *\n * @example Has double hash.\n * getHash('/path#abc#another'); // 'abc#another'\n */\nexport function getHash(value: string): string | null {\n const match = value.match(/#(.+)/);\n return match ? match[1] : null;\n}\n","import {\n BrowserNavigatorConOptions,\n BrowserNavigatorHistoryItem,\n} from '@/navigation/BrowserNavigator/types.js';\nimport { BrowserNavigator } from '@/navigation/BrowserNavigator/BrowserNavigator.js';\nimport { isPageReload } from '@/navigation/isPageReload.js';\nimport {\n createBrowserNavigatorFromLocation\n} from '@/navigation/BrowserNavigator/createBrowserNavigatorFromLocation.js';\n\n\nfunction instantiate<State>(\n sessionStorageKey: string,\n options?: BrowserNavigatorConOptions,\n): BrowserNavigator<State> {\n // If page was reloaded, we assume that navigator had to previously save its state in the\n // session storage.\n if (isPageReload()) {\n const stateRaw = sessionStorage.getItem(sessionStorageKey);\n if (stateRaw) {\n try {\n const { index, history } = JSON.parse(stateRaw);\n return new BrowserNavigator(\n history as BrowserNavigatorHistoryItem<State>[],\n index as number,\n options\n );\n } catch (e) {\n console.error('Unable to restore hash navigator state.', e);\n }\n }\n }\n\n // In case, we could not restore its state, or it is a fresh start, we can create an empty\n // navigator. We are creating BrowserNavigator from the window.location.\n return createBrowserNavigatorFromLocation(options);\n}\n\n/**\n * Initializes a standard Mini Apps navigator.\n * @param sessionStorageKey - session storage key, containing the navigator state.\n * @param options - additional BrowserNavigator options.\n */\nexport function initNavigator<State>(\n sessionStorageKey: string,\n options?: BrowserNavigatorConOptions,\n): BrowserNavigator<State> {\n const navigator = instantiate<State>(sessionStorageKey, options);\n\n const saveState = () => sessionStorage.setItem(sessionStorageKey, JSON.stringify({\n index: navigator.index,\n history: navigator.history,\n }));\n\n // Whenever navigator changes its state, we save it in the session storage.\n navigator.on('change', saveState);\n\n // Save the initial state to make sure nothing will break when the page was reloaded.\n saveState();\n\n return navigator;\n}\n"],"names":["createSingleton","create","onReset","cached","reset","unsubscribe","listener","ee","miniAppsEventEmitter","count","resetMiniAppsEventEmitter","subscribe","Logger","scope","options","level","args","now","date","textColor","bgColor","commonCss","logger","debugEnabled","onEvent","name","payload","setDebug","enable","log","EventEmitter","__publicField","event","l","once","listeners","i","onWindow","type","createCleanup","fns","cleanedUp","cache","fn","clean","SDKError","message","cause","createError","ERR_METHOD_UNSUPPORTED","ERR_METHOD_PARAMETER_UNSUPPORTED","ERR_UNKNOWN_ENV","ERR_INVOKE_CUSTOM_METHOD_RESPONSE","ERR_TIMED_OUT","ERR_UNEXPECTED_TYPE","ERR_PARSE","ERR_NAVIGATION_HISTORY_EMPTY","ERR_NAVIGATION_INDEX_INVALID","ERR_NAVIGATION_ITEM_INVALID","ERR_SSR_INIT","ERR_INVALID_PATH_BASE","createTypeError","ValueParser","parser","isOptional","value","createValueParserGenerator","boolean","asString","parseBySchema","schema","getField","result","field","definition","from","definitionType","parsedValue","error","toRecord","formattedValue","json","record","number","num","string","parseMessage","v","cleanupEventHandlers","prop","emitMiniAppsEvent","eventType","eventData","defineEventHandlers","path","pointer","item","idx","arr","parsers","createMiniAppsEventEmitter","subEmitter","mainEmitter","cleanup","data","get","emitter","off","on","isRecord","compareVersions","a","b","aParts","bParts","len","aVal","bVal","versionLessOrEqual","supports","method","paramOrVersion","inVersion","hasExternalNotify","hasWebviewProxy","isIframe","INITIAL_TARGET_ORIGIN","currentTargetOrigin","setTargetOrigin","targetOrigin","postEvent","paramsOrOptions","postOptions","targetOriginFn","createPostEvent","version","params","captureSameReq","reqId","req_id","createTimeoutError","timeout","withTimeout","funcOrPromise","_","rej","request","resolve","promise","res","capture","ev","defaultPostEvent","invokeCustomMethod","requestId","classNames","values","entry","mergeClassNames","partials","acc","partial","key","className","isRGB","isRGBShort","toRGB","color","match","component","formatted","isColorDark","rgb","modifier","dec","State","state","keyOrState","keyValue","WithStateUtils","shape","createSupportsFn","WithSupportsAndStateUtils","stateShape","supportsSchema","BackButton","isVisible","visible","searchParams","paramValue","chat","user","initData","keyToLocal","keyToExternal","themeParams","rgbOptional","k","parseLaunchParams","retrieveFromUrl","urlString","retrieveFromLocation","getFirstNavigationEntry","retrieveFromPerformance","navigationEntry","formatKey","m","setStorageValue","getStorageValue","retrieveFromStorage","serializeThemeParams","serializeLaunchParams","initDataRaw","platform","showSettings","startParam","botInline","saveToStorage","retrieveLaunchParams","retrieve","lp","isPageReload","createRequestIdGenerator","createReqId","createComponentInitFn","factoryStaticOrSK","factoryDynamic","factoryOptions","addCleanup","bindChange","initBackButton","WithSupportsAndTrackableState","formatEvent","BiometryManager","rest","reason","token","response","requestBiometryInfo","initBiometryManager","WithTrackableState","ClosingBehavior","isConfirmationNeeded","initClosingBehavior","WithSupports","parseArray","ArrayParser","itemParser","array","parserTypeName","objectFromKeys","keys","CloudStorage","createRequestId","keyOrKeys","initCloudStorage","HapticFeedback","style","initHapticFeedback","InitData","canSendAfter","initInitData","parseInitData","Invoice","isOpened","urlOrSlug","slug","hostname","pathname","initInvoice","MainButton","isEnabled","isLoaderVisible","text","initMainButton","contact","createSupportsParamFn","tmaMethod","param","sleep","duration","MiniApp","supportsOriginal","returnBack","deadlineAt","sleepTime","status","size","chatTypes","initMiniApp","preparePopupParams","title","buttons","preparedButtons","id","Popup","buttonId","initPopup","QRScanner","textOrOptions","qr","initQRScanner","SettingsButton","initSettingsButton","parseThemeParams","ThemeParams","initThemeParams","tp","requestThemeParams","ensurePrefix","prefix","createSafeURL","urlOrPath","Utils","url","instantOrOptions","formattedUrl","search","initUtils","requestViewport","isExpanded","isStateStable","truncate","Viewport","stableHeight","height","width","truncatedHeight","initViewport","viewport","setCSSVar","bindMiniAppCSSVars","miniApp","getVarName","property","headerVar","bgVar","actualize","headerColor","secondaryBgColor","bindThemeParamsCSSVars","getCSSVarName","bindViewportCSSVars","heightVar","widthVar","stableHeightVar","setHeight","setWidth","setStableHeight","initWeb","acceptCustomStyles","html","isSSR","isTMA","mockTelegramEnv","launchParamsRaw","wiredPostMessage","postMessage","notify","proxy","isSDKError","isSDKErrorOfType","prepareItem","relativePathname","BasicNavigator","history","_index","delta","fit","index","fitIndex","historyItem","prevIndex","basicItemToBrowser","urlToPath","isAbsolute","itemOrPath","relativePath","hash","go","remove","drop","shouldGoBack","getPathname","CURSOR_VOID","CURSOR_BACK","CURSOR_FORWARD","BrowserNavigator","hashMode","base","to","e","fnState","createBrowserNavigatorFromLocation","href","getHash","instantiate","sessionStorageKey","stateRaw","initNavigator","navigator","saveState"],"mappings":";;;AAKgB,SAAAA,GACdC,GACAC,GAUA;AACI,MAAAC;AACJ,QAAMC,IAAQ,MAAM;AACP,IAAAD,MAAA,UAAaD,KAAWA,EAAQC,CAAM,GACxCA,IAAA;AAAA,EAAA;AAGJ,SAAA,CAAC,MAAOA,MAAW,SAAYA,IAASF,EAAOG,CAAK,IAAID,GAASC,CAAK;AAC/E;AClBO,SAASC,GAAYC,GAA2C;AACrE,QAAMC,IAAKC,KACL,EAAE,OAAAC,EAAU,IAAAF;AAClB,EAAAA,EAAG,YAAYD,CAAQ,GAGnBG,KAAS,CAACF,EAAG,SACWG;AAE9B;ACLO,SAASC,GAAUL,GAA4D;AAC/D,SAAAE,EAAA,EAAE,UAAUF,CAAQ,GAClC,MAAMD,GAAYC,CAAQ;AACnC;ACJO,MAAMM,GAAiD;AAAA,EAC5D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3X,CAAO;AACnD;AAOgB,SAAAiY,GACdF,GACA/X,GACyB;AACnB,QAAAkY,IAAYJ,GAAmBC,GAAmB/X,CAAO,GAEzDmY,IAAY,MAAM,eAAe,QAAQJ,GAAmB,KAAK,UAAU;AAAA,IAC/E,OAAOG,EAAU;AAAA,IACjB,SAASA,EAAU;AAAA,EACpB,CAAA,CAAC;AAGQ,SAAAA,EAAA,GAAG,UAAUC,CAAS,GAGtBA,KAEHD;AACT;"}
1
+ {"version":3,"file":"index.js","sources":["../../../node_modules/.pnpm/fp-ts@2.16.11/node_modules/fp-ts/es6/function.js","../../../node_modules/.pnpm/fp-ts@2.16.11/node_modules/fp-ts/es6/internal.js","../../../node_modules/.pnpm/fp-ts@2.16.11/node_modules/fp-ts/es6/Apply.js","../../../node_modules/.pnpm/fp-ts@2.16.11/node_modules/fp-ts/es6/Functor.js","../../../node_modules/.pnpm/fp-ts@2.16.11/node_modules/fp-ts/es6/Chain.js","../../../node_modules/.pnpm/fp-ts@2.16.11/node_modules/fp-ts/es6/Either.js","../src/helpers/access.ts","../src/helpers/createIsSupportedSignal.ts","../../../node_modules/.pnpm/fp-ts@2.16.11/node_modules/fp-ts/es6/Option.js","../../../node_modules/.pnpm/fp-ts@2.16.11/node_modules/fp-ts/es6/EitherT.js","../../../node_modules/.pnpm/fp-ts@2.16.11/node_modules/fp-ts/es6/Task.js","../../../node_modules/.pnpm/fp-ts@2.16.11/node_modules/fp-ts/es6/TaskEither.js","../src/errors.ts","../src/with-checks/withChecksFp.ts","../src/with-checks/throwifyWithChecksFp.ts","../src/helpers/removeUndefined.ts","../src/helpers/shallowEqual.ts","../src/composables/Stateful.ts","../src/composables/Mountable.ts","../src/composables/Button.ts","../src/features/BackButton/BackButton.ts","../src/fn-options/sharedFeatureOptions.ts","../src/helpers/component-storage.ts","../src/helpers/navigation.ts","../src/fn-options/createFnOption.ts","../src/fn-options/withStateRestore.ts","../src/globals/signals-registry.ts","../src/globals/post-event.ts","../src/fn-options/withPostEvent.ts","../src/globals/version.ts","../src/fn-options/withVersion.ts","../src/fn-options/buttonOptions.ts","../src/features/BackButton/instance.ts","../src/composables/AsyncMountable.ts","../src/features/Biometry/Biometry.ts","../src/globals/request.ts","../src/fn-options/withRequest.ts","../src/features/Biometry/instance.ts","../src/features/ClosingBehavior/ClosingBehavior.ts","../src/features/ClosingBehavior/instance.ts","../src/features/CloudStorage/CloudStorage.ts","../src/globals/createRequestId.ts","../src/globals/invokeCustomMethod.ts","../src/fn-options/withInvokeCustomMethod.ts","../src/features/CloudStorage/instance.ts","../src/features/emoji-status/requestEmojiStatusAccess.ts","../src/features/emoji-status/setEmojiStatus.ts","../src/features/HapticFeedback/HapticFeedback.ts","../src/features/HapticFeedback/instance.ts","../src/features/home-screen/addToHomeScreen.ts","../src/features/home-screen/checkHomeScreenStatus.ts","../src/features/InitData/InitData.ts","../src/features/InitData/instance.ts","../src/features/Invoice/Invoice.ts","../src/features/Invoice/instance.ts","../src/features/links/openLink.ts","../src/features/links/openTelegramLink.ts","../src/features/links/shareURL.ts","../src/features/LocationManager/LocationManager.ts","../src/features/LocationManager/instance.ts","../src/features/MainButton/MainButton.ts","../src/fn-options/bottomButtonOptions.ts","../src/globals/themeParams.ts","../src/helpers/css-vars.ts","../src/helpers/isColorDark.ts","../src/features/ThemeParams/ThemeParams.ts","../src/features/ThemeParams/instance.ts","../src/features/MainButton/instance.ts","../src/features/MiniApp/MiniApp.ts","../src/features/MiniApp/instance.ts","../src/features/Popup/prepareParams.ts","../src/features/Popup/Popup.ts","../src/features/Popup/instance.ts","../src/features/privacy/requestPhoneAccess.ts","../src/features/privacy/requestContact.ts","../src/features/privacy/requestWriteAccess.ts","../src/features/QrScanner/QrScanner.ts","../src/features/QrScanner/instance.ts","../src/features/SecondaryButton/SecondaryButton.ts","../src/features/SecondaryButton/instance.ts","../src/features/SettingsButton/SettingsButton.ts","../src/features/SettingsButton/instance.ts","../src/features/SwipeBehavior/SwipeBehavior.ts","../src/features/SwipeBehavior/instance.ts","../src/features/uncategorized/copyTextToClipboard.ts","../src/features/uncategorized/downloadFile.ts","../src/features/uncategorized/getCurrentTime.ts","../src/features/uncategorized/hideKeyboard.ts","../src/features/uncategorized/readTextFromClipboard.ts","../src/features/uncategorized/retrieveAndroidDeviceDataFrom.ts","../src/features/uncategorized/retrieveAndroidDeviceData.ts","../src/features/uncategorized/sendData.ts","../src/features/uncategorized/shareMessage.ts","../src/features/uncategorized/shareStory.ts","../src/globals/inline-mode.ts","../src/features/uncategorized/switchInlineQuery.ts","../src/features/Viewport/Viewport.ts","../src/features/Viewport/instance.ts","../src/init.ts"],"sourcesContent":["var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n};\n// -------------------------------------------------------------------------------------\n// instances\n// -------------------------------------------------------------------------------------\n/**\n * @category instances\n * @since 2.10.0\n */\nexport var getBooleanAlgebra = function (B) {\n return function () { return ({\n meet: function (x, y) { return function (a) { return B.meet(x(a), y(a)); }; },\n join: function (x, y) { return function (a) { return B.join(x(a), y(a)); }; },\n zero: function () { return B.zero; },\n one: function () { return B.one; },\n implies: function (x, y) { return function (a) { return B.implies(x(a), y(a)); }; },\n not: function (x) { return function (a) { return B.not(x(a)); }; }\n }); };\n};\n/**\n * Unary functions form a semigroup as long as you can provide a semigroup for the codomain.\n *\n * @example\n * import { Predicate, getSemigroup } from 'fp-ts/function'\n * import * as B from 'fp-ts/boolean'\n *\n * const f: Predicate<number> = (n) => n <= 2\n * const g: Predicate<number> = (n) => n >= 0\n *\n * const S1 = getSemigroup(B.SemigroupAll)<number>()\n *\n * assert.deepStrictEqual(S1.concat(f, g)(1), true)\n * assert.deepStrictEqual(S1.concat(f, g)(3), false)\n *\n * const S2 = getSemigroup(B.SemigroupAny)<number>()\n *\n * assert.deepStrictEqual(S2.concat(f, g)(1), true)\n * assert.deepStrictEqual(S2.concat(f, g)(3), true)\n *\n * @category instances\n * @since 2.10.0\n */\nexport var getSemigroup = function (S) {\n return function () { return ({\n concat: function (f, g) { return function (a) { return S.concat(f(a), g(a)); }; }\n }); };\n};\n/**\n * Unary functions form a monoid as long as you can provide a monoid for the codomain.\n *\n * @example\n * import { Predicate } from 'fp-ts/Predicate'\n * import { getMonoid } from 'fp-ts/function'\n * import * as B from 'fp-ts/boolean'\n *\n * const f: Predicate<number> = (n) => n <= 2\n * const g: Predicate<number> = (n) => n >= 0\n *\n * const M1 = getMonoid(B.MonoidAll)<number>()\n *\n * assert.deepStrictEqual(M1.concat(f, g)(1), true)\n * assert.deepStrictEqual(M1.concat(f, g)(3), false)\n *\n * const M2 = getMonoid(B.MonoidAny)<number>()\n *\n * assert.deepStrictEqual(M2.concat(f, g)(1), true)\n * assert.deepStrictEqual(M2.concat(f, g)(3), true)\n *\n * @category instances\n * @since 2.10.0\n */\nexport var getMonoid = function (M) {\n var getSemigroupM = getSemigroup(M);\n return function () { return ({\n concat: getSemigroupM().concat,\n empty: function () { return M.empty; }\n }); };\n};\n/**\n * @category instances\n * @since 2.10.0\n */\nexport var getSemiring = function (S) { return ({\n add: function (f, g) { return function (x) { return S.add(f(x), g(x)); }; },\n zero: function () { return S.zero; },\n mul: function (f, g) { return function (x) { return S.mul(f(x), g(x)); }; },\n one: function () { return S.one; }\n}); };\n/**\n * @category instances\n * @since 2.10.0\n */\nexport var getRing = function (R) {\n var S = getSemiring(R);\n return {\n add: S.add,\n mul: S.mul,\n one: S.one,\n zero: S.zero,\n sub: function (f, g) { return function (x) { return R.sub(f(x), g(x)); }; }\n };\n};\n// -------------------------------------------------------------------------------------\n// utils\n// -------------------------------------------------------------------------------------\n/**\n * @since 2.11.0\n */\nexport var apply = function (a) {\n return function (f) {\n return f(a);\n };\n};\n/**\n * @since 2.0.0\n */\nexport function identity(a) {\n return a;\n}\n/**\n * @since 2.0.0\n */\nexport var unsafeCoerce = identity;\n/**\n * @since 2.0.0\n */\nexport function constant(a) {\n return function () { return a; };\n}\n/**\n * A thunk that returns always `true`.\n *\n * @since 2.0.0\n */\nexport var constTrue = /*#__PURE__*/ constant(true);\n/**\n * A thunk that returns always `false`.\n *\n * @since 2.0.0\n */\nexport var constFalse = /*#__PURE__*/ constant(false);\n/**\n * A thunk that returns always `null`.\n *\n * @since 2.0.0\n */\nexport var constNull = /*#__PURE__*/ constant(null);\n/**\n * A thunk that returns always `undefined`.\n *\n * @since 2.0.0\n */\nexport var constUndefined = /*#__PURE__*/ constant(undefined);\n/**\n * A thunk that returns always `void`.\n *\n * @since 2.0.0\n */\nexport var constVoid = constUndefined;\nexport function flip(f) {\n return function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n if (args.length > 1) {\n return f(args[1], args[0]);\n }\n return function (a) { return f(a)(args[0]); };\n };\n}\nexport function flow(ab, bc, cd, de, ef, fg, gh, hi, ij) {\n switch (arguments.length) {\n case 1:\n return ab;\n case 2:\n return function () {\n return bc(ab.apply(this, arguments));\n };\n case 3:\n return function () {\n return cd(bc(ab.apply(this, arguments)));\n };\n case 4:\n return function () {\n return de(cd(bc(ab.apply(this, arguments))));\n };\n case 5:\n return function () {\n return ef(de(cd(bc(ab.apply(this, arguments)))));\n };\n case 6:\n return function () {\n return fg(ef(de(cd(bc(ab.apply(this, arguments))))));\n };\n case 7:\n return function () {\n return gh(fg(ef(de(cd(bc(ab.apply(this, arguments)))))));\n };\n case 8:\n return function () {\n return hi(gh(fg(ef(de(cd(bc(ab.apply(this, arguments))))))));\n };\n case 9:\n return function () {\n return ij(hi(gh(fg(ef(de(cd(bc(ab.apply(this, arguments)))))))));\n };\n }\n return;\n}\n/**\n * @since 2.0.0\n */\nexport function tuple() {\n var t = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n t[_i] = arguments[_i];\n }\n return t;\n}\n/**\n * @since 2.0.0\n */\nexport function increment(n) {\n return n + 1;\n}\n/**\n * @since 2.0.0\n */\nexport function decrement(n) {\n return n - 1;\n}\n/**\n * @since 2.0.0\n */\nexport function absurd(_) {\n throw new Error('Called `absurd` function which should be uncallable');\n}\n/**\n * Creates a tupled version of this function: instead of `n` arguments, it accepts a single tuple argument.\n *\n * @example\n * import { tupled } from 'fp-ts/function'\n *\n * const add = tupled((x: number, y: number): number => x + y)\n *\n * assert.strictEqual(add([1, 2]), 3)\n *\n * @since 2.4.0\n */\nexport function tupled(f) {\n return function (a) { return f.apply(void 0, a); };\n}\n/**\n * Inverse function of `tupled`\n *\n * @since 2.4.0\n */\nexport function untupled(f) {\n return function () {\n var a = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n a[_i] = arguments[_i];\n }\n return f(a);\n };\n}\nexport function pipe(a, ab, bc, cd, de, ef, fg, gh, hi) {\n switch (arguments.length) {\n case 1:\n return a;\n case 2:\n return ab(a);\n case 3:\n return bc(ab(a));\n case 4:\n return cd(bc(ab(a)));\n case 5:\n return de(cd(bc(ab(a))));\n case 6:\n return ef(de(cd(bc(ab(a)))));\n case 7:\n return fg(ef(de(cd(bc(ab(a))))));\n case 8:\n return gh(fg(ef(de(cd(bc(ab(a)))))));\n case 9:\n return hi(gh(fg(ef(de(cd(bc(ab(a))))))));\n default: {\n var ret = arguments[0];\n for (var i = 1; i < arguments.length; i++) {\n ret = arguments[i](ret);\n }\n return ret;\n }\n }\n}\n/**\n * Type hole simulation\n *\n * @since 2.7.0\n */\nexport var hole = absurd;\n/**\n * @since 2.11.0\n */\nexport var SK = function (_, b) { return b; };\n/**\n * Use `Predicate` module instead.\n *\n * @category zone of death\n * @since 2.0.0\n * @deprecated\n */\nexport function not(predicate) {\n return function (a) { return !predicate(a); };\n}\n/**\n * Use `Endomorphism` module instead.\n *\n * @category zone of death\n * @since 2.10.0\n * @deprecated\n */\nexport var getEndomorphismMonoid = function () { return ({\n concat: function (first, second) { return flow(first, second); },\n empty: identity\n}); };\n/** @internal */\nexport var dual = function (arity, body) {\n var isDataFirst = typeof arity === 'number' ? function (args) { return args.length >= arity; } : arity;\n return function () {\n var args = Array.from(arguments);\n if (isDataFirst(arguments)) {\n return body.apply(this, args);\n }\n return function (self) { return body.apply(void 0, __spreadArray([self], args, false)); };\n };\n};\n","var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n};\nimport { dual } from './function';\n// -------------------------------------------------------------------------------------\n// Option\n// -------------------------------------------------------------------------------------\n/** @internal */\nexport var isNone = function (fa) { return fa._tag === 'None'; };\n/** @internal */\nexport var isSome = function (fa) { return fa._tag === 'Some'; };\n/** @internal */\nexport var none = { _tag: 'None' };\n/** @internal */\nexport var some = function (a) { return ({ _tag: 'Some', value: a }); };\n// -------------------------------------------------------------------------------------\n// Either\n// -------------------------------------------------------------------------------------\n/** @internal */\nexport var isLeft = function (ma) { return ma._tag === 'Left'; };\n/** @internal */\nexport var isRight = function (ma) { return ma._tag === 'Right'; };\n/** @internal */\nexport var left = function (e) { return ({ _tag: 'Left', left: e }); };\n/** @internal */\nexport var right = function (a) { return ({ _tag: 'Right', right: a }); };\n// -------------------------------------------------------------------------------------\n// ReadonlyNonEmptyArray\n// -------------------------------------------------------------------------------------\n/** @internal */\nexport var singleton = function (a) { return [a]; };\n/** @internal */\nexport var isNonEmpty = function (as) { return as.length > 0; };\n/** @internal */\nexport var head = function (as) { return as[0]; };\n/** @internal */\nexport var tail = function (as) { return as.slice(1); };\n// -------------------------------------------------------------------------------------\n// empty\n// -------------------------------------------------------------------------------------\n/** @internal */\nexport var emptyReadonlyArray = [];\n/** @internal */\nexport var emptyRecord = {};\n// -------------------------------------------------------------------------------------\n// Record\n// -------------------------------------------------------------------------------------\n/** @internal */\nexport var has = Object.prototype.hasOwnProperty;\n// -------------------------------------------------------------------------------------\n// NonEmptyArray\n// -------------------------------------------------------------------------------------\n/** @internal */\nexport var fromReadonlyNonEmptyArray = function (as) { return __spreadArray([as[0]], as.slice(1), true); };\n/** @internal */\nexport var liftNullable = function (F) {\n return function (f, onNullable) {\n return function () {\n var a = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n a[_i] = arguments[_i];\n }\n var o = f.apply(void 0, a);\n return F.fromEither(o == null ? left(onNullable.apply(void 0, a)) : right(o));\n };\n };\n};\n/** @internal */\nexport var liftOption = function (F) {\n return function (f, onNone) {\n return function () {\n var a = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n a[_i] = arguments[_i];\n }\n var o = f.apply(void 0, a);\n return F.fromEither(isNone(o) ? left(onNone.apply(void 0, a)) : right(o.value));\n };\n };\n};\n/** @internal */\nexport var flatMapNullable = function (F, M) {\n return /*#__PURE__*/ dual(3, function (self, f, onNullable) {\n return M.flatMap(self, liftNullable(F)(f, onNullable));\n });\n};\n/** @internal */\nexport var flatMapOption = function (F, M) {\n return /*#__PURE__*/ dual(3, function (self, f, onNone) { return M.flatMap(self, liftOption(F)(f, onNone)); });\n};\n/** @internal */\nexport var flatMapEither = function (F, M) {\n return /*#__PURE__*/ dual(2, function (self, f) {\n return M.flatMap(self, function (a) { return F.fromEither(f(a)); });\n });\n};\n/** @internal */\nexport var flatMapIO = function (F, M) {\n return /*#__PURE__*/ dual(2, function (self, f) {\n return M.flatMap(self, function (a) { return F.fromIO(f(a)); });\n });\n};\n/** @internal */\nexport var flatMapTask = function (F, M) {\n return /*#__PURE__*/ dual(2, function (self, f) {\n return M.flatMap(self, function (a) { return F.fromTask(f(a)); });\n });\n};\n/** @internal */\nexport var flatMapReader = function (F, M) {\n return /*#__PURE__*/ dual(2, function (self, f) {\n return M.flatMap(self, function (a) { return F.fromReader(f(a)); });\n });\n};\n","/**\n * The `Apply` class provides the `ap` which is used to apply a function to an argument under a type constructor.\n *\n * `Apply` can be used to lift functions of two or more arguments to work on values wrapped with the type constructor\n * `f`.\n *\n * Instances must satisfy the following law in addition to the `Functor` laws:\n *\n * 1. Associative composition: `F.ap(F.ap(F.map(fbc, bc => ab => a => bc(ab(a))), fab), fa) <-> F.ap(fbc, F.ap(fab, fa))`\n *\n * Formally, `Apply` represents a strong lax semi-monoidal endofunctor.\n *\n * @example\n * import * as O from 'fp-ts/Option'\n * import { pipe } from 'fp-ts/function'\n *\n * const f = (a: string) => (b: number) => (c: boolean) => a + String(b) + String(c)\n * const fa: O.Option<string> = O.some('s')\n * const fb: O.Option<number> = O.some(1)\n * const fc: O.Option<boolean> = O.some(true)\n *\n * assert.deepStrictEqual(\n * pipe(\n * // lift a function\n * O.some(f),\n * // apply the first argument\n * O.ap(fa),\n * // apply the second argument\n * O.ap(fb),\n * // apply the third argument\n * O.ap(fc)\n * ),\n * O.some('s1true')\n * )\n *\n * @since 2.0.0\n */\nimport { tuple } from './function';\nimport * as _ from './internal';\nexport function ap(F, G) {\n return function (fa) {\n return function (fab) {\n return F.ap(F.map(fab, function (gab) { return function (ga) { return G.ap(gab, ga); }; }), fa);\n };\n };\n}\nexport function apFirst(A) {\n return function (second) { return function (first) {\n return A.ap(A.map(first, function (a) { return function () { return a; }; }), second);\n }; };\n}\nexport function apSecond(A) {\n return function (second) {\n return function (first) {\n return A.ap(A.map(first, function () { return function (b) { return b; }; }), second);\n };\n };\n}\nexport function apS(F) {\n return function (name, fb) {\n return function (fa) {\n return F.ap(F.map(fa, function (a) { return function (b) {\n var _a;\n return Object.assign({}, a, (_a = {}, _a[name] = b, _a));\n }; }), fb);\n };\n };\n}\nexport function getApplySemigroup(F) {\n return function (S) { return ({\n concat: function (first, second) {\n return F.ap(F.map(first, function (x) { return function (y) { return S.concat(x, y); }; }), second);\n }\n }); };\n}\nfunction curried(f, n, acc) {\n return function (x) {\n var combined = Array(acc.length + 1);\n for (var i = 0; i < acc.length; i++) {\n combined[i] = acc[i];\n }\n combined[acc.length] = x;\n return n === 0 ? f.apply(null, combined) : curried(f, n - 1, combined);\n };\n}\nvar tupleConstructors = {\n 1: function (a) { return [a]; },\n 2: function (a) { return function (b) { return [a, b]; }; },\n 3: function (a) { return function (b) { return function (c) { return [a, b, c]; }; }; },\n 4: function (a) { return function (b) { return function (c) { return function (d) { return [a, b, c, d]; }; }; }; },\n 5: function (a) { return function (b) { return function (c) { return function (d) { return function (e) { return [a, b, c, d, e]; }; }; }; }; }\n};\nfunction getTupleConstructor(len) {\n if (!_.has.call(tupleConstructors, len)) {\n tupleConstructors[len] = curried(tuple, len - 1, []);\n }\n return tupleConstructors[len];\n}\nexport function sequenceT(F) {\n return function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n var len = args.length;\n var f = getTupleConstructor(len);\n var fas = F.map(args[0], f);\n for (var i = 1; i < len; i++) {\n fas = F.ap(fas, args[i]);\n }\n return fas;\n };\n}\nfunction getRecordConstructor(keys) {\n var len = keys.length;\n switch (len) {\n case 1:\n return function (a) {\n var _a;\n return (_a = {}, _a[keys[0]] = a, _a);\n };\n case 2:\n return function (a) { return function (b) {\n var _a;\n return (_a = {}, _a[keys[0]] = a, _a[keys[1]] = b, _a);\n }; };\n case 3:\n return function (a) { return function (b) { return function (c) {\n var _a;\n return (_a = {}, _a[keys[0]] = a, _a[keys[1]] = b, _a[keys[2]] = c, _a);\n }; }; };\n case 4:\n return function (a) { return function (b) { return function (c) { return function (d) {\n var _a;\n return (_a = {},\n _a[keys[0]] = a,\n _a[keys[1]] = b,\n _a[keys[2]] = c,\n _a[keys[3]] = d,\n _a);\n }; }; }; };\n case 5:\n return function (a) { return function (b) { return function (c) { return function (d) { return function (e) {\n var _a;\n return (_a = {},\n _a[keys[0]] = a,\n _a[keys[1]] = b,\n _a[keys[2]] = c,\n _a[keys[3]] = d,\n _a[keys[4]] = e,\n _a);\n }; }; }; }; };\n default:\n return curried(function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n var r = {};\n for (var i = 0; i < len; i++) {\n r[keys[i]] = args[i];\n }\n return r;\n }, len - 1, []);\n }\n}\nexport function sequenceS(F) {\n return function (r) {\n var keys = Object.keys(r);\n var len = keys.length;\n var f = getRecordConstructor(keys);\n var fr = F.map(r[keys[0]], f);\n for (var i = 1; i < len; i++) {\n fr = F.ap(fr, r[keys[i]]);\n }\n return fr;\n };\n}\n","/**\n * A `Functor` is a type constructor which supports a mapping operation `map`.\n *\n * `map` can be used to turn functions `a -> b` into functions `f a -> f b` whose argument and return types use the type\n * constructor `f` to represent some computational context.\n *\n * Instances must satisfy the following laws:\n *\n * 1. Identity: `F.map(fa, a => a) <-> fa`\n * 2. Composition: `F.map(fa, a => bc(ab(a))) <-> F.map(F.map(fa, ab), bc)`\n *\n * @since 2.0.0\n */\nimport { pipe } from './function';\nexport function map(F, G) {\n return function (f) { return function (fa) { return F.map(fa, function (ga) { return G.map(ga, f); }); }; };\n}\nexport function flap(F) {\n return function (a) { return function (fab) { return F.map(fab, function (f) { return f(a); }); }; };\n}\nexport function bindTo(F) {\n return function (name) { return function (fa) { return F.map(fa, function (a) {\n var _a;\n return (_a = {}, _a[name] = a, _a);\n }); }; };\n}\nfunction let_(F) {\n return function (name, f) { return function (fa) { return F.map(fa, function (a) {\n var _a;\n return Object.assign({}, a, (_a = {}, _a[name] = f(a), _a));\n }); }; };\n}\nexport { \n/**\n * @since 2.13.0\n */\nlet_ as let };\n/** @deprecated */\nexport function getFunctorComposition(F, G) {\n var _map = map(F, G);\n return {\n map: function (fga, f) { return pipe(fga, _map(f)); }\n };\n}\n/** @internal */\nexport function as(F) {\n return function (self, b) { return F.map(self, function () { return b; }); };\n}\n/** @internal */\nexport function asUnit(F) {\n var asM = as(F);\n return function (self) { return asM(self, undefined); };\n}\n","export function chainFirst(M) {\n var tapM = tap(M);\n return function (f) { return function (first) { return tapM(first, f); }; };\n}\n/** @internal */\nexport function tap(M) {\n return function (first, f) { return M.chain(first, function (a) { return M.map(f(a), function () { return a; }); }); };\n}\nexport function bind(M) {\n return function (name, f) { return function (ma) { return M.chain(ma, function (a) { return M.map(f(a), function (b) {\n var _a;\n return Object.assign({}, a, (_a = {}, _a[name] = b, _a));\n }); }); }; };\n}\n","import { getApplicativeMonoid } from './Applicative';\nimport { apFirst as apFirst_, apS as apS_, apSecond as apSecond_, getApplySemigroup as getApplySemigroup_ } from './Apply';\nimport * as chainable from './Chain';\nimport { tailRec } from './ChainRec';\nimport { chainOptionK as chainOptionK_, filterOrElse as filterOrElse_, fromOption as fromOption_, fromOptionK as fromOptionK_, fromPredicate as fromPredicate_ } from './FromEither';\nimport { dual, flow, identity, pipe } from './function';\nimport { as as as_, asUnit as asUnit_, bindTo as bindTo_, flap as flap_, let as let__ } from './Functor';\nimport * as _ from './internal';\nimport { separated } from './Separated';\nimport { wiltDefault, witherDefault } from './Witherable';\n// -------------------------------------------------------------------------------------\n// constructors\n// -------------------------------------------------------------------------------------\n/**\n * Constructs a new `Either` holding a `Left` value. This usually represents a failure, due to the right-bias of this\n * structure.\n *\n * @category constructors\n * @since 2.0.0\n */\nexport var left = _.left;\n/**\n * Constructs a new `Either` holding a `Right` value. This usually represents a successful value due to the right bias\n * of this structure.\n *\n * @category constructors\n * @since 2.0.0\n */\nexport var right = _.right;\n/**\n * @category sequencing\n * @since 2.14.0\n */\nexport var flatMap = /*#__PURE__*/ dual(2, function (ma, f) { return (isLeft(ma) ? ma : f(ma.right)); });\nvar _map = function (fa, f) { return pipe(fa, map(f)); };\nvar _ap = function (fab, fa) { return pipe(fab, ap(fa)); };\n/* istanbul ignore next */\nvar _reduce = function (fa, b, f) { return pipe(fa, reduce(b, f)); };\n/* istanbul ignore next */\nvar _foldMap = function (M) { return function (fa, f) {\n var foldMapM = foldMap(M);\n return pipe(fa, foldMapM(f));\n}; };\n/* istanbul ignore next */\nvar _reduceRight = function (fa, b, f) { return pipe(fa, reduceRight(b, f)); };\nvar _traverse = function (F) {\n var traverseF = traverse(F);\n return function (ta, f) { return pipe(ta, traverseF(f)); };\n};\nvar _bimap = function (fa, f, g) { return pipe(fa, bimap(f, g)); };\nvar _mapLeft = function (fa, f) { return pipe(fa, mapLeft(f)); };\n/* istanbul ignore next */\nvar _alt = function (fa, that) { return pipe(fa, alt(that)); };\n/* istanbul ignore next */\nvar _extend = function (wa, f) { return pipe(wa, extend(f)); };\nvar _chainRec = function (a, f) {\n return tailRec(f(a), function (e) {\n return isLeft(e) ? right(left(e.left)) : isLeft(e.right) ? left(f(e.right.left)) : right(right(e.right.right));\n });\n};\n/**\n * @category type lambdas\n * @since 2.0.0\n */\nexport var URI = 'Either';\n/**\n * @category instances\n * @since 2.0.0\n */\nexport var getShow = function (SE, SA) { return ({\n show: function (ma) { return (isLeft(ma) ? \"left(\".concat(SE.show(ma.left), \")\") : \"right(\".concat(SA.show(ma.right), \")\")); }\n}); };\n/**\n * @category instances\n * @since 2.0.0\n */\nexport var getEq = function (EL, EA) { return ({\n equals: function (x, y) {\n return x === y || (isLeft(x) ? isLeft(y) && EL.equals(x.left, y.left) : isRight(y) && EA.equals(x.right, y.right));\n }\n}); };\n/**\n * Semigroup returning the left-most non-`Left` value. If both operands are `Right`s then the inner values are\n * concatenated using the provided `Semigroup`\n *\n * @example\n * import { getSemigroup, left, right } from 'fp-ts/Either'\n * import { SemigroupSum } from 'fp-ts/number'\n *\n * const S = getSemigroup<string, number>(SemigroupSum)\n * assert.deepStrictEqual(S.concat(left('a'), left('b')), left('a'))\n * assert.deepStrictEqual(S.concat(left('a'), right(2)), right(2))\n * assert.deepStrictEqual(S.concat(right(1), left('b')), right(1))\n * assert.deepStrictEqual(S.concat(right(1), right(2)), right(3))\n *\n * @category instances\n * @since 2.0.0\n */\nexport var getSemigroup = function (S) { return ({\n concat: function (x, y) { return (isLeft(y) ? x : isLeft(x) ? y : right(S.concat(x.right, y.right))); }\n}); };\n/**\n * Builds a `Compactable` instance for `Either` given `Monoid` for the left side.\n *\n * @category filtering\n * @since 2.10.0\n */\nexport var getCompactable = function (M) {\n var empty = left(M.empty);\n return {\n URI: URI,\n _E: undefined,\n compact: function (ma) { return (isLeft(ma) ? ma : ma.right._tag === 'None' ? empty : right(ma.right.value)); },\n separate: function (ma) {\n return isLeft(ma)\n ? separated(ma, ma)\n : isLeft(ma.right)\n ? separated(right(ma.right.left), empty)\n : separated(empty, right(ma.right.right));\n }\n };\n};\n/**\n * Builds a `Filterable` instance for `Either` given `Monoid` for the left side\n *\n * @category filtering\n * @since 2.10.0\n */\nexport var getFilterable = function (M) {\n var empty = left(M.empty);\n var _a = getCompactable(M), compact = _a.compact, separate = _a.separate;\n var filter = function (ma, predicate) {\n return isLeft(ma) ? ma : predicate(ma.right) ? ma : empty;\n };\n var partition = function (ma, p) {\n return isLeft(ma)\n ? separated(ma, ma)\n : p(ma.right)\n ? separated(empty, right(ma.right))\n : separated(right(ma.right), empty);\n };\n return {\n URI: URI,\n _E: undefined,\n map: _map,\n compact: compact,\n separate: separate,\n filter: filter,\n filterMap: function (ma, f) {\n if (isLeft(ma)) {\n return ma;\n }\n var ob = f(ma.right);\n return ob._tag === 'None' ? empty : right(ob.value);\n },\n partition: partition,\n partitionMap: function (ma, f) {\n if (isLeft(ma)) {\n return separated(ma, ma);\n }\n var e = f(ma.right);\n return isLeft(e) ? separated(right(e.left), empty) : separated(empty, right(e.right));\n }\n };\n};\n/**\n * Builds `Witherable` instance for `Either` given `Monoid` for the left side\n *\n * @category filtering\n * @since 2.0.0\n */\nexport var getWitherable = function (M) {\n var F_ = getFilterable(M);\n var C = getCompactable(M);\n return {\n URI: URI,\n _E: undefined,\n map: _map,\n compact: F_.compact,\n separate: F_.separate,\n filter: F_.filter,\n filterMap: F_.filterMap,\n partition: F_.partition,\n partitionMap: F_.partitionMap,\n traverse: _traverse,\n sequence: sequence,\n reduce: _reduce,\n foldMap: _foldMap,\n reduceRight: _reduceRight,\n wither: witherDefault(Traversable, C),\n wilt: wiltDefault(Traversable, C)\n };\n};\n/**\n * The default [`Applicative`](#applicative) instance returns the first error, if you want to\n * get all errors you need to provide a way to concatenate them via a `Semigroup`.\n *\n * @example\n * import * as A from 'fp-ts/Apply'\n * import * as E from 'fp-ts/Either'\n * import { pipe } from 'fp-ts/function'\n * import * as S from 'fp-ts/Semigroup'\n * import * as string from 'fp-ts/string'\n *\n * const parseString = (u: unknown): E.Either<string, string> =>\n * typeof u === 'string' ? E.right(u) : E.left('not a string')\n *\n * const parseNumber = (u: unknown): E.Either<string, number> =>\n * typeof u === 'number' ? E.right(u) : E.left('not a number')\n *\n * interface Person {\n * readonly name: string\n * readonly age: number\n * }\n *\n * const parsePerson = (\n * input: Record<string, unknown>\n * ): E.Either<string, Person> =>\n * pipe(\n * E.Do,\n * E.apS('name', parseString(input.name)),\n * E.apS('age', parseNumber(input.age))\n * )\n *\n * assert.deepStrictEqual(parsePerson({}), E.left('not a string')) // <= first error\n *\n * const Applicative = E.getApplicativeValidation(\n * pipe(string.Semigroup, S.intercalate(', '))\n * )\n *\n * const apS = A.apS(Applicative)\n *\n * const parsePersonAll = (\n * input: Record<string, unknown>\n * ): E.Either<string, Person> =>\n * pipe(\n * E.Do,\n * apS('name', parseString(input.name)),\n * apS('age', parseNumber(input.age))\n * )\n *\n * assert.deepStrictEqual(parsePersonAll({}), E.left('not a string, not a number')) // <= all errors\n *\n * @category error handling\n * @since 2.7.0\n */\nexport var getApplicativeValidation = function (SE) { return ({\n URI: URI,\n _E: undefined,\n map: _map,\n ap: function (fab, fa) {\n return isLeft(fab)\n ? isLeft(fa)\n ? left(SE.concat(fab.left, fa.left))\n : fab\n : isLeft(fa)\n ? fa\n : right(fab.right(fa.right));\n },\n of: of\n}); };\n/**\n * The default [`Alt`](#alt) instance returns the last error, if you want to\n * get all errors you need to provide a way to concatenate them via a `Semigroup`.\n *\n * @example\n * import * as E from 'fp-ts/Either'\n * import { pipe } from 'fp-ts/function'\n * import * as S from 'fp-ts/Semigroup'\n * import * as string from 'fp-ts/string'\n *\n * const parseString = (u: unknown): E.Either<string, string> =>\n * typeof u === 'string' ? E.right(u) : E.left('not a string')\n *\n * const parseNumber = (u: unknown): E.Either<string, number> =>\n * typeof u === 'number' ? E.right(u) : E.left('not a number')\n *\n * const parse = (u: unknown): E.Either<string, string | number> =>\n * pipe(\n * parseString(u),\n * E.alt<string, string | number>(() => parseNumber(u))\n * )\n *\n * assert.deepStrictEqual(parse(true), E.left('not a number')) // <= last error\n *\n * const Alt = E.getAltValidation(pipe(string.Semigroup, S.intercalate(', ')))\n *\n * const parseAll = (u: unknown): E.Either<string, string | number> =>\n * Alt.alt<string | number>(parseString(u), () => parseNumber(u))\n *\n * assert.deepStrictEqual(parseAll(true), E.left('not a string, not a number')) // <= all errors\n *\n * @category error handling\n * @since 2.7.0\n */\nexport var getAltValidation = function (SE) { return ({\n URI: URI,\n _E: undefined,\n map: _map,\n alt: function (me, that) {\n if (isRight(me)) {\n return me;\n }\n var ea = that();\n return isLeft(ea) ? left(SE.concat(me.left, ea.left)) : ea;\n }\n}); };\n/**\n * @category mapping\n * @since 2.0.0\n */\nexport var map = function (f) { return function (fa) {\n return isLeft(fa) ? fa : right(f(fa.right));\n}; };\n/**\n * @category instances\n * @since 2.7.0\n */\nexport var Functor = {\n URI: URI,\n map: _map\n};\n/**\n * Maps the `Right` value of this `Either` to the specified constant value.\n *\n * @category mapping\n * @since 2.16.0\n */\nexport var as = dual(2, as_(Functor));\n/**\n * Maps the `Right` value of this `Either` to the void constant value.\n *\n * @category mapping\n * @since 2.16.0\n */\nexport var asUnit = asUnit_(Functor);\n/**\n * @category constructors\n * @since 2.7.0\n */\nexport var of = right;\n/**\n * @category instances\n * @since 2.10.0\n */\nexport var Pointed = {\n URI: URI,\n of: of\n};\n/**\n * Less strict version of [`ap`](#ap).\n *\n * The `W` suffix (short for **W**idening) means that the error types will be merged.\n *\n * @since 2.8.0\n */\nexport var apW = function (fa) { return function (fab) {\n return isLeft(fab) ? fab : isLeft(fa) ? fa : right(fab.right(fa.right));\n}; };\n/**\n * @since 2.0.0\n */\nexport var ap = apW;\n/**\n * @category instances\n * @since 2.10.0\n */\nexport var Apply = {\n URI: URI,\n map: _map,\n ap: _ap\n};\n/**\n * @category instances\n * @since 2.7.0\n */\nexport var Applicative = {\n URI: URI,\n map: _map,\n ap: _ap,\n of: of\n};\n/**\n * @category instances\n * @since 2.10.0\n */\nexport var Chain = {\n URI: URI,\n map: _map,\n ap: _ap,\n chain: flatMap\n};\n/**\n * @category instances\n * @since 2.7.0\n */\nexport var Monad = {\n URI: URI,\n map: _map,\n ap: _ap,\n of: of,\n chain: flatMap\n};\n/**\n * Left-associative fold of a structure.\n *\n * @example\n * import { pipe } from 'fp-ts/function'\n * import * as E from 'fp-ts/Either'\n *\n * const startWith = 'prefix'\n * const concat = (a: string, b: string) => `${a}:${b}`\n *\n * assert.deepStrictEqual(\n * pipe(E.right('a'), E.reduce(startWith, concat)),\n * 'prefix:a'\n * )\n *\n * assert.deepStrictEqual(\n * pipe(E.left('e'), E.reduce(startWith, concat)),\n * 'prefix'\n * )\n *\n * @category folding\n * @since 2.0.0\n */\nexport var reduce = function (b, f) { return function (fa) {\n return isLeft(fa) ? b : f(b, fa.right);\n}; };\n/**\n * Map each element of the structure to a monoid, and combine the results.\n *\n * @example\n * import { pipe } from 'fp-ts/function'\n * import * as E from 'fp-ts/Either'\n * import * as S from 'fp-ts/string'\n *\n * const yell = (a: string) => `${a}!`\n *\n * assert.deepStrictEqual(\n * pipe(E.right('a'), E.foldMap(S.Monoid)(yell)),\n * 'a!'\n * )\n *\n * assert.deepStrictEqual(\n * pipe(E.left('e'), E.foldMap(S.Monoid)(yell)),\n * S.Monoid.empty\n * )\n *\n * @category folding\n * @since 2.0.0\n */\nexport var foldMap = function (M) { return function (f) { return function (fa) {\n return isLeft(fa) ? M.empty : f(fa.right);\n}; }; };\n/**\n * Right-associative fold of a structure.\n *\n * @example\n * import { pipe } from 'fp-ts/function'\n * import * as E from 'fp-ts/Either'\n *\n * const startWith = 'postfix'\n * const concat = (a: string, b: string) => `${a}:${b}`\n *\n * assert.deepStrictEqual(\n * pipe(E.right('a'), E.reduceRight(startWith, concat)),\n * 'a:postfix'\n * )\n *\n * assert.deepStrictEqual(\n * pipe(E.left('e'), E.reduceRight(startWith, concat)),\n * 'postfix'\n * )\n *\n * @category folding\n * @since 2.0.0\n */\nexport var reduceRight = function (b, f) { return function (fa) {\n return isLeft(fa) ? b : f(fa.right, b);\n}; };\n/**\n * @category instances\n * @since 2.7.0\n */\nexport var Foldable = {\n URI: URI,\n reduce: _reduce,\n foldMap: _foldMap,\n reduceRight: _reduceRight\n};\n/**\n * Map each element of a structure to an action, evaluate these actions from left to right, and collect the results.\n *\n * @example\n * import { pipe } from 'fp-ts/function'\n * import * as RA from 'fp-ts/ReadonlyArray'\n * import * as E from 'fp-ts/Either'\n * import * as O from 'fp-ts/Option'\n *\n * assert.deepStrictEqual(\n * pipe(E.right(['a']), E.traverse(O.Applicative)(RA.head)),\n * O.some(E.right('a'))\n * )\n *\n * assert.deepStrictEqual(\n * pipe(E.right([]), E.traverse(O.Applicative)(RA.head)),\n * O.none\n * )\n *\n * @category traversing\n * @since 2.6.3\n */\nexport var traverse = function (F) {\n return function (f) {\n return function (ta) {\n return isLeft(ta) ? F.of(left(ta.left)) : F.map(f(ta.right), right);\n };\n };\n};\n/**\n * Evaluate each monadic action in the structure from left to right, and collect the results.\n *\n * @example\n * import { pipe } from 'fp-ts/function'\n * import * as E from 'fp-ts/Either'\n * import * as O from 'fp-ts/Option'\n *\n * assert.deepStrictEqual(\n * pipe(E.right(O.some('a')), E.sequence(O.Applicative)),\n * O.some(E.right('a'))\n * )\n *\n * assert.deepStrictEqual(\n * pipe(E.right(O.none), E.sequence(O.Applicative)),\n * O.none\n * )\n *\n * @category traversing\n * @since 2.6.3\n */\nexport var sequence = function (F) {\n return function (ma) {\n return isLeft(ma) ? F.of(left(ma.left)) : F.map(ma.right, right);\n };\n};\n/**\n * @category instances\n * @since 2.7.0\n */\nexport var Traversable = {\n URI: URI,\n map: _map,\n reduce: _reduce,\n foldMap: _foldMap,\n reduceRight: _reduceRight,\n traverse: _traverse,\n sequence: sequence\n};\n/**\n * Map a pair of functions over the two type arguments of the bifunctor.\n *\n * @category mapping\n * @since 2.0.0\n */\nexport var bimap = function (f, g) { return function (fa) {\n return isLeft(fa) ? left(f(fa.left)) : right(g(fa.right));\n}; };\n/**\n * Map a function over the first type argument of a bifunctor.\n *\n * @category error handling\n * @since 2.0.0\n */\nexport var mapLeft = function (f) { return function (fa) {\n return isLeft(fa) ? left(f(fa.left)) : fa;\n}; };\n/**\n * @category instances\n * @since 2.7.0\n */\nexport var Bifunctor = {\n URI: URI,\n bimap: _bimap,\n mapLeft: _mapLeft\n};\n/**\n * Less strict version of [`alt`](#alt).\n *\n * The `W` suffix (short for **W**idening) means that the error and the return types will be merged.\n *\n * @category error handling\n * @since 2.9.0\n */\nexport var altW = function (that) { return function (fa) {\n return isLeft(fa) ? that() : fa;\n}; };\n/**\n * Identifies an associative operation on a type constructor. It is similar to `Semigroup`, except that it applies to\n * types of kind `* -> *`.\n *\n * In case of `Either` returns the left-most non-`Left` value (or the right-most `Left` value if both values are `Left`).\n *\n * | x | y | pipe(x, alt(() => y) |\n * | -------- | -------- | -------------------- |\n * | left(a) | left(b) | left(b) |\n * | left(a) | right(2) | right(2) |\n * | right(1) | left(b) | right(1) |\n * | right(1) | right(2) | right(1) |\n *\n * @example\n * import * as E from 'fp-ts/Either'\n * import { pipe } from 'fp-ts/function'\n *\n * assert.deepStrictEqual(\n * pipe(\n * E.left('a'),\n * E.alt(() => E.left('b'))\n * ),\n * E.left('b')\n * )\n * assert.deepStrictEqual(\n * pipe(\n * E.left('a'),\n * E.alt(() => E.right(2))\n * ),\n * E.right(2)\n * )\n * assert.deepStrictEqual(\n * pipe(\n * E.right(1),\n * E.alt(() => E.left('b'))\n * ),\n * E.right(1)\n * )\n * assert.deepStrictEqual(\n * pipe(\n * E.right(1),\n * E.alt(() => E.right(2))\n * ),\n * E.right(1)\n * )\n *\n * @category error handling\n * @since 2.0.0\n */\nexport var alt = altW;\n/**\n * @category instances\n * @since 2.7.0\n */\nexport var Alt = {\n URI: URI,\n map: _map,\n alt: _alt\n};\n/**\n * @since 2.0.0\n */\nexport var extend = function (f) { return function (wa) {\n return isLeft(wa) ? wa : right(f(wa));\n}; };\n/**\n * @category instances\n * @since 2.7.0\n */\nexport var Extend = {\n URI: URI,\n map: _map,\n extend: _extend\n};\n/**\n * @category instances\n * @since 2.7.0\n */\nexport var ChainRec = {\n URI: URI,\n map: _map,\n ap: _ap,\n chain: flatMap,\n chainRec: _chainRec\n};\n/**\n * @since 2.6.3\n */\nexport var throwError = left;\n/**\n * @category instances\n * @since 2.7.0\n */\nexport var MonadThrow = {\n URI: URI,\n map: _map,\n ap: _ap,\n of: of,\n chain: flatMap,\n throwError: throwError\n};\n/**\n * @category instances\n * @since 2.10.0\n */\nexport var FromEither = {\n URI: URI,\n fromEither: identity\n};\n/**\n * @example\n * import { fromPredicate, left, right } from 'fp-ts/Either'\n * import { pipe } from 'fp-ts/function'\n *\n * assert.deepStrictEqual(\n * pipe(\n * 1,\n * fromPredicate(\n * (n) => n > 0,\n * () => 'error'\n * )\n * ),\n * right(1)\n * )\n * assert.deepStrictEqual(\n * pipe(\n * -1,\n * fromPredicate(\n * (n) => n > 0,\n * () => 'error'\n * )\n * ),\n * left('error')\n * )\n *\n * @category lifting\n * @since 2.0.0\n */\nexport var fromPredicate = /*#__PURE__*/ fromPredicate_(FromEither);\n// -------------------------------------------------------------------------------------\n// conversions\n// -------------------------------------------------------------------------------------\n/**\n * @example\n * import * as E from 'fp-ts/Either'\n * import { pipe } from 'fp-ts/function'\n * import * as O from 'fp-ts/Option'\n *\n * assert.deepStrictEqual(\n * pipe(\n * O.some(1),\n * E.fromOption(() => 'error')\n * ),\n * E.right(1)\n * )\n * assert.deepStrictEqual(\n * pipe(\n * O.none,\n * E.fromOption(() => 'error')\n * ),\n * E.left('error')\n * )\n *\n * @category conversions\n * @since 2.0.0\n */\nexport var fromOption = \n/*#__PURE__*/ fromOption_(FromEither);\n// -------------------------------------------------------------------------------------\n// refinements\n// -------------------------------------------------------------------------------------\n/**\n * Returns `true` if the either is an instance of `Left`, `false` otherwise.\n *\n * @category refinements\n * @since 2.0.0\n */\nexport var isLeft = _.isLeft;\n/**\n * Returns `true` if the either is an instance of `Right`, `false` otherwise.\n *\n * @category refinements\n * @since 2.0.0\n */\nexport var isRight = _.isRight;\n/**\n * Less strict version of [`match`](#match).\n *\n * The `W` suffix (short for **W**idening) means that the handler return types will be merged.\n *\n * @category pattern matching\n * @since 2.10.0\n */\nexport var matchW = function (onLeft, onRight) {\n return function (ma) {\n return isLeft(ma) ? onLeft(ma.left) : onRight(ma.right);\n };\n};\n/**\n * Alias of [`matchW`](#matchw).\n *\n * @category pattern matching\n * @since 2.10.0\n */\nexport var foldW = matchW;\n/**\n * Takes two functions and an `Either` value, if the value is a `Left` the inner value is applied to the first function,\n * if the value is a `Right` the inner value is applied to the second function.\n *\n * @example\n * import { match, left, right } from 'fp-ts/Either'\n * import { pipe } from 'fp-ts/function'\n *\n * function onLeft(errors: Array<string>): string {\n * return `Errors: ${errors.join(', ')}`\n * }\n *\n * function onRight(value: number): string {\n * return `Ok: ${value}`\n * }\n *\n * assert.strictEqual(\n * pipe(\n * right(1),\n * match(onLeft, onRight)\n * ),\n * 'Ok: 1'\n * )\n * assert.strictEqual(\n * pipe(\n * left(['error 1', 'error 2']),\n * match(onLeft, onRight)\n * ),\n * 'Errors: error 1, error 2'\n * )\n *\n * @category pattern matching\n * @since 2.10.0\n */\nexport var match = matchW;\n/**\n * Alias of [`match`](#match).\n *\n * @category pattern matching\n * @since 2.0.0\n */\nexport var fold = match;\n/**\n * Less strict version of [`getOrElse`](#getorelse).\n *\n * The `W` suffix (short for **W**idening) means that the handler return type will be merged.\n *\n * @category error handling\n * @since 2.6.0\n */\nexport var getOrElseW = function (onLeft) {\n return function (ma) {\n return isLeft(ma) ? onLeft(ma.left) : ma.right;\n };\n};\n/**\n * Returns the wrapped value if it's a `Right` or a default value if is a `Left`.\n *\n * @example\n * import { getOrElse, left, right } from 'fp-ts/Either'\n * import { pipe } from 'fp-ts/function'\n *\n * assert.deepStrictEqual(\n * pipe(\n * right(1),\n * getOrElse(() => 0)\n * ),\n * 1\n * )\n * assert.deepStrictEqual(\n * pipe(\n * left('error'),\n * getOrElse(() => 0)\n * ),\n * 0\n * )\n *\n * @category error handling\n * @since 2.0.0\n */\nexport var getOrElse = getOrElseW;\n// -------------------------------------------------------------------------------------\n// combinators\n// -------------------------------------------------------------------------------------\n/**\n * @category mapping\n * @since 2.10.0\n */\nexport var flap = /*#__PURE__*/ flap_(Functor);\n/**\n * Combine two effectful actions, keeping only the result of the first.\n *\n * @since 2.0.0\n */\nexport var apFirst = /*#__PURE__*/ apFirst_(Apply);\n/**\n * Less strict version of [`apFirst`](#apfirst)\n *\n * The `W` suffix (short for **W**idening) means that the error types will be merged.\n *\n * @since 2.12.0\n */\nexport var apFirstW = apFirst;\n/**\n * Combine two effectful actions, keeping only the result of the second.\n *\n * @since 2.0.0\n */\nexport var apSecond = /*#__PURE__*/ apSecond_(Apply);\n/**\n * Less strict version of [`apSecond`](#apsecond)\n *\n * The `W` suffix (short for **W**idening) means that the error types will be merged.\n *\n * @since 2.12.0\n */\nexport var apSecondW = apSecond;\n/**\n * Composes computations in sequence, using the return value of one computation to determine the next computation and\n * keeping only the result of the first.\n *\n * @category combinators\n * @since 2.15.0\n */\nexport var tap = /*#__PURE__*/ dual(2, chainable.tap(Chain));\n/**\n * Less strict version of [`flatten`](#flatten).\n *\n * The `W` suffix (short for **W**idening) means that the error types will be merged.\n *\n * @category sequencing\n * @since 2.11.0\n */\nexport var flattenW = \n/*#__PURE__*/ flatMap(identity);\n/**\n * The `flatten` function is the conventional monad join operator. It is used to remove one level of monadic structure, projecting its bound argument into the outer level.\n *\n * @example\n * import * as E from 'fp-ts/Either'\n *\n * assert.deepStrictEqual(E.flatten(E.right(E.right('a'))), E.right('a'))\n * assert.deepStrictEqual(E.flatten(E.right(E.left('e'))), E.left('e'))\n * assert.deepStrictEqual(E.flatten(E.left('e')), E.left('e'))\n *\n * @category sequencing\n * @since 2.0.0\n */\nexport var flatten = flattenW;\n/**\n * @since 2.0.0\n */\nexport var duplicate = /*#__PURE__*/ extend(identity);\n/**\n * Use `liftOption`.\n *\n * @category legacy\n * @since 2.10.0\n */\nexport var fromOptionK = \n/*#__PURE__*/ fromOptionK_(FromEither);\n/**\n * Use `flatMapOption`.\n *\n * @category legacy\n * @since 2.11.0\n */\nexport var chainOptionK = /*#__PURE__*/ chainOptionK_(FromEither, Chain);\n/**\n * Use `flatMapOption`.\n *\n * @category legacy\n * @since 2.13.2\n */\nexport var chainOptionKW = chainOptionK;\n/** @internal */\nvar _FromEither = {\n fromEither: FromEither.fromEither\n};\n/**\n * @category lifting\n * @since 2.15.0\n */\nexport var liftNullable = /*#__PURE__*/ _.liftNullable(_FromEither);\n/**\n * @category lifting\n * @since 2.15.0\n */\nexport var liftOption = /*#__PURE__*/ _.liftOption(_FromEither);\n/** @internal */\nvar _FlatMap = {\n flatMap: flatMap\n};\n/**\n * @category sequencing\n * @since 2.15.0\n */\nexport var flatMapNullable = /*#__PURE__*/ _.flatMapNullable(_FromEither, _FlatMap);\n/**\n * @category sequencing\n * @since 2.15.0\n */\nexport var flatMapOption = /*#__PURE__*/ _.flatMapOption(_FromEither, _FlatMap);\n/**\n * @example\n * import * as E from 'fp-ts/Either'\n * import { pipe } from 'fp-ts/function'\n *\n * assert.deepStrictEqual(\n * pipe(\n * E.right(1),\n * E.filterOrElse(\n * (n) => n > 0,\n * () => 'error'\n * )\n * ),\n * E.right(1)\n * )\n * assert.deepStrictEqual(\n * pipe(\n * E.right(-1),\n * E.filterOrElse(\n * (n) => n > 0,\n * () => 'error'\n * )\n * ),\n * E.left('error')\n * )\n * assert.deepStrictEqual(\n * pipe(\n * E.left('a'),\n * E.filterOrElse(\n * (n) => n > 0,\n * () => 'error'\n * )\n * ),\n * E.left('a')\n * )\n *\n * @category filtering\n * @since 2.0.0\n */\nexport var filterOrElse = /*#__PURE__*/ filterOrElse_(FromEither, Chain);\n/**\n * Less strict version of [`filterOrElse`](#filterorelse).\n *\n * The `W` suffix (short for **W**idening) means that the error types will be merged.\n *\n * @category filtering\n * @since 2.9.0\n */\nexport var filterOrElseW = filterOrElse;\n/**\n * Returns a `Right` if is a `Left` (and vice versa).\n *\n * @since 2.0.0\n */\nexport var swap = function (ma) { return (isLeft(ma) ? right(ma.left) : left(ma.right)); };\n/**\n * Less strict version of [`orElse`](#orelse).\n *\n * The `W` suffix (short for **W**idening) means that the return types will be merged.\n *\n * @category error handling\n * @since 2.10.0\n */\nexport var orElseW = function (onLeft) {\n return function (ma) {\n return isLeft(ma) ? onLeft(ma.left) : ma;\n };\n};\n/**\n * Useful for recovering from errors.\n *\n * @category error handling\n * @since 2.0.0\n */\nexport var orElse = orElseW;\n/**\n * Takes a default and a nullable value, if the value is not nully, turn it into a `Right`, if the value is nully use\n * the provided default as a `Left`.\n *\n * @example\n * import { fromNullable, left, right } from 'fp-ts/Either'\n *\n * const parse = fromNullable('nully')\n *\n * assert.deepStrictEqual(parse(1), right(1))\n * assert.deepStrictEqual(parse(null), left('nully'))\n *\n * @category conversions\n * @since 2.0.0\n */\nexport var fromNullable = function (e) {\n return function (a) {\n return a == null ? left(e) : right(a);\n };\n};\n/**\n * Constructs a new `Either` from a function that might throw.\n *\n * See also [`tryCatchK`](#trycatchk).\n *\n * @example\n * import * as E from 'fp-ts/Either'\n *\n * const unsafeHead = <A>(as: ReadonlyArray<A>): A => {\n * if (as.length > 0) {\n * return as[0]\n * } else {\n * throw new Error('empty array')\n * }\n * }\n *\n * const head = <A>(as: ReadonlyArray<A>): E.Either<Error, A> =>\n * E.tryCatch(() => unsafeHead(as), e => (e instanceof Error ? e : new Error('unknown error')))\n *\n * assert.deepStrictEqual(head([]), E.left(new Error('empty array')))\n * assert.deepStrictEqual(head([1, 2, 3]), E.right(1))\n *\n * @category interop\n * @since 2.0.0\n */\nexport var tryCatch = function (f, onThrow) {\n try {\n return right(f());\n }\n catch (e) {\n return left(onThrow(e));\n }\n};\n/**\n * Converts a function that may throw to one returning a `Either`.\n *\n * @category interop\n * @since 2.10.0\n */\nexport var tryCatchK = function (f, onThrow) {\n return function () {\n var a = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n a[_i] = arguments[_i];\n }\n return tryCatch(function () { return f.apply(void 0, a); }, onThrow);\n };\n};\n/**\n * Use `liftNullable`.\n *\n * @category legacy\n * @since 2.9.0\n */\nexport var fromNullableK = function (e) {\n var from = fromNullable(e);\n return function (f) { return flow(f, from); };\n};\n/**\n * Use `flatMapNullable`.\n *\n * @category legacy\n * @since 2.9.0\n */\nexport var chainNullableK = function (e) {\n var from = fromNullableK(e);\n return function (f) { return flatMap(from(f)); };\n};\n/**\n * @category conversions\n * @since 2.10.0\n */\nexport var toUnion = /*#__PURE__*/ foldW(identity, identity);\n// -------------------------------------------------------------------------------------\n// utils\n// -------------------------------------------------------------------------------------\n/**\n * Default value for the `onError` argument of `tryCatch`\n *\n * @since 2.0.0\n */\nexport function toError(e) {\n try {\n return e instanceof Error ? e : new Error(String(e));\n }\n catch (error) {\n return new Error();\n }\n}\nexport function elem(E) {\n return function (a, ma) {\n if (ma === undefined) {\n var elemE_1 = elem(E);\n return function (ma) { return elemE_1(a, ma); };\n }\n return isLeft(ma) ? false : E.equals(a, ma.right);\n };\n}\n/**\n * Returns `false` if `Left` or returns the result of the application of the given predicate to the `Right` value.\n *\n * @example\n * import { exists, left, right } from 'fp-ts/Either'\n *\n * const gt2 = exists((n: number) => n > 2)\n *\n * assert.strictEqual(gt2(left('a')), false)\n * assert.strictEqual(gt2(right(1)), false)\n * assert.strictEqual(gt2(right(3)), true)\n *\n * @since 2.0.0\n */\nexport var exists = function (predicate) {\n return function (ma) {\n return isLeft(ma) ? false : predicate(ma.right);\n };\n};\n// -------------------------------------------------------------------------------------\n// do notation\n// -------------------------------------------------------------------------------------\n/**\n * @category do notation\n * @since 2.9.0\n */\nexport var Do = /*#__PURE__*/ of(_.emptyRecord);\n/**\n * @category do notation\n * @since 2.8.0\n */\nexport var bindTo = /*#__PURE__*/ bindTo_(Functor);\nvar let_ = /*#__PURE__*/ let__(Functor);\nexport { \n/**\n * @category do notation\n * @since 2.13.0\n */\nlet_ as let };\n/**\n * @category do notation\n * @since 2.8.0\n */\nexport var bind = /*#__PURE__*/ chainable.bind(Chain);\n/**\n * The `W` suffix (short for **W**idening) means that the error types will be merged.\n *\n * @category do notation\n * @since 2.8.0\n */\nexport var bindW = bind;\n/**\n * @category do notation\n * @since 2.8.0\n */\nexport var apS = /*#__PURE__*/ apS_(Apply);\n/**\n * Less strict version of [`apS`](#aps).\n *\n * The `W` suffix (short for **W**idening) means that the error types will be merged.\n *\n * @category do notation\n * @since 2.8.0\n */\nexport var apSW = apS;\n/**\n * @since 2.11.0\n */\nexport var ApT = /*#__PURE__*/ of(_.emptyReadonlyArray);\n// -------------------------------------------------------------------------------------\n// array utils\n// -------------------------------------------------------------------------------------\n/**\n * Equivalent to `ReadonlyNonEmptyArray#traverseWithIndex(Applicative)`.\n *\n * @category traversing\n * @since 2.11.0\n */\nexport var traverseReadonlyNonEmptyArrayWithIndex = function (f) {\n return function (as) {\n var e = f(0, _.head(as));\n if (isLeft(e)) {\n return e;\n }\n var out = [e.right];\n for (var i = 1; i < as.length; i++) {\n var e_1 = f(i, as[i]);\n if (isLeft(e_1)) {\n return e_1;\n }\n out.push(e_1.right);\n }\n return right(out);\n };\n};\n/**\n * Equivalent to `ReadonlyArray#traverseWithIndex(Applicative)`.\n *\n * @category traversing\n * @since 2.11.0\n */\nexport var traverseReadonlyArrayWithIndex = function (f) {\n var g = traverseReadonlyNonEmptyArrayWithIndex(f);\n return function (as) { return (_.isNonEmpty(as) ? g(as) : ApT); };\n};\n/**\n * Equivalent to `ReadonlyArray#traverseWithIndex(Applicative)`.\n *\n * @category traversing\n * @since 2.9.0\n */\nexport var traverseArrayWithIndex = traverseReadonlyArrayWithIndex;\n/**\n * Equivalent to `ReadonlyArray#traverse(Applicative)`.\n *\n * @category traversing\n * @since 2.9.0\n */\nexport var traverseArray = function (f) { return traverseReadonlyArrayWithIndex(function (_, a) { return f(a); }); };\n/**\n * Equivalent to `ReadonlyArray#sequence(Applicative)`.\n *\n * @category traversing\n * @since 2.9.0\n */\nexport var sequenceArray = \n/*#__PURE__*/ traverseArray(identity);\n// -------------------------------------------------------------------------------------\n// legacy\n// -------------------------------------------------------------------------------------\n/**\n * Alias of `flatMap`.\n *\n * @category legacy\n * @since 2.6.0\n */\nexport var chainW = flatMap;\n/**\n * Alias of `flatMap`.\n *\n * @category legacy\n * @since 2.0.0\n */\nexport var chain = flatMap;\n/**\n * Alias of `tap`.\n *\n * @category legacy\n * @since 2.0.0\n */\nexport var chainFirst = tap;\n/**\n * Alias of `tap`.\n *\n * @category legacy\n * @since 2.8.0\n */\nexport var chainFirstW = tap;\n/**\n * Use [`parse`](./Json.ts.html#parse) instead.\n *\n * @category zone of death\n * @since 2.0.0\n * @deprecated\n */\nexport function parseJSON(s, onError) {\n return tryCatch(function () { return JSON.parse(s); }, onError);\n}\n/**\n * Use [`stringify`](./Json.ts.html#stringify) instead.\n *\n * @category zone of death\n * @since 2.0.0\n * @deprecated\n */\nexport var stringifyJSON = function (u, onError) {\n return tryCatch(function () {\n var s = JSON.stringify(u);\n if (typeof s !== 'string') {\n throw new Error('Converting unsupported structure to JSON');\n }\n return s;\n }, onError);\n};\n/**\n * This instance is deprecated, use small, specific instances instead.\n * For example if a function needs a `Functor` instance, pass `E.Functor` instead of `E.either`\n * (where `E` is from `import E from 'fp-ts/Either'`)\n *\n * @category zone of death\n * @since 2.0.0\n * @deprecated\n */\nexport var either = {\n URI: URI,\n map: _map,\n of: of,\n ap: _ap,\n chain: flatMap,\n reduce: _reduce,\n foldMap: _foldMap,\n reduceRight: _reduceRight,\n traverse: _traverse,\n sequence: sequence,\n bimap: _bimap,\n mapLeft: _mapLeft,\n alt: _alt,\n extend: _extend,\n chainRec: _chainRec,\n throwError: throwError\n};\n/**\n * Use [`getApplySemigroup`](./Apply.ts.html#getapplysemigroup) instead.\n *\n * Semigroup returning the left-most `Left` value. If both operands are `Right`s then the inner values\n * are concatenated using the provided `Semigroup`\n *\n * @category zone of death\n * @since 2.0.0\n * @deprecated\n */\nexport var getApplySemigroup = \n/*#__PURE__*/ getApplySemigroup_(Apply);\n/**\n * Use [`getApplicativeMonoid`](./Applicative.ts.html#getapplicativemonoid) instead.\n *\n * @category zone of death\n * @since 2.0.0\n * @deprecated\n */\nexport var getApplyMonoid = \n/*#__PURE__*/ getApplicativeMonoid(Applicative);\n/**\n * Use [`getApplySemigroup`](./Apply.ts.html#getapplysemigroup) instead.\n *\n * @category zone of death\n * @since 2.0.0\n * @deprecated\n */\nexport var getValidationSemigroup = function (SE, SA) {\n return getApplySemigroup_(getApplicativeValidation(SE))(SA);\n};\n/**\n * Use [`getApplicativeMonoid`](./Applicative.ts.html#getapplicativemonoid) instead.\n *\n * @category zone of death\n * @since 2.0.0\n * @deprecated\n */\nexport var getValidationMonoid = function (SE, MA) {\n return getApplicativeMonoid(getApplicativeValidation(SE))(MA);\n};\n/**\n * Use [`getApplicativeValidation`](#getapplicativevalidation) and [`getAltValidation`](#getaltvalidation) instead.\n *\n * @category zone of death\n * @since 2.0.0\n * @deprecated\n */\nexport function getValidation(SE) {\n var ap = getApplicativeValidation(SE).ap;\n var alt = getAltValidation(SE).alt;\n return {\n URI: URI,\n _E: undefined,\n map: _map,\n of: of,\n chain: flatMap,\n bimap: _bimap,\n mapLeft: _mapLeft,\n reduce: _reduce,\n foldMap: _foldMap,\n reduceRight: _reduceRight,\n extend: _extend,\n traverse: _traverse,\n sequence: sequence,\n chainRec: _chainRec,\n throwError: throwError,\n ap: ap,\n alt: alt\n };\n}\n","import type { MaybeAccessor } from '@/types.js';\n\nexport function access<T>(value: MaybeAccessor<T>): T {\n return typeof value === 'function' ? (value as any)() as T : value;\n}\n","import { type MethodName, supports } from '@tma.js/bridge';\nimport { type Computed, computed } from '@tma.js/signals';\nimport type { Version } from '@tma.js/types';\n\nimport type { MaybeAccessor } from '@/types.js';\nimport { access } from '@/helpers/access.js';\n\nexport function createIsSupportedSignal(\n method: MethodName,\n version: MaybeAccessor<Version>,\n): Computed<boolean> {\n return computed(() => supports(method, access(version)));\n}\n","import { getApplicativeMonoid } from './Applicative';\nimport { apFirst as apFirst_, apS as apS_, apSecond as apSecond_, getApplySemigroup as getApplySemigroup_ } from './Apply';\nimport * as chainable from './Chain';\nimport { chainEitherK as chainEitherK_, fromEitherK as fromEitherK_, tapEither as tapEither_ } from './FromEither';\nimport { constNull, constUndefined, dual, flow, identity, pipe } from './function';\nimport { as as as_, asUnit as asUnit_, bindTo as bindTo_, flap as flap_, let as let__ } from './Functor';\nimport * as _ from './internal';\nimport { not } from './Predicate';\nimport { first, last } from './Semigroup';\nimport { separated } from './Separated';\nimport { wiltDefault, witherDefault } from './Witherable';\nimport { guard as guard_ } from './Zero';\n// -------------------------------------------------------------------------------------\n// constructors\n// -------------------------------------------------------------------------------------\n/**\n * `None` doesn't have a constructor, instead you can use it directly as a value. Represents a missing value.\n *\n * @category constructors\n * @since 2.0.0\n */\nexport var none = _.none;\n/**\n * Constructs a `Some`. Represents an optional value that exists.\n *\n * @category constructors\n * @since 2.0.0\n */\nexport var some = _.some;\nexport function fromPredicate(predicate) {\n return function (a) { return (predicate(a) ? some(a) : none); };\n}\n/**\n * Returns the `Left` value of an `Either` if possible.\n *\n * @example\n * import { getLeft, none, some } from 'fp-ts/Option'\n * import { right, left } from 'fp-ts/Either'\n *\n * assert.deepStrictEqual(getLeft(right(1)), none)\n * assert.deepStrictEqual(getLeft(left('a')), some('a'))\n *\n * @category constructors\n * @since 2.0.0\n */\nexport var getLeft = function (ma) { return (ma._tag === 'Right' ? none : some(ma.left)); };\n/**\n * Returns the `Right` value of an `Either` if possible.\n *\n * @example\n * import { getRight, none, some } from 'fp-ts/Option'\n * import { right, left } from 'fp-ts/Either'\n *\n * assert.deepStrictEqual(getRight(right(1)), some(1))\n * assert.deepStrictEqual(getRight(left('a')), none)\n *\n * @category constructors\n * @since 2.0.0\n */\nexport var getRight = function (ma) { return (ma._tag === 'Left' ? none : some(ma.right)); };\nvar _map = function (fa, f) { return pipe(fa, map(f)); };\nvar _ap = function (fab, fa) { return pipe(fab, ap(fa)); };\nvar _reduce = function (fa, b, f) { return pipe(fa, reduce(b, f)); };\nvar _foldMap = function (M) {\n var foldMapM = foldMap(M);\n return function (fa, f) { return pipe(fa, foldMapM(f)); };\n};\nvar _reduceRight = function (fa, b, f) { return pipe(fa, reduceRight(b, f)); };\nvar _traverse = function (F) {\n var traverseF = traverse(F);\n return function (ta, f) { return pipe(ta, traverseF(f)); };\n};\n/* istanbul ignore next */\nvar _alt = function (fa, that) { return pipe(fa, alt(that)); };\nvar _filter = function (fa, predicate) { return pipe(fa, filter(predicate)); };\n/* istanbul ignore next */\nvar _filterMap = function (fa, f) { return pipe(fa, filterMap(f)); };\n/* istanbul ignore next */\nvar _extend = function (wa, f) { return pipe(wa, extend(f)); };\n/* istanbul ignore next */\nvar _partition = function (fa, predicate) {\n return pipe(fa, partition(predicate));\n};\n/* istanbul ignore next */\nvar _partitionMap = function (fa, f) { return pipe(fa, partitionMap(f)); };\n/**\n * @category type lambdas\n * @since 2.0.0\n */\nexport var URI = 'Option';\n/**\n * @category instances\n * @since 2.0.0\n */\nexport var getShow = function (S) { return ({\n show: function (ma) { return (isNone(ma) ? 'none' : \"some(\".concat(S.show(ma.value), \")\")); }\n}); };\n/**\n * @example\n * import { none, some, getEq } from 'fp-ts/Option'\n * import * as N from 'fp-ts/number'\n *\n * const E = getEq(N.Eq)\n * assert.strictEqual(E.equals(none, none), true)\n * assert.strictEqual(E.equals(none, some(1)), false)\n * assert.strictEqual(E.equals(some(1), none), false)\n * assert.strictEqual(E.equals(some(1), some(2)), false)\n * assert.strictEqual(E.equals(some(1), some(1)), true)\n *\n * @category instances\n * @since 2.0.0\n */\nexport var getEq = function (E) { return ({\n equals: function (x, y) { return x === y || (isNone(x) ? isNone(y) : isNone(y) ? false : E.equals(x.value, y.value)); }\n}); };\n/**\n * The `Ord` instance allows `Option` values to be compared with\n * `compare`, whenever there is an `Ord` instance for\n * the type the `Option` contains.\n *\n * `None` is considered to be less than any `Some` value.\n *\n *\n * @example\n * import { none, some, getOrd } from 'fp-ts/Option'\n * import * as N from 'fp-ts/number'\n *\n * const O = getOrd(N.Ord)\n * assert.strictEqual(O.compare(none, none), 0)\n * assert.strictEqual(O.compare(none, some(1)), -1)\n * assert.strictEqual(O.compare(some(1), none), 1)\n * assert.strictEqual(O.compare(some(1), some(2)), -1)\n * assert.strictEqual(O.compare(some(1), some(1)), 0)\n *\n * @category instances\n * @since 2.0.0\n */\nexport var getOrd = function (O) { return ({\n equals: getEq(O).equals,\n compare: function (x, y) { return (x === y ? 0 : isSome(x) ? (isSome(y) ? O.compare(x.value, y.value) : 1) : isSome(y) ? -1 : 0); }\n}); };\n/**\n * Monoid returning the left-most non-`None` value. If both operands are `Some`s then the inner values are\n * concatenated using the provided `Semigroup`\n *\n * | x | y | concat(x, y) |\n * | ------- | ------- | ------------------ |\n * | none | none | none |\n * | some(a) | none | some(a) |\n * | none | some(b) | some(b) |\n * | some(a) | some(b) | some(concat(a, b)) |\n *\n * @example\n * import { getMonoid, some, none } from 'fp-ts/Option'\n * import { SemigroupSum } from 'fp-ts/number'\n *\n * const M = getMonoid(SemigroupSum)\n * assert.deepStrictEqual(M.concat(none, none), none)\n * assert.deepStrictEqual(M.concat(some(1), none), some(1))\n * assert.deepStrictEqual(M.concat(none, some(1)), some(1))\n * assert.deepStrictEqual(M.concat(some(1), some(2)), some(3))\n *\n * @category instances\n * @since 2.0.0\n */\nexport var getMonoid = function (S) { return ({\n concat: function (x, y) { return (isNone(x) ? y : isNone(y) ? x : some(S.concat(x.value, y.value))); },\n empty: none\n}); };\n/**\n * @category mapping\n * @since 2.0.0\n */\nexport var map = function (f) { return function (fa) {\n return isNone(fa) ? none : some(f(fa.value));\n}; };\n/**\n * @category instances\n * @since 2.7.0\n */\nexport var Functor = {\n URI: URI,\n map: _map\n};\n/**\n * Maps the `Some` value of this `Option` to the specified constant value.\n *\n * @category mapping\n * @since 2.16.0\n */\nexport var as = dual(2, as_(Functor));\n/**\n * Maps the `Some` value of this `Option` to the void constant value.\n *\n * @category mapping\n * @since 2.16.0\n */\nexport var asUnit = asUnit_(Functor);\n/**\n * @category constructors\n * @since 2.7.0\n */\nexport var of = some;\n/**\n * @category instances\n * @since 2.10.0\n */\nexport var Pointed = {\n URI: URI,\n of: of\n};\n/**\n * @since 2.0.0\n */\nexport var ap = function (fa) { return function (fab) {\n return isNone(fab) ? none : isNone(fa) ? none : some(fab.value(fa.value));\n}; };\n/**\n * @category instances\n * @since 2.10.0\n */\nexport var Apply = {\n URI: URI,\n map: _map,\n ap: _ap\n};\n/**\n * @category instances\n * @since 2.7.0\n */\nexport var Applicative = {\n URI: URI,\n map: _map,\n ap: _ap,\n of: of\n};\n/**\n * @category sequencing\n * @since 2.14.0\n */\nexport var flatMap = /*#__PURE__*/ dual(2, function (ma, f) { return (isNone(ma) ? none : f(ma.value)); });\n/**\n * @category instances\n * @since 2.10.0\n */\nexport var Chain = {\n URI: URI,\n map: _map,\n ap: _ap,\n chain: flatMap\n};\n/**\n * @category instances\n * @since 2.7.0\n */\nexport var Monad = {\n URI: URI,\n map: _map,\n ap: _ap,\n of: of,\n chain: flatMap\n};\n/**\n * @category folding\n * @since 2.0.0\n */\nexport var reduce = function (b, f) { return function (fa) {\n return isNone(fa) ? b : f(b, fa.value);\n}; };\n/**\n * @category folding\n * @since 2.0.0\n */\nexport var foldMap = function (M) { return function (f) { return function (fa) {\n return isNone(fa) ? M.empty : f(fa.value);\n}; }; };\n/**\n * @category folding\n * @since 2.0.0\n */\nexport var reduceRight = function (b, f) { return function (fa) {\n return isNone(fa) ? b : f(fa.value, b);\n}; };\n/**\n * @category instances\n * @since 2.7.0\n */\nexport var Foldable = {\n URI: URI,\n reduce: _reduce,\n foldMap: _foldMap,\n reduceRight: _reduceRight\n};\n/**\n * Returns the provided `Option` `that` if `self` is `None`, otherwise returns `self`.\n *\n * @param self - The first `Option` to be checked.\n * @param that - The `Option` to return if `self` is `None`.\n *\n * @example\n * import * as O from \"fp-ts/Option\"\n *\n * assert.deepStrictEqual(O.orElse(O.none, () => O.none), O.none)\n * assert.deepStrictEqual(O.orElse(O.some(1), () => O.none), O.some(1))\n * assert.deepStrictEqual(O.orElse(O.none, () => O.some('b')), O.some('b'))\n * assert.deepStrictEqual(O.orElse(O.some(1), () => O.some('b')), O.some(1))\n *\n * @category error handling\n * @since 2.16.0\n */\nexport var orElse = dual(2, function (self, that) { return (isNone(self) ? that() : self); });\n/**\n * Alias of `orElse`.\n *\n * Less strict version of [`alt`](#alt).\n *\n * The `W` suffix (short for **W**idening) means that the return types will be merged.\n *\n * @category legacy\n * @since 2.9.0\n */\nexport var altW = orElse;\n/**\n * Alias of `orElse`.\n *\n * @category legacy\n * @since 2.0.0\n */\nexport var alt = orElse;\n/**\n * @category instances\n * @since 2.7.0\n */\nexport var Alt = {\n URI: URI,\n map: _map,\n alt: _alt\n};\n/**\n * @since 2.7.0\n */\nexport var zero = function () { return none; };\n/**\n * @category instances\n * @since 2.11.0\n */\nexport var Zero = {\n URI: URI,\n zero: zero\n};\n/**\n * @category do notation\n * @since 2.11.0\n */\nexport var guard = /*#__PURE__*/ guard_(Zero, Pointed);\n/**\n * @category instances\n * @since 2.7.0\n */\nexport var Alternative = {\n URI: URI,\n map: _map,\n ap: _ap,\n of: of,\n alt: _alt,\n zero: zero\n};\n/**\n * @since 2.0.0\n */\nexport var extend = function (f) { return function (wa) {\n return isNone(wa) ? none : some(f(wa));\n}; };\n/**\n * @category instances\n * @since 2.7.0\n */\nexport var Extend = {\n URI: URI,\n map: _map,\n extend: _extend\n};\n/**\n * @category filtering\n * @since 2.0.0\n */\nexport var compact = /*#__PURE__*/ flatMap(identity);\nvar defaultSeparated = /*#__PURE__*/ separated(none, none);\n/**\n * @category filtering\n * @since 2.0.0\n */\nexport var separate = function (ma) {\n return isNone(ma) ? defaultSeparated : separated(getLeft(ma.value), getRight(ma.value));\n};\n/**\n * @category instances\n * @since 2.7.0\n */\nexport var Compactable = {\n URI: URI,\n compact: compact,\n separate: separate\n};\n/**\n * @category filtering\n * @since 2.0.0\n */\nexport var filter = function (predicate) {\n return function (fa) {\n return isNone(fa) ? none : predicate(fa.value) ? fa : none;\n };\n};\n/**\n * @category filtering\n * @since 2.0.0\n */\nexport var filterMap = function (f) { return function (fa) {\n return isNone(fa) ? none : f(fa.value);\n}; };\n/**\n * @category filtering\n * @since 2.0.0\n */\nexport var partition = function (predicate) {\n return function (fa) {\n return separated(_filter(fa, not(predicate)), _filter(fa, predicate));\n };\n};\n/**\n * @category filtering\n * @since 2.0.0\n */\nexport var partitionMap = function (f) { return flow(map(f), separate); };\n/**\n * @category instances\n * @since 2.7.0\n */\nexport var Filterable = {\n URI: URI,\n map: _map,\n compact: compact,\n separate: separate,\n filter: _filter,\n filterMap: _filterMap,\n partition: _partition,\n partitionMap: _partitionMap\n};\n/**\n * @category traversing\n * @since 2.6.3\n */\nexport var traverse = function (F) {\n return function (f) {\n return function (ta) {\n return isNone(ta) ? F.of(none) : F.map(f(ta.value), some);\n };\n };\n};\n/**\n * @category traversing\n * @since 2.6.3\n */\nexport var sequence = function (F) {\n return function (ta) {\n return isNone(ta) ? F.of(none) : F.map(ta.value, some);\n };\n};\n/**\n * @category instances\n * @since 2.7.0\n */\nexport var Traversable = {\n URI: URI,\n map: _map,\n reduce: _reduce,\n foldMap: _foldMap,\n reduceRight: _reduceRight,\n traverse: _traverse,\n sequence: sequence\n};\nvar _wither = /*#__PURE__*/ witherDefault(Traversable, Compactable);\nvar _wilt = /*#__PURE__*/ wiltDefault(Traversable, Compactable);\n/**\n * @category filtering\n * @since 2.6.5\n */\nexport var wither = function (F) {\n var _witherF = _wither(F);\n return function (f) { return function (fa) { return _witherF(fa, f); }; };\n};\n/**\n * @category filtering\n * @since 2.6.5\n */\nexport var wilt = function (F) {\n var _wiltF = _wilt(F);\n return function (f) { return function (fa) { return _wiltF(fa, f); }; };\n};\n/**\n * @category instances\n * @since 2.7.0\n */\nexport var Witherable = {\n URI: URI,\n map: _map,\n reduce: _reduce,\n foldMap: _foldMap,\n reduceRight: _reduceRight,\n traverse: _traverse,\n sequence: sequence,\n compact: compact,\n separate: separate,\n filter: _filter,\n filterMap: _filterMap,\n partition: _partition,\n partitionMap: _partitionMap,\n wither: _wither,\n wilt: _wilt\n};\n/**\n * @since 2.7.0\n */\nexport var throwError = function () { return none; };\n/**\n * @category instances\n * @since 2.7.0\n */\nexport var MonadThrow = {\n URI: URI,\n map: _map,\n ap: _ap,\n of: of,\n chain: flatMap,\n throwError: throwError\n};\n/**\n * Transforms an `Either` to an `Option` discarding the error.\n *\n * Alias of [getRight](#getright)\n *\n * @category conversions\n * @since 2.0.0\n */\nexport var fromEither = getRight;\n/**\n * @category instances\n * @since 2.11.0\n */\nexport var FromEither = {\n URI: URI,\n fromEither: fromEither\n};\n// -------------------------------------------------------------------------------------\n// refinements\n// -------------------------------------------------------------------------------------\n/**\n * Returns `true` if the option is an instance of `Some`, `false` otherwise.\n *\n * @example\n * import { some, none, isSome } from 'fp-ts/Option'\n *\n * assert.strictEqual(isSome(some(1)), true)\n * assert.strictEqual(isSome(none), false)\n *\n * @category refinements\n * @since 2.0.0\n */\nexport var isSome = _.isSome;\n/**\n * Returns `true` if the option is `None`, `false` otherwise.\n *\n * @example\n * import { some, none, isNone } from 'fp-ts/Option'\n *\n * assert.strictEqual(isNone(some(1)), false)\n * assert.strictEqual(isNone(none), true)\n *\n * @category refinements\n * @since 2.0.0\n */\nexport var isNone = function (fa) { return fa._tag === 'None'; };\n/**\n * Less strict version of [`match`](#match).\n *\n * The `W` suffix (short for **W**idening) means that the handler return types will be merged.\n *\n * @category pattern matching\n * @since 2.10.0\n */\nexport var matchW = function (onNone, onSome) {\n return function (ma) {\n return isNone(ma) ? onNone() : onSome(ma.value);\n };\n};\n/**\n * Alias of [`matchW`](#matchw).\n *\n * @category pattern matching\n * @since 2.10.0\n */\nexport var foldW = matchW;\n/**\n * Takes a (lazy) default value, a function, and an `Option` value, if the `Option` value is `None` the default value is\n * returned, otherwise the function is applied to the value inside the `Some` and the result is returned.\n *\n * @example\n * import { some, none, match } from 'fp-ts/Option'\n * import { pipe } from 'fp-ts/function'\n *\n * assert.strictEqual(\n * pipe(\n * some(1),\n * match(() => 'a none', a => `a some containing ${a}`)\n * ),\n * 'a some containing 1'\n * )\n *\n * assert.strictEqual(\n * pipe(\n * none,\n * match(() => 'a none', a => `a some containing ${a}`)\n * ),\n * 'a none'\n * )\n *\n * @category pattern matching\n * @since 2.10.0\n */\nexport var match = matchW;\n/**\n * Alias of [`match`](#match).\n *\n * @category pattern matching\n * @since 2.0.0\n */\nexport var fold = match;\n/**\n * Less strict version of [`getOrElse`](#getorelse).\n *\n * The `W` suffix (short for **W**idening) means that the handler return type will be merged.\n *\n * @category error handling\n * @since 2.6.0\n */\nexport var getOrElseW = function (onNone) {\n return function (ma) {\n return isNone(ma) ? onNone() : ma.value;\n };\n};\n/**\n * Extracts the value out of the structure, if it exists. Otherwise returns the given default value\n *\n * @example\n * import { some, none, getOrElse } from 'fp-ts/Option'\n * import { pipe } from 'fp-ts/function'\n *\n * assert.strictEqual(\n * pipe(\n * some(1),\n * getOrElse(() => 0)\n * ),\n * 1\n * )\n * assert.strictEqual(\n * pipe(\n * none,\n * getOrElse(() => 0)\n * ),\n * 0\n * )\n *\n * @category error handling\n * @since 2.0.0\n */\nexport var getOrElse = getOrElseW;\n/**\n * @category mapping\n * @since 2.10.0\n */\nexport var flap = /*#__PURE__*/ flap_(Functor);\n/**\n * Combine two effectful actions, keeping only the result of the first.\n *\n * @since 2.0.0\n */\nexport var apFirst = /*#__PURE__*/ apFirst_(Apply);\n/**\n * Combine two effectful actions, keeping only the result of the second.\n *\n * @since 2.0.0\n */\nexport var apSecond = /*#__PURE__*/ apSecond_(Apply);\n/**\n * @category sequencing\n * @since 2.0.0\n */\nexport var flatten = compact;\n/**\n * Composes computations in sequence, using the return value of one computation to determine the next computation and\n * keeping only the result of the first.\n *\n * @category combinators\n * @since 2.15.0\n */\nexport var tap = /*#__PURE__*/ dual(2, chainable.tap(Chain));\n/**\n * Composes computations in sequence, using the return value of one computation to determine the next computation and\n * keeping only the result of the first.\n *\n * @example\n * import { pipe } from 'fp-ts/function'\n * import * as O from 'fp-ts/Option'\n * import * as E from 'fp-ts/Either'\n *\n * const compute = (value: number) => pipe(\n * O.of(value),\n * O.tapEither((value) => value > 0 ? E.right('ok') : E.left('error')),\n * )\n *\n * assert.deepStrictEqual(compute(1), O.of(1))\n * assert.deepStrictEqual(compute(-42), O.none)\n *\n * @category combinators\n * @since 2.16.0\n */\nexport var tapEither = /*#__PURE__*/ dual(2, tapEither_(FromEither, Chain));\n/**\n * @since 2.0.0\n */\nexport var duplicate = /*#__PURE__*/ extend(identity);\n/**\n * @category lifting\n * @since 2.11.0\n */\nexport var fromEitherK = /*#__PURE__*/ fromEitherK_(FromEither);\n/**\n * @category sequencing\n * @since 2.11.0\n */\nexport var chainEitherK = \n/*#__PURE__*/ chainEitherK_(FromEither, Chain);\n/**\n * Alias of `tapEither`.\n *\n * @category legacy\n * @since 2.12.0\n */\nexport var chainFirstEitherK = tapEither;\n/**\n * Constructs a new `Option` from a nullable type. If the value is `null` or `undefined`, returns `None`, otherwise\n * returns the value wrapped in a `Some`.\n *\n * @example\n * import { none, some, fromNullable } from 'fp-ts/Option'\n *\n * assert.deepStrictEqual(fromNullable(undefined), none)\n * assert.deepStrictEqual(fromNullable(null), none)\n * assert.deepStrictEqual(fromNullable(1), some(1))\n *\n * @category conversions\n * @since 2.0.0\n */\nexport var fromNullable = function (a) { return (a == null ? none : some(a)); };\n/**\n * Transforms an exception into an `Option`. If `f` throws, returns `None`, otherwise returns the output wrapped in a\n * `Some`.\n *\n * See also [`tryCatchK`](#trycatchk).\n *\n * @example\n * import { none, some, tryCatch } from 'fp-ts/Option'\n *\n * assert.deepStrictEqual(\n * tryCatch(() => {\n * throw new Error()\n * }),\n * none\n * )\n * assert.deepStrictEqual(tryCatch(() => 1), some(1))\n *\n * @category interop\n * @since 2.0.0\n */\nexport var tryCatch = function (f) {\n try {\n return some(f());\n }\n catch (e) {\n return none;\n }\n};\n/**\n * Converts a function that may throw to one returning a `Option`.\n *\n * @category interop\n * @since 2.10.0\n */\nexport var tryCatchK = function (f) {\n return function () {\n var a = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n a[_i] = arguments[_i];\n }\n return tryCatch(function () { return f.apply(void 0, a); });\n };\n};\n/**\n * Returns a *smart constructor* from a function that returns a nullable value.\n *\n * @example\n * import { fromNullableK, none, some } from 'fp-ts/Option'\n *\n * const f = (s: string): number | undefined => {\n * const n = parseFloat(s)\n * return isNaN(n) ? undefined : n\n * }\n *\n * const g = fromNullableK(f)\n *\n * assert.deepStrictEqual(g('1'), some(1))\n * assert.deepStrictEqual(g('a'), none)\n *\n * @category lifting\n * @since 2.9.0\n */\nexport var fromNullableK = function (f) { return flow(f, fromNullable); };\n/**\n * This is `chain` + `fromNullable`, useful when working with optional values.\n *\n * @example\n * import { some, none, fromNullable, chainNullableK } from 'fp-ts/Option'\n * import { pipe } from 'fp-ts/function'\n *\n * interface Employee {\n * readonly company?: {\n * readonly address?: {\n * readonly street?: {\n * readonly name?: string\n * }\n * }\n * }\n * }\n *\n * const employee1: Employee = { company: { address: { street: { name: 'high street' } } } }\n *\n * assert.deepStrictEqual(\n * pipe(\n * fromNullable(employee1.company),\n * chainNullableK(company => company.address),\n * chainNullableK(address => address.street),\n * chainNullableK(street => street.name)\n * ),\n * some('high street')\n * )\n *\n * const employee2: Employee = { company: { address: { street: {} } } }\n *\n * assert.deepStrictEqual(\n * pipe(\n * fromNullable(employee2.company),\n * chainNullableK(company => company.address),\n * chainNullableK(address => address.street),\n * chainNullableK(street => street.name)\n * ),\n * none\n * )\n *\n * @category sequencing\n * @since 2.9.0\n */\nexport var chainNullableK = function (f) {\n return function (ma) {\n return isNone(ma) ? none : fromNullable(f(ma.value));\n };\n};\n/**\n * Extracts the value out of the structure, if it exists. Otherwise returns `null`.\n *\n * @example\n * import { some, none, toNullable } from 'fp-ts/Option'\n * import { pipe } from 'fp-ts/function'\n *\n * assert.strictEqual(\n * pipe(\n * some(1),\n * toNullable\n * ),\n * 1\n * )\n * assert.strictEqual(\n * pipe(\n * none,\n * toNullable\n * ),\n * null\n * )\n *\n * @category conversions\n * @since 2.0.0\n */\nexport var toNullable = /*#__PURE__*/ match(constNull, identity);\n/**\n * Extracts the value out of the structure, if it exists. Otherwise returns `undefined`.\n *\n * @example\n * import { some, none, toUndefined } from 'fp-ts/Option'\n * import { pipe } from 'fp-ts/function'\n *\n * assert.strictEqual(\n * pipe(\n * some(1),\n * toUndefined\n * ),\n * 1\n * )\n * assert.strictEqual(\n * pipe(\n * none,\n * toUndefined\n * ),\n * undefined\n * )\n *\n * @category conversions\n * @since 2.0.0\n */\nexport var toUndefined = /*#__PURE__*/ match(constUndefined, identity);\nexport function elem(E) {\n return function (a, ma) {\n if (ma === undefined) {\n var elemE_1 = elem(E);\n return function (ma) { return elemE_1(a, ma); };\n }\n return isNone(ma) ? false : E.equals(a, ma.value);\n };\n}\n/**\n * Returns `true` if the predicate is satisfied by the wrapped value\n *\n * @example\n * import { some, none, exists } from 'fp-ts/Option'\n * import { pipe } from 'fp-ts/function'\n *\n * assert.strictEqual(\n * pipe(\n * some(1),\n * exists(n => n > 0)\n * ),\n * true\n * )\n * assert.strictEqual(\n * pipe(\n * some(1),\n * exists(n => n > 1)\n * ),\n * false\n * )\n * assert.strictEqual(\n * pipe(\n * none,\n * exists(n => n > 0)\n * ),\n * false\n * )\n *\n * @since 2.0.0\n */\nexport var exists = function (predicate) {\n return function (ma) {\n return isNone(ma) ? false : predicate(ma.value);\n };\n};\n// -------------------------------------------------------------------------------------\n// do notation\n// -------------------------------------------------------------------------------------\n/**\n * @category do notation\n * @since 2.9.0\n */\nexport var Do = /*#__PURE__*/ of(_.emptyRecord);\n/**\n * @category do notation\n * @since 2.8.0\n */\nexport var bindTo = /*#__PURE__*/ bindTo_(Functor);\nvar let_ = /*#__PURE__*/ let__(Functor);\nexport { \n/**\n * @category do notation\n * @since 2.13.0\n */\nlet_ as let };\n/**\n * @category do notation\n * @since 2.8.0\n */\nexport var bind = /*#__PURE__*/ chainable.bind(Chain);\n/**\n * @category do notation\n * @since 2.8.0\n */\nexport var apS = /*#__PURE__*/ apS_(Apply);\n/**\n * @since 2.11.0\n */\nexport var ApT = /*#__PURE__*/ of(_.emptyReadonlyArray);\n// -------------------------------------------------------------------------------------\n// array utils\n// -------------------------------------------------------------------------------------\n/**\n * Equivalent to `ReadonlyNonEmptyArray#traverseWithIndex(Applicative)`.\n *\n * @category traversing\n * @since 2.11.0\n */\nexport var traverseReadonlyNonEmptyArrayWithIndex = function (f) {\n return function (as) {\n var o = f(0, _.head(as));\n if (isNone(o)) {\n return none;\n }\n var out = [o.value];\n for (var i = 1; i < as.length; i++) {\n var o_1 = f(i, as[i]);\n if (isNone(o_1)) {\n return none;\n }\n out.push(o_1.value);\n }\n return some(out);\n };\n};\n/**\n * Equivalent to `ReadonlyArray#traverseWithIndex(Applicative)`.\n *\n * @category traversing\n * @since 2.11.0\n */\nexport var traverseReadonlyArrayWithIndex = function (f) {\n var g = traverseReadonlyNonEmptyArrayWithIndex(f);\n return function (as) { return (_.isNonEmpty(as) ? g(as) : ApT); };\n};\n/**\n * Equivalent to `ReadonlyArray#traverseWithIndex(Applicative)`.\n *\n * @category traversing\n * @since 2.9.0\n */\nexport var traverseArrayWithIndex = traverseReadonlyArrayWithIndex;\n/**\n * Equivalent to `ReadonlyArray#traverse(Applicative)`.\n *\n * @category traversing\n * @since 2.9.0\n */\nexport var traverseArray = function (f) {\n return traverseReadonlyArrayWithIndex(function (_, a) { return f(a); });\n};\n/**\n * Equivalent to `ReadonlyArray#sequence(Applicative)`.\n *\n * @category traversing\n * @since 2.9.0\n */\nexport var sequenceArray = \n/*#__PURE__*/ traverseArray(identity);\n// -------------------------------------------------------------------------------------\n// legacy\n// -------------------------------------------------------------------------------------\n/**\n * Alias of `flatMap`.\n *\n * @category legacy\n * @since 2.0.0\n */\nexport var chain = flatMap;\n/**\n * Alias of `tap`.\n *\n * @category legacy\n * @since 2.0.0\n */\nexport var chainFirst = tap;\n// -------------------------------------------------------------------------------------\n// deprecated\n// -------------------------------------------------------------------------------------\n/**\n * Use `Refinement` module instead.\n *\n * @category zone of death\n * @since 2.0.0\n * @deprecated\n */\nexport function getRefinement(getOption) {\n return function (a) { return isSome(getOption(a)); };\n}\n/**\n * Use [`chainNullableK`](#chainnullablek) instead.\n *\n * @category zone of death\n * @since 2.0.0\n * @deprecated\n */\nexport var mapNullable = chainNullableK;\n/**\n * This instance is deprecated, use small, specific instances instead.\n * For example if a function needs a `Functor` instance, pass `O.Functor` instead of `O.option`\n * (where `O` is from `import O from 'fp-ts/Option'`)\n *\n * @category zone of death\n * @since 2.0.0\n * @deprecated\n */\nexport var option = {\n URI: URI,\n map: _map,\n of: of,\n ap: _ap,\n chain: flatMap,\n reduce: _reduce,\n foldMap: _foldMap,\n reduceRight: _reduceRight,\n traverse: _traverse,\n sequence: sequence,\n zero: zero,\n alt: _alt,\n extend: _extend,\n compact: compact,\n separate: separate,\n filter: _filter,\n filterMap: _filterMap,\n partition: _partition,\n partitionMap: _partitionMap,\n wither: _wither,\n wilt: _wilt,\n throwError: throwError\n};\n/**\n * Use [`getApplySemigroup`](./Apply.ts.html#getapplysemigroup) instead.\n *\n * @category zone of death\n * @since 2.0.0\n * @deprecated\n */\nexport var getApplySemigroup = /*#__PURE__*/ getApplySemigroup_(Apply);\n/**\n * Use [`getApplicativeMonoid`](./Applicative.ts.html#getapplicativemonoid) instead.\n *\n * @category zone of death\n * @since 2.0.0\n * @deprecated\n */\nexport var getApplyMonoid = /*#__PURE__*/ getApplicativeMonoid(Applicative);\n/**\n * Use\n *\n * ```ts\n * import { first } from 'fp-ts/Semigroup'\n * import { getMonoid } from 'fp-ts/Option'\n *\n * getMonoid(first())\n * ```\n *\n * instead.\n *\n * Monoid returning the left-most non-`None` value\n *\n * | x | y | concat(x, y) |\n * | ------- | ------- | ------------ |\n * | none | none | none |\n * | some(a) | none | some(a) |\n * | none | some(b) | some(b) |\n * | some(a) | some(b) | some(a) |\n *\n * @example\n * import { getFirstMonoid, some, none } from 'fp-ts/Option'\n *\n * const M = getFirstMonoid<number>()\n * assert.deepStrictEqual(M.concat(none, none), none)\n * assert.deepStrictEqual(M.concat(some(1), none), some(1))\n * assert.deepStrictEqual(M.concat(none, some(2)), some(2))\n * assert.deepStrictEqual(M.concat(some(1), some(2)), some(1))\n *\n * @category zone of death\n * @since 2.0.0\n * @deprecated\n */\nexport var getFirstMonoid = function () { return getMonoid(first()); };\n/**\n * Use\n *\n * ```ts\n * import { last } from 'fp-ts/Semigroup'\n * import { getMonoid } from 'fp-ts/Option'\n *\n * getMonoid(last())\n * ```\n *\n * instead.\n *\n * Monoid returning the right-most non-`None` value\n *\n * | x | y | concat(x, y) |\n * | ------- | ------- | ------------ |\n * | none | none | none |\n * | some(a) | none | some(a) |\n * | none | some(b) | some(b) |\n * | some(a) | some(b) | some(b) |\n *\n * @example\n * import { getLastMonoid, some, none } from 'fp-ts/Option'\n *\n * const M = getLastMonoid<number>()\n * assert.deepStrictEqual(M.concat(none, none), none)\n * assert.deepStrictEqual(M.concat(some(1), none), some(1))\n * assert.deepStrictEqual(M.concat(none, some(2)), some(2))\n * assert.deepStrictEqual(M.concat(some(1), some(2)), some(2))\n *\n * @category zone of death\n * @since 2.0.0\n * @deprecated\n */\nexport var getLastMonoid = function () { return getMonoid(last()); };\n","import { ap as ap_ } from './Apply';\nimport * as E from './Either';\nimport { flow, pipe } from './function';\nimport { map as map_ } from './Functor';\nexport function right(F) {\n return flow(E.right, F.of);\n}\nexport function left(F) {\n return flow(E.left, F.of);\n}\nexport function rightF(F) {\n return function (fa) { return F.map(fa, E.right); };\n}\nexport function leftF(F) {\n return function (fe) { return F.map(fe, E.left); };\n}\nexport function fromNullable(F) {\n return function (e) { return flow(E.fromNullable(e), F.of); };\n}\nexport function fromNullableK(F) {\n var fromNullableF = fromNullable(F);\n return function (e) {\n var fromNullableFE = fromNullableF(e);\n return function (f) { return flow(f, fromNullableFE); };\n };\n}\nexport function chainNullableK(M) {\n var chainM = chain(M);\n var fromNullableKM = fromNullableK(M);\n return function (e) {\n var fromNullableKMe = fromNullableKM(e);\n return function (f) { return chainM(fromNullableKMe(f)); };\n };\n}\nexport function map(F) {\n return map_(F, E.Functor);\n}\nexport function ap(F) {\n return ap_(F, E.Apply);\n}\nexport function chain(M) {\n var flatMapM = flatMap(M);\n return function (f) { return function (ma) { return flatMapM(ma, f); }; };\n}\n/** @internal */\nexport function flatMap(M) {\n return function (ma, f) { return M.chain(ma, function (e) { return (E.isLeft(e) ? M.of(e) : f(e.right)); }); };\n}\nexport function alt(M) {\n return function (second) { return function (first) { return M.chain(first, function (e) { return (E.isLeft(e) ? second() : M.of(e)); }); }; };\n}\nexport function bimap(F) {\n var mapBothF = mapBoth(F);\n return function (f, g) { return function (self) { return mapBothF(self, f, g); }; };\n}\n/** @internal */\nexport function mapBoth(F) {\n return function (self, f, g) { return F.map(self, E.bimap(f, g)); };\n}\nexport function mapLeft(F) {\n var mapErrorF = mapError(F);\n return function (f) { return function (self) { return mapErrorF(self, f); }; };\n}\n/** @internal */\nexport function mapError(F) {\n return function (self, f) { return F.map(self, E.mapLeft(f)); };\n}\nexport function altValidation(M, S) {\n return function (second) { return function (first) {\n return M.chain(first, E.match(function (e1) {\n return M.map(second(), E.mapLeft(function (e2) { return S.concat(e1, e2); }));\n }, right(M)));\n }; };\n}\nexport function match(F) {\n return function (onLeft, onRight) { return function (ma) { return F.map(ma, E.match(onLeft, onRight)); }; };\n}\nexport function matchE(M) {\n return function (onLeft, onRight) { return function (ma) { return M.chain(ma, E.match(onLeft, onRight)); }; };\n}\nexport function getOrElse(M) {\n return function (onLeft) { return function (ma) { return M.chain(ma, E.match(onLeft, M.of)); }; };\n}\nexport function orElse(M) {\n return function (onLeft) { return function (ma) { return M.chain(ma, function (e) { return (E.isLeft(e) ? onLeft(e.left) : M.of(e)); }); }; };\n}\nexport function orElseFirst(M) {\n var tapErrorM = tapError(M);\n return function (onLeft) { return function (ma) { return tapErrorM(ma, onLeft); }; };\n}\n/** @internal */\nexport function tapError(M) {\n var orElseM = orElse(M);\n return function (ma, onLeft) {\n return pipe(ma, orElseM(function (e) { return M.map(onLeft(e), function (eb) { return (E.isLeft(eb) ? eb : E.left(e)); }); }));\n };\n}\nexport function orLeft(M) {\n return function (onLeft) { return function (ma) {\n return M.chain(ma, E.match(function (e) { return M.map(onLeft(e), E.left); }, function (a) { return M.of(E.right(a)); }));\n }; };\n}\nexport function swap(F) {\n return function (ma) { return F.map(ma, E.swap); };\n}\nexport function toUnion(F) {\n return function (fa) { return F.map(fa, E.toUnion); };\n}\n/** @deprecated */\n/* istanbul ignore next */\nexport function getEitherM(M) {\n var _ap = ap(M);\n var _map = map(M);\n var _chain = chain(M);\n var _alt = alt(M);\n var _bimap = bimap(M);\n var _mapLeft = mapLeft(M);\n var _fold = matchE(M);\n var _getOrElse = getOrElse(M);\n var _orElse = orElse(M);\n return {\n map: function (fa, f) { return pipe(fa, _map(f)); },\n ap: function (fab, fa) { return pipe(fab, _ap(fa)); },\n of: right(M),\n chain: function (ma, f) { return pipe(ma, _chain(f)); },\n alt: function (fa, that) { return pipe(fa, _alt(that)); },\n bimap: function (fea, f, g) { return pipe(fea, _bimap(f, g)); },\n mapLeft: function (fea, f) { return pipe(fea, _mapLeft(f)); },\n fold: function (fa, onLeft, onRight) { return pipe(fa, _fold(onLeft, onRight)); },\n getOrElse: function (fa, onLeft) { return pipe(fa, _getOrElse(onLeft)); },\n orElse: function (fa, f) { return pipe(fa, _orElse(f)); },\n swap: swap(M),\n rightM: rightF(M),\n leftM: leftF(M),\n left: left(M)\n };\n}\n","/**\n * ```ts\n * interface Task<A> {\n * (): Promise<A>\n * }\n * ```\n *\n * `Task<A>` represents an asynchronous computation that yields a value of type `A` and **never fails**.\n * If you want to represent an asynchronous computation that may fail, please see `TaskEither`.\n *\n * @since 2.0.0\n */\nimport { getApplicativeMonoid } from './Applicative';\nimport { apFirst as apFirst_, apS as apS_, apSecond as apSecond_, getApplySemigroup as getApplySemigroup_ } from './Apply';\nimport * as chainable from './Chain';\nimport { fromIOK as fromIOK_, tapIO as tapIO_ } from './FromIO';\nimport { dual, identity, pipe } from './function';\nimport { as as as_, asUnit as asUnit_, bindTo as bindTo_, flap as flap_, let as let__ } from './Functor';\nimport * as _ from './internal';\n// -------------------------------------------------------------------------------------\n// conversions\n// -------------------------------------------------------------------------------------\n/**\n * @category conversions\n * @since 2.0.0\n */\nexport var fromIO = function (ma) { return function () { return Promise.resolve().then(ma); }; };\n// -------------------------------------------------------------------------------------\n// combinators\n// -------------------------------------------------------------------------------------\n/**\n * Creates a task that will complete after a time delay\n *\n * @example\n * import { sequenceT } from 'fp-ts/Apply'\n * import * as T from 'fp-ts/Task'\n * import { takeRight } from 'fp-ts/Array'\n *\n * async function test() {\n * const log: Array<string> = []\n * const append = (message: string): T.Task<void> =>\n * T.fromIO(() => {\n * log.push(message)\n * })\n * const fa = append('a')\n * const fb = T.delay(20)(append('b'))\n * const fc = T.delay(10)(append('c'))\n * const fd = append('d')\n * await sequenceT(T.ApplyPar)(fa, fb, fc, fd)()\n * assert.deepStrictEqual(takeRight(2)(log), ['c', 'b'])\n * }\n *\n * test()\n *\n * @since 2.0.0\n */\nexport function delay(millis) {\n return function (ma) { return function () {\n return new Promise(function (resolve) {\n setTimeout(function () {\n Promise.resolve().then(ma).then(resolve);\n }, millis);\n });\n }; };\n}\nvar _map = function (fa, f) { return pipe(fa, map(f)); };\nvar _apPar = function (fab, fa) { return pipe(fab, ap(fa)); };\nvar _apSeq = function (fab, fa) { return flatMap(fab, function (f) { return pipe(fa, map(f)); }); };\n/**\n * `map` can be used to turn functions `(a: A) => B` into functions `(fa: F<A>) => F<B>` whose argument and return types\n * use the type constructor `F` to represent some computational context.\n *\n * @category mapping\n * @since 2.0.0\n */\nexport var map = function (f) { return function (fa) { return function () {\n return Promise.resolve().then(fa).then(f);\n}; }; };\n/**\n * @since 2.0.0\n */\nexport var ap = function (fa) { return function (fab) { return function () {\n return Promise.all([Promise.resolve().then(fab), Promise.resolve().then(fa)]).then(function (_a) {\n var f = _a[0], a = _a[1];\n return f(a);\n });\n}; }; };\n/**\n * @category constructors\n * @since 2.0.0\n */\nexport var of = function (a) { return function () { return Promise.resolve(a); }; };\n/**\n * @category sequencing\n * @since 2.14.0\n */\nexport var flatMap = /*#__PURE__*/ dual(2, function (ma, f) {\n return function () {\n return Promise.resolve()\n .then(ma)\n .then(function (a) { return f(a)(); });\n };\n});\n/**\n * @category sequencing\n * @since 2.0.0\n */\nexport var flatten = /*#__PURE__*/ flatMap(identity);\n/**\n * @category type lambdas\n * @since 2.0.0\n */\nexport var URI = 'Task';\n/**\n * Monoid returning the first completed task.\n *\n * Note: uses `Promise.race` internally.\n *\n * @example\n * import * as T from 'fp-ts/Task'\n *\n * async function test() {\n * const S = T.getRaceMonoid<string>()\n * const fa = T.delay(20)(T.of('a'))\n * const fb = T.delay(10)(T.of('b'))\n * assert.deepStrictEqual(await S.concat(fa, fb)(), 'b')\n * }\n *\n * test()\n *\n * @category instances\n * @since 2.0.0\n */\nexport function getRaceMonoid() {\n return {\n concat: function (x, y) { return function () { return Promise.race([Promise.resolve().then(x), Promise.resolve().then(y)]); }; },\n empty: never\n };\n}\n/**\n * @category instances\n * @since 2.7.0\n */\nexport var Functor = {\n URI: URI,\n map: _map\n};\n/**\n * Maps the value to the specified constant value.\n *\n * @category mapping\n * @since 2.16.0\n */\nexport var as = dual(2, as_(Functor));\n/**\n * Maps the value to the void constant value.\n *\n * @category mapping\n * @since 2.16.0\n */\nexport var asUnit = asUnit_(Functor);\n/**\n * @category mapping\n * @since 2.10.0\n */\nexport var flap = /*#__PURE__*/ flap_(Functor);\n/**\n * @category instances\n * @since 2.10.0\n */\nexport var Pointed = {\n URI: URI,\n of: of\n};\n/**\n * Runs computations in parallel.\n *\n * @category instances\n * @since 2.10.0\n */\nexport var ApplyPar = {\n URI: URI,\n map: _map,\n ap: _apPar\n};\n/**\n * Combine two effectful actions, keeping only the result of the first.\n *\n * @since 2.0.0\n */\nexport var apFirst = /*#__PURE__*/ apFirst_(ApplyPar);\n/**\n * Combine two effectful actions, keeping only the result of the second.\n *\n * @since 2.0.0\n */\nexport var apSecond = /*#__PURE__*/ apSecond_(ApplyPar);\n/**\n * Runs computations in parallel.\n *\n * @category instances\n * @since 2.7.0\n */\nexport var ApplicativePar = {\n URI: URI,\n map: _map,\n ap: _apPar,\n of: of\n};\n/**\n * Runs computations sequentially.\n *\n * @category instances\n * @since 2.10.0\n */\nexport var ApplySeq = {\n URI: URI,\n map: _map,\n ap: _apSeq\n};\n/**\n * Runs computations sequentially.\n *\n * @category instances\n * @since 2.7.0\n */\nexport var ApplicativeSeq = {\n URI: URI,\n map: _map,\n ap: _apSeq,\n of: of\n};\n/**\n * @category instances\n * @since 2.10.0\n */\nexport var Chain = {\n URI: URI,\n map: _map,\n ap: _apPar,\n chain: flatMap\n};\n/**\n * @category instances\n * @since 2.10.0\n */\nexport var Monad = {\n URI: URI,\n map: _map,\n of: of,\n ap: _apPar,\n chain: flatMap\n};\n/**\n * @category instances\n * @since 2.10.0\n */\nexport var MonadIO = {\n URI: URI,\n map: _map,\n of: of,\n ap: _apPar,\n chain: flatMap,\n fromIO: fromIO\n};\n/**\n * @category zone of death\n * @since 2.7.0\n * @deprecated\n */\nexport var fromTask = identity;\n/**\n * @category instances\n * @since 2.10.0\n */\nexport var MonadTask = {\n URI: URI,\n map: _map,\n of: of,\n ap: _apPar,\n chain: flatMap,\n fromIO: fromIO,\n fromTask: fromTask\n};\n/**\n * @category instances\n * @since 2.10.0\n */\nexport var FromIO = {\n URI: URI,\n fromIO: fromIO\n};\n/** @internal */\nvar _FlatMap = {\n flatMap: flatMap\n};\n/** @internal */\nvar _FromIO = {\n fromIO: FromIO.fromIO\n};\n/**\n * @category sequencing\n * @since 2.16.0\n */\nexport var flatMapIO = _.flatMapIO(_FromIO, _FlatMap);\n/**\n * Composes computations in sequence, using the return value of one computation to determine the next computation and\n * keeping only the result of the first.\n *\n * @category combinators\n * @since 2.15.0\n */\nexport var tap = /*#__PURE__*/ dual(2, chainable.tap(Chain));\n/**\n * Composes computations in sequence, using the return value of one computation to determine the next computation and\n * keeping only the result of the first.\n *\n * @example\n * import { pipe } from 'fp-ts/function'\n * import * as T from 'fp-ts/Task'\n * import * as Console from 'fp-ts/Console'\n *\n * // Will produce `Hello, fp-ts` to the stdout\n * const effect = pipe(\n * T.of('fp-ts'),\n * T.tapIO((value) => Console.log(`Hello, ${value}`)),\n * )\n *\n * async function test() {\n * assert.deepStrictEqual(await effect(), 'fp-ts')\n * }\n *\n * test()\n *\n * @category combinators\n * @since 2.16.0\n */\nexport var tapIO = /*#__PURE__*/ dual(2, tapIO_(FromIO, Chain));\n/**\n * @category lifting\n * @since 2.4.0\n */\nexport var fromIOK = \n/*#__PURE__*/ fromIOK_(FromIO);\n/**\n * Alias of `flatMapIO`.\n *\n * @category legacy\n * @since 2.4.0\n */\nexport var chainIOK = flatMapIO;\n/**\n * Alias of `tapIO`.\n *\n * @category legacy\n * @since 2.10.0\n */\nexport var chainFirstIOK = tapIO;\n/**\n * @category instances\n * @since 2.10.0\n */\nexport var FromTask = {\n URI: URI,\n fromIO: fromIO,\n fromTask: fromTask\n};\n// -------------------------------------------------------------------------------------\n// utils\n// -------------------------------------------------------------------------------------\n/**\n * A `Task` that never completes.\n *\n * @since 2.0.0\n */\nexport var never = function () { return new Promise(function (_) { return undefined; }); };\n// -------------------------------------------------------------------------------------\n// do notation\n// -------------------------------------------------------------------------------------\n/**\n * @category do notation\n * @since 2.9.0\n */\nexport var Do = /*#__PURE__*/ of(_.emptyRecord);\n/**\n * @category do notation\n * @since 2.8.0\n */\nexport var bindTo = /*#__PURE__*/ bindTo_(Functor);\nvar let_ = /*#__PURE__*/ let__(Functor);\nexport { \n/**\n * @category do notation\n * @since 2.13.0\n */\nlet_ as let };\n/**\n * @category do notation\n * @since 2.8.0\n */\nexport var bind = /*#__PURE__*/ chainable.bind(Chain);\n/**\n * @category do notation\n * @since 2.8.0\n */\nexport var apS = /*#__PURE__*/ apS_(ApplyPar);\n/**\n * @since 2.11.0\n */\nexport var ApT = /*#__PURE__*/ of(_.emptyReadonlyArray);\n// -------------------------------------------------------------------------------------\n// array utils\n// -------------------------------------------------------------------------------------\n/**\n * Equivalent to `ReadonlyNonEmptyArray#traverseWithIndex(ApplicativePar)`.\n *\n * @category traversing\n * @since 2.11.0\n */\nexport var traverseReadonlyNonEmptyArrayWithIndex = function (f) {\n return function (as) {\n return function () {\n return Promise.all(as.map(function (a, i) { return Promise.resolve().then(function () { return f(i, a)(); }); }));\n };\n };\n};\n/**\n * Equivalent to `ReadonlyArray#traverseWithIndex(ApplicativePar)`.\n *\n * @category traversing\n * @since 2.11.0\n */\nexport var traverseReadonlyArrayWithIndex = function (f) {\n var g = traverseReadonlyNonEmptyArrayWithIndex(f);\n return function (as) { return (_.isNonEmpty(as) ? g(as) : ApT); };\n};\n/**\n * Equivalent to `ReadonlyNonEmptyArray#traverseWithIndex(ApplicativeSeq)`.\n *\n * @category traversing\n * @since 2.11.0\n */\nexport var traverseReadonlyNonEmptyArrayWithIndexSeq = function (f) {\n return function (as) {\n return function () {\n return _.tail(as).reduce(function (acc, a, i) {\n return acc.then(function (bs) {\n return Promise.resolve()\n .then(f(i + 1, a))\n .then(function (b) {\n bs.push(b);\n return bs;\n });\n });\n }, Promise.resolve()\n .then(f(0, _.head(as)))\n .then(_.singleton));\n };\n };\n};\n/**\n * Equivalent to `ReadonlyArray#traverseWithIndex(ApplicativeSeq)`.\n *\n * @category traversing\n * @since 2.11.0\n */\nexport var traverseReadonlyArrayWithIndexSeq = function (f) {\n var g = traverseReadonlyNonEmptyArrayWithIndexSeq(f);\n return function (as) { return (_.isNonEmpty(as) ? g(as) : ApT); };\n};\n/**\n * Equivalent to `ReadonlyArray#traverseWithIndex(Applicative)`.\n *\n * @category traversing\n * @since 2.9.0\n */\nexport var traverseArrayWithIndex = traverseReadonlyArrayWithIndex;\n/**\n * Equivalent to `ReadonlyArray#traverse(Applicative)`.\n *\n * @category traversing\n * @since 2.9.0\n */\nexport var traverseArray = function (f) {\n return traverseReadonlyArrayWithIndex(function (_, a) { return f(a); });\n};\n/**\n * Equivalent to `ReadonlyArray#sequence(Applicative)`.\n *\n * @category traversing\n * @since 2.9.0\n */\nexport var sequenceArray = \n/*#__PURE__*/ traverseArray(identity);\n/**\n * Equivalent to `ReadonlyArray#traverseWithIndex(ApplicativeSeq)`.\n *\n * @category traversing\n * @since 2.9.0\n */\nexport var traverseSeqArrayWithIndex = traverseReadonlyArrayWithIndexSeq;\n/**\n * Equivalent to `ReadonlyArray#traverse(ApplicativeSeq)`.\n *\n * @category traversing\n * @since 2.9.0\n */\nexport var traverseSeqArray = function (f) {\n return traverseReadonlyArrayWithIndexSeq(function (_, a) { return f(a); });\n};\n/**\n * Equivalent to `ReadonlyArray#sequence(ApplicativeSeq)`.\n *\n * @category traversing\n * @since 2.9.0\n */\nexport var sequenceSeqArray = \n/*#__PURE__*/ traverseSeqArray(identity);\n// -------------------------------------------------------------------------------------\n// legacy\n// -------------------------------------------------------------------------------------\n/**\n * Alias of `flatMap`.\n *\n * @category legacy\n * @since 2.0.0\n */\nexport var chain = flatMap;\n/**\n * Alias of `tap`.\n *\n * @category legacy\n * @since 2.0.0\n */\nexport var chainFirst = tap;\n// -------------------------------------------------------------------------------------\n// deprecated\n// -------------------------------------------------------------------------------------\n/**\n * This instance is deprecated, use small, specific instances instead.\n * For example if a function needs a `Functor` instance, pass `T.Functor` instead of `T.task`\n * (where `T` is from `import T from 'fp-ts/Task'`)\n *\n * @category zone of death\n * @since 2.0.0\n * @deprecated\n */\nexport var task = {\n URI: URI,\n map: _map,\n of: of,\n ap: _apPar,\n chain: flatMap,\n fromIO: fromIO,\n fromTask: fromTask\n};\n/**\n * This instance is deprecated, use small, specific instances instead.\n * For example if a function needs a `Functor` instance, pass `T.Functor` instead of `T.taskSeq`\n * (where `T` is from `import T from 'fp-ts/Task'`)\n *\n * @category zone of death\n * @since 2.0.0\n * @deprecated\n */\nexport var taskSeq = {\n URI: URI,\n map: _map,\n of: of,\n ap: _apSeq,\n chain: flatMap,\n fromIO: fromIO,\n fromTask: fromTask\n};\n/**\n * Use [`getApplySemigroup`](./Apply.ts.html#getapplysemigroup) instead.\n *\n * @category zone of death\n * @since 2.0.0\n * @deprecated\n */\nexport var getSemigroup = /*#__PURE__*/ getApplySemigroup_(ApplySeq);\n/**\n * Use [`getApplicativeMonoid`](./Applicative.ts.html#getapplicativemonoid) instead.\n *\n * Lift a monoid into 'Task', the inner values are concatenated using the provided `Monoid`.\n *\n * @category zone of death\n * @since 2.0.0\n * @deprecated\n */\nexport var getMonoid = /*#__PURE__*/ getApplicativeMonoid(ApplicativeSeq);\n","var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nvar __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n};\nimport { getApplicativeMonoid } from './Applicative';\nimport { ap as ap_, apFirst as apFirst_, apS as apS_, apSecond as apSecond_, getApplySemigroup as getApplySemigroup_ } from './Apply';\nimport * as chainable from './Chain';\nimport { compact as compact_, separate as separate_ } from './Compactable';\nimport * as E from './Either';\nimport * as ET from './EitherT';\nimport { filter as filter_, filterMap as filterMap_, partition as partition_, partitionMap as partitionMap_ } from './Filterable';\nimport { chainOptionK as chainOptionK_, filterOrElse as filterOrElse_, fromEitherK as fromEitherK_, fromOption as fromOption_, fromOptionK as fromOptionK_, fromPredicate as fromPredicate_, tapEither as tapEither_ } from './FromEither';\nimport { fromIOK as fromIOK_, tapIO as tapIO_ } from './FromIO';\nimport { fromTaskK as fromTaskK_, tapTask as tapTask_ } from './FromTask';\nimport { dual, flow, identity, pipe, SK } from './function';\nimport { as as as_, asUnit as asUnit_, bindTo as bindTo_, flap as flap_, let as let__ } from './Functor';\nimport * as _ from './internal';\nimport * as T from './Task';\n// -------------------------------------------------------------------------------------\n// constructors\n// -------------------------------------------------------------------------------------\n/**\n * @category constructors\n * @since 2.0.0\n */\nexport var left = /*#__PURE__*/ ET.left(T.Pointed);\n/**\n * @category constructors\n * @since 2.0.0\n */\nexport var right = /*#__PURE__*/ ET.right(T.Pointed);\n/**\n * @category constructors\n * @since 2.0.0\n */\nexport var rightTask = /*#__PURE__*/ ET.rightF(T.Functor);\n/**\n * @category constructors\n * @since 2.0.0\n */\nexport var leftTask = /*#__PURE__*/ ET.leftF(T.Functor);\n/**\n * @category constructors\n * @since 2.0.0\n */\nexport var rightIO = /*#__PURE__*/ flow(T.fromIO, rightTask);\n/**\n * @category constructors\n * @since 2.0.0\n */\nexport var leftIO = /*#__PURE__*/ flow(T.fromIO, leftTask);\n// -------------------------------------------------------------------------------------\n// conversions\n// -------------------------------------------------------------------------------------\n/**\n * @category conversions\n * @since 2.7.0\n */\nexport var fromIO = rightIO;\n/**\n * @category conversions\n * @since 2.7.0\n */\nexport var fromTask = rightTask;\n/**\n * @category conversions\n * @since 2.0.0\n */\nexport var fromEither = T.of;\n/**\n * @category conversions\n * @since 2.0.0\n */\nexport var fromIOEither = T.fromIO;\n/**\n * @category conversions\n * @since 2.11.0\n */\nexport var fromTaskOption = function (onNone) {\n return T.map(E.fromOption(onNone));\n};\n/**\n * @category pattern matching\n * @since 2.10.0\n */\nexport var match = \n/*#__PURE__*/ ET.match(T.Functor);\n/**\n * Less strict version of [`match`](#match).\n *\n * The `W` suffix (short for **W**idening) means that the handler return types will be merged.\n *\n * @category pattern matching\n * @since 2.10.0\n */\nexport var matchW = match;\n/**\n * The `E` suffix (short for **E**ffect) means that the handlers return an effect (`Task`).\n *\n * @category pattern matching\n * @since 2.10.0\n */\nexport var matchE = /*#__PURE__*/ ET.matchE(T.Monad);\n/**\n * Alias of [`matchE`](#matche).\n *\n * @category pattern matching\n * @since 2.0.0\n */\nexport var fold = matchE;\n/**\n * Less strict version of [`matchE`](#matche).\n *\n * The `W` suffix (short for **W**idening) means that the handler return types will be merged.\n *\n * @category pattern matching\n * @since 2.10.0\n */\nexport var matchEW = matchE;\n/**\n * Alias of [`matchEW`](#matchew).\n *\n * @category pattern matching\n * @since 2.10.0\n */\nexport var foldW = matchEW;\n/**\n * @category error handling\n * @since 2.0.0\n */\nexport var getOrElse = \n/*#__PURE__*/ ET.getOrElse(T.Monad);\n/**\n * Less strict version of [`getOrElse`](#getorelse).\n *\n * The `W` suffix (short for **W**idening) means that the handler return type will be merged.\n *\n * @category error handling\n * @since 2.6.0\n */\nexport var getOrElseW = getOrElse;\n/**\n * Transforms a `Promise` that may reject to a `Promise` that never rejects and returns an `Either` instead.\n *\n * See also [`tryCatchK`](#trycatchk).\n *\n * @example\n * import { left, right } from 'fp-ts/Either'\n * import { tryCatch } from 'fp-ts/TaskEither'\n *\n * tryCatch(() => Promise.resolve(1), String)().then(result => {\n * assert.deepStrictEqual(result, right(1))\n * })\n * tryCatch(() => Promise.reject('error'), String)().then(result => {\n * assert.deepStrictEqual(result, left('error'))\n * })\n *\n * @category interop\n * @since 2.0.0\n */\nexport var tryCatch = function (f, onRejected) {\n return function () { return __awaiter(void 0, void 0, void 0, function () {\n var reason_1;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n _a.trys.push([0, 2, , 3]);\n return [4 /*yield*/, f().then(_.right)];\n case 1: return [2 /*return*/, _a.sent()];\n case 2:\n reason_1 = _a.sent();\n return [2 /*return*/, _.left(onRejected(reason_1))];\n case 3: return [2 /*return*/];\n }\n });\n }); };\n};\n/**\n * Converts a function returning a `Promise` to one returning a `TaskEither`.\n *\n * @category interop\n * @since 2.5.0\n */\nexport var tryCatchK = function (f, onRejected) {\n return function () {\n var a = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n a[_i] = arguments[_i];\n }\n return tryCatch(function () { return f.apply(void 0, a); }, onRejected);\n };\n};\n/**\n * @category conversions\n * @since 2.10.0\n */\nexport var toUnion = /*#__PURE__*/ ET.toUnion(T.Functor);\n/**\n * @category conversions\n * @since 2.12.0\n */\nexport var fromNullable = /*#__PURE__*/ ET.fromNullable(T.Pointed);\n/**\n * Use `liftNullable`.\n *\n * @category legacy\n * @since 2.12.0\n */\nexport var fromNullableK = /*#__PURE__*/ ET.fromNullableK(T.Pointed);\n/**\n * Use `flatMapNullable`.\n *\n * @category legacy\n * @since 2.12.0\n */\nexport var chainNullableK = \n/*#__PURE__*/ ET.chainNullableK(T.Monad);\n// -------------------------------------------------------------------------------------\n// combinators\n// -------------------------------------------------------------------------------------\n/**\n * Returns `ma` if is a `Right` or the value returned by `onLeft` otherwise.\n *\n * See also [alt](#alt).\n *\n * @example\n * import * as E from 'fp-ts/Either'\n * import { pipe } from 'fp-ts/function'\n * import * as TE from 'fp-ts/TaskEither'\n *\n * async function test() {\n * const errorHandler = TE.orElse((error: string) => TE.right(`recovering from ${error}...`))\n * assert.deepStrictEqual(await pipe(TE.right('ok'), errorHandler)(), E.right('ok'))\n * assert.deepStrictEqual(await pipe(TE.left('ko'), errorHandler)(), E.right('recovering from ko...'))\n * }\n *\n * test()\n *\n * @category error handling\n * @since 2.0.0\n */\nexport var orElse = \n/*#__PURE__*/ ET.orElse(T.Monad);\n/**\n * Less strict version of [`orElse`](#orelse).\n *\n * The `W` suffix (short for **W**idening) means that the return types will be merged.\n *\n * @category error handling\n * @since 2.10.0\n */\nexport var orElseW = orElse;\n/**\n * Returns an effect that effectfully \"peeks\" at the failure of this effect.\n *\n * @category error handling\n * @since 2.15.0\n */\nexport var tapError = /*#__PURE__*/ dual(2, ET.tapError(T.Monad));\n/**\n * @category error handling\n * @since 2.12.0\n */\nexport var orElseFirstIOK = function (onLeft) { return tapError(fromIOK(onLeft)); };\n/**\n * @category error handling\n * @since 2.12.0\n */\nexport var orElseFirstTaskK = function (onLeft) { return tapError(fromTaskK(onLeft)); };\n/**\n * @category error handling\n * @since 2.11.0\n */\nexport var orLeft = \n/*#__PURE__*/ ET.orLeft(T.Monad);\n/**\n * @since 2.0.0\n */\nexport var swap = /*#__PURE__*/ ET.swap(T.Functor);\n/**\n * @category lifting\n * @since 2.11.0\n */\nexport var fromTaskOptionK = function (onNone) {\n var from = fromTaskOption(onNone);\n return function (f) { return flow(f, from); };\n};\n/**\n * Use `flatMapTaskOption`.\n *\n * The `W` suffix (short for **W**idening) means that the error types will be merged.\n *\n * @category legacy\n * @since 2.12.3\n */\nexport var chainTaskOptionKW = function (onNone) {\n return function (f) {\n return function (ma) {\n return flatMap(ma, fromTaskOptionK(onNone)(f));\n };\n };\n};\n/**\n * Use `flatMapTaskOption`.\n *\n * @category legacy\n * @since 2.11.0\n */\nexport var chainTaskOptionK = chainTaskOptionKW;\n/**\n * @category lifting\n * @since 2.4.0\n */\nexport var fromIOEitherK = function (f) { return flow(f, fromIOEither); };\nvar _map = function (fa, f) { return pipe(fa, map(f)); };\nvar _apPar = function (fab, fa) { return pipe(fab, ap(fa)); };\nvar _apSeq = function (fab, fa) { return flatMap(fab, function (f) { return pipe(fa, map(f)); }); };\n/* istanbul ignore next */\nvar _alt = function (fa, that) { return pipe(fa, alt(that)); };\n/**\n * `map` can be used to turn functions `(a: A) => B` into functions `(fa: F<A>) => F<B>` whose argument and return types\n * use the type constructor `F` to represent some computational context.\n *\n * @category mapping\n * @since 2.0.0\n */\nexport var map = /*#__PURE__*/ ET.map(T.Functor);\n/**\n * Returns a `TaskEither` whose failure and success channels have been mapped by the specified pair of functions, `f` and `g`.\n *\n * @example\n * import * as TaskEither from 'fp-ts/TaskEither'\n * import * as Either from 'fp-ts/Either'\n *\n * const f = (s: string) => new Error(s)\n * const g = (n: number) => n * 2\n *\n * async function test() {\n * assert.deepStrictEqual(await TaskEither.mapBoth(TaskEither.right(1), f, g)(), Either.right(2))\n * assert.deepStrictEqual(await TaskEither.mapBoth(TaskEither.left('err'), f, g)(), Either.left(new Error('err')))\n * }\n *\n * test()\n *\n * @category error handling\n * @since 2.16.0\n */\nexport var mapBoth = /*#__PURE__*/ dual(3, ET.mapBoth(T.Functor));\n/**\n * Alias of `mapBoth`.\n *\n * @category legacy\n * @since 2.0.0\n */\nexport var bimap = mapBoth;\n/**\n * Returns a `TaskEither` with its error channel mapped using the specified function.\n *\n * @example\n * import * as TaskEither from 'fp-ts/TaskEither'\n * import * as Either from 'fp-ts/Either'\n *\n * const f = (s: string) => new Error(s)\n *\n * async function test() {\n * assert.deepStrictEqual(await TaskEither.mapError(TaskEither.right(1), f)(), Either.right(1))\n * assert.deepStrictEqual(await TaskEither.mapError(TaskEither.left('err'), f)(), Either.left(new Error('err')))\n * }\n *\n * test()\n *\n * @category error handling\n * @since 2.16.0\n */\nexport var mapError = /*#__PURE__*/ dual(2, ET.mapError(T.Functor));\n/**\n * Alias of `mapError`.\n *\n * @category legacy\n * @since 2.0.0\n */\nexport var mapLeft = mapError;\n/**\n * @since 2.0.0\n */\nexport var ap = \n/*#__PURE__*/ ET.ap(T.ApplyPar);\n/**\n * Less strict version of [`ap`](#ap).\n *\n * The `W` suffix (short for **W**idening) means that the error types will be merged.\n *\n * @since 2.8.0\n */\nexport var apW = ap;\n/**\n * @category sequencing\n * @since 2.14.0\n */\nexport var flatMap = /*#__PURE__*/ dual(2, ET.flatMap(T.Monad));\n/**\n * Less strict version of [`flatten`](#flatten).\n *\n * The `W` suffix (short for **W**idening) means that the error types will be merged.\n *\n * @category sequencing\n * @since 2.11.0\n */\nexport var flattenW = \n/*#__PURE__*/ flatMap(identity);\n/**\n * @category sequencing\n * @since 2.0.0\n */\nexport var flatten = flattenW;\n/**\n * Identifies an associative operation on a type constructor. It is similar to `Semigroup`, except that it applies to\n * types of kind `* -> *`.\n *\n * In case of `TaskEither` returns `fa` if is a `Right` or the value returned by `that` otherwise.\n *\n * See also [orElse](#orelse).\n *\n * @example\n * import * as E from 'fp-ts/Either'\n * import { pipe } from 'fp-ts/function'\n * import * as TE from 'fp-ts/TaskEither'\n *\n * async function test() {\n * assert.deepStrictEqual(\n * await pipe(\n * TE.right(1),\n * TE.alt(() => TE.right(2))\n * )(),\n * E.right(1)\n * )\n * assert.deepStrictEqual(\n * await pipe(\n * TE.left('a'),\n * TE.alt(() => TE.right(2))\n * )(),\n * E.right(2)\n * )\n * assert.deepStrictEqual(\n * await pipe(\n * TE.left('a'),\n * TE.alt(() => TE.left('b'))\n * )(),\n * E.left('b')\n * )\n * }\n *\n * test()\n *\n * @category error handling\n * @since 2.0.0\n */\nexport var alt = \n/*#__PURE__*/ ET.alt(T.Monad);\n/**\n * Less strict version of [`alt`](#alt).\n *\n * The `W` suffix (short for **W**idening) means that the error and the return types will be merged.\n *\n * @category error handling\n * @since 2.9.0\n */\nexport var altW = alt;\n/**\n * @category constructors\n * @since 2.0.0\n */\nexport var of = right;\n/**\n * @since 2.7.0\n */\nexport var throwError = left;\n/**\n * @category type lambdas\n * @since 2.0.0\n */\nexport var URI = 'TaskEither';\n/**\n * The default [`ApplicativePar`](#applicativepar) instance returns the first error, if you want to\n * get all errors you need to provide a way to concatenate them via a `Semigroup`.\n *\n * @example\n * import * as E from 'fp-ts/Either'\n * import { pipe } from 'fp-ts/function'\n * import * as RA from 'fp-ts/ReadonlyArray'\n * import * as S from 'fp-ts/Semigroup'\n * import * as string from 'fp-ts/string'\n * import * as T from 'fp-ts/Task'\n * import * as TE from 'fp-ts/TaskEither'\n *\n * interface User {\n * readonly id: string\n * readonly name: string\n * }\n *\n * const remoteDatabase: ReadonlyArray<User> = [\n * { id: 'id1', name: 'John' },\n * { id: 'id2', name: 'Mary' },\n * { id: 'id3', name: 'Joey' }\n * ]\n *\n * const fetchUser = (id: string): TE.TaskEither<string, User> =>\n * pipe(\n * remoteDatabase,\n * RA.findFirst((user) => user.id === id),\n * TE.fromOption(() => `${id} not found`)\n * )\n *\n * async function test() {\n * assert.deepStrictEqual(\n * await pipe(['id4', 'id5'], RA.traverse(TE.ApplicativePar)(fetchUser))(),\n * E.left('id4 not found') // <= first error\n * )\n *\n * const Applicative = TE.getApplicativeTaskValidation(\n * T.ApplyPar,\n * pipe(string.Semigroup, S.intercalate(', '))\n * )\n *\n * assert.deepStrictEqual(\n * await pipe(['id4', 'id5'], RA.traverse(Applicative)(fetchUser))(),\n * E.left('id4 not found, id5 not found') // <= all errors\n * )\n * }\n *\n * test()\n *\n * @category error handling\n * @since 2.7.0\n */\nexport function getApplicativeTaskValidation(A, S) {\n var ap = ap_(A, E.getApplicativeValidation(S));\n return {\n URI: URI,\n _E: undefined,\n map: _map,\n ap: function (fab, fa) { return pipe(fab, ap(fa)); },\n of: of\n };\n}\n/**\n * The default [`Alt`](#alt) instance returns the last error, if you want to\n * get all errors you need to provide a way to concatenate them via a `Semigroup`.\n *\n * See [`getAltValidation`](./Either.ts.html#getaltvalidation).\n *\n * @category error handling\n * @since 2.7.0\n */\nexport function getAltTaskValidation(S) {\n var alt = ET.altValidation(T.Monad, S);\n return {\n URI: URI,\n _E: undefined,\n map: _map,\n alt: function (fa, that) { return pipe(fa, alt(that)); }\n };\n}\n/**\n * @category filtering\n * @since 2.10.0\n */\nexport var getCompactable = function (M) {\n var C = E.getCompactable(M);\n return {\n URI: URI,\n _E: undefined,\n compact: compact_(T.Functor, C),\n separate: separate_(T.Functor, C, E.Functor)\n };\n};\n/**\n * @category filtering\n * @since 2.1.0\n */\nexport function getFilterable(M) {\n var F = E.getFilterable(M);\n var C = getCompactable(M);\n var filter = filter_(T.Functor, F);\n var filterMap = filterMap_(T.Functor, F);\n var partition = partition_(T.Functor, F);\n var partitionMap = partitionMap_(T.Functor, F);\n return {\n URI: URI,\n _E: undefined,\n map: _map,\n compact: C.compact,\n separate: C.separate,\n filter: function (fa, predicate) { return pipe(fa, filter(predicate)); },\n filterMap: function (fa, f) { return pipe(fa, filterMap(f)); },\n partition: function (fa, predicate) { return pipe(fa, partition(predicate)); },\n partitionMap: function (fa, f) { return pipe(fa, partitionMap(f)); }\n };\n}\n/**\n * @category instances\n * @since 2.7.0\n */\nexport var Functor = {\n URI: URI,\n map: _map\n};\n/**\n * Maps the `Right` value of this `TaskEither` to the specified constant value.\n *\n * @category mapping\n * @since 2.16.0\n */\nexport var as = dual(2, as_(Functor));\n/**\n * Maps the `Right` value of this `TaskEither` to the void constant value.\n *\n * @category mapping\n * @since 2.16.0\n */\nexport var asUnit = asUnit_(Functor);\n/**\n * @category mapping\n * @since 2.10.0\n */\nexport var flap = /*#__PURE__*/ flap_(Functor);\n/**\n * @category instances\n * @since 2.10.0\n */\nexport var Pointed = {\n URI: URI,\n of: of\n};\n/**\n * Runs computations in parallel.\n *\n * @category instances\n * @since 2.10.0\n */\nexport var ApplyPar = {\n URI: URI,\n map: _map,\n ap: _apPar\n};\n/**\n * Combine two effectful actions, keeping only the result of the first.\n *\n * @since 2.0.0\n */\nexport var apFirst = /*#__PURE__*/ apFirst_(ApplyPar);\n/**\n * Less strict version of [`apFirst`](#apfirst).\n *\n * The `W` suffix (short for **W**idening) means that the error types will be merged.\n *\n * @since 2.12.0\n */\nexport var apFirstW = apFirst;\n/**\n * Combine two effectful actions, keeping only the result of the second.\n *\n * @since 2.0.0\n */\nexport var apSecond = /*#__PURE__*/ apSecond_(ApplyPar);\n/**\n * Less strict version of [`apSecond`](#apsecond).\n *\n * The `W` suffix (short for **W**idening) means that the error types will be merged.\n *\n * @since 2.12.0\n */\nexport var apSecondW = apSecond;\n/**\n * Runs computations in parallel.\n *\n * @category instances\n * @since 2.7.0\n */\nexport var ApplicativePar = {\n URI: URI,\n map: _map,\n ap: _apPar,\n of: of\n};\n/**\n * Runs computations sequentially.\n *\n * @category instances\n * @since 2.10.0\n */\nexport var ApplySeq = {\n URI: URI,\n map: _map,\n ap: _apSeq\n};\n/**\n * Runs computations sequentially.\n *\n * @category instances\n * @since 2.7.0\n */\nexport var ApplicativeSeq = {\n URI: URI,\n map: _map,\n ap: _apSeq,\n of: of\n};\n/**\n * @category instances\n * @since 2.10.0\n */\nexport var Chain = {\n URI: URI,\n map: _map,\n ap: _apPar,\n chain: flatMap\n};\n/**\n * @category instances\n * @since 2.10.0\n */\nexport var Monad = {\n URI: URI,\n map: _map,\n ap: _apPar,\n chain: flatMap,\n of: of\n};\n/**\n * @category instances\n * @since 2.10.0\n */\nexport var MonadIO = {\n URI: URI,\n map: _map,\n ap: _apPar,\n chain: flatMap,\n of: of,\n fromIO: fromIO\n};\n/**\n * @category instances\n * @since 2.10.0\n */\nexport var MonadTask = {\n URI: URI,\n map: _map,\n ap: _apPar,\n chain: flatMap,\n of: of,\n fromIO: fromIO,\n fromTask: fromTask\n};\n/**\n * @category instances\n * @since 2.10.0\n */\nexport var MonadThrow = {\n URI: URI,\n map: _map,\n ap: _apPar,\n chain: flatMap,\n of: of,\n throwError: throwError\n};\n/**\n * @category instances\n * @since 2.10.0\n */\nexport var FromEither = {\n URI: URI,\n fromEither: fromEither\n};\n/**\n * @category instances\n * @since 2.10.0\n */\nexport var FromIO = {\n URI: URI,\n fromIO: fromIO\n};\n/**\n * @category instances\n * @since 2.10.0\n */\nexport var FromTask = {\n URI: URI,\n fromIO: fromIO,\n fromTask: fromTask\n};\n/**\n * Composes computations in sequence, using the return value of one computation to determine the next computation and\n * keeping only the result of the first.\n *\n * @category combinators\n * @since 2.15.0\n */\nexport var tap = /*#__PURE__*/ dual(2, chainable.tap(Chain));\n/**\n * Composes computations in sequence, using the return value of one computation to determine the next computation and\n * keeping only the result of the first.\n *\n * @example\n * import * as E from 'fp-ts/Either'\n * import { pipe } from 'fp-ts/function'\n * import * as TE from 'fp-ts/TaskEither'\n *\n * const checkString = (value: string) => pipe(\n * TE.of(value),\n * TE.tapEither(() => value.length > 0 ? E.right('ok') : E.left('error'))\n * )\n *\n * async function test() {\n * assert.deepStrictEqual(await checkString('')(), E.left('error'))\n * assert.deepStrictEqual(await checkString('fp-ts')(), E.right('fp-ts'))\n * }\n *\n * test()\n *\n * @category combinators\n * @since 2.16.0\n */\nexport var tapEither = /*#__PURE__*/ dual(2, tapEither_(FromEither, Chain));\n/**\n * Composes computations in sequence, using the return value of one computation to determine the next computation and\n * keeping only the result of the first.\n *\n * @example\n * import { pipe } from 'fp-ts/function'\n * import * as TE from 'fp-ts/TaskEither'\n * import * as E from 'fp-ts/Either'\n * import * as Console from 'fp-ts/Console'\n *\n *\n * // Will produce `Hello, fp-ts` to the stdout\n * const effectA = TE.tapIO(\n * TE.of(1),\n * (value) => Console.log(`Hello, ${value}`)\n * )\n *\n * // No output to the stdout\n * const effectB = pipe(\n * TE.left('error'),\n * TE.tapIO((value) => Console.log(`Hello, ${value}`))\n * )\n *\n * async function test() {\n * assert.deepStrictEqual(await effectA(), E.of(1))\n * assert.deepStrictEqual(await effectB(), E.left('error'))\n * }\n *\n * test()\n *\n * @category combinators\n * @since 2.16.0\n */\nexport var tapIO = /*#__PURE__*/ dual(2, tapIO_(FromIO, Chain));\n/**\n * Composes computations in sequence, using the return value of one computation to determine the next computation and\n * keeping only the result of the first.\n *\n * @example\n * import * as TE from 'fp-ts/TaskEither'\n * import * as T from 'fp-ts/Task'\n * import * as E from 'fp-ts/Either'\n *\n *\n * const effect = TE.tapIO(\n * TE.of(1),\n * (value) => T.of(value + 1)\n * )\n *\n * async function test() {\n * assert.deepStrictEqual(await effect(), E.of(1))\n * }\n *\n * test()\n *\n * @category combinators\n * @since 2.16.0\n */\nexport var tapTask = /*#__PURE__*/ dual(2, tapTask_(FromTask, Chain));\n/**\n * @category instances\n * @since 2.7.0\n */\nexport var Bifunctor = {\n URI: URI,\n bimap: mapBoth,\n mapLeft: mapError\n};\n/**\n * @category instances\n * @since 2.7.0\n */\nexport var Alt = {\n URI: URI,\n map: _map,\n alt: _alt\n};\n/**\n * @category conversions\n * @since 2.0.0\n */\nexport var fromOption = \n/*#__PURE__*/ fromOption_(FromEither);\n/**\n * Use `liftOption`.\n *\n * @category legacy\n * @since 2.10.0\n */\nexport var fromOptionK = \n/*#__PURE__*/ fromOptionK_(FromEither);\n/**\n * Use `flatMapOption`.\n *\n * @category legacy\n * @since 2.10.0\n */\nexport var chainOptionK = /*#__PURE__*/ chainOptionK_(FromEither, Chain);\n/**\n * Use `flatMapOption`.\n *\n * @category legacy\n * @since 2.13.2\n */\nexport var chainOptionKW = chainOptionK;\n/** @internal */\nvar _FromEither = {\n fromEither: FromEither.fromEither\n};\n/**\n * @category lifting\n * @since 2.15.0\n */\nexport var liftNullable = /*#__PURE__*/ _.liftNullable(_FromEither);\n/**\n * @category lifting\n * @since 2.15.0\n */\nexport var liftOption = /*#__PURE__*/ _.liftOption(_FromEither);\n/** @internal */\nvar _FlatMap = {\n flatMap: flatMap\n};\n/** @internal */\nvar _FromIO = {\n fromIO: FromIO.fromIO\n};\n/** @internal */\nvar _FromTask = {\n fromTask: fromTask\n};\n/**\n * @category sequencing\n * @since 2.15.0\n */\nexport var flatMapNullable = /*#__PURE__*/ _.flatMapNullable(_FromEither, _FlatMap);\n/**\n * @category sequencing\n * @since 2.15.0\n */\nexport var flatMapOption = /*#__PURE__*/ _.flatMapOption(_FromEither, _FlatMap);\n/**\n * @category sequencing\n * @since 2.15.0\n */\nexport var flatMapEither = /*#__PURE__*/ _.flatMapEither(_FromEither, _FlatMap);\n/**\n * @category sequencing\n * @since 2.15.0\n */\nexport var flatMapIO = /*#__PURE__*/ _.flatMapIO(_FromIO, _FlatMap);\n/**\n * @category sequencing\n * @since 2.16.0\n */\nexport var flatMapTask = /*#__PURE__*/ _.flatMapTask(_FromTask, _FlatMap);\n/**\n * @category sequencing\n * @since 2.16.0\n */\nexport var flatMapIOEither = /*#__PURE__*/ dual(2, function (self, f) {\n return flatMap(self, fromIOEitherK(f));\n});\n/**\n * @category sequencing\n * @since 2.16.0\n */\nexport var flatMapTaskOption = /*#__PURE__*/ dual(3, function (self, f, onNone) {\n return flatMap(self, function (a) { return fromTaskOption(function () { return onNone(a); })(f(a)); });\n});\n/**\n * Alias of `flatMapEither`.\n *\n * @category legacy\n * @since 2.4.0\n */\nexport var chainEitherK = flatMapEither;\n/**\n * Alias of `flatMapEither`.\n *\n * @category legacy\n * @since 2.6.1\n */\nexport var chainEitherKW = flatMapEither;\n/**\n * Alias of `tapEither`.\n *\n * @category legacy\n * @since 2.12.0\n */\nexport var chainFirstEitherK = tapEither;\n/**\n * Alias of `tapEither`.\n *\n * Less strict version of [`chainFirstEitherK`](#chainfirsteitherk).\n *\n * The `W` suffix (short for **W**idening) means that the error types will be merged.\n *\n * @category legacy\n * @since 2.12.0\n */\nexport var chainFirstEitherKW = tapEither;\n/**\n * @category lifting\n * @since 2.0.0\n */\nexport var fromPredicate = /*#__PURE__*/ fromPredicate_(FromEither);\n/**\n * @category filtering\n * @since 2.0.0\n */\nexport var filterOrElse = /*#__PURE__*/ filterOrElse_(FromEither, Chain);\n/**\n * Less strict version of [`filterOrElse`](#filterorelse).\n *\n * The `W` suffix (short for **W**idening) means that the error types will be merged.\n *\n * @category filtering\n * @since 2.9.0\n */\nexport var filterOrElseW = filterOrElse;\n/**\n * @category lifting\n * @since 2.4.0\n */\nexport var fromEitherK = /*#__PURE__*/ fromEitherK_(FromEither);\n/**\n * @category lifting\n * @since 2.10.0\n */\nexport var fromIOK = /*#__PURE__*/ fromIOK_(FromIO);\n/**\n * Alias of `flatMapIO`.\n *\n * @category legacy\n * @since 2.10.0\n */\nexport var chainIOK = flatMapIO;\n/**\n * Alias of `tapIO`.\n *\n * @category legacy\n * @since 2.10.0\n */\nexport var chainFirstIOK = tapIO;\n/**\n * @category lifting\n * @since 2.10.0\n */\nexport var fromTaskK = /*#__PURE__*/ fromTaskK_(FromTask);\n/**\n * Alias of `flatMapTask`.\n *\n * @category legacy\n * @since 2.10.0\n */\nexport var chainTaskK = flatMapTask;\n/**\n * Alias of `tapTask`.\n *\n * @category legacy\n * @since 2.10.0\n */\nexport var chainFirstTaskK = tapTask;\n/**\n * Alias of `flatMapIOEither`.\n *\n * Less strict version of [`chainIOEitherK`](#chainioeitherk).\n *\n * The `W` suffix (short for **W**idening) means that the error types will be merged.\n *\n * @category legacy\n * @since 2.6.1\n */\nexport var chainIOEitherKW = flatMapIOEither;\n/**\n * Alias of `flatMapIOEither`.\n *\n * @category legacy\n * @since 2.4.0\n */\nexport var chainIOEitherK = flatMapIOEither;\nexport function taskify(f) {\n return function () {\n var args = Array.prototype.slice.call(arguments);\n return function () {\n return new Promise(function (resolve) {\n var cbResolver = function (e, r) { return (e != null ? resolve(_.left(e)) : resolve(_.right(r))); };\n f.apply(null, args.concat(cbResolver));\n });\n };\n };\n}\n/**\n * Make sure that a resource is cleaned up in the event of an exception (\\*). The release action is called regardless of\n * whether the body action throws (\\*) or returns.\n *\n * (\\*) i.e. returns a `Left`\n *\n * @since 2.0.0\n */\nexport var bracket = function (acquire, use, release) { return bracketW(acquire, use, release); };\n/**\n * Less strict version of [`bracket`](#bracket).\n *\n * The `W` suffix (short for **W**idening) means that the error types will be merged.\n *\n * @since 2.12.0\n */\nexport var bracketW = function (acquire, use, release) {\n return flatMap(acquire, function (a) { return T.flatMap(use(a), function (e) { return flatMap(release(a, e), function () { return T.of(e); }); }); });\n};\n// -------------------------------------------------------------------------------------\n// do notation\n// -------------------------------------------------------------------------------------\n/**\n * @category do notation\n * @since 2.9.0\n */\nexport var Do = /*#__PURE__*/ of(_.emptyRecord);\n/**\n * @category do notation\n * @since 2.8.0\n */\nexport var bindTo = /*#__PURE__*/ bindTo_(Functor);\nvar let_ = /*#__PURE__*/ let__(Functor);\nexport { \n/**\n * @category do notation\n * @since 2.13.0\n */\nlet_ as let };\n/**\n * @category do notation\n * @since 2.8.0\n */\nexport var bind = /*#__PURE__*/ chainable.bind(Chain);\n/**\n * The `W` suffix (short for **W**idening) means that the error types will be merged.\n *\n * @category do notation\n * @since 2.8.0\n */\nexport var bindW = bind;\n/**\n * @category do notation\n * @since 2.8.0\n */\nexport var apS = /*#__PURE__*/ apS_(ApplyPar);\n/**\n * Less strict version of [`apS`](#aps).\n *\n * The `W` suffix (short for **W**idening) means that the error types will be merged.\n *\n * @category do notation\n * @since 2.8.0\n */\nexport var apSW = apS;\n/**\n * @since 2.11.0\n */\nexport var ApT = /*#__PURE__*/ of(_.emptyReadonlyArray);\n// -------------------------------------------------------------------------------------\n// array utils\n// -------------------------------------------------------------------------------------\n/**\n * Equivalent to `ReadonlyNonEmptyArray#traverseWithIndex(ApplicativePar)`.\n *\n * @category traversing\n * @since 2.11.0\n */\nexport var traverseReadonlyNonEmptyArrayWithIndex = function (f) {\n return flow(T.traverseReadonlyNonEmptyArrayWithIndex(f), T.map(E.traverseReadonlyNonEmptyArrayWithIndex(SK)));\n};\n/**\n * Equivalent to `ReadonlyArray#traverseWithIndex(ApplicativePar)`.\n *\n * @category traversing\n * @since 2.11.0\n */\nexport var traverseReadonlyArrayWithIndex = function (f) {\n var g = traverseReadonlyNonEmptyArrayWithIndex(f);\n return function (as) { return (_.isNonEmpty(as) ? g(as) : ApT); };\n};\n/**\n * Equivalent to `ReadonlyArray#traverseWithIndex(ApplicativeSeq)`.\n *\n * @category traversing\n * @since 2.11.0\n */\nexport var traverseReadonlyNonEmptyArrayWithIndexSeq = function (f) {\n return function (as) {\n return function () {\n return _.tail(as).reduce(function (acc, a, i) {\n return acc.then(function (ebs) {\n return _.isLeft(ebs)\n ? acc\n : f(i + 1, a)().then(function (eb) {\n if (_.isLeft(eb)) {\n return eb;\n }\n ebs.right.push(eb.right);\n return ebs;\n });\n });\n }, f(0, _.head(as))().then(E.map(_.singleton)));\n };\n };\n};\n/**\n * Equivalent to `ReadonlyArray#traverseWithIndex(ApplicativeSeq)`.\n *\n * @category traversing\n * @since 2.11.0\n */\nexport var traverseReadonlyArrayWithIndexSeq = function (f) {\n var g = traverseReadonlyNonEmptyArrayWithIndexSeq(f);\n return function (as) { return (_.isNonEmpty(as) ? g(as) : ApT); };\n};\n/**\n * Equivalent to `ReadonlyArray#traverseWithIndex(Applicative)`.\n *\n * @category traversing\n * @since 2.9.0\n */\nexport var traverseArrayWithIndex = traverseReadonlyArrayWithIndex;\n/**\n * Equivalent to `ReadonlyArray#traverse(Applicative)`.\n *\n * @category traversing\n * @since 2.9.0\n */\nexport var traverseArray = function (f) { return traverseReadonlyArrayWithIndex(function (_, a) { return f(a); }); };\n/**\n * Equivalent to `ReadonlyArray#sequence(Applicative)`.\n *\n * @category traversing\n * @since 2.9.0\n */\nexport var sequenceArray = \n/*#__PURE__*/ traverseArray(identity);\n/**\n * Equivalent to `ReadonlyArray#traverseWithIndex(ApplicativeSeq)`.\n *\n * @category traversing\n * @since 2.9.0\n */\nexport var traverseSeqArrayWithIndex = traverseReadonlyArrayWithIndexSeq;\n/**\n * Equivalent to `ReadonlyArray#traverse(ApplicativeSeq)`.\n *\n * @category traversing\n * @since 2.9.0\n */\nexport var traverseSeqArray = function (f) { return traverseReadonlyArrayWithIndexSeq(function (_, a) { return f(a); }); };\n/**\n * Equivalent to `ReadonlyArray#sequence(ApplicativeSeq)`.\n *\n * @category traversing\n * @since 2.9.0\n */\nexport var sequenceSeqArray = \n/*#__PURE__*/ traverseSeqArray(identity);\n// -------------------------------------------------------------------------------------\n// legacy\n// -------------------------------------------------------------------------------------\n/**\n * Alias of `flatMap`.\n *\n * @category legacy\n * @since 2.0.0\n */\nexport var chain = flatMap;\n/**\n * Alias of `flatMap`.\n *\n * @category legacy\n * @since 2.6.0\n */\nexport var chainW = flatMap;\n/**\n * Alias of `tap`.\n *\n * @category legacy\n * @since 2.0.0\n */\nexport var chainFirst = tap;\n/**\n * Alias of `tap`.\n *\n * @category legacy\n * @since 2.8.0\n */\nexport var chainFirstW = tap;\n/**\n * Alias of `tapError`.\n *\n * @category legacy\n * @since 2.11.0\n */\nexport var orElseFirst = tapError;\n/**\n * Alias of `tapError`.\n *\n * @category legacy\n * @since 2.11.0\n */\nexport var orElseFirstW = tapError;\n// -------------------------------------------------------------------------------------\n// deprecated\n// -------------------------------------------------------------------------------------\n/**\n * This instance is deprecated, use small, specific instances instead.\n * For example if a function needs a `Functor` instance, pass `TE.Functor` instead of `TE.taskEither`\n * (where `TE` is from `import TE from 'fp-ts/TaskEither'`)\n *\n * @category zone of death\n * @since 2.0.0\n * @deprecated\n */\nexport var taskEither = {\n URI: URI,\n bimap: mapBoth,\n mapLeft: mapError,\n map: _map,\n of: of,\n ap: _apPar,\n chain: flatMap,\n alt: _alt,\n fromIO: fromIO,\n fromTask: fromTask,\n throwError: throwError\n};\n/**\n * This instance is deprecated, use small, specific instances instead.\n * For example if a function needs a `Functor` instance, pass `TE.Functor` instead of `TE.taskEitherSeq`\n * (where `TE` is from `import TE from 'fp-ts/TaskEither'`)\n *\n * @category zone of death\n * @since 2.0.0\n * @deprecated\n */\nexport var taskEitherSeq = {\n URI: URI,\n bimap: mapBoth,\n mapLeft: mapError,\n map: _map,\n of: of,\n ap: _apSeq,\n chain: flatMap,\n alt: _alt,\n fromIO: fromIO,\n fromTask: fromTask,\n throwError: throwError\n};\n/**\n * Use [`getApplySemigroup`](./Apply.ts.html#getapplysemigroup) instead.\n *\n * @category zone of death\n * @since 2.0.0\n * @deprecated\n */\nexport var getApplySemigroup = \n/*#__PURE__*/ getApplySemigroup_(ApplySeq);\n/**\n * Use [`getApplicativeMonoid`](./Applicative.ts.html#getapplicativemonoid) instead.\n *\n * @category zone of death\n * @since 2.0.0\n * @deprecated\n */\nexport var getApplyMonoid = \n/*#__PURE__*/ getApplicativeMonoid(ApplicativeSeq);\n/**\n * Use [`getApplySemigroup`](./Apply.ts.html#getapplysemigroup) instead.\n *\n * @category zone of death\n * @since 2.0.0\n * @deprecated\n */\nexport var getSemigroup = function (S) {\n return getApplySemigroup_(T.ApplySeq)(E.getSemigroup(S));\n};\n/**\n * Use [`getApplicativeTaskValidation`](#getapplicativetaskvalidation) and [`getAltTaskValidation`](#getalttaskvalidation) instead.\n *\n * @category zone of death\n * @since 2.0.0\n * @deprecated\n */\nexport function getTaskValidation(SE) {\n var applicativeTaskValidation = getApplicativeTaskValidation(T.ApplicativePar, SE);\n var altTaskValidation = getAltTaskValidation(SE);\n return {\n URI: URI,\n _E: undefined,\n map: _map,\n ap: applicativeTaskValidation.ap,\n of: of,\n chain: flatMap,\n bimap: mapBoth,\n mapLeft: mapError,\n alt: altTaskValidation.alt,\n fromIO: fromIO,\n fromTask: fromTask,\n throwError: throwError\n };\n}\n","import { errorClass, errorClassWithData } from 'error-kid';\nimport type { BaseIssue } from 'valibot';\n\nfunction msgToTuple(message?: string): [string?] {\n return [message];\n}\n\nexport class ValidationError extends errorClassWithData<\n { input: unknown; issues: BaseIssue<any>[] },\n [input: unknown, issues: BaseIssue<any>[]]\n>(\n 'ValidationError',\n (input, issues) => ({ input, issues }),\n 'Validation error',\n) {\n}\n\nexport class CSSVarsBoundError extends errorClass(\n 'CSSVarsBoundError',\n 'CSS variables are already bound',\n) {\n}\n\nexport class NotAvailableError extends errorClass<[message: string]>(\n 'NotAvailableError',\n msgToTuple,\n) {\n}\n\nexport class InvalidEnvError extends errorClass<[message?: string]>(\n 'InvalidEnvError',\n msgToTuple,\n) {\n}\n\nexport class FunctionUnavailableError extends errorClass<[message?: string]>(\n 'FunctionNotAvailableError',\n msgToTuple,\n) {\n}\n\nexport class InvalidArgumentsError extends errorClass<[message: string, cause?: unknown]>(\n 'InvalidArgumentsError',\n (message, cause) => [message, { cause }],\n) {\n}\n\nexport class ConcurrentCallError extends errorClass<[message: string]>(\n 'ConcurrentCallError',\n msgToTuple,\n) {\n}\n\nexport class SetEmojiStatusError extends errorClass<[error: string]>(\n 'SetEmojiStatusError',\n error => [`Failed to set emoji status: ${error}`],\n) {\n}\n\nexport class AccessDeniedError extends errorClass<[message: string]>(\n 'AccessDeniedError',\n msgToTuple,\n) {\n}\n\nexport class FullscreenFailedError extends errorClass<[message: string]>(\n 'FullscreenFailedError',\n msgToTuple,\n) {\n}\n\nexport class ShareMessageError extends errorClass<[error: string]>(\n 'ShareMessageError',\n msgToTuple,\n) {\n}\n\nexport class UnknownThemeParamsKeyError extends errorClass<[key: string]>(\n 'UnknownThemeParamsKeyError',\n key => [`Unknown theme params key passed: ${key}`],\n) {\n}\n","import {\n type MethodName,\n supports,\n type MethodNameWithVersionedParams,\n type MethodVersionedParams,\n} from '@tma.js/bridge';\nimport { type Computed, computed } from '@tma.js/signals';\nimport type {\n If,\n IsNever,\n AnyFnAnyEither,\n RightOfReturn,\n LeftOfReturn,\n MaybeMonadReturnTypeToCommon,\n AnyFn,\n} from '@tma.js/toolkit';\nimport type { Version } from '@tma.js/types';\nimport * as O from 'fp-ts/Option';\nimport * as E from 'fp-ts/Either';\nimport * as TE from 'fp-ts/TaskEither';\n\nimport { FunctionUnavailableError } from '@/errors.js';\nimport type { MaybeAccessor } from '@/types.js';\nimport { access } from '@/helpers/access.js';\n\ntype IfReturnsTask<Fn extends AnyFnAnyEither, A, B> =\n ReturnType<Fn> extends TE.TaskEither<any, any> ? A : B;\n\ntype OptionsBasedRequires<O extends WithChecksOptions<any>> = O extends { requires: any }\n ? true : false;\n\ntype OptionsBasedSupports<O extends WithChecksOptions<any>> = O extends { supports: any }\n ? Extract<keyof O['supports'], string> : never;\n\ntype OptionsBasedFn<Opts extends WithChecksOptions<any>> = (...args: any[]) => (\n Opts['returns'] extends 'plain'\n ? any\n : Opts['returns'] extends 'promise'\n ? PromiseLike<any>\n : Opts['returns'] extends 'task'\n ? TE.TaskEither<any, any>\n : E.Either<any, any>\n);\n\n/**\n * @returns Error text if something is wrong.\n */\nexport type CustomSupportFn = () => string | undefined;\n\nexport type Require =\n | MethodName\n | CustomSupportFn\n | { every: (MethodName | CustomSupportFn)[] }\n | { some: (MethodName | CustomSupportFn)[] };\n\n/**\n * A map where the key is a method name with versioned parameters, and the value is a tuple\n * containing the method and parameter names. The third tuple value is a function accepting\n * the wrapped function arguments and returning true if support check must be applied.\n */\nexport type SupportsMap<Args extends any[]> = {\n [OptionName: string]: {\n [M in MethodNameWithVersionedParams]: {\n /**\n * Method name.\n * @example 'web_app_set_header_color'\n */\n method: M;\n /**\n * Method version-dependent parameter.\n * @example `color`\n */\n param: MethodVersionedParams<M>;\n /**\n * @returns True if the support function should be called.\n * @param args - function arguments.\n */\n shouldCheck: (...args: Args) => boolean;\n };\n }[MethodNameWithVersionedParams];\n};\n\ntype WrappedFnReturnType<Fn extends AnyFn> = ReturnType<Fn> extends E.Either<any, any>\n ? E.Either<FunctionUnavailableError | LeftOfReturn<Fn>, RightOfReturn<Fn>>\n : ReturnType<Fn> extends TE.TaskEither<any, any>\n ? TE.TaskEither<FunctionUnavailableError | LeftOfReturn<Fn>, RightOfReturn<Fn>>\n : ReturnType<Fn> extends PromiseLike<infer U>\n ? TE.TaskEither<FunctionUnavailableError, U>\n : E.Either<FunctionUnavailableError, ReturnType<Fn>>;\n\nexport type WrappedFn<Fn extends AnyFn> = (...args: Parameters<Fn>) => WrappedFnReturnType<Fn>;\n\nexport type WithChecksFp<\n Fn extends AnyFn,\n HasSupportCheck extends boolean,\n SupportsMapKeySchema extends string = never,\n> =\n & WrappedFn<Fn>\n & {\n /**\n * A signal returning `true` if the function is available in the current environment and\n * conditions.\n *\n * To be more accurate, the method checks the following:\n * 1. The current environment is Telegram Mini Apps.\n * 2. The SDK package is initialized (if this requirement is specified).\n * 3. If passed, the `isSupported` signal returned true.\n * 4. If passed, the `isMounted` signal returned true.\n *\n * *You should use this function when possible because it provides must-have code security\n * mechanisms and makes a developer sure that he is using the package properly.*\n *\n * @returns True if the function is available in the current environment.\n * @example\n * if (backButton.show.isAvailable()) {\n * backButton.show();\n * }\n */\n isAvailable: Computed<boolean>;\n /**\n * Calls the function only in case it is available.\n *\n * It uses the `isAvailable` internally to check if the function is available for call.\n * @example\n * backButton.show.ifAvailable();\n */\n ifAvailable(...args: Parameters<Fn>): O.Option<ReturnType<Fn>>;\n }\n & If<HasSupportCheck, {\n /**\n * The signal returning `true` if the function is supported by the Telegram client,\n * including some possible additional conditions.\n *\n * It is highly recommended to use this signal only in certain narrow cases when only the\n * function support check is required, but not its availability.\n *\n * This signal is not applying additional operations like checking if the current environment\n * is Mini Apps and the SDK is initialized.\n *\n * To check if the function is available for use, use the `isAvailable` signal.\n *\n * @returns True if this function is supported.\n * @see isAvailable\n * @example\n * if (backButton.show.isSupported()) {\n * console.log('The method is supported');\n * }\n */\n isSupported: Computed<boolean>;\n }, {}>\n & If<IsNever<SupportsMapKeySchema>, {}, {\n /**\n * A map where the key is the function-specific option name and value is a signal indicating\n * if it is supported by the current environment.\n * @example\n * if (miniApp.setHeaderColor.isAvailable()) {\n * if (miniApp.setHeaderColor.supports('rgb')) {\n * miniApp.setHeaderColor('#ffaabb');\n * } else {\n * miniApp.setHeaderColor('bg_color');\n * }\n * }\n */\n supports: (key: SupportsMapKeySchema) => boolean;\n }>;\n\nexport type WithChecks<\n Fn extends AnyFn,\n HasSupportCheck extends boolean,\n SupportsMapKeySchema extends string = never,\n> =\n & ((...args: Parameters<Fn>) => MaybeMonadReturnTypeToCommon<Fn>)\n & Omit<WithChecksFp<Fn, HasSupportCheck, SupportsMapKeySchema>, 'ifAvailable'>\n & {\n /**\n * Calls the function only in case it is available.\n *\n * It uses the `isAvailable` internally to check if the function is available for call.\n * @example\n * backButton.show.ifAvailable();\n */\n ifAvailable(...args: Parameters<Fn>):\n | { ok: true; data: MaybeMonadReturnTypeToCommon<Fn> }\n | { ok: false };\n };\n\nexport interface WithChecksOptions<Fn extends AnyFn> {\n /**\n * Signal returning true if the owning component is mounted.\n */\n isMounted?: () => boolean;\n /**\n * Signal returning true if the owning component is mounting.\n */\n isMounting?: () => boolean;\n /**\n * A value determining the function requirements. This will enable additional checks for\n * the function before being called.\n */\n requires?: Require;\n /**\n * A signal to retrieve the current Telegram Mini Apps version or the value itself.\n */\n isTma: MaybeAccessor<boolean>;\n /**\n * A map where the key is a method name with versioned parameters, and the value is a tuple\n * containing the method and parameter names. The third tuple value is a function accepting\n * the wrapped function arguments and returning true if support check must be applied.\n */\n supports?: SupportsMap<Parameters<Fn>>;\n /**\n * A signal to retrieve the current Telegram Mini Apps version or the value itself.\n */\n version?: MaybeAccessor<Version>;\n /**\n * Allows to determine what exactly should be returned from the function - TaskEither or Either.\n * There is no other way to know it until the function itself is called, but we need to perform\n * some checks before calling it and return a valid value based on the function return type.\n */\n returns: Fn extends AnyFnAnyEither\n ? IfReturnsTask<Fn, 'task', 'either'>\n : ReturnType<Fn> extends PromiseLike<any> ? 'promise' : 'plain';\n}\n\nexport function withChecksFp<Fn extends AnyFn, O extends WithChecksOptions<Fn>>(\n fn: Fn,\n options: O,\n): WithChecksFp<Fn, OptionsBasedRequires<O>, OptionsBasedSupports<O>> {\n const version = computed(() => access(options.version) || '100');\n const isTma = computed(() => access(options.isTma));\n\n // Simplify the isSupported value to work with an array of validators or a single object.\n const { requires: optionsIsSupported } = options;\n const isSupportedSimplified = optionsIsSupported\n ? typeof optionsIsSupported === 'object'\n ? optionsIsSupported\n : { every: [optionsIsSupported] }\n : undefined;\n\n /**\n * @param optionName - target option.\n * @returns True if specified option is supported.\n */\n const isOptionSupported = (optionName: string): boolean => {\n if (!options.supports) {\n return true;\n }\n const optionSettings = options.supports[optionName];\n return supports(optionSettings.method, optionSettings.param, version());\n };\n\n /**\n * @returns All found errors according to the isSupported variable value.\n */\n const calculateSupportError = (): string | undefined => {\n // isSupported was not specified. In this case, we assume that the function has no\n // dependencies and is always supported.\n if (!isSupportedSimplified) {\n return;\n }\n const [mode, requirements] = 'every' in isSupportedSimplified\n ? ['every', isSupportedSimplified.every] as const\n : ['some', isSupportedSimplified.some] as const;\n\n for (let i = 0; i < requirements.length; i++) {\n const requirement = requirements[i];\n const error = typeof requirement === 'function'\n ? requirement()\n : supports(requirement, version())\n ? undefined\n : `it is unsupported in Mini Apps version ${version()}`;\n // Return only if there was an error and all requirements must be satisfied, or\n // this was the last one requirement (when some of the requirements must be met).\n if (error && (mode === 'every' || i === requirements.length - 1)) {\n return error;\n }\n }\n };\n\n /**\n * @returns An error related to supports.<name> check.\n */\n const calculateOptionSupportError = (\n ...args: Parameters<Fn>\n ): string | undefined => {\n for (const k in options.supports) {\n if (options.supports[k].shouldCheck(...args) && !isOptionSupported(k)) {\n return `option ${k} is not supported in Mini Apps version ${version()}`;\n }\n }\n };\n\n const isSupported = computed(() => !calculateSupportError());\n const isInitialized = computed(() => version() !== '0.0');\n const isMounted = computed(() => (options.isMounted ? options.isMounted() : true));\n const isAvailable = computed(\n () => isTma()\n && isInitialized()\n && isSupported()\n && isMounted(),\n );\n\n const wrapError = (message: string): WrappedFnReturnType<Fn> => {\n const err = new FunctionUnavailableError(message);\n return (['task', 'promise'].includes(options.returns)\n ? TE.left(err)\n : E.left(err)) as WrappedFnReturnType<Fn>;\n };\n\n return Object.assign(\n (...args: Parameters<Fn>): WrappedFnReturnType<Fn> => {\n const errMessagePrefix = 'Unable to call function:';\n if (!isTma()) {\n return wrapError(`${errMessagePrefix} it can't be called outside Mini Apps`);\n }\n if (!isInitialized()) {\n return wrapError(`${errMessagePrefix} the SDK was not initialized. Use the SDK init() function`);\n }\n const supportErr = calculateSupportError();\n if (supportErr) {\n return wrapError(`${errMessagePrefix} ${supportErr}`);\n }\n const supportsOptionErr = calculateOptionSupportError(...args);\n if (supportsOptionErr) {\n return wrapError(`${errMessagePrefix} ${supportsOptionErr}`);\n }\n if (!isMounted()) {\n const message = options.isMounting?.()\n ? 'mounting. Wait for the mount completion'\n : 'unmounted. Use the mount() method';\n return wrapError(`${errMessagePrefix} the component is ${message}`);\n }\n const { returns } = options;\n if (returns === 'plain') {\n return E.tryCatch(() => fn(...args), e => e) as WrappedFnReturnType<Fn>;\n }\n if (returns === 'promise') {\n return TE.tryCatch(() => fn(...args), e => e) as WrappedFnReturnType<Fn>;\n }\n return fn(...args);\n },\n fn,\n {\n isAvailable,\n ifAvailable(...args: Parameters<Fn>): O.Option<ReturnType<Fn>> {\n return isAvailable() ? O.some(fn(...args) as ReturnType<Fn>) : O.none;\n },\n },\n isSupportedSimplified ? { isSupported } : {},\n options.supports ? { supports: isOptionSupported } : {},\n );\n}\n\nexport function createWithChecksFp<O extends WithChecksOptions<any>>(options: O) {\n return <Fn extends OptionsBasedFn<O>>(fn: Fn): WithChecksFp<\n Fn,\n OptionsBasedRequires<O>,\n OptionsBasedSupports<O>\n > => withChecksFp(fn, options);\n}\n","import { pipe } from 'fp-ts/function';\nimport * as O from 'fp-ts/Option';\nimport { throwifyFpFn, throwifyAnyEither, type AnyFn } from '@tma.js/toolkit';\n\nimport type { WithChecksFp, WithChecks } from '@/with-checks/withChecksFp.js';\n\nexport function throwifyWithChecksFp<\n Fn extends AnyFn,\n HasSupportCheck extends boolean,\n SupportsMapKeySchema extends string,\n>(\n fn: WithChecksFp<Fn, HasSupportCheck, SupportsMapKeySchema>,\n): WithChecks<Fn, HasSupportCheck, SupportsMapKeySchema> {\n return Object.assign(throwifyFpFn(fn), {\n ifAvailable(...args: Parameters<Fn>) {\n return pipe(\n fn.ifAvailable(...args),\n O.match(\n () => ({ ok: false }),\n data => ({\n ok: true,\n data: throwifyAnyEither(data),\n }),\n ),\n );\n },\n }) as unknown as WithChecks<Fn, HasSupportCheck, SupportsMapKeySchema>;\n}\n","import type { UnionRequiredKeys } from '@tma.js/toolkit';\n\ntype RemoveUndefined<T> = {\n [K in UnionRequiredKeys<T>]-?: T[K]\n};\n\n/**\n * @returns Object with keys having undefined values.\n * @param value - an object to remove undefined values from.\n */\nexport function removeUndefined<T extends {}>(value: T): RemoveUndefined<T> {\n const result = {} as RemoveUndefined<T>;\n for (const k in value) {\n const v = value[k];\n v !== undefined && ((result as any)[k] = v);\n }\n return result;\n}\n","export function shallowEqual<T extends object>(a: T, b: T): boolean {\n const aKeys = Object.keys(a);\n const bKeys = Object.keys(b);\n return aKeys.length !== bKeys.length\n ? false\n : aKeys.every(aKey => {\n return Object.prototype.hasOwnProperty.call(b, aKey)\n && (a as any)[aKey] === (b as any)[aKey];\n });\n}\n","import { type Computed, computed, type Signal, signal } from '@tma.js/signals';\n\nimport { removeUndefined } from '@/helpers/removeUndefined.js';\nimport { shallowEqual } from '@/helpers/shallowEqual.js';\n\nexport interface StatefulOptions<S> {\n /**\n * The initial state.\n */\n initialState: S;\n /**\n * A function to call whenever the state changes.\n * @param state - updated state.\n */\n onChange: (state: S) => void;\n}\n\nexport class Stateful<S extends object> {\n constructor({ initialState, onChange }: StatefulOptions<S>) {\n this._state = signal(initialState, { equals: shallowEqual });\n this.state = computed(this._state);\n this.state.sub(onChange);\n }\n\n protected readonly _state: Signal<S>;\n\n /**\n * The current state.\n */\n readonly state: Computed<S>;\n\n /**\n * Creates a computed signal based on the state.\n * @param key - a state key to use as a source.\n */\n getter<K extends keyof S>(key: K): Computed<S[K]> {\n return computed(() => this._state()[key]);\n }\n\n /**\n * Updates the state.\n * @param state - updates to apply.\n */\n readonly setState = (state: Partial<S>): void => {\n const nextState = { ...this.state(), ...removeUndefined(state) };\n if (!shallowEqual(nextState, this.state())) {\n this._state.set(nextState);\n }\n };\n\n /**\n * @returns True if specified payload will update the state.\n * @param state\n */\n hasDiff(state: Partial<S>): boolean {\n return !shallowEqual({ ...this.state(), ...removeUndefined(state) }, this.state());\n }\n}\n","import { batch, computed, signal } from '@tma.js/signals';\nimport * as E from 'fp-ts/Either';\nimport { pipe } from 'fp-ts/function';\n\nimport type { MaybeAccessor } from '@/types.js';\nimport { access } from '@/helpers/access.js';\n\nexport interface MountableOptions<S, Err> {\n /**\n * A state to use if the `restoreState` function returned falsy value or\n * `isPageReload` returned false.\n */\n initialState: S | (() => E.Either<Err, S>);\n /**\n * @returns True if the current page was reloaded.\n */\n isPageReload: MaybeAccessor<boolean>;\n /**\n * A function to call whenever the component was mounted.\n * @param state - restored state.\n */\n onMounted?: (state: S) => void;\n /**\n * A function to call whenever the component was unmounted.\n */\n onUnmounted?: VoidFunction;\n /**\n * Attempts to restore previously saved component state. This function\n * will only be called if the current page was reloaded.\n */\n restoreState: () => (S | undefined);\n}\n\nexport class Mountable<S extends object, Err = never> {\n constructor({\n onMounted,\n restoreState,\n initialState,\n onUnmounted,\n isPageReload,\n }: MountableOptions<S, Err>) {\n this.mount = () => {\n if (this.isMounted()) {\n return E.right(undefined);\n }\n const restored = access(isPageReload) ? restoreState() : undefined;\n const state = restored\n ? E.right(restored)\n : (typeof initialState === 'function' ? initialState() : E.right(initialState));\n\n return pipe(state, E.map(s => {\n batch(() => {\n this._isMounted.set(true);\n onMounted?.(s);\n });\n }));\n };\n\n this.unmount = () => {\n if (this._isMounted()) {\n batch(() => {\n this._isMounted.set(false);\n onUnmounted?.();\n });\n }\n };\n }\n\n private readonly _isMounted = signal(false);\n\n /**\n * Signal indicating if the component is mounted.\n */\n readonly isMounted = computed(this._isMounted);\n\n /**\n * Mounts the component restoring its state and calling required side effects.\n */\n readonly mount: () => E.Either<Err, void>;\n\n /**\n * Unmounts the component.\n */\n readonly unmount: () => void;\n}\n","import * as E from 'fp-ts/Either';\nimport { pipe } from 'fp-ts/function';\nimport { computed, type Computed } from '@tma.js/signals';\nimport type { PostEventError, MethodName, MethodParams } from '@tma.js/bridge';\n\nimport { createIsSupportedSignal } from '@/helpers/createIsSupportedSignal.js';\nimport {\n type WithChecksFp,\n type WithChecks,\n createWithChecksFp,\n} from '@/with-checks/withChecksFp.js';\nimport { throwifyWithChecksFp } from '@/with-checks/throwifyWithChecksFp.js';\nimport type { SharedFeatureOptions } from '@/fn-options/sharedFeatureOptions.js';\nimport type { WithStateRestore } from '@/fn-options/withStateRestore.js';\nimport { Stateful } from '@/composables/Stateful.js';\nimport { Mountable } from '@/composables/Mountable.js';\nimport { removeUndefined } from '@/helpers/removeUndefined.js';\nimport type { WithPostEvent } from '@/fn-options/withPostEvent.js';\nimport type { WithVersion } from '@/fn-options/withVersion.js';\n\ntype ButtonEither = E.Either<PostEventError, void>;\n\ntype BoolFields<S> = {\n [K in keyof S]-?: S[K] extends boolean ? K : never;\n}[keyof S];\n\nexport interface ButtonOptions<S, M extends MethodName>\n extends SharedFeatureOptions,\n WithStateRestore<S>,\n WithPostEvent,\n WithVersion {\n /**\n * The initial button state.\n */\n initialState: S;\n /**\n * Removes a component click listener.\n * @param listener - a listener to remove.\n * @param once - should the listener be called only once.\n */\n offClick: (listener: VoidFunction, once?: boolean) => void;\n /**\n * Adds a component click listener.\n * @returns A function to remove listener.\n * @param listener - a listener to add.\n * @param once - should the listener be called only once.\n */\n onClick: (listener: VoidFunction, once?: boolean) => VoidFunction;\n /**\n * A Mini Apps method to commit changes.\n */\n method: M;\n /**\n * A function to create method payload.\n * @param state\n */\n payload: (state: S) => MethodParams<M>;\n}\n\nexport class Button<S extends object, M extends MethodName> {\n constructor({\n isTma,\n storage,\n onClick,\n offClick,\n initialState,\n isPageReload,\n postEvent,\n payload,\n method,\n version,\n }: ButtonOptions<S, M>) {\n const stateful = new Stateful({\n initialState,\n onChange(state) {\n storage.set(state);\n },\n });\n const mountable = new Mountable<S>({\n initialState,\n isPageReload,\n onMounted: stateful.setState,\n restoreState: storage.get,\n });\n\n const wrapOptions = { version, requires: method, isTma };\n const wrapSupportedPlain = createWithChecksFp({\n ...wrapOptions,\n returns: 'plain',\n });\n const wrapMountedEither = createWithChecksFp({\n ...wrapOptions,\n returns: 'either',\n isMounted: mountable.isMounted,\n });\n\n this.isMounted = mountable.isMounted;\n this.isSupported = createIsSupportedSignal(method, version);\n this.state = stateful.state;\n\n this.setStateFp = wrapMountedEither(state => {\n const nextState = { ...this.state(), ...removeUndefined(state) };\n if (!stateful.hasDiff(nextState)) {\n return E.right(undefined);\n }\n return pipe(\n postEvent(method as any, payload(nextState)),\n E.map(() => {\n stateful.setState(nextState);\n }),\n );\n });\n this.setState = throwifyWithChecksFp(this.setStateFp);\n this.onClickFp = wrapSupportedPlain(onClick);\n this.onClick = throwifyWithChecksFp(this.onClickFp);\n this.offClickFp = wrapSupportedPlain(offClick);\n this.offClick = throwifyWithChecksFp(this.offClickFp);\n this.mountFp = wrapSupportedPlain(() => {\n const nothing = () => undefined;\n return pipe(mountable.mount(), E.match(nothing, nothing));\n });\n this.mount = throwifyWithChecksFp(this.mountFp);\n this.unmount = mountable.unmount;\n this.stateSetters = key => {\n const wrapped = wrapMountedEither(value => {\n return this.setStateFp({ [key]: value } as unknown as Partial<S>);\n });\n return [throwifyWithChecksFp(wrapped), wrapped];\n };\n this.stateBoolSetters = <K extends keyof S>(key: K) => {\n const [, setFp] = this.stateSetters(key);\n const setFalse = wrapMountedEither(() => setFp(false as S[K]));\n const setTrue = wrapMountedEither(() => setFp(true as S[K]));\n return [\n [throwifyWithChecksFp(setFalse), setFalse],\n [throwifyWithChecksFp(setTrue), setTrue],\n ];\n };\n }\n\n /**\n * Signal indicating if the component is currently mounted.\n */\n readonly isMounted: Computed<boolean>;\n\n /**\n * Signal indicating if the component is supported.\n */\n readonly isSupported: Computed<boolean>;\n\n /**\n * Complete button state.\n */\n readonly state: Computed<S>;\n\n /**\n * @returns A computed based on the specified state and its related key.\n * @param key - a key to use.\n */\n stateGetter<K extends keyof S>(key: K): Computed<S[K]> {\n return computed(() => this.state()[key]);\n }\n\n /**\n * @returns A setter with checks for the specified key.\n * @param key\n */\n readonly stateSetters: <K extends keyof S>(key: K) => [\n throwing: WithChecks<(value: S[K]) => void, true>,\n fp: WithChecksFp<(value: S[K]) => ButtonEither, true>,\n ];\n\n /**\n * @returns Setters with checks to set a specified boolean key.\n * @param key\n */\n readonly stateBoolSetters: <K extends BoolFields<S>>(key: K) => [\n setFalse: [\n throwing: WithChecks<() => void, true>,\n fp: WithChecksFp<() => ButtonEither, true>,\n ],\n setTrue: [\n throwing: WithChecks<() => void, true>,\n fp: WithChecksFp<() => ButtonEither, true>,\n ],\n ];\n\n /**\n * Updates the button state.\n */\n readonly setStateFp: WithChecksFp<(state: Partial<S>) => ButtonEither, true>;\n\n /**\n * @see setStateFp\n */\n readonly setState: WithChecks<(state: Partial<S>) => void, true>;\n\n /**\n * Adds a new button listener.\n * @param listener - event listener.\n * @param once - should the listener be called only once.\n * @returns A function to remove bound listener.\n * @example\n * const off = button.onClick(() => {\n * console.log('User clicked the button');\n * off();\n * });\n */\n readonly onClickFp: WithChecksFp<(listener: VoidFunction, once?: boolean) => VoidFunction, true>;\n\n /**\n * @see onClickFp\n */\n readonly onClick: WithChecks<(listener: VoidFunction, once?: boolean) => VoidFunction, true>;\n\n /**\n * Removes the button click listener.\n * @param listener - event listener.\n * @param once - should the listener be called only once.\n * @example\n * function listener() {\n * console.log('User clicked the button');\n * button.offClick(listener);\n * }\n * button.onClick(listener);\n */\n readonly offClickFp: WithChecksFp<\n (listener: VoidFunction, once?: boolean) => void,\n true\n >;\n\n /**\n * @see offClickFp\n */\n readonly offClick: WithChecks<(listener: VoidFunction, once?: boolean) => void, true>;\n\n /**\n * Mounts the component restoring its state.\n * @since Mini Apps v6.1\n */\n readonly mountFp: WithChecksFp<() => void, true>;\n\n /**\n * @see mountFp\n */\n readonly mount: WithChecks<() => void, true>;\n\n /**\n * Unmounts the component.\n *\n * Note that this function does not remove listeners added via the `onClick`\n * function, so you have to remove them on your own.\n * @see onClick\n */\n readonly unmount: () => void;\n}\n","import type { Computed } from '@tma.js/signals';\nimport * as E from 'fp-ts/Either';\nimport type { PostEventError } from '@tma.js/bridge';\n\nimport { Button, type ButtonOptions } from '@/composables/Button.js';\nimport type { WithChecksFp, WithChecks } from '@/with-checks/withChecksFp.js';\n\nexport interface BackButtonState {\n isVisible: boolean;\n}\n\nexport type BackButtonOptions = Omit<\n ButtonOptions<BackButtonState, 'web_app_setup_back_button'>,\n 'method' | 'payload' | 'initialState'\n>;\n\n/**\n * @since Mini Apps v6.1\n */\nexport class BackButton {\n constructor(options: BackButtonOptions) {\n const button = new Button({\n ...options,\n method: 'web_app_setup_back_button',\n payload: state => ({ is_visible: state.isVisible }),\n initialState: { isVisible: false },\n });\n\n this.isVisible = button.stateGetter('isVisible');\n this.isMounted = button.isMounted;\n this.isSupported = button.isSupported;\n [[this.hide, this.hideFp], [this.show, this.showFp]] = button.stateBoolSetters('isVisible');\n this.onClick = button.onClick;\n this.onClickFp = button.onClickFp;\n this.offClick = button.offClick;\n this.offClickFp = button.offClickFp;\n this.mount = button.mount;\n this.mountFp = button.mountFp;\n this.unmount = button.unmount;\n }\n\n /**\n * Signal indicating if the component is currently visible.\n */\n readonly isVisible: Computed<boolean>;\n\n /**\n * Signal indicating if the component is currently mounted.\n */\n readonly isMounted: Computed<boolean>;\n\n /**\n * Signal indicating if the component is supported.\n */\n readonly isSupported: Computed<boolean>;\n\n /**\n * Hides the button.\n * @since Mini Apps v6.1\n */\n readonly hideFp: WithChecksFp<() => E.Either<PostEventError, void>, true>;\n\n /**\n * @see hideFp\n */\n readonly hide: WithChecks<() => void, true>;\n\n /**\n * Shows the button.\n * @since Mini Apps v6.1\n */\n readonly showFp: WithChecksFp<() => E.Either<PostEventError, void>, true>;\n\n /**\n * @see showFp\n */\n readonly show: WithChecks<() => void, true>;\n\n /**\n * Adds a new button listener.\n * @param listener - event listener.\n * @param once - should the listener be called only once.\n * @returns A function to remove bound listener.\n * @since Mini Apps v6.1\n * @example\n * const off = button.onClick(() => {\n * console.log('User clicked the button');\n * off();\n * });\n */\n readonly onClickFp: WithChecksFp<\n (listener: VoidFunction, once?: boolean) => VoidFunction,\n true\n >;\n\n /**\n * @see onClickFp\n */\n readonly onClick: WithChecks<(listener: VoidFunction, once?: boolean) => VoidFunction, true>;\n\n /**\n * Removes the button click listener.\n * @param listener - event listener.\n * @param once - should the listener be called only once.\n * @since Mini Apps v6.1\n * @example\n * function listener() {\n * console.log('User clicked the button');\n * button.offClick(listener);\n * }\n * button.onClick(listener);\n */\n readonly offClickFp: WithChecksFp<\n (listener: VoidFunction, once?: boolean) => void,\n true\n >;\n\n /**\n * @see offClickFp\n */\n readonly offClick: WithChecks<(listener: VoidFunction, once?: boolean) => void, true>;\n\n /**\n * Mounts the component restoring its state.\n * @since Mini Apps v6.1\n */\n readonly mountFp: WithChecksFp<() => void, true>;\n\n /**\n * @see mountFp\n */\n readonly mount: WithChecks<() => void, true>;\n\n /**\n * Unmounts the component.\n *\n * Note that this function does not remove listeners added via the `onClick`\n * function, so you have to remove them on your own.\n * @see onClick\n */\n readonly unmount: () => void;\n}\n","import { computed } from '@tma.js/signals';\nimport { isTMAFp } from '@tma.js/bridge';\n\nimport type { MaybeAccessor } from '@/types.js';\n\nexport interface SharedFeatureOptions {\n /**\n * True if the current environment is Telegram Mini Apps.\n */\n isTma: MaybeAccessor<boolean>;\n}\n\nexport function sharedFeatureOptions(): SharedFeatureOptions {\n return { isTma: computed(() => isTMAFp()) };\n}\n","import { getStorageValue, setStorageValue } from '@tma.js/toolkit';\n\nexport interface ComponentStorage<T> {\n get: () => T | undefined;\n set: (value: T) => void;\n}\n\n/**\n * Creates a new sessionStorage-based component storage.\n * @param key - session storage key to use.\n */\nexport function createComponentSessionStorage<T>(key: string): ComponentStorage<T> {\n return {\n get: () => getStorageValue<T>(key),\n set(value) {\n setStorageValue<T>(key, value);\n },\n };\n}\n","/**\n * Returns the first navigation entry from window.performance.\n * @returns First navigation entry or null, in case performance functionality is not supported\n * or navigation entry was not found.\n */\nfunction getFirstNavigationEntry(): PerformanceNavigationTiming | undefined {\n return performance.getEntriesByType('navigation')[0] as PerformanceNavigationTiming | undefined;\n}\n\n/**\n * @returns True, if the current page was reloaded.\n * @see https://stackoverflow.com/a/36444134/11894710\n */\nexport function isPageReload(): boolean {\n const entry = getFirstNavigationEntry();\n return !!entry && entry.type === 'reload';\n}\n","import type { MaybeAccessor } from '@/types.js';\nimport { access } from '@/helpers/access.js';\n\nexport function createFnOption<T>(mix: MaybeAccessor<T>) {\n return <O extends object>(obj: O) => {\n return { ...obj, ...access(mix) };\n };\n}\n","import { type ComponentStorage, createComponentSessionStorage } from '@/helpers/component-storage.js';\nimport { isPageReload } from '@/helpers/navigation.js';\nimport { createFnOption } from '@/fn-options/createFnOption.js';\nimport type { MaybeAccessor } from '@/types.js';\n\nexport interface WithStateRestore<T> {\n /**\n * A storage the component could use to store its data.\n */\n storage: ComponentStorage<T>;\n /**\n * True if the current page is reloaded.\n */\n isPageReload: MaybeAccessor<boolean>;\n}\n\nexport function withStateRestore<S>(storageName: string) {\n return createFnOption<WithStateRestore<S>>({\n storage: createComponentSessionStorage<S>(storageName),\n isPageReload,\n });\n}\n","import {\n computed,\n type Computed,\n type Signal,\n signal,\n type SignalOptions,\n} from '@tma.js/signals';\n\nexport type SignalsTuple<T> = [Signal<T>, Computed<T>];\n\nconst signals: (Signal<any> | Computed<any>)[] = [];\n\n/**\n * Creates a new signal with the initial value.\n * @param initialValue - the initial value.\n * @param options - additional options.\n */\nexport function createSignal<T>(\n initialValue: T,\n options?: SignalOptions<T>,\n): Signal<T>;\n\n/**\n * Creates a new signal without the initial value.\n * @param initialValue - the initial value.\n * @param options - additional options.\n */\nexport function createSignal<T>(\n initialValue?: T,\n options?: SignalOptions<T | undefined>,\n): Signal<T | undefined>;\n\n// #__NO_SIDE_EFFECTS__\nexport function createSignal<T>(\n initialValue?: T,\n options?: SignalOptions<T | undefined>,\n): Signal<T | undefined> {\n const s = signal(initialValue, options);\n signals.push(s);\n return s;\n}\n\n/**\n * Creates a signal, which wil be automatically updated if some of its dependant signals were\n * modified.\n * @param fn - computation function.\n * @param options - additional functions.\n */\n// #__NO_SIDE_EFFECTS__\nexport function createComputed<T>(fn: (prev?: T) => T, options?: SignalOptions<T>): Computed<T> {\n const s = computed(fn, options);\n signals.push(s);\n return s;\n}\n\n/**\n * Resets all signals states.\n */\nexport function resetSignals() {\n signals.forEach(s => {\n s.unsubAll();\n 'reset' in s && s.reset();\n });\n}\n\n/**\n * @returns A tuple, containing a manual and computed signals. The computed signal is based on\n * the manual one.\n * @param initialValue - the initial value.\n * @param options - additional options.\n */\nexport function createSignalsTuple<T>(\n initialValue: T,\n options?: SignalOptions<T>,\n): SignalsTuple<T>;\n\n/**\n * @returns A tuple, containing a manual and computed signals. The computed signal is based on\n * the manual one.\n * @param initialValue - an initial value.\n * @param options - additional options.\n */\nexport function createSignalsTuple<T>(\n initialValue?: T,\n options?: SignalOptions<T | undefined>,\n): SignalsTuple<T | undefined>;\n\n// #__NO_SIDE_EFFECTS__\nexport function createSignalsTuple<T>(\n initialValue?: T,\n options?: SignalOptions<T | undefined>,\n): SignalsTuple<T | undefined> {\n const s = createSignal(initialValue, options);\n return [s, createComputed(s)];\n}\n","import { postEventFp as _postEventFp, type PostEventFpFn, type PostEventFn } from '@tma.js/bridge';\nimport { throwifyAnyEither } from '@tma.js/toolkit';\n\nimport { createSignal } from '@/globals/signals-registry.js';\n\nexport const postEventFpSignal = createSignal(_postEventFp);\n\nexport const postEventFp: PostEventFpFn = (...args: any[]) => {\n return (postEventFpSignal as any)()(...args);\n};\n\nexport const postEvent: PostEventFn = (...args: any[]) => {\n return throwifyAnyEither((postEventFp as any)(...args));\n};\n","import { type PostEventFpFn } from '@tma.js/bridge';\n\nimport { createFnOption } from '@/fn-options/createFnOption.js';\nimport { postEventFp } from '@/globals/post-event.js';\n\nexport interface WithPostEvent {\n /**\n * A postEvent function to use to call Mini Apps methods.\n */\n postEvent: PostEventFpFn;\n}\n\nexport const withPostEvent = createFnOption<WithPostEvent>({\n postEvent: postEventFp,\n});\n","import type { Version } from '@tma.js/types';\n\nimport { createSignal } from '@/globals/signals-registry.js';\n\n/**\n * The current Mini Apps version.\n */\nexport const version = createSignal<Version>('0.0');\n","import type { Version } from '@tma.js/types';\n\nimport type { MaybeAccessor } from '@/types.js';\nimport { version } from '@/globals/version.js';\nimport { createFnOption } from '@/fn-options/createFnOption.js';\n\nexport interface WithVersion {\n /**\n * The currently supported Telegram Mini Apps version by the Telegram client.\n */\n version: MaybeAccessor<Version>;\n}\n\nexport const withVersion = createFnOption<WithVersion>({ version });\n","import { on, off, type EventName } from '@tma.js/bridge';\nimport { pipe } from 'fp-ts/function';\n\nimport { sharedFeatureOptions } from '@/fn-options/sharedFeatureOptions.js';\nimport { withStateRestore } from '@/fn-options/withStateRestore.js';\nimport { withPostEvent } from '@/fn-options/withPostEvent.js';\nimport { withVersion } from '@/fn-options/withVersion.js';\n\nexport function buttonOptions<S>(storageName: string, trackedClickEvent: EventName) {\n return {\n ...pipe(\n sharedFeatureOptions(),\n withPostEvent,\n withVersion,\n withStateRestore<S>(storageName),\n ),\n onClick(listener: VoidFunction, once?: boolean): VoidFunction {\n return on(trackedClickEvent, listener, once);\n },\n offClick(listener: VoidFunction, once?: boolean): void {\n off(trackedClickEvent, listener, once);\n },\n };\n}\n","import { BackButton } from '@/features/BackButton/BackButton.js';\nimport { buttonOptions } from '@/fn-options/buttonOptions.js';\n\nexport const backButton = new BackButton(buttonOptions('backButton', 'back_button_pressed'));\n","import { batch, computed, signal } from '@tma.js/signals';\nimport * as TE from 'fp-ts/TaskEither';\nimport { pipe } from 'fp-ts/function';\n\nimport type { AsyncOptions, MaybeAccessor } from '@/types.js';\nimport { access } from '@/helpers/access.js';\n\nexport interface AsyncMountableOptions<S, E> {\n /**\n * A function to retrieve the initial state.\n * @param options - additional options.\n */\n initialState: (options?: AsyncOptions) => TE.TaskEither<E, S>;\n /**\n * @returns True if the current page was reloaded.\n */\n isPageReload: MaybeAccessor<boolean>;\n /**\n * A function to call whenever the component was mounted.\n * @param state - restored state.\n */\n onMounted?: (state: S) => void;\n /**\n * A function to call whenever the component was unmounted.\n */\n onUnmounted?: VoidFunction;\n /**\n * Attempts to restore previously saved component state. This function\n * will only be called if the current page was reloaded.\n */\n restoreState: () => (S | undefined);\n}\n\nexport class AsyncMountable<S extends object, E> {\n constructor({\n initialState,\n onMounted,\n restoreState,\n onUnmounted,\n isPageReload,\n }: AsyncMountableOptions<S, E>) {\n this.mount = options => {\n if (this._isMounted()) {\n return TE.right(undefined);\n }\n const restored = access(isPageReload) ? restoreState() : undefined;\n return pipe(\n restored ? TE.right(restored) : initialState(options),\n TE.map(state => {\n // The user could call mount several times in a row while the\n // component was still mounting. We should prevent calling the\n // same hooks several times in this case.\n if (!this._isMounted()) {\n batch(() => {\n this._isMounted.set(true);\n onMounted?.(state);\n });\n }\n }),\n );\n };\n\n this.unmount = () => {\n if (this._isMounted()) {\n batch(() => {\n this._isMounted.set(false);\n onUnmounted?.();\n });\n }\n };\n }\n\n private readonly _isMounted = signal(false);\n\n /**\n * Signal indicating if the component is mounted.\n */\n readonly isMounted = computed(this._isMounted);\n\n /**\n * Mounts the component restoring its state and calling required side effects.\n * @param options - additional execution options.\n */\n readonly mount: (options?: AsyncOptions) => TE.TaskEither<E, void>;\n\n /**\n * Unmounts the component.\n */\n readonly unmount: () => void;\n}\n","import type { Computed } from '@tma.js/signals';\nimport type {\n RequestError,\n PostEventError,\n EventPayload,\n BiometryAuthRequestStatus,\n EventListener,\n BiometryTokenUpdateStatus,\n} from '@tma.js/bridge';\nimport { BetterPromise } from 'better-promises';\nimport * as E from 'fp-ts/Either';\nimport * as TE from 'fp-ts/TaskEither';\nimport { pipe } from 'fp-ts/function';\n\nimport { createWithChecksFp, WithChecks, WithChecksFp } from '@/with-checks/withChecksFp.js';\nimport { createIsSupportedSignal } from '@/helpers/createIsSupportedSignal.js';\nimport { NotAvailableError } from '@/errors.js';\nimport type {\n BiometryAuthenticateOptions, BiometryOptions,\n BiometryRequestAccessOptions,\n BiometryState,\n BiometryUpdateTokenOptions,\n} from '@/features/Biometry/types.js';\nimport type { AsyncOptions } from '@/types.js';\nimport { Stateful } from '@/composables/Stateful.js';\nimport { AsyncMountable } from '@/composables/AsyncMountable.js';\nimport { throwifyWithChecksFp } from '@/with-checks/throwifyWithChecksFp.js';\n\ntype BiometryTask<T> = TE.TaskEither<RequestError, T>;\n\ninterface AuthenticateResult {\n /**\n * Authentication status.\n */\n status: BiometryAuthRequestStatus;\n /**\n * Token from the local secure storage saved previously.\n */\n token?: string;\n}\n\nconst notAvailableError = new NotAvailableError('Biometry is not available');\n\nfunction eventToState(event: EventPayload<'biometry_info_received'>): BiometryState {\n let available = false;\n let tokenSaved = false;\n let deviceId = '';\n let accessRequested = false;\n let type = '';\n let accessGranted = false;\n if (event.available) {\n available = true;\n tokenSaved = event.token_saved;\n deviceId = event.device_id;\n accessRequested = event.access_requested;\n type = event.type;\n accessGranted = event.access_granted;\n }\n return { available, tokenSaved, deviceId, type, accessGranted, accessRequested };\n}\n\n/**\n * @since Mini Apps v7.2\n */\nexport class Biometry {\n constructor({\n version,\n request,\n postEvent,\n storage,\n onInfoReceived,\n offInfoReceived,\n isTma,\n isPageReload,\n }: BiometryOptions) {\n const listener: EventListener<'biometry_info_received'> = event => {\n stateful.setState(eventToState(event));\n };\n\n const stateful = new Stateful<BiometryState>({\n initialState: {\n available: false,\n type: 'unknown',\n accessGranted: false,\n accessRequested: false,\n deviceId: '',\n tokenSaved: false,\n },\n onChange: storage.set,\n });\n const mountable = new AsyncMountable({\n initialState(options) {\n return pipe(\n request('web_app_biometry_get_info', 'biometry_info_received', options),\n TE.map(eventToState),\n );\n },\n isPageReload,\n onMounted(state) {\n stateful.setState(state);\n onInfoReceived(listener);\n },\n onUnmounted() {\n offInfoReceived(listener);\n },\n restoreState: storage.get,\n });\n\n const wrapOptions = { version, requires: 'web_app_biometry_request_auth', isTma } as const;\n const wrapSupportedEither = createWithChecksFp({\n ...wrapOptions,\n returns: 'either',\n });\n const wrapSupportedTask = createWithChecksFp({\n ...wrapOptions,\n returns: 'task',\n });\n const wrapMountedTask = createWithChecksFp({\n ...wrapOptions,\n isMounted: mountable.isMounted,\n returns: 'task',\n });\n\n this.isAvailable = stateful.getter('available');\n this.isMounted = mountable.isMounted;\n this.isSupported = createIsSupportedSignal('web_app_biometry_request_auth', version);\n this.state = stateful.state;\n this.unmount = mountable.unmount;\n this.mountFp = wrapSupportedTask(mountable.mount);\n\n this.authenticateFp = wrapMountedTask(options => {\n return !this.isAvailable()\n ? TE.left(notAvailableError)\n : pipe(\n request('web_app_biometry_request_auth', 'biometry_auth_requested', {\n ...options,\n params: { reason: ((options || {}).reason || '').trim() },\n }),\n TE.map(response => {\n stateful.setState({ token: response.token });\n return response;\n }),\n );\n });\n\n this.openSettingsFp = wrapSupportedEither(() => postEvent('web_app_biometry_open_settings'));\n\n this.requestAccessFp = wrapMountedTask(options => {\n return pipe(\n request('web_app_biometry_request_access', 'biometry_info_received', {\n ...options,\n params: { reason: ((options || {}).reason || '').trim() },\n }),\n TE.chain(response => {\n const state = eventToState(response);\n if (!state.available) {\n return TE.left(notAvailableError);\n }\n stateful.setState(state);\n return TE.right(state.accessRequested);\n }),\n );\n });\n\n this.updateTokenFp = wrapMountedTask((options = {}) => {\n return pipe(\n request('web_app_biometry_update_token', 'biometry_token_updated', {\n ...options,\n params: { token: options.token || '', reason: options.reason?.trim() },\n }),\n TE.map(response => response.status),\n );\n });\n\n this.authenticate = throwifyWithChecksFp(this.authenticateFp);\n this.openSettings = throwifyWithChecksFp(this.openSettingsFp);\n this.requestAccess = throwifyWithChecksFp(this.requestAccessFp);\n this.updateToken = throwifyWithChecksFp(this.updateTokenFp);\n this.mount = throwifyWithChecksFp(this.mountFp);\n }\n\n /**\n * Signal indicating if biometry is available.\n */\n readonly isAvailable: Computed<boolean>;\n\n /**\n * Signal indicating if the component is supported.\n */\n readonly isSupported: Computed<boolean>;\n\n /**\n * Signal indicating if the component is mounted.\n */\n readonly isMounted: Computed<boolean>;\n\n /**\n * Complete component state.\n */\n readonly state: Computed<BiometryState>;\n\n /**\n * Attempts to authenticate a user using biometrics and fetch a previously stored secure token.\n * @param options - method options.\n * @since Mini Apps v7.2\n * @returns Token from the local secure storage saved previously or undefined.\n * @example\n * const { status, token } = await biometry.authenticate({\n * reason: 'Authenticate to open wallet',\n * });\n */\n readonly authenticateFp: WithChecksFp<(options?: BiometryAuthenticateOptions) => BiometryTask<{\n /**\n * Authentication status.\n */\n status: BiometryAuthRequestStatus;\n /**\n * Token from the local secure storage saved previously.\n */\n token?: string;\n }>, true>;\n\n /**\n * @see authenticateFp\n */\n readonly authenticate: WithChecks<\n (options?: BiometryAuthenticateOptions) => BetterPromise<AuthenticateResult>,\n true\n >;\n\n /**\n * Opens the biometric access settings for bots. Useful when you need to request biometrics\n * access to users who haven't granted it yet.\n *\n * _Note that this method can be called only in response to user interaction with the Mini App\n * interface (e.g. a click inside the Mini App or on the main button)_.\n * @since Mini Apps v7.2\n */\n readonly openSettingsFp: WithChecksFp<() => E.Either<PostEventError, void>, true>;\n\n /**\n * @see openSettingsFp\n */\n readonly openSettings: WithChecks<() => void, true>;\n\n /**\n * Requests permission to use biometrics.\n * @since Mini Apps v7.2\n * @returns Promise with true, if access was granted.\n * @example\n * const accessGranted = await biometry.requestAccess({\n * reason: 'Authenticate to open wallet',\n * });\n */\n readonly requestAccessFp: WithChecksFp<\n (options?: BiometryRequestAccessOptions) => BiometryTask<boolean>,\n true\n >;\n\n /**\n * @see requestAccessFp\n */\n readonly requestAccess: WithChecks<\n (options?: BiometryRequestAccessOptions) => BetterPromise<boolean>,\n true\n >;\n\n /**\n * Updates the biometric token in a secure storage on the device.\n * @since Mini Apps v7.2\n * @returns Promise with `true`, if token was updated.\n * @example Setting a new token\n * biometry.updateToken({\n * token: 'abcdef',\n * })\n * @example Deleting the token\n * biometry.updateToken();\n */\n readonly updateTokenFp: WithChecksFp<\n (options?: BiometryUpdateTokenOptions) => BiometryTask<BiometryTokenUpdateStatus>,\n true\n >;\n\n /**\n * @see updateTokenFp\n */\n readonly updateToken: WithChecks<\n (options?: BiometryUpdateTokenOptions) => BetterPromise<BiometryTokenUpdateStatus>,\n true\n >;\n\n /**\n * Mounts the component restoring its state.\n * @since Mini Apps v7.2\n */\n readonly mountFp: WithChecksFp<(options?: AsyncOptions) => BiometryTask<void>, true>;\n\n /**\n * @see mountFp\n */\n readonly mount: WithChecks<(options?: AsyncOptions) => BetterPromise<void>, true>;\n\n /**\n * Unmounts the component.\n */\n readonly unmount: () => void;\n}\n","import { requestFp as _requestFp, type RequestFpFn, type RequestFn } from '@tma.js/bridge';\nimport { BetterPromise } from 'better-promises';\n\nimport { postEventFp } from '@/globals/post-event.js';\n\nexport const requestFp: RequestFpFn = (method: any, events: any, options: any) => {\n return _requestFp(method, events, {\n postEvent: postEventFp,\n ...options,\n });\n};\n\nexport const request: RequestFn = (...args: any[]) => {\n return BetterPromise.fn(() => (requestFp as any)(...args)());\n};\n","import type { RequestFpFn } from '@tma.js/bridge';\n\nimport { createFnOption } from '@/fn-options/createFnOption.js';\nimport { requestFp } from '@/globals/request.js';\n\nexport interface WithRequest {\n /**\n * A request function to use to call Mini Apps methods.\n */\n request: RequestFpFn;\n}\n\nexport const withRequest = createFnOption<WithRequest>({\n request: requestFp,\n});\n","import { on, off } from '@tma.js/bridge';\nimport { pipe } from 'fp-ts/function';\n\nimport { Biometry } from '@/features/Biometry/Biometry.js';\nimport type { BiometryState } from '@/features/Biometry/types.js';\nimport { sharedFeatureOptions } from '@/fn-options/sharedFeatureOptions.js';\nimport { withRequest } from '@/fn-options/withRequest.js';\nimport { withStateRestore } from '@/fn-options/withStateRestore.js';\nimport { withPostEvent } from '@/fn-options/withPostEvent.js';\nimport { withVersion } from '@/fn-options/withVersion.js';\n\nexport const biometry = new Biometry({\n ...pipe(\n sharedFeatureOptions(),\n withPostEvent,\n withVersion,\n withRequest,\n withStateRestore<BiometryState>('biometry'),\n ),\n offInfoReceived(listener) {\n off('biometry_info_received', listener);\n },\n onInfoReceived(listener) {\n return on('biometry_info_received', listener);\n },\n});\n","import type { Computed } from '@tma.js/signals';\nimport * as E from 'fp-ts/Either';\nimport type { PostEventError } from '@tma.js/bridge';\nimport { pipe } from 'fp-ts/function';\n\nimport {\n createWithChecksFp,\n type WithChecks,\n type WithChecksFp,\n} from '@/with-checks/withChecksFp.js';\nimport { Stateful } from '@/composables/Stateful.js';\nimport { Mountable } from '@/composables/Mountable.js';\nimport { throwifyWithChecksFp } from '@/with-checks/throwifyWithChecksFp.js';\nimport type { WithStateRestore } from '@/fn-options/withStateRestore.js';\nimport type { WithPostEvent } from '@/fn-options/withPostEvent.js';\nimport type { SharedFeatureOptions } from '@/fn-options/sharedFeatureOptions.js';\n\nexport interface ClosingBehaviorState {\n isConfirmationEnabled: boolean;\n}\n\nexport interface ClosingBehaviorOptions\n extends WithStateRestore<ClosingBehaviorState>,\n WithPostEvent,\n SharedFeatureOptions {\n}\n\nexport class ClosingBehavior {\n constructor({ postEvent, storage, isTma, isPageReload }: ClosingBehaviorOptions) {\n const stateful = new Stateful({\n initialState: { isConfirmationEnabled: false },\n onChange(state) {\n storage.set(state);\n },\n });\n const mountable = new Mountable({\n onMounted: stateful.setState,\n restoreState: storage.get,\n initialState: { isConfirmationEnabled: false },\n isPageReload,\n });\n\n const wrapOptions = { requires: 'web_app_setup_closing_behavior', isTma } as const;\n const wrapSupportedPlain = createWithChecksFp({\n ...wrapOptions,\n returns: 'plain',\n });\n const wrapMountedEither = createWithChecksFp({\n ...wrapOptions,\n returns: 'either',\n isMounted: mountable.isMounted,\n });\n\n const setClosingConfirmation = (isConfirmationEnabled: boolean) => {\n if (isConfirmationEnabled === this.isConfirmationEnabled()) {\n return E.right(undefined);\n }\n stateful.setState({ isConfirmationEnabled });\n return postEvent('web_app_setup_closing_behavior', {\n need_confirmation: isConfirmationEnabled,\n });\n };\n\n this.isConfirmationEnabled = stateful.getter('isConfirmationEnabled');\n this.isMounted = mountable.isMounted;\n\n this.disableConfirmationFp = wrapMountedEither(() => {\n return setClosingConfirmation(false);\n });\n this.enableConfirmationFp = wrapMountedEither(() => {\n return setClosingConfirmation(true);\n });\n this.mountFp = wrapSupportedPlain(() => {\n const nothing = () => undefined;\n return pipe(mountable.mount(), E.match(nothing, nothing));\n });\n this.unmount = mountable.unmount;\n\n this.disableConfirmation = throwifyWithChecksFp(this.disableConfirmationFp);\n this.enableConfirmation = throwifyWithChecksFp(this.enableConfirmationFp);\n this.mount = throwifyWithChecksFp(this.mountFp);\n }\n\n /**\n * Signal indicating if closing confirmation dialog is currently enabled.\n */\n readonly isConfirmationEnabled: Computed<boolean>;\n\n /**\n * Signal indicating if the component is currently mounted.\n */\n readonly isMounted: Computed<boolean>;\n\n /**\n * Mounts the component restoring its state.\n */\n readonly mountFp: WithChecksFp<() => void, false>;\n\n /**\n * @see mountFp\n */\n readonly mount: WithChecks<() => void, false>;\n\n /**\n * Unmounts the component.\n */\n readonly unmount: () => void;\n\n /**\n * Disables the closing confirmation dialog.\n */\n readonly disableConfirmationFp: WithChecksFp<() => E.Either<PostEventError, void>, false>;\n\n /**\n * @see disableConfirmationFp\n */\n readonly disableConfirmation: WithChecks<() => void, false>;\n\n /**\n * Enables the closing confirmation dialog.\n */\n readonly enableConfirmationFp: WithChecksFp<() => E.Either<PostEventError, void>, false>;\n\n /**\n * @see enableConfirmationFp\n */\n readonly enableConfirmation: WithChecks<() => void, false>;\n}\n","import { pipe } from 'fp-ts/function';\n\nimport {\n ClosingBehavior,\n type ClosingBehaviorState,\n} from '@/features/ClosingBehavior/ClosingBehavior.js';\nimport { sharedFeatureOptions } from '@/fn-options/sharedFeatureOptions.js';\nimport { withStateRestore } from '@/fn-options/withStateRestore.js';\nimport { withPostEvent } from '@/fn-options/withPostEvent.js';\n\nexport const closingBehavior = new ClosingBehavior(pipe(\n sharedFeatureOptions(),\n withStateRestore<ClosingBehaviorState>('closingBehavior'),\n withPostEvent,\n));\n","import type { Computed } from '@tma.js/signals';\nimport type { InvokeCustomMethodFpOptions, RequestError } from '@tma.js/bridge';\nimport { BetterPromise } from 'better-promises';\nimport { array, parse, record, string } from 'valibot';\nimport * as TE from 'fp-ts/TaskEither';\nimport { pipe } from 'fp-ts/function';\n\nimport { createWithChecksFp, type WithChecks, type WithChecksFp } from '@/with-checks/withChecksFp.js';\nimport { createIsSupportedSignal } from '@/helpers/createIsSupportedSignal.js';\nimport type { WithVersion } from '@/fn-options/withVersion.js';\nimport type { WithInvokeCustomMethod } from '@/fn-options/withInvokeCustomMethod.js';\nimport type { SharedFeatureOptions } from '@/fn-options/sharedFeatureOptions.js';\nimport { throwifyWithChecksFp } from '@/with-checks/throwifyWithChecksFp.js';\n\ntype CloudStorageTask<T> = TE.TaskEither<RequestError, T>;\n\nexport interface CloudStorageOptions extends WithVersion,\n WithInvokeCustomMethod,\n SharedFeatureOptions {\n}\n\n/**\n * @since Mini Apps v6.9\n */\nexport class CloudStorage {\n constructor({ version, isTma, invokeCustomMethod }: CloudStorageOptions) {\n const wrapSupportedTask = createWithChecksFp({\n version,\n requires: 'web_app_invoke_custom_method',\n isTma,\n returns: 'task',\n });\n\n this.isSupported = createIsSupportedSignal('web_app_invoke_custom_method', version);\n this.deleteItemFp = wrapSupportedTask((keyOrKeys, options) => {\n const keys = Array.isArray(keyOrKeys) ? keyOrKeys : [keyOrKeys];\n return pipe(\n keys.length\n ? invokeCustomMethod('deleteStorageValues', { keys }, options)\n : TE.right(undefined),\n TE.map(() => undefined),\n );\n });\n this.getItemFp = wrapSupportedTask((key, options) => {\n return pipe(\n this.getItemsFp([key], options),\n TE.map(values => values[key] || ''),\n );\n });\n this.getItemsFp = wrapSupportedTask((keys, options) => {\n return pipe(\n keys.length ? invokeCustomMethod('getStorageValues', { keys }, options) : TE.right({}),\n TE.map(data => {\n return {\n // Fulfill the response with probably missing keys.\n ...keys.reduce<Record<string, string>>((acc, key) => {\n acc[key] = '';\n return acc;\n }, {}),\n ...parse(record(string(), string()), data),\n };\n }),\n );\n });\n this.getKeysFp = wrapSupportedTask(options => {\n return pipe(\n invokeCustomMethod('getStorageKeys', {}, options),\n TE.map(data => parse(array(string()), data)),\n );\n });\n this.setItemFp = wrapSupportedTask((key, value, options) => {\n return pipe(\n invokeCustomMethod('saveStorageValue', { key, value }, options),\n TE.map(() => undefined),\n );\n });\n this.clearFp = wrapSupportedTask(options => {\n return pipe(this.getKeysFp(options), TE.chain(this.deleteItemFp));\n });\n\n this.deleteItem = throwifyWithChecksFp(this.deleteItemFp);\n this.getItem = throwifyWithChecksFp(this.getItemFp);\n this.getItems = throwifyWithChecksFp(this.getItemsFp);\n this.getKeys = throwifyWithChecksFp(this.getKeysFp);\n this.setItem = throwifyWithChecksFp(this.setItemFp);\n this.clear = throwifyWithChecksFp(this.clearFp);\n }\n\n /**\n * Signal indicating if the component is supported.\n */\n readonly isSupported: Computed<boolean>;\n\n /**\n * Deletes specified key or keys from the cloud storage.\n * @param keyOrKeys - key or keys to delete.\n * @param options - request execution options.\n * @since Mini Apps v6.9\n */\n readonly deleteItemFp: WithChecksFp<\n (keyOrKeys: string | string[], options?: InvokeCustomMethodFpOptions) => CloudStorageTask<void>,\n true\n >;\n\n readonly deleteItem: WithChecks<\n (keyOrKeys: string | string[], options?: InvokeCustomMethodFpOptions) => BetterPromise<void>,\n true\n >;\n\n /**\n * Gets a single key value from the cloud storage.\n * @param key - a key to get.\n * @param options - request execution options.\n * @returns A key value as a string.\n * @since Mini Apps v6.9\n */\n readonly getItemFp: WithChecksFp<\n (key: string, options?: InvokeCustomMethodFpOptions) => CloudStorageTask<string>,\n true\n >;\n\n /**\n * @see getItemFp\n */\n readonly getItem: WithChecks<{\n <K extends string>(\n keys: K[],\n options?: InvokeCustomMethodFpOptions,\n ): BetterPromise<Record<K, string>>;\n (key: string, options?: InvokeCustomMethodFpOptions): BetterPromise<string>;\n }, true>;\n\n /**\n * Gets multiple keys' values from the cloud storage.\n * @param keys - keys list.\n * @param options - request execution options.\n * @returns A map, where a key is one of the specified in the `keys` argument,\n * and a value is a corresponding storage value if an array of keys was passed.\n * @since Mini Apps v6.9\n */\n readonly getItemsFp: WithChecksFp<\n <K extends string>(\n keys: K[],\n options?: InvokeCustomMethodFpOptions,\n ) => CloudStorageTask<Record<K, string>>,\n true\n >;\n\n /**\n * @see getItemsFp\n */\n readonly getItems: WithChecks<\n <K extends string>(\n keys: K[],\n options?: InvokeCustomMethodFpOptions,\n ) => BetterPromise<Record<K, string>>,\n true\n >;\n\n /**\n * Returns a list of all keys presented in the cloud storage.\n * @param options - request execution options.\n * @since Mini Apps v6.9\n */\n readonly getKeysFp: WithChecksFp<\n (options?: InvokeCustomMethodFpOptions) => CloudStorageTask<string[]>,\n true\n >;\n\n /**\n * @see getKeysFp\n */\n readonly getKeys: WithChecks<\n (options?: InvokeCustomMethodFpOptions) => BetterPromise<string[]>,\n true\n >;\n\n /**\n * Saves the specified value by a key.\n * @param key - storage key.\n * @param value - storage value.\n * @param options - request execution options.\n * @since Mini Apps v6.9\n */\n readonly setItemFp: WithChecksFp<\n (key: string, value: string, options?: InvokeCustomMethodFpOptions) => CloudStorageTask<void>,\n true\n >;\n\n /**\n * @see setItemFp\n */\n readonly setItem: WithChecks<\n (key: string, value: string, options?: InvokeCustomMethodFpOptions) => BetterPromise<void>,\n true\n >;\n\n /**\n * Clears the cloud storage.\n * @param options - additional options.\n * @since Mini Apps v6.9\n */\n readonly clearFp: WithChecksFp<\n (options?: InvokeCustomMethodFpOptions) => CloudStorageTask<void>,\n true\n >;\n\n /**\n * @see clearFp\n */\n readonly clear: WithChecks<(options?: InvokeCustomMethodFpOptions) => BetterPromise<void>, true>;\n}\n","import { createSignal } from '@/globals/signals-registry.js';\n\nconst lastRequestId = createSignal(0);\n\n/**\n * @returns A new request identifier.\n */\nexport function createRequestId(): string {\n lastRequestId.set(lastRequestId() + 1);\n return lastRequestId().toString();\n}\n","import {\n type RequestError,\n type CustomMethodName,\n type CustomMethodParams,\n type InvokeCustomMethodOptions,\n invokeCustomMethodFp,\n} from '@tma.js/bridge';\nimport * as TE from 'fp-ts/TaskEither';\n\nimport { createRequestId } from '@/globals/createRequestId.js';\nimport { postEventFp } from '@/globals/post-event.js';\n\n/**\n * Invokes known custom method. Returns method execution result.\n * @param method - method name.\n * @param params - method parameters.\n * @param options - additional options.\n */\nexport function invokeCustomMethod<M extends CustomMethodName>(\n method: M,\n params: CustomMethodParams<M>,\n options?: InvokeCustomMethodOptions,\n): TE.TaskEither<RequestError, unknown>;\n\n/**\n * Invokes unknown custom method. Returns method execution result.\n * @param method - method name.\n * @param params - method parameters.\n * @param options - additional options.\n */\nexport function invokeCustomMethod(\n method: string,\n params: object,\n options?: InvokeCustomMethodOptions,\n): TE.TaskEither<RequestError, unknown>;\n\nexport function invokeCustomMethod(\n method: string,\n params: object,\n options?: InvokeCustomMethodOptions,\n): TE.TaskEither<RequestError, unknown> {\n return invokeCustomMethodFp(method, params, createRequestId(), {\n ...options || {},\n postEvent: postEventFp,\n });\n}\n","import type * as TE from 'fp-ts/TaskEither';\nimport type {\n CustomMethodParams,\n CustomMethodName,\n InvokeCustomMethodError,\n InvokeCustomMethodFpOptions,\n RequestError,\n} from '@tma.js/bridge';\n\nimport { invokeCustomMethod } from '@/globals/invokeCustomMethod.js';\nimport { createFnOption } from '@/fn-options/createFnOption.js';\n\nexport type { InvokeCustomMethodError };\n\nexport interface InvokeCustomMethodNoRequestIdFn {\n <M extends CustomMethodName>(\n this: void,\n method: M,\n params: CustomMethodParams<M>,\n options?: InvokeCustomMethodFpOptions,\n ): TE.TaskEither<InvokeCustomMethodError, unknown>;\n\n (\n this: void,\n method: string,\n params: object,\n options?: InvokeCustomMethodFpOptions,\n ): TE.TaskEither<RequestError, unknown>;\n}\n\nexport interface WithInvokeCustomMethod {\n invokeCustomMethod: InvokeCustomMethodNoRequestIdFn;\n}\n\nexport const withInvokeCustomMethod = createFnOption<WithInvokeCustomMethod>({\n invokeCustomMethod,\n});\n","import { pipe } from 'fp-ts/function';\n\nimport { CloudStorage } from '@/features/CloudStorage/CloudStorage.js';\nimport { sharedFeatureOptions } from '@/fn-options/sharedFeatureOptions.js';\nimport { withVersion } from '@/fn-options/withVersion.js';\nimport { withInvokeCustomMethod } from '@/fn-options/withInvokeCustomMethod.js';\n\nexport const cloudStorage = new CloudStorage(pipe(\n sharedFeatureOptions(),\n withVersion,\n withInvokeCustomMethod,\n));\n","import { pipe } from 'fp-ts/function';\nimport * as TE from 'fp-ts/TaskEither';\nimport type { EmojiStatusAccessRequestedStatus, RequestError } from '@tma.js/bridge';\n\nimport type { AsyncOptions } from '@/types.js';\nimport { withVersion, type WithVersion } from '@/fn-options/withVersion.js';\nimport { withRequest, type WithRequest } from '@/fn-options/withRequest.js';\nimport { withChecksFp } from '@/with-checks/withChecksFp.js';\nimport {\n sharedFeatureOptions,\n type SharedFeatureOptions,\n} from '@/fn-options/sharedFeatureOptions.js';\nimport { throwifyWithChecksFp } from '@/with-checks/throwifyWithChecksFp.js';\n\ninterface CreateOptions extends SharedFeatureOptions, WithVersion, WithRequest {\n}\n\nfunction create({ request, ...rest }: CreateOptions) {\n return withChecksFp((\n options: AsyncOptions,\n ): TE.TaskEither<RequestError, EmojiStatusAccessRequestedStatus> => {\n return pipe(\n request('web_app_request_emoji_status_access', 'emoji_status_access_requested', options),\n TE.map(response => response.status),\n );\n }, { ...rest, requires: 'web_app_request_emoji_status_access', returns: 'task' });\n}\n\n/**\n * Shows a native popup requesting permission for the bot to manage user's emoji status.\n * @param options - additional options.\n * @returns Emoji status access status.\n * @since Mini Apps v8.0\n * @example\n * const status = await requestEmojiStatusAccess();\n */\nexport const requestEmojiStatusAccessFp = create(pipe(\n sharedFeatureOptions(),\n withVersion,\n withRequest,\n));\n\n/**\n * @see requestEmojiStatusAccessFp\n */\nexport const requestEmojiStatusAccess = throwifyWithChecksFp(requestEmojiStatusAccessFp);\n","import * as TE from 'fp-ts/TaskEither';\nimport { pipe } from 'fp-ts/function';\nimport { RequestError } from '@tma.js/bridge';\n\nimport type { AsyncOptions } from '@/types.js';\nimport { SetEmojiStatusError } from '@/errors.js';\nimport { withChecksFp } from '@/with-checks/withChecksFp.js';\nimport {\n type SharedFeatureOptions,\n sharedFeatureOptions,\n} from '@/fn-options/sharedFeatureOptions.js';\nimport { withRequest, type WithRequest } from '@/fn-options/withRequest.js';\nimport { withVersion, type WithVersion } from '@/fn-options/withVersion.js';\nimport { throwifyWithChecksFp } from '@/with-checks/throwifyWithChecksFp.js';\n\nexport interface SetEmojiStatusOptions extends AsyncOptions {\n duration?: number;\n}\n\ninterface CreateOptions extends SharedFeatureOptions, WithRequest, WithVersion {\n}\n\nfunction create({ request, ...rest }: CreateOptions) {\n return withChecksFp((\n customEmojiId: string,\n options?: SetEmojiStatusOptions,\n ): TE.TaskEither<RequestError | SetEmojiStatusError, void> => {\n return pipe(\n request('web_app_set_emoji_status', ['emoji_status_set', 'emoji_status_failed'], {\n params: {\n custom_emoji_id: customEmojiId,\n duration: (options || {}).duration,\n },\n ...options,\n }),\n TE.chainW(response => {\n return response && 'error' in response\n ? TE.left(new SetEmojiStatusError(response.error))\n : TE.right(undefined);\n }),\n );\n }, {\n ...rest,\n requires: 'web_app_set_emoji_status',\n returns: 'task',\n });\n}\n\n/**\n * Opens a dialog allowing the user to set the specified custom emoji as their status.\n * @returns Nothing if status set was successful.\n * @param options - additional options.\n * @since Mini Apps v8.0\n * @example\n * pipe(\n * setEmojiStatusFp('5361800828313167608'),\n * TE.match(error => {\n * console.error('Error occurred', error);\n * }, () => {\n * console.log('Status set');\n * }),\n * );\n * const statusSet = await setEmojiStatus('5361800828313167608');\n */\nexport const setEmojiStatusFp = create(pipe(\n sharedFeatureOptions(),\n withRequest,\n withVersion,\n));\n\n/**\n * @see setEmojiStatusFp\n */\nexport const setEmojiStatus = throwifyWithChecksFp(setEmojiStatusFp);\n","import type { Computed } from '@tma.js/signals';\nimport type {\n ImpactHapticFeedbackStyle,\n NotificationHapticFeedbackType,\n} from '@tma.js/bridge';\nimport * as E from 'fp-ts/Either';\nimport type { PostEventError } from '@tma.js/bridge';\n\nimport { createIsSupportedSignal } from '@/helpers/createIsSupportedSignal.js';\nimport type { SharedFeatureOptions } from '@/fn-options/sharedFeatureOptions.js';\nimport { createWithChecksFp, type WithChecksFp, type WithChecks } from '@/with-checks/withChecksFp.js';\nimport { throwifyWithChecksFp } from '@/with-checks/throwifyWithChecksFp.js';\nimport type { WithVersion } from '@/fn-options/withVersion.js';\nimport type { WithPostEvent } from '@/fn-options/withPostEvent.js';\n\ntype HapticFeedbackEither = E.Either<PostEventError, void>;\n\nexport interface HapticFeedbackOptions extends WithVersion, WithPostEvent, SharedFeatureOptions {\n}\n\n/**\n * @since Mini Apps v6.1\n */\nexport class HapticFeedback {\n constructor({ postEvent, isTma, version }: HapticFeedbackOptions) {\n const HAPTIC_METHOD_NAME = 'web_app_trigger_haptic_feedback';\n const wrapSupported = createWithChecksFp({\n requires: HAPTIC_METHOD_NAME,\n isTma,\n version,\n returns: 'plain',\n });\n\n this.isSupported = createIsSupportedSignal(HAPTIC_METHOD_NAME, version);\n this.impactOccurredFp = wrapSupported(style => {\n return postEvent(HAPTIC_METHOD_NAME, { type: 'impact', impact_style: style });\n });\n this.notificationOccurredFp = wrapSupported(type => {\n return postEvent(HAPTIC_METHOD_NAME, { type: 'notification', notification_type: type });\n });\n this.selectionChangedFp = wrapSupported(() => {\n return postEvent(HAPTIC_METHOD_NAME, { type: 'selection_change' });\n });\n\n this.impactOccurred = throwifyWithChecksFp(this.impactOccurredFp);\n this.notificationOccurred = throwifyWithChecksFp(this.notificationOccurredFp);\n this.selectionChanged = throwifyWithChecksFp(this.selectionChangedFp);\n }\n\n /**\n * Signal indicating if the component is supported.\n */\n readonly isSupported: Computed<boolean>;\n\n /**\n * A method that tells if an impact occurred. The Telegram app may play the\n * appropriate haptics based on style value passed.\n * @param style - impact style.\n * @since Mini Apps v6.1\n */\n impactOccurredFp: WithChecksFp<(style: ImpactHapticFeedbackStyle) => HapticFeedbackEither, true>;\n\n /**\n * @see impactOccurredFp\n */\n impactOccurred: WithChecks<(style: ImpactHapticFeedbackStyle) => void, true>;\n\n /**\n * A method tells that a task or action has succeeded, failed, or produced\n * a warning. The Telegram app may play the appropriate haptics based on type\n * value passed.\n * @param type - notification type.\n * @since Mini Apps v6.1\n */\n notificationOccurredFp: WithChecksFp<\n (type: NotificationHapticFeedbackType) => HapticFeedbackEither,\n true\n >;\n\n /**\n * @see notificationOccurredFp\n */\n notificationOccurred: WithChecks<(type: NotificationHapticFeedbackType) => void, true>;\n\n /**\n * A method tells that the user has changed a selection. The Telegram app may\n * play the appropriate haptics.\n *\n * Do not use this feedback when the user makes or confirms a selection; use\n * it only when the selection changes.\n * @since Mini Apps v6.1\n */\n selectionChangedFp: WithChecksFp<() => HapticFeedbackEither, true>;\n\n /**\n * @see selectionChangedFp\n */\n selectionChanged: WithChecks<() => void, true>;\n}\n","import { pipe } from 'fp-ts/function';\n\nimport { HapticFeedback } from '@/features/HapticFeedback/HapticFeedback.js';\nimport { sharedFeatureOptions } from '@/fn-options/sharedFeatureOptions.js';\nimport { withPostEvent } from '@/fn-options/withPostEvent.js';\nimport { withVersion } from '@/fn-options/withVersion.js';\n\nexport const hapticFeedback = new HapticFeedback(pipe(\n sharedFeatureOptions(),\n withPostEvent,\n withVersion,\n));\n","import { pipe } from 'fp-ts/function';\nimport type * as E from 'fp-ts/Either';\nimport type { PostEventError } from '@tma.js/bridge';\n\nimport {\n sharedFeatureOptions,\n type SharedFeatureOptions,\n} from '@/fn-options/sharedFeatureOptions.js';\nimport { withPostEvent, type WithPostEvent } from '@/fn-options/withPostEvent.js';\nimport { withVersion, type WithVersion } from '@/fn-options/withVersion.js';\nimport { withChecksFp } from '@/with-checks/withChecksFp.js';\nimport { throwifyWithChecksFp } from '@/with-checks/throwifyWithChecksFp.js';\n\ninterface CreateOptions extends SharedFeatureOptions, WithPostEvent, WithVersion {\n}\n\nfunction create({ postEvent, ...rest }: CreateOptions) {\n return withChecksFp((): E.Either<PostEventError, void> => {\n return postEvent('web_app_add_to_home_screen');\n }, { ...rest, requires: 'web_app_add_to_home_screen', returns: 'either' });\n}\n\n/**\n * Prompts the user to add the Mini App to the home screen.\n * @since Mini Apps v8.0\n */\nexport const addToHomeScreenFp = create(pipe(\n sharedFeatureOptions(),\n withVersion,\n withPostEvent,\n));\n\n/**\n * @see addToHomeScreenFp\n */\nexport const addToHomeScreen = throwifyWithChecksFp(addToHomeScreenFp);\n","import { pipe } from 'fp-ts/function';\nimport * as TE from 'fp-ts/TaskEither';\nimport type { HomeScreenStatus, RequestError } from '@tma.js/bridge';\n\nimport {\n sharedFeatureOptions,\n type SharedFeatureOptions,\n} from '@/fn-options/sharedFeatureOptions.js';\nimport { withVersion, type WithVersion } from '@/fn-options/withVersion.js';\nimport { withChecksFp } from '@/with-checks/withChecksFp.js';\nimport { throwifyWithChecksFp } from '@/with-checks/throwifyWithChecksFp.js';\nimport { withRequest, type WithRequest } from '@/fn-options/withRequest.js';\nimport type { AsyncOptions } from '@/types.js';\n\ninterface CreateOptions extends SharedFeatureOptions, WithRequest, WithVersion {\n}\n\nfunction create({ request, ...rest }: CreateOptions) {\n return withChecksFp((options?: AsyncOptions): TE.TaskEither<RequestError, HomeScreenStatus> => {\n return pipe(\n request('web_app_check_home_screen', 'home_screen_checked', options),\n TE.map(response => response.status || 'unknown'),\n );\n }, { ...rest, requires: 'web_app_check_home_screen', returns: 'task' });\n}\n\n/**\n * Sends a request to the native Telegram application to check if the current mini\n * application is added to the device's home screen.\n * @param options - additional options.\n * @since Mini Apps v8.0\n */\nexport const checkHomeScreenStatusFp = create(pipe(\n sharedFeatureOptions(),\n withVersion,\n withRequest,\n));\n\n/**\n * @see checkHomeScreenStatusFp\n */\nexport const checkHomeScreenStatus = throwifyWithChecksFp(checkHomeScreenStatusFp);\n","import { computed, type Computed, signal } from '@tma.js/signals';\nimport type { InitData as InitDataType } from '@tma.js/types';\nimport * as E from 'fp-ts/Either';\nimport * as O from 'fp-ts/Option';\nimport { pipe } from 'fp-ts/function';\nimport { throwifyFpFn } from '@tma.js/toolkit';\n\nexport interface InitDataOptions<Err> {\n /**\n * Retrieves init data from the current environment.\n */\n retrieveInitData: () => E.Either<Err, O.Option<{\n raw: string;\n obj: InitDataType;\n }>>;\n}\n\nexport class InitData<Err extends Error> {\n constructor({ retrieveInitData }: InitDataOptions<Err>) {\n this.restoreFp = () => {\n return pipe(\n retrieveInitData(),\n E.map(O.match(() => undefined, ({ raw, obj }) => {\n this._state.set(obj);\n this._raw.set(raw);\n })),\n );\n };\n this.restore = throwifyFpFn(this.restoreFp);\n }\n\n private fromState<K extends keyof InitDataType>(key: K): Computed<InitDataType[K] | undefined> {\n return computed(() => {\n const s = this._state();\n return s ? s[key] : undefined;\n });\n }\n\n private readonly _state = signal<InitDataType>();\n\n private readonly _raw = signal<string>();\n\n /**\n * Complete component state.\n */\n readonly state = computed(this._state);\n\n /**\n * @see InitDataType.auth_date\n */\n readonly authDate = this.fromState('auth_date');\n\n /**\n * @see InitDataType.can_send_after\n */\n readonly canSendAfter = this.fromState('can_send_after');\n\n /**\n * Date after which it is allowed to call\n * the [answerWebAppQuery](https://core.telegram.org/bots/api#answerwebappquery) method.\n */\n readonly canSendAfterDate = computed(() => {\n const authDateValue = this.authDate();\n const canSendAfterValue = this.canSendAfter();\n\n return canSendAfterValue && authDateValue\n ? new Date(authDateValue.getTime() + (canSendAfterValue * 1000))\n : undefined;\n });\n\n /**\n * @see InitDataType.chat\n */\n readonly chat = this.fromState('chat');\n\n /**\n * @see InitDataType.chat_type\n */\n readonly chatType = this.fromState('chat_type');\n\n /**\n * @see InitDataType.chat_instance\n */\n readonly chatInstance = this.fromState('chat_instance');\n\n /**\n * @see InitDataType.hash\n */\n readonly hash = this.fromState('hash');\n\n /**\n * @see InitDataType.query_id\n */\n readonly queryId = this.fromState('query_id');\n\n /**\n * Raw representation of init data.\n */\n readonly raw = computed(this._raw);\n\n /**\n * @see InitDataType.receiver\n */\n readonly receiver = this.fromState('receiver');\n\n /**\n * @see InitDataType.signature\n */\n readonly signature = this.fromState('signature');\n\n /**\n * @see InitDataType.start_param\n */\n readonly startParam = this.fromState('start_param');\n\n /**\n * @see InitDataType.user\n */\n readonly user = this.fromState('user');\n\n /**\n * Restores the component state.\n */\n readonly restoreFp: () => E.Either<Err, void>;\n\n /**\n * @see restoreFp\n */\n readonly restore: () => void;\n}\n","import { retrieveRawInitDataFp, retrieveLaunchParamsFp } from '@tma.js/bridge';\nimport { pipe } from 'fp-ts/function';\nimport * as E from 'fp-ts/Either';\nimport * as O from 'fp-ts/Option';\n\nimport { InitData } from '@/features/InitData/InitData.js';\n\nexport const initData = new InitData({\n retrieveInitData() {\n return pipe(\n E.Do,\n E.bindW('obj', () => pipe(\n retrieveLaunchParamsFp(),\n E.map(({ tgWebAppData }) => {\n return tgWebAppData ? O.some(tgWebAppData) : O.none;\n }),\n )),\n E.bindW('raw', retrieveRawInitDataFp),\n E.map(({ obj, raw }) => {\n return pipe(\n O.Do,\n O.bind('obj', () => obj),\n O.bind('raw', () => raw),\n );\n }),\n );\n },\n});\n","import { computed, type Computed, signal } from '@tma.js/signals';\nimport type { InvoiceStatus, RequestError } from '@tma.js/bridge';\nimport { BetterPromise } from 'better-promises';\nimport * as TE from 'fp-ts/TaskEither';\nimport { pipe } from 'fp-ts/function';\n\nimport { createWithChecksFp, type WithChecks, type WithChecksFp } from '@/with-checks/withChecksFp.js';\nimport { createIsSupportedSignal } from '@/helpers/createIsSupportedSignal.js';\nimport type { AsyncOptions } from '@/types.js';\nimport { ConcurrentCallError, InvalidArgumentsError } from '@/errors.js';\nimport type { WithVersion } from '@/fn-options/withVersion.js';\nimport type { WithRequest } from '@/fn-options/withRequest.js';\nimport type { SharedFeatureOptions } from '@/fn-options/sharedFeatureOptions.js';\nimport { throwifyWithChecksFp } from '@/with-checks/throwifyWithChecksFp.js';\n\ntype InvoiceTask<E, T> = TE.TaskEither<RequestError | ConcurrentCallError | E, T>;\n\nexport interface InvoiceOptions extends WithVersion, WithRequest, SharedFeatureOptions {\n}\n\n/**\n * @since Mini Apps v6.1\n */\nexport class Invoice {\n constructor({ version, request, isTma }: InvoiceOptions) {\n const wrapSupportedTask = createWithChecksFp({\n version,\n isTma,\n requires: 'web_app_open_invoice',\n returns: 'task',\n });\n\n const isOpened = signal(false);\n const toggleClosed = () => {\n isOpened.set(false);\n };\n\n this.isSupported = createIsSupportedSignal('web_app_open_invoice', version);\n this.isOpened = computed(isOpened);\n this.openSlugFp = wrapSupportedTask((slug, options) => {\n return pipe(\n this.isOpened()\n ? TE.left(new ConcurrentCallError('Invoice is already opened'))\n : TE.right(undefined as never),\n TE.chain(() => {\n isOpened.set(true);\n return request('web_app_open_invoice', 'invoice_closed', {\n ...options,\n params: { slug },\n capture: data => slug === data.slug,\n });\n }),\n TE.mapBoth(err => {\n toggleClosed();\n return err;\n }, data => {\n toggleClosed();\n return data.status;\n }),\n );\n });\n this.openUrlFp = wrapSupportedTask((url, options) => {\n const { hostname, pathname } = new URL(url, window.location.href);\n if (hostname !== 't.me') {\n return TE.left(new InvalidArgumentsError(`Link has unexpected hostname: ${hostname}`));\n }\n\n // Valid examples:\n // \"/invoice/my-slug\"\n // \"/$my-slug\"\n const match = pathname.match(/^\\/(\\$|invoice\\/)([A-Za-z0-9\\-_=]+)$/);\n if (!match) {\n return TE.left(new InvalidArgumentsError(\n 'Expected to receive a link with a pathname in format \"/invoice/{slug}\" or \"/${slug}\"',\n ));\n }\n return this.openSlugFp(match[2], options);\n });\n\n this.openUrl = throwifyWithChecksFp(this.openUrlFp);\n this.openSlug = throwifyWithChecksFp(this.openSlugFp);\n }\n\n /**\n * Signal indicating if any invoice is currently opened.\n */\n readonly isOpened: Computed<boolean>;\n\n /**\n * Signal indicating if the component is supported.\n */\n readonly isSupported: Computed<boolean>;\n\n /**\n * Opens an invoice using its slug or URL.\n * @param slug - invoice slug.\n * @param options - additional options.\n * @since Mini Apps v6.1\n * @example\n * const status = await invoice.openSlug('kJNFS331');\n */\n readonly openSlugFp: WithChecksFp<\n (slug: string, options?: AsyncOptions) => InvoiceTask<never, InvoiceStatus>,\n true\n >;\n\n /**\n * @see openSlugFp\n */\n readonly openSlug: WithChecks<\n (slug: string, options?: AsyncOptions) => BetterPromise<InvoiceStatus>,\n true\n >;\n\n /**\n * Opens an invoice using its URL.\n * @param url - invoice URL.\n * @param options - additional options.\n * @since Mini Apps v6.1\n * @example\n * const status = await invoice.openUrl('https://t.me/$kJNFS331');\n */\n readonly openUrlFp: WithChecksFp<\n (url: string, options?: AsyncOptions) => (\n InvoiceTask<InvalidArgumentsError, InvoiceStatus>\n ),\n true\n >;\n\n /**\n * @see openUrlFp\n */\n readonly openUrl: WithChecks<\n (url: string, options?: AsyncOptions) => BetterPromise<InvoiceStatus>,\n true\n >;\n}\n","import { pipe } from 'fp-ts/function';\n\nimport { Invoice } from '@/features/Invoice/Invoice.js';\nimport { sharedFeatureOptions } from '@/fn-options/sharedFeatureOptions.js';\nimport { withRequest } from '@/fn-options/withRequest.js';\nimport { withVersion } from '@/fn-options/withVersion.js';\n\nexport const invoice = new Invoice(pipe(sharedFeatureOptions(), withRequest, withVersion));\n","import { pipe } from 'fp-ts/function';\nimport * as E from 'fp-ts/Either';\nimport type { OpenLinkBrowser, PostEventError } from '@tma.js/bridge';\n\nimport {\n type SharedFeatureOptions,\n sharedFeatureOptions,\n} from '@/fn-options/sharedFeatureOptions.js';\nimport { type WithPostEvent, withPostEvent } from '@/fn-options/withPostEvent.js';\nimport { withChecksFp } from '@/with-checks/withChecksFp.js';\nimport { InvalidArgumentsError } from '@/errors.js';\nimport { throwifyWithChecksFp } from '@/with-checks/throwifyWithChecksFp.js';\n\ninterface CreateOptions extends SharedFeatureOptions, WithPostEvent {\n}\n\nexport interface OpenLinkOptions {\n /**\n * Attempts to use the instant view mode.\n */\n tryInstantView?: boolean;\n /**\n * A preferred browser to open the link in.\n */\n tryBrowser?: OpenLinkBrowser;\n}\n\nexport type OpenLinkError = PostEventError | InvalidArgumentsError;\n\nfunction create({ postEvent, ...rest }: CreateOptions) {\n return withChecksFp((\n url: string | URL,\n options: OpenLinkOptions = {},\n ): E.Either<OpenLinkError, void> => {\n if (typeof url === 'string') {\n try {\n url = new URL(url);\n } catch (e) {\n return E.left(new InvalidArgumentsError(`\"${url.toString()}\" is invalid URL`, e));\n }\n }\n return postEvent('web_app_open_link', {\n url: url.toString(),\n try_browser: options.tryBrowser,\n try_instant_view: options.tryInstantView,\n });\n }, { ...rest, returns: 'either' });\n}\n\n/**\n * Opens a link.\n *\n * The Mini App will not be closed.\n *\n * Note that this method can be called only in response to the user\n * interaction with the Mini App interface (e.g. click inside the Mini App or on the main button).\n * @param url - URL to be opened.\n * @param options - additional options.\n * @example\n * openLink('https://google.com', {\n * tryInstantView: true,\n * tryBrowser: 'chrome',\n * });\n */\nexport const openLinkFp = create(pipe(\n sharedFeatureOptions(),\n withPostEvent,\n));\n\nexport const openLink = throwifyWithChecksFp(openLinkFp);\n","import { pipe } from 'fp-ts/function';\nimport * as E from 'fp-ts/Either';\nimport { supports, type PostEventError } from '@tma.js/bridge';\n\nimport {\n type SharedFeatureOptions,\n sharedFeatureOptions,\n} from '@/fn-options/sharedFeatureOptions.js';\nimport { withPostEvent, type WithPostEvent } from '@/fn-options/withPostEvent.js';\nimport { withChecksFp } from '@/with-checks/withChecksFp.js';\nimport { InvalidArgumentsError } from '@/errors.js';\nimport { throwifyWithChecksFp } from '@/with-checks/throwifyWithChecksFp.js';\nimport { withVersion, type WithVersion } from '@/fn-options/withVersion.js';\nimport { access } from '@/helpers/access.js';\n\ninterface CreateOptions extends SharedFeatureOptions, WithPostEvent, WithVersion {\n}\n\nexport type OpenTelegramLinkError = PostEventError | InvalidArgumentsError;\n\nfunction create({ postEvent, version, ...rest }: CreateOptions) {\n return withChecksFp((\n url: string | URL,\n ): E.Either<OpenTelegramLinkError, void> => {\n const urlString = url.toString();\n if (!urlString.match(/^https:\\/\\/t.me\\/.+/)) {\n return E.left(new InvalidArgumentsError(`\"${urlString}\" is invalid URL`));\n }\n\n if (supports('web_app_open_tg_link', access(version))) {\n url = new URL(url);\n return postEvent('web_app_open_tg_link', { path_full: url.pathname + url.search });\n }\n\n window.location.href = urlString;\n return E.right(undefined);\n }, { ...rest, returns: 'either' });\n}\n\n/**\n * Opens a Telegram link inside the Telegram app. The function expects passing a link in a full\n * format using the hostname \"t.me\".\n *\n * The Mini App will be closed.\n * @param url - URL to be opened.\n * @example\n * openTelegramLink('https://t.me/heyqbnk');\n */\nexport const openTelegramLinkFp = create(pipe(\n sharedFeatureOptions(),\n withPostEvent,\n withVersion,\n));\n\n/**\n * @see openTelegramLinkFp\n */\nexport const openTelegramLink = throwifyWithChecksFp(openTelegramLinkFp);\n","import type * as E from 'fp-ts/Either';\nimport type { PostEventError } from '@tma.js/bridge';\n\nimport { withChecksFp } from '@/with-checks/withChecksFp.js';\nimport {\n sharedFeatureOptions,\n type SharedFeatureOptions,\n} from '@/fn-options/sharedFeatureOptions.js';\nimport { openTelegramLinkFp } from '@/features/links/openTelegramLink.js';\nimport { throwifyWithChecksFp } from '@/with-checks/throwifyWithChecksFp.js';\n\ninterface CreateOptions extends SharedFeatureOptions {\n openTelegramLink: (url: string) => E.Either<PostEventError, void>;\n}\n\nexport type ShareURLError = PostEventError;\n\nfunction create({ openTelegramLink, ...rest }: CreateOptions) {\n return withChecksFp((url: string, text?: string): E.Either<ShareURLError, void> => {\n return openTelegramLink(\n 'https://t.me/share/url?' + new URLSearchParams({ url, text: text || '' })\n .toString()\n // By default, URL search params encode spaces with \"+\".\n // We are replacing them with \"%20\", because plus symbols are working incorrectly\n // in Telegram.\n .replace(/\\+/g, '%20'),\n );\n }, { ...rest, returns: 'either' });\n}\n\n/**\n * Shares the specified URL with the passed to the chats, selected by user.\n * After being called, it closes the mini application.\n *\n * This method uses Telegram's Share Links.\n * @param url - URL to share.\n * @param text - text to append after the URL.\n * @see https://core.telegram.org/api/links#share-links\n * @see https://core.telegram.org/widgets/share#custom-buttons\n */\nexport const shareURLFp = create({\n ...sharedFeatureOptions(),\n openTelegramLink: openTelegramLinkFp,\n});\n\n/**\n * @see shareURLFp\n */\nexport const shareURL = throwifyWithChecksFp(shareURLFp);\n","import type { Computed } from '@tma.js/signals';\nimport type { EventPayload, RequestError, PostEventError } from '@tma.js/bridge';\nimport type { Maybe } from '@tma.js/toolkit';\nimport { BetterPromise } from 'better-promises';\nimport * as E from 'fp-ts/Either';\nimport * as TE from 'fp-ts/TaskEither';\nimport { pipe } from 'fp-ts/function';\n\nimport { createWithChecksFp, type WithChecks, type WithChecksFp } from '@/with-checks/withChecksFp.js';\nimport { createIsSupportedSignal } from '@/helpers/createIsSupportedSignal.js';\nimport type { AsyncOptions } from '@/types.js';\nimport type {\n LocationManagerOptions,\n LocationManagerRequestLocationResponse,\n LocationManagerState,\n} from '@/features/LocationManager/types.js';\nimport { Stateful } from '@/composables/Stateful.js';\nimport { AsyncMountable } from '@/composables/AsyncMountable.js';\nimport { throwifyWithChecksFp } from '@/with-checks/throwifyWithChecksFp.js';\n\nfunction eventToState(event: EventPayload<'location_checked'>): LocationManagerState {\n let available = false;\n let accessRequested: Maybe<boolean>;\n let accessGranted: Maybe<boolean>;\n if (event.available) {\n available = true;\n accessRequested = event.access_requested;\n accessGranted = event.access_granted;\n }\n return {\n available,\n accessGranted: accessGranted || false,\n accessRequested: accessRequested || false,\n };\n}\n\n/**\n * @since Mini Apps v8.0\n */\nexport class LocationManager {\n constructor({\n version,\n request,\n postEvent,\n storage,\n isTma,\n isPageReload,\n }: LocationManagerOptions) {\n const stateful = new Stateful({\n initialState: {\n available: false,\n accessGranted: false,\n accessRequested: false,\n },\n onChange: storage.set,\n });\n const mountable = new AsyncMountable<LocationManagerState, RequestError>({\n isPageReload,\n restoreState: storage.get,\n onMounted: stateful.setState,\n initialState(options) {\n return pipe(\n request('web_app_check_location', 'location_checked', options),\n TE.map(eventToState),\n );\n },\n });\n\n const wrapOptions = { version, requires: 'web_app_check_location', isTma } as const;\n const wrapSupportedEither = createWithChecksFp({\n ...wrapOptions,\n returns: 'either',\n });\n const wrapSupportedTask = createWithChecksFp({\n ...wrapOptions,\n returns: 'task',\n });\n const wrapMountedTask = createWithChecksFp({\n ...wrapOptions,\n returns: 'task',\n isMounted: mountable.isMounted,\n });\n\n this.isAvailable = stateful.getter('available');\n this.isAccessRequested = stateful.getter('accessRequested');\n this.isAccessGranted = stateful.getter('accessGranted');\n this.isSupported = createIsSupportedSignal('web_app_check_location', version);\n this.isMounted = mountable.isMounted;\n this.state = stateful.state;\n\n this.unmount = mountable.unmount;\n this.mountFp = wrapSupportedTask(mountable.mount);\n this.openSettingsFp = wrapSupportedEither(() => {\n return postEvent('web_app_open_location_settings');\n });\n this.requestLocationFp = wrapMountedTask(options => {\n return pipe(\n request('web_app_request_location', 'location_requested', options),\n TE.map(response => {\n if (!response.available) {\n stateful.setState({ available: false });\n return null;\n }\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { available, ...rest } = response;\n return rest;\n }),\n );\n });\n\n this.mount = throwifyWithChecksFp(this.mountFp);\n this.openSettings = throwifyWithChecksFp(this.openSettingsFp);\n this.requestLocation = throwifyWithChecksFp(this.requestLocationFp);\n }\n\n /**\n * Complete location manager state.\n */\n readonly state: Computed<LocationManagerState>;\n\n /**\n * Signal indicating whether the location data tracking is currently available.\n */\n readonly isAvailable: Computed<boolean>;\n\n /**\n * Signal indicating whether the user has granted the app permission to track location data.\n */\n readonly isAccessGranted: Computed<boolean>;\n\n /**\n * Signal indicating whether the app has previously requested permission to track location data.\n */\n readonly isAccessRequested: Computed<boolean>;\n\n /**\n * Signal indicating if the component is currently mounted.\n */\n readonly isMounted: Computed<boolean>;\n\n /**\n * Signal indicating if the component is supported.\n */\n readonly isSupported: Computed<boolean>;\n\n /**\n * Opens the location access settings for bots. Useful when you need to request location access\n * from users who haven't granted it yet.\n *\n * Note that this method can be called only in response to user interaction with the Mini App\n * interface (e.g., a click inside the Mini App or on the main button).\n * @since Mini Apps v8.0\n */\n readonly openSettingsFp: WithChecksFp<() => E.Either<PostEventError, void>, true>;\n\n /**\n * @see openSettingsFp\n */\n readonly openSettings: WithChecks<() => void, true>;\n\n /**\n * Requests location data.\n * @since Mini Apps v8.0\n * @returns Promise with location data or null it access was not granted.\n */\n readonly requestLocationFp: WithChecksFp<\n (options?: AsyncOptions) => (\n TE.TaskEither<RequestError, LocationManagerRequestLocationResponse | null>\n ),\n true\n >;\n\n /**\n * @see requestLocationFp\n */\n readonly requestLocation: WithChecks<\n (options?: AsyncOptions) => BetterPromise<LocationManagerRequestLocationResponse | null>,\n true\n >;\n\n /**\n * Mounts the component restoring its state.\n * @since Mini Apps v8.0\n */\n readonly mountFp: WithChecksFp<\n (options?: AsyncOptions) => TE.TaskEither<RequestError, void>,\n true\n >;\n\n /**\n * @see mountFp\n */\n readonly mount: WithChecks<(options?: AsyncOptions) => BetterPromise<void>, true>;\n\n /**\n * Unmounts the component.\n */\n readonly unmount: () => void;\n}\n","import { pipe } from 'fp-ts/function';\n\nimport { LocationManager } from '@/features/LocationManager/LocationManager.js';\nimport { sharedFeatureOptions } from '@/fn-options/sharedFeatureOptions.js';\nimport { withRequest } from '@/fn-options/withRequest.js';\nimport { withStateRestore } from '@/fn-options/withStateRestore.js';\nimport type { LocationManagerState } from '@/features/LocationManager/types.js';\nimport { withPostEvent } from '@/fn-options/withPostEvent.js';\nimport { withVersion } from '@/fn-options/withVersion.js';\n\nexport const locationManager = new LocationManager(pipe(\n sharedFeatureOptions(),\n withPostEvent,\n withVersion,\n withRequest,\n withStateRestore<LocationManagerState>('locationManager'),\n));\n","import { computed, type Computed } from '@tma.js/signals';\nimport type { RGB } from '@tma.js/types';\nimport type { PostEventError } from '@tma.js/bridge';\nimport * as E from 'fp-ts/Either';\n\nimport type { WithChecks, WithChecksFp } from '@/with-checks/withChecksFp.js';\nimport { Button, type ButtonOptions } from '@/composables/Button.js';\nimport type { MaybeAccessor } from '@/types.js';\nimport { access } from '@/helpers/access.js';\n\ntype MainButtonEither = E.Either<PostEventError, void>;\n\nexport interface MainButtonState {\n isVisible: boolean;\n bgColor?: RGB;\n hasShineEffect: boolean;\n isEnabled: boolean;\n isLoaderVisible: boolean;\n text: string;\n textColor?: RGB;\n}\n\nexport interface MainButtonOptions extends Omit<\n ButtonOptions<MainButtonState, 'web_app_setup_main_button'>,\n 'initialState' | 'method' | 'payload' | 'version'\n> {\n /**\n * Default values for different kinds of the button properties.\n */\n defaults: {\n bgColor: MaybeAccessor<RGB>;\n textColor: MaybeAccessor<RGB>;\n };\n}\n\nexport class MainButton {\n constructor({ defaults, ...options }: MainButtonOptions) {\n const button = new Button({\n ...options,\n version: '100',\n initialState: {\n hasShineEffect: false,\n isEnabled: true,\n isLoaderVisible: false,\n isVisible: false,\n text: 'Continue',\n },\n method: 'web_app_setup_main_button',\n payload: state => ({\n has_shine_effect: state.hasShineEffect,\n is_visible: state.isVisible,\n is_active: state.isEnabled,\n is_progress_visible: state.isLoaderVisible,\n text: state.text,\n color: state.bgColor,\n text_color: state.textColor,\n }),\n });\n\n const withDefault = (\n field: 'bgColor' | 'textColor',\n getDefault: MaybeAccessor<RGB>,\n ) => {\n const fromState = button.stateGetter(field);\n return computed(() => fromState() || access(getDefault));\n };\n\n this.bgColor = withDefault('bgColor', defaults.bgColor);\n this.textColor = withDefault('textColor', defaults.textColor);\n this.hasShineEffect = button.stateGetter('hasShineEffect');\n this.isEnabled = button.stateGetter('isEnabled');\n this.isLoaderVisible = button.stateGetter('isLoaderVisible');\n this.text = button.stateGetter('text');\n this.isVisible = button.stateGetter('isVisible');\n this.isMounted = button.isMounted;\n this.state = button.state;\n\n [this.setBgColor, this.setBgColorFp] = button.stateSetters('bgColor');\n [this.setTextColor, this.setTextColorFp] = button.stateSetters('textColor');\n [\n [this.disableShineEffect, this.disableShineEffectFp],\n [this.enableShineEffect, this.enableShineEffectFp],\n ] = button.stateBoolSetters('hasShineEffect');\n [\n [this.disable, this.disableFp],\n [this.enable, this.enableFp],\n ] = button.stateBoolSetters('isEnabled');\n [\n [this.hideLoader, this.hideLoaderFp],\n [this.showLoader, this.showLoaderFp],\n ] = button.stateBoolSetters('isLoaderVisible');\n\n [this.setText, this.setTextFp] = button.stateSetters('text');\n [[this.hide, this.hideFp], [this.show, this.showFp]] = button.stateBoolSetters('isVisible');\n this.setParams = button.setState;\n this.setParamsFp = button.setStateFp;\n this.onClick = button.onClick;\n this.onClickFp = button.onClickFp;\n this.offClick = button.offClick;\n this.offClickFp = button.offClickFp;\n this.mount = button.mount;\n this.mountFp = button.mountFp;\n this.unmount = button.unmount;\n }\n\n //#region Properties.\n /**\n * The button background color.\n */\n readonly bgColor: Computed<RGB>;\n\n /**\n * True if the button has a shining effect.\n */\n readonly hasShineEffect: Computed<boolean>;\n\n /**\n * True if the button is clickable.\n */\n readonly isEnabled: Computed<boolean>;\n\n /**\n * True if the button loader is visible.\n */\n readonly isLoaderVisible: Computed<boolean>;\n\n /**\n * True if the button is visible.\n */\n readonly isVisible: Computed<boolean>;\n\n /**\n * Signal indicating if the component is currently mounted.\n */\n readonly isMounted: Computed<boolean>;\n\n /**\n * The complete button state.\n */\n readonly state: Computed<MainButtonState>;\n\n /**\n * The button displayed text.\n */\n readonly text: Computed<string>;\n\n /**\n * The button text color.\n *\n * Note that this value is computed based on the external defaults. For\n * example, if not explicitly set, this value may be equal to one of theme\n * params colors.\n */\n readonly textColor: Computed<RGB>;\n //#endregion\n\n //#region Methods.\n /**\n * Shows the button.\n */\n readonly showFp: WithChecksFp<() => MainButtonEither, false>;\n\n /**\n * @see showFp\n */\n readonly show: WithChecks<() => void, false>;\n\n /**\n * Hides the button.\n */\n readonly hideFp: WithChecksFp<() => MainButtonEither, false>;\n\n /**\n * @see hideFp\n */\n readonly hide: WithChecks<() => void, false>;\n\n /**\n * Enables the button.\n */\n readonly enableFp: WithChecksFp<() => MainButtonEither, false>;\n\n /**\n * @see enableFp\n */\n readonly enable: WithChecks<() => void, false>;\n\n /**\n * Enables the button.\n */\n readonly enableShineEffectFp: WithChecksFp<() => MainButtonEither, false>;\n\n /**\n * @see enableShineEffectFp\n */\n readonly enableShineEffect: WithChecks<() => void, false>;\n\n /**\n * Disables the button.\n */\n readonly disableFp: WithChecksFp<() => MainButtonEither, false>;\n\n /**\n * @see disableFp\n */\n readonly disable: WithChecks<() => void, false>;\n\n /**\n * Enables the button.\n */\n readonly disableShineEffectFp: WithChecksFp<() => MainButtonEither, false>;\n\n /**\n * @see disableShineEffectFp\n */\n readonly disableShineEffect: WithChecks<() => void, false>;\n\n /**\n * Updates the button background color.\n */\n readonly setBgColorFp: WithChecksFp<(value: RGB) => MainButtonEither, false>;\n\n /**\n * @see setBgColorFp\n */\n readonly setBgColor: WithChecks<(value: RGB) => void, false>;\n\n /**\n * Updates the button text color.\n */\n readonly setTextColorFp: WithChecksFp<(value: RGB) => MainButtonEither, false>;\n\n /**\n * @see setTextColorFp\n */\n readonly setTextColor: WithChecks<(value: RGB) => void, false>;\n\n /**\n * Updates the button text.\n */\n readonly setTextFp: WithChecksFp<(value: string) => MainButtonEither, false>;\n\n /**\n * @see setTextFp\n */\n readonly setText: WithChecks<(value: string) => void, false>;\n\n /**\n * Shows the button loader.\n */\n readonly showLoaderFp: WithChecksFp<() => MainButtonEither, false>;\n\n /**\n * @see showLoaderFp\n */\n readonly showLoader: WithChecks<() => void, false>;\n\n /**\n * Hides the button loader.\n */\n readonly hideLoaderFp: WithChecksFp<() => MainButtonEither, false>;\n\n /**\n * @see hideLoaderFp\n */\n readonly hideLoader: WithChecks<() => void, false>;\n\n /**\n * Updates the button state.\n * @param state - updates to apply.\n * @example\n * button.setParams({\n * text: 'Submit',\n * isEnabled: true,\n * hasShineEffect: true,\n * });\n */\n readonly setParamsFp: WithChecksFp<(state: Partial<MainButtonState>) => MainButtonEither, false>;\n\n readonly setParams: WithChecks<(state: Partial<MainButtonState>) => void, false>;\n\n /**\n * Mounts the component restoring its state.\n */\n readonly mountFp: WithChecksFp<() => void, false>;\n\n /**\n * @see mountFp\n */\n readonly mount: WithChecks<() => void, false>;\n\n /**\n * Unmounts the component.\n */\n readonly unmount: () => void;\n\n /**\n * Adds a new button listener.\n * @param listener - event listener.\n * @param once - should the listener be called only once.\n * @returns A function to remove bound listener.\n * @example\n * const off = button.onClick(() => {\n * console.log('User clicked the button');\n * off();\n * });\n */\n readonly onClickFp: WithChecksFp<(listener: VoidFunction, once?: boolean) => VoidFunction, false>;\n\n /**\n * @see onClickFp\n */\n readonly onClick: WithChecks<(listener: VoidFunction, once?: boolean) => VoidFunction, false>;\n\n /**\n * Removes the button click listener.\n * @param listener - event listener.\n * @param once - should the listener be called only once.\n * @example\n * function listener() {\n * console.log('User clicked the button');\n * button.offClick(listener);\n * }\n * button.onClick(listener);\n */\n readonly offClickFp: WithChecksFp<(listener: VoidFunction, once?: boolean) => void, false>;\n\n /**\n * @see offClickFp\n */\n readonly offClick: WithChecks<(listener: VoidFunction, once?: boolean) => void, false>;\n //#endregion\n}\n","import type { EventName } from '@tma.js/bridge';\nimport { pipe } from 'fp-ts/function';\n\nimport { buttonOptions } from '@/fn-options/buttonOptions.js';\n\nexport function bottomButtonOptions<S, D>(\n storageName: string,\n trackedClickEvent: EventName,\n defaults: D,\n) {\n return pipe(\n buttonOptions<S>(storageName, trackedClickEvent),\n obj => ({ ...obj, defaults }),\n );\n}\n","import type { ThemeParams } from '@tma.js/types';\n\nimport { createSignal } from '@/globals/signals-registry.js';\n\n/**\n * Mini application's theme parameters.\n */\nexport const themeParams = createSignal<ThemeParams>({});\n","/**\n * Sets CSS variable globally.\n * @param name - variable name.\n * @param value - variable value.\n */\nexport function setCssVar(name: string, value: string | null): void {\n document.documentElement.style.setProperty(name, value);\n}\n\n/**\n * Deletes specified CSS variable.\n * @param name - variable name.\n */\nexport function deleteCssVar(name: string): void {\n document.documentElement.style.removeProperty(name);\n}\n","import { throwifyFpFn } from '@tma.js/toolkit';\nimport { toRGBFullFp } from '@tma.js/transformers';\nimport * as E from 'fp-ts/Either';\nimport { pipe } from 'fp-ts/function';\n\n/**\n * @param color - color in any format acceptable by the `toRGB` function.\n * @returns True if the color is recognized as dark.\n * @see toRGB\n */\nexport function isColorDarkFp(color: string): E.Either<Error, boolean> {\n return pipe(\n toRGBFullFp(color),\n E.map(rgb => {\n // Actual formula: hsp = Math.sqrt(0.299 * r * r + 0.587 * g * g + 0.114 * b * b)\n // See: https://stackoverflow.com/a/596243\n return Math.sqrt(\n [0.299, 0.587, 0.114].reduce<number>((acc, modifier, idx) => {\n // Extract part of #RRGGBB pattern and convert it to DEC.\n const dec = parseInt(rgb.slice(1 + (idx * 2), 1 + ((idx + 1) * 2)), 16);\n return acc + (dec * dec * modifier);\n }, 0),\n ) < 120;\n }),\n );\n}\n\n/**\n * @see isColorDarkFp\n */\nexport const isColorDark = throwifyFpFn(isColorDarkFp);\n","import { computed, type Computed, signal } from '@tma.js/signals';\nimport type { ThemeParams as ThemeParamsType, RGB } from '@tma.js/types';\nimport { snakeToKebab } from '@tma.js/toolkit';\nimport type { EventListener } from '@tma.js/bridge';\nimport * as E from 'fp-ts/Either';\n\nimport {\n createWithChecksFp,\n type WithChecks,\n type WithChecksFp,\n} from '@/with-checks/withChecksFp.js';\nimport { throwifyWithChecksFp } from '@/with-checks/throwifyWithChecksFp.js';\nimport { Stateful } from '@/composables/Stateful.js';\nimport { Mountable } from '@/composables/Mountable.js';\nimport { CSSVarsBoundError } from '@/errors.js';\nimport { deleteCssVar, setCssVar } from '@/helpers/css-vars.js';\nimport { isColorDark } from '@/helpers/isColorDark.js';\nimport type { WithStateRestore } from '@/fn-options/withStateRestore.js';\nimport type { SharedFeatureOptions } from '@/fn-options/sharedFeatureOptions.js';\nimport type { MaybeAccessor } from '@/types.js';\nimport { access } from '@/helpers/access.js';\n\nexport type ThemeParamsState = ThemeParamsType;\n\nexport interface ThemeParamsOptions extends WithStateRestore<ThemeParamsState>,\n SharedFeatureOptions {\n /**\n * Removes a theme change listener.\n * @param listener - a listener to remove.\n */\n offChange: (listener: EventListener<'theme_changed'>) => void;\n /**\n * Adds a theme change listener.\n * @returns A function to remove listener.\n * @param listener - a listener to add.\n */\n onChange: (listener: EventListener<'theme_changed'>) => void;\n /**\n * Theme parameters initial state.\n */\n initialState: MaybeAccessor<ThemeParamsType>;\n}\n\nexport interface ThemeParamsGetCssVarNameFn {\n /**\n * @param property - palette key.\n * @returns Computed complete CSS variable name.\n */\n (property: Extract<keyof ThemeParamsType, string>): string;\n}\n\nexport class ThemeParams {\n constructor({\n initialState,\n onChange,\n offChange,\n isTma,\n storage,\n isPageReload,\n }: ThemeParamsOptions) {\n const stateful = new Stateful<ThemeParamsState>({\n initialState: {},\n onChange: storage.set,\n });\n const listener: EventListener<'theme_changed'> = event => {\n stateful.setState(event.theme_params);\n };\n const mountable = new Mountable<ThemeParamsType>({\n initialState: () => E.right(access(initialState)),\n isPageReload,\n onMounted(state) {\n stateful.setState(state);\n onChange(listener);\n },\n onUnmounted() {\n offChange(listener);\n },\n restoreState: storage.get,\n });\n\n const wrapOptions = { isTma, returns: 'either' } as const;\n const wrapSupportedEither = createWithChecksFp(wrapOptions);\n const wrapMountedEither = createWithChecksFp({\n ...wrapOptions,\n isMounted: mountable.isMounted,\n });\n\n // Colors.\n this.accentTextColor = stateful.getter('accent_text_color');\n this.bgColor = stateful.getter('bg_color');\n this.buttonColor = stateful.getter('button_color');\n this.buttonTextColor = stateful.getter('button_text_color');\n this.bottomBarBgColor = stateful.getter('bottom_bar_bg_color');\n this.destructiveTextColor = stateful.getter('destructive_text_color');\n this.headerBgColor = stateful.getter('header_bg_color');\n this.hintColor = stateful.getter('hint_color');\n this.linkColor = stateful.getter('link_color');\n this.secondaryBgColor = stateful.getter('secondary_bg_color');\n this.sectionBgColor = stateful.getter('section_bg_color');\n this.sectionHeaderTextColor = stateful.getter('section_header_text_color');\n this.sectionSeparatorColor = stateful.getter('section_separator_color');\n this.subtitleTextColor = stateful.getter('subtitle_text_color');\n this.textColor = stateful.getter('text_color');\n\n // Other public signals.\n this.state = stateful.state;\n this.isMounted = mountable.isMounted;\n this.bindCssVarsFp = wrapMountedEither(getCSSVarName => {\n if (this._isCssVarsBound()) {\n return E.left(new CSSVarsBoundError());\n }\n getCSSVarName ||= prop => `--tg-theme-${snakeToKebab(prop)}`;\n\n const forEachEntry = (fn: (key: string, value: RGB) => void): void => {\n Object.entries(stateful.state()).forEach(([k, v]) => {\n v && fn(k, v);\n });\n };\n\n const actualize = (): void => {\n forEachEntry((k, v) => {\n setCssVar(getCSSVarName(k), v);\n });\n };\n\n actualize();\n stateful.state.sub(actualize);\n this._isCssVarsBound.set(true);\n\n return E.right(() => {\n forEachEntry(deleteCssVar);\n stateful.state.unsub(actualize);\n this._isCssVarsBound.set(false);\n });\n });\n this.mountFp = wrapSupportedEither(mountable.mount);\n this.unmount = mountable.unmount;\n\n this.bindCssVars = throwifyWithChecksFp(this.bindCssVarsFp);\n this.mount = throwifyWithChecksFp(this.mountFp);\n }\n\n //#region Colors.\n /**\n * @since v6.10\n */\n readonly accentTextColor: Computed<RGB | undefined>;\n\n readonly bgColor: Computed<RGB | undefined>;\n\n readonly buttonColor: Computed<RGB | undefined>;\n\n readonly buttonTextColor: Computed<RGB | undefined>;\n\n /**\n * @since v7.10\n */\n readonly bottomBarBgColor: Computed<RGB | undefined>;\n\n readonly destructiveTextColor: Computed<RGB | undefined>;\n\n /**\n * @since v6.10\n */\n readonly headerBgColor: Computed<RGB | undefined>;\n\n readonly hintColor: Computed<RGB | undefined>;\n\n readonly linkColor: Computed<RGB | undefined>;\n\n readonly secondaryBgColor: Computed<RGB | undefined>;\n\n /**\n * @since v6.10\n */\n readonly sectionBgColor: Computed<RGB | undefined>;\n\n /**\n * @since v6.10\n */\n readonly sectionHeaderTextColor: Computed<RGB | undefined>;\n\n /**\n * @since v7.6\n */\n readonly sectionSeparatorColor: Computed<RGB | undefined>;\n\n /**\n * @since v6.10\n */\n readonly subtitleTextColor: Computed<RGB | undefined>;\n\n readonly textColor: Computed<RGB | undefined>;\n //#endregion\n\n //#region CSS variables.\n private readonly _isCssVarsBound = signal(false);\n\n /**\n * True if CSS variables are currently bound.\n */\n readonly isCssVarsBound = computed(this._isCssVarsBound);\n\n /**\n * Creates CSS variables connected with the current theme parameters.\n *\n * By default, created CSS variables names are following the pattern \"--tg-theme-{name}\", where\n * {name} is a theme parameters key name converted from snake case to kebab case.\n *\n * Default variables:\n * - `--tg-theme-bg-color`\n * - `--tg-theme-secondary-text-color`\n *\n * Variables are being automatically updated if theme parameters were changed.\n *\n * @param getCSSVarName - function, returning complete CSS variable name for the specified\n * theme parameters key.\n * @returns Function to stop updating variables.\n * @throws {CSSVarsBoundError} CSS variables are already bound\n * @example Using custom CSS vars generator\n * themeParams.bindCssVars(key => `--my-prefix-${key}`);\n */\n readonly bindCssVarsFp: WithChecksFp<\n (getCSSVarName?: ThemeParamsGetCssVarNameFn) => E.Either<CSSVarsBoundError, VoidFunction>,\n false\n >;\n\n /**\n * @see bindCssVarsFp\n */\n readonly bindCssVars: WithChecks<\n (getCSSVarName?: ThemeParamsGetCssVarNameFn) => VoidFunction,\n false\n >;\n //#endregion\n\n //#region Other public signals.\n /**\n * Complete component state.\n */\n readonly state: Computed<ThemeParamsType>;\n\n /**\n * @returns True if the current color scheme is recognized as dark.\n * This value is calculated based on the current theme's background color.\n */\n readonly isDark = computed(() => {\n const color = this.bgColor();\n return !color || isColorDark(color);\n });\n //#endregion\n\n //#region Mounting.\n /**\n * Signal indicating if the component is currently mounted.\n */\n readonly isMounted: Computed<boolean>;\n\n /**\n * Mounts the component restoring its state.\n */\n readonly mountFp: WithChecksFp<() => E.Either<never, void>, false>;\n\n /**\n * @see mountFp\n */\n readonly mount: WithChecks<() => void, false>;\n\n /**\n * Unmounts the component.\n */\n readonly unmount: () => void;\n //#endregion\n}\n","import { on, off } from '@tma.js/bridge';\nimport { pipe } from 'fp-ts/function';\nimport { themeParams as globalThemeParams } from '@/globals/themeParams.js';\n\nimport { ThemeParams, type ThemeParamsState } from '@/features/ThemeParams/ThemeParams.js';\nimport { sharedFeatureOptions } from '@/fn-options/sharedFeatureOptions.js';\nimport { withStateRestore } from '@/fn-options/withStateRestore.js';\n\nexport const themeParams = new ThemeParams({\n ...pipe(\n sharedFeatureOptions(),\n withStateRestore<ThemeParamsState>('themeParams'),\n ),\n offChange(listener) {\n off('theme_changed', listener);\n },\n onChange(listener) {\n on('theme_changed', listener);\n },\n initialState: globalThemeParams,\n});\n","import { computed } from '@tma.js/signals';\n\nimport { MainButton } from '@/features/MainButton/MainButton.js';\nimport { bottomButtonOptions } from '@/fn-options/bottomButtonOptions.js';\nimport { themeParams } from '@/features/ThemeParams/instance.js';\n\nexport const mainButton = new MainButton(\n bottomButtonOptions('mainButton', 'main_button_pressed', {\n bgColor: computed(() => themeParams.buttonColor() || '#2481cc'),\n textColor: computed(() => themeParams.buttonTextColor() || '#ffffff'),\n }),\n);\n","import type { KnownThemeParamsKey, RGB, ThemeParams } from '@tma.js/types';\nimport { type Computed, computed } from '@tma.js/signals';\nimport {\n supports,\n type PostEventError,\n type EventPayload,\n type EventListener,\n} from '@tma.js/bridge';\nimport { createCbCollector, camelToKebab } from '@tma.js/toolkit';\nimport { isRGB } from '@tma.js/transformers';\nimport { pipe } from 'fp-ts/function';\nimport { signal } from '@tma.js/signals';\nimport * as E from 'fp-ts/Either';\n\nimport { isColorDark } from '@/helpers/isColorDark.js';\nimport {\n createWithChecksFp,\n type WithChecks,\n withChecksFp,\n type WithChecksFp,\n} from '@/with-checks/withChecksFp.js';\nimport { CSSVarsBoundError, UnknownThemeParamsKeyError } from '@/errors.js';\nimport type { WithPostEvent } from '@/fn-options/withPostEvent.js';\nimport type { SharedFeatureOptions } from '@/fn-options/sharedFeatureOptions.js';\nimport type { WithVersion } from '@/fn-options/withVersion.js';\nimport { Stateful } from '@/composables/Stateful.js';\nimport type { WithStateRestore } from '@/fn-options/withStateRestore.js';\nimport { Mountable } from '@/composables/Mountable.js';\nimport { access } from '@/helpers/access.js';\nimport { throwifyWithChecksFp } from '@/with-checks/throwifyWithChecksFp.js';\nimport { deleteCssVar, setCssVar } from '@/helpers/css-vars.js';\n\ntype AnyColor = RGB | KnownThemeParamsKey | string;\n\nexport interface MiniAppState {\n bgColor: AnyColor;\n bottomBarColor: AnyColor;\n headerColor: AnyColor;\n isActive: boolean;\n}\n\nexport interface MiniAppGetCssVarNameFn {\n /**\n * @param property - mini app property.\n * @returns Computed complete CSS variable name.\n */\n (property: 'bgColor' | 'bottomBarColor' | 'headerColor'): string;\n}\n\ntype WithListeners<Handlers extends string, Payload> = {\n [K in Handlers]: (listener: (payload: Payload) => void) => void;\n};\n\nexport interface MiniAppOptions extends WithPostEvent,\n WithVersion,\n WithStateRestore<MiniAppState>,\n WithListeners<'onVisibilityChanged' | 'offVisibilityChanged', EventPayload<'visibility_changed'>>,\n SharedFeatureOptions {\n /**\n * The current theme parameters.\n */\n theme: Computed<ThemeParams>;\n}\n\n/**\n * @since Mini Apps v6.1\n */\nexport class MiniApp {\n constructor({\n storage,\n isPageReload,\n version,\n postEvent,\n isTma,\n theme,\n onVisibilityChanged,\n offVisibilityChanged,\n }: MiniAppOptions) {\n //#region Mounting.\n const visibilityChangedListener: EventListener<'visibility_changed'> = event => {\n stateful.setState({ isActive: event.is_visible });\n };\n const themeChangedListener = (theme: ThemeParams) => {\n // Sometimes we may have the following colors to be specified as some theme params keys.\n // Due to the Mini Apps nature, we are not really allowed to do that, but we want to provide\n // such an opportunity to developers.\n //\n // So if the developer specified some field as a reference to some theme params key, we\n // should find an according RGB color for it and send it to the Telegram client. The excluded\n // keys are 'bg_color' and 'secondary_bg_color' - they are known to the Telegram client.\n //\n // - 'web_app_set_header_color' accepts RGB only.\n // - 'web_app_set_background_color' and 'web_app_set_bottom_bar_color' accept RGB and such\n // values as 'bg_color' and 'secondary_bg_color'.\n ([\n [this.headerColor, 'web_app_set_header_color'],\n [this.bgColor, 'web_app_set_background_color'],\n [this.bottomBarColor, 'web_app_set_bottom_bar_color'],\n ] as const).forEach(([signal, method]) => {\n const color = signal();\n // The value is already RGB, we have nothing to do here.\n if (isRGB(color)) {\n return;\n }\n // The real RGB value should only be extracted of the 'web_app_set_header_color' should be\n // used (it accepts only RGB values) or the color\n // is not 'bg_color' and 'secondary_bg_color' (other methods may work with such values).\n if (\n method === 'web_app_set_header_color'\n || !['bg_color', 'secondary_bg_color'].includes(color)\n ) {\n const rgb = theme[color];\n if (rgb) {\n postEvent(method, { color: rgb });\n }\n }\n });\n };\n const mountable = new Mountable({\n initialState() {\n const tp = access(theme);\n return E.right({\n bgColor: tp.bg_color || 'bg_color',\n headerColor: tp.header_bg_color || 'header_bg_color',\n bottomBarColor: tp.bottom_bar_bg_color || 'bottom_bar_bg_color',\n isActive: true,\n });\n },\n isPageReload,\n onMounted: state => {\n this.setBgColorFp.ifAvailable(state.bgColor);\n this.setBottomBarColorFp.ifAvailable(state.bottomBarColor);\n this.setHeaderColorFp.ifAvailable(state.headerColor);\n onVisibilityChanged(visibilityChangedListener);\n theme.sub(themeChangedListener);\n stateful.setState(state);\n },\n onUnmounted() {\n offVisibilityChanged(visibilityChangedListener);\n theme.unsub(themeChangedListener);\n },\n restoreState: storage.get,\n });\n this.isMounted = mountable.isMounted;\n this.mountFp = withChecksFp(() => {\n const nothing = () => undefined;\n return pipe(mountable.mount(), E.match(nothing, nothing));\n }, { isTma, returns: 'plain' });\n this.mount = throwifyWithChecksFp(this.mountFp);\n this.unmount = mountable.unmount;\n //#endregion\n\n //#region State.\n const stateful = new Stateful({\n initialState: {\n bgColor: 'bg_color',\n bottomBarColor: 'bottom_bar_bg_color',\n headerColor: 'bg_color',\n isActive: false,\n },\n onChange: storage.set,\n });\n this.state = stateful.state;\n\n const rgbBasedOn = (color: AnyColor): RGB | undefined => {\n return isRGB(color) ? color : access(theme)[color];\n };\n const computedRgbBasedOn = (signal: Computed<AnyColor>): Computed<RGB | undefined> => {\n return computed(() => rgbBasedOn(signal()));\n };\n //#endregion\n\n //#region Other properties.\n this.isActive = stateful.getter('isActive');\n this.isSupported = computed(() => {\n return ([\n 'web_app_set_header_color',\n 'web_app_set_background_color',\n 'web_app_set_bottom_bar_color',\n ] as const).some(method => supports(method, access(version)));\n });\n //#endregion\n\n //#region Css vars.\n const isCssVarsBound = signal(false);\n this.isCssVarsBound = computed(isCssVarsBound);\n this.bindCssVarsFp = withChecksFp(getCSSVarName => {\n if (isCssVarsBound()) {\n return E.left(new CSSVarsBoundError());\n }\n const [addCleanup, cleanup] = createCbCollector(() => {\n isCssVarsBound.set(false);\n });\n\n const bind = (cssVar: string, signal: Computed<RGB | undefined>) => {\n const update = () => {\n setCssVar(cssVar, signal() || null);\n };\n update();\n addCleanup(signal.sub(update), deleteCssVar.bind(null, cssVar));\n };\n\n getCSSVarName ||= prop => `--tg-${camelToKebab(prop)}`;\n bind(getCSSVarName('bgColor'), this.bgColorRgb);\n bind(getCSSVarName('bottomBarColor'), this.bottomBarColorRgb);\n bind(getCSSVarName('headerColor'), this.headerColorRgb);\n\n isCssVarsBound.set(true);\n\n return E.right(cleanup);\n }, { isTma, returns: 'either', isMounted: this.isMounted });\n this.bindCssVars = throwifyWithChecksFp(this.bindCssVarsFp);\n //#endregion\n\n //#region Colors.\n type GenColorToolsetResult<K extends Exclude<keyof MiniAppState, 'isActive'>> = [\n rawColor: Computed<AnyColor>,\n rgbColor: Computed<RGB | undefined>,\n throwing: WithChecks<\n (color: AnyColor) => void,\n true,\n K extends 'headerColor' ? 'rgb' : never\n >,\n fp: WithChecksFp<\n (color: AnyColor) => E.Either<UnknownThemeParamsKeyError | PostEventError, void>,\n true,\n K extends 'headerColor' ? 'rgb' : never\n >,\n ];\n const genColorToolset = <K extends Exclude<keyof MiniAppState, 'isActive'>>(\n stateKey: K,\n ): GenColorToolsetResult<K> => {\n const rawColor = stateful.getter(stateKey);\n const rgbColor = computedRgbBasedOn(rawColor);\n const method = ({\n headerColor: 'web_app_set_header_color',\n bgColor: 'web_app_set_background_color',\n bottomBarColor: 'web_app_set_bottom_bar_color',\n } as const)[stateKey];\n\n const fp = withChecksFp(\n (color: AnyColor): E.Either<UnknownThemeParamsKeyError | PostEventError, void> => {\n if (color === rawColor()) {\n return E.right(undefined);\n }\n if (\n method === 'web_app_set_header_color'\n && (color === 'bg_color' || color === 'secondary_bg_color')\n ) {\n return postEvent('web_app_set_header_color', { color_key: color });\n }\n const rgb = rgbBasedOn(color);\n return pipe(\n rgb\n ? postEvent(method, { color: rgb })\n : E.left(new UnknownThemeParamsKeyError(color)),\n E.map(() => {\n stateful.setState({ [stateKey]: rgb });\n }),\n );\n },\n {\n isTma,\n version,\n requires: method,\n isMounted: this.isMounted,\n returns: 'either',\n supports: stateKey === 'headerColor'\n ? {\n rgb: {\n method: 'web_app_set_header_color',\n param: 'color',\n shouldCheck: isRGB,\n },\n }\n : undefined,\n },\n );\n\n return [rawColor, rgbColor, throwifyWithChecksFp(fp), fp] as GenColorToolsetResult<K>;\n };\n [\n this.bgColor,\n this.bgColorRgb,\n this.setBgColor,\n this.setBgColorFp,\n ] = genColorToolset('bgColor');\n [\n this.headerColor,\n this.headerColorRgb,\n this.setHeaderColor,\n this.setHeaderColorFp,\n ] = genColorToolset('headerColor');\n [\n this.bottomBarColor,\n this.bottomBarColorRgb,\n this.setBottomBarColor,\n this.setBottomBarColorFp,\n ] = genColorToolset('bottomBarColor');\n //#endregion\n\n //#region Other methods.\n const withBasicEither = createWithChecksFp({ isTma, returns: 'either' });\n this.closeFp = withBasicEither(returnBack => {\n return postEvent('web_app_close', { return_back: returnBack });\n });\n this.close = throwifyWithChecksFp(this.closeFp);\n\n this.readyFp = withBasicEither(() => postEvent('web_app_ready'));\n this.ready = throwifyWithChecksFp(this.readyFp);\n //#endregion\n }\n\n //#region Other properties.\n /**\n * Signal indicating if the component is supported.\n */\n readonly isSupported: Computed<boolean>;\n\n /**\n * True if the current Mini App background color is recognized as dark.\n */\n readonly isDark = computed(() => {\n const color = this.bgColorRgb();\n return color ? isColorDark(color) : false;\n });\n\n /**\n * Signal indicating if the mini app is currently active.\n */\n readonly isActive: Computed<boolean>;\n\n /**\n * Complete component state.\n */\n readonly state: Computed<MiniAppState>;\n //#endregion\n\n //#region CSS variables.\n /**\n * True if the CSS variables are currently bound.\n */\n readonly isCssVarsBound: Computed<boolean>;\n\n /**\n * Creates CSS variables connected with the mini app.\n *\n * Default variables:\n * - `--tg-bg-color`\n * - `--tg-header-color`\n * - `--tg-bottom-bar-color`\n *\n * Variables are being automatically updated if theme parameters were changed.\n *\n * @param getCSSVarName - function, returning complete CSS variable name for the specified\n * mini app key.\n * @returns Function to stop updating variables.\n * @example Using no arguments\n * miniApp.bindCssVars();\n * @example Using custom CSS vars generator\n * miniApp.bindCssVars(key => `--my-prefix-${key}`);\n */\n readonly bindCssVarsFp: WithChecksFp<\n (getCssVarName?: MiniAppGetCssVarNameFn) => E.Either<CSSVarsBoundError, VoidFunction>,\n false\n >;\n\n readonly bindCssVars: WithChecks<(getCssVarName?: MiniAppGetCssVarNameFn) => VoidFunction, false>;\n //#endregion\n\n //#region Mounting.\n /**\n * Signal indicating if the component is mounted.\n */\n readonly isMounted: Computed<boolean>;\n\n /**\n * Mounts the component.\n *\n * This function restores the component state and is automatically saving it in the local storage\n * if it changed.\n * @since Mini Apps v6.1\n */\n readonly mountFp: WithChecksFp<() => void, false>;\n\n /**\n * @see mount\n */\n readonly mount: WithChecks<() => void, false>;\n\n /**\n * Unmounts the component.\n */\n readonly unmount: () => void;\n //#endregion\n\n //#region Background color.\n /**\n * The Mini App background color.\n *\n * Represents an RGB color, or theme parameters key, like \"bg_color\", \"secondary_bg_color\", etc.\n *\n * Note that using a theme parameters key, background color becomes bound to the current\n * theme parameters, making it automatically being updated whenever theme parameters change.\n * In order to remove this bind, use an explicit RGB color.\n */\n readonly bgColor: Computed<AnyColor>;\n\n /**\n * RGB representation of the background color.\n *\n * This value requires the Theme Params component to be mounted to extract a valid RGB value\n * of the color key.\n */\n readonly bgColorRgb: Computed<RGB | undefined>;\n\n /**\n * Updates the mini app background color.\n * @since Mini Apps v6.1\n */\n readonly setBgColorFp: WithChecksFp<\n (color: AnyColor) => E.Either<PostEventError | UnknownThemeParamsKeyError, void>,\n true\n >;\n\n /**\n * @see setBgColorFp\n */\n readonly setBgColor: WithChecks<(color: AnyColor) => void, true>;\n //#endregion\n\n //#region Header color.\n /**\n * The Mini App header color.\n */\n readonly headerColor: Computed<AnyColor>;\n\n /**\n * RGB representation of the header color.\n *\n * This value requires the Theme Params component to be mounted to extract a valid RGB value\n * of the color key.\n */\n readonly headerColorRgb: Computed<RGB | undefined>;\n\n /**\n * Updates the mini app header color.\n * @since Mini Apps v6.1\n */\n readonly setHeaderColorFp: WithChecksFp<\n (color: AnyColor) => E.Either<PostEventError | UnknownThemeParamsKeyError, void>,\n true,\n 'rgb'\n >;\n\n /**\n * @see setHeaderColorFp\n */\n readonly setHeaderColor: WithChecks<(color: AnyColor) => void, true, 'rgb'>;\n //#endregion\n\n //#region Bottom bar background color.\n /**\n * The Mini App bottom bar background color.\n */\n readonly bottomBarColor: Computed<AnyColor>;\n\n /**\n * RGB representation of the bottom bar background color.\n *\n * This value requires the Theme Params component to be mounted to extract a valid RGB value\n * of the color key.\n */\n readonly bottomBarColorRgb: Computed<RGB | undefined>;\n\n /**\n * Updates the mini app bottom bar bg color.\n * @since Mini Apps v7.10\n */\n readonly setBottomBarColorFp: WithChecksFp<\n (color: AnyColor) => E.Either<PostEventError | UnknownThemeParamsKeyError, void>,\n true\n >;\n\n /**\n * @see setBottomBarColorFp\n */\n readonly setBottomBarColor: WithChecks<(color: AnyColor) => void, true>;\n //#endregion\n\n //#region Other methods.\n /**\n * Closes the Mini App.\n * @param returnBack - should the client return to the previous activity.\n */\n readonly closeFp: WithChecksFp<(returnBack?: boolean) => E.Either<PostEventError, void>, false>;\n\n /**\n * @see closeFp\n */\n readonly close: WithChecks<(returnBack?: boolean) => void, false>;\n\n /**\n * Informs the Telegram app that the Mini App is ready to be displayed.\n *\n * It is recommended to call this method as early as possible, as soon as all\n * essential interface elements loaded.\n *\n * Once this method is called, the loading placeholder is hidden and the Mini\n * App shown.\n *\n * If the method is not called, the placeholder will be hidden only when the\n * page was fully loaded.\n */\n readonly readyFp: WithChecksFp<() => E.Either<PostEventError, void>, false>;\n\n /**\n * @see readyFp\n */\n readonly ready: WithChecks<() => void, false>;\n //#endregion\n}\n","import { pipe } from 'fp-ts/function';\nimport { on, off } from '@tma.js/bridge';\n\nimport { MiniApp, type MiniAppState } from '@/features/MiniApp/MiniApp.js';\nimport { sharedFeatureOptions } from '@/fn-options/sharedFeatureOptions.js';\nimport { withPostEvent } from '@/fn-options/withPostEvent.js';\nimport { withVersion } from '@/fn-options/withVersion.js';\nimport { withStateRestore } from '@/fn-options/withStateRestore.js';\nimport { themeParams } from '@/features/ThemeParams/instance.js';\n\nexport const miniApp = new MiniApp({\n ...pipe(\n sharedFeatureOptions(),\n withPostEvent,\n withVersion,\n withStateRestore<MiniAppState>('miniApp'),\n ),\n offVisibilityChanged(listener) {\n off('visibility_changed', listener);\n },\n onVisibilityChanged(listener) {\n on('visibility_changed', listener);\n },\n theme: themeParams.state,\n});\n","import type { PopupParams, PopupButton } from '@tma.js/bridge';\nimport * as E from 'fp-ts/Either';\n\nimport { InvalidArgumentsError } from '@/errors.js';\nimport type { ShowOptions } from '@/features/Popup/types.js';\n\n/**\n * Prepares popup parameters before sending them to native app.\n * @param params - popup parameters.\n */\nexport function prepareParams(params: ShowOptions): E.Either<InvalidArgumentsError, PopupParams> {\n const message = params.message.trim();\n const title = (params.title || '').trim();\n const paramsButtons = params.buttons || [];\n\n if (title.length > 64) {\n return E.left(new InvalidArgumentsError(`Invalid title: ${title}`));\n }\n if (!message || message.length > 256) {\n return E.left(new InvalidArgumentsError(`Invalid message: ${message}`));\n }\n if (paramsButtons.length > 3) {\n return E.left(new InvalidArgumentsError(`Invalid buttons count: ${paramsButtons.length}`));\n }\n\n const buttons: PopupButton[] = [];\n if (!paramsButtons.length) {\n buttons.push({ type: 'close', id: '' });\n } else {\n for (let i = 0; i < paramsButtons.length; i++) {\n const button = paramsButtons[i];\n const id = button.id || '';\n if (id.length > 64) {\n return E.left(new InvalidArgumentsError(`Button with index ${i} has invalid id: ${id}`));\n }\n\n if (!button.type || button.type === 'default' || button.type === 'destructive') {\n const text = button.text.trim();\n if (!text || text.length > 64) {\n return E.left(new InvalidArgumentsError(`Button with index ${i} has invalid text: ${text}`));\n }\n buttons.push({ type: button.type, text, id });\n } else {\n buttons.push({ type: button.type, id });\n }\n }\n }\n\n return E.right({ title, message, buttons });\n}\n","import * as TE from 'fp-ts/TaskEither';\nimport type { RequestError } from '@tma.js/bridge';\nimport { type Computed, signal, computed } from '@tma.js/signals';\nimport type { BetterPromise } from 'better-promises';\nimport { pipe } from 'fp-ts/function';\n\nimport type { SharedFeatureOptions } from '@/fn-options/sharedFeatureOptions.js';\nimport { createWithChecksFp, type WithChecksFp, type WithChecks } from '@/with-checks/withChecksFp.js';\nimport { throwifyWithChecksFp } from '@/with-checks/throwifyWithChecksFp.js';\nimport type { ShowOptions } from '@/features/Popup/types.js';\nimport { ConcurrentCallError, type InvalidArgumentsError } from '@/errors.js';\nimport { createIsSupportedSignal } from '@/helpers/createIsSupportedSignal.js';\nimport type { WithVersion } from '@/fn-options/withVersion.js';\nimport type { WithRequest } from '@/fn-options/withRequest.js';\nimport { prepareParams } from '@/features/Popup/prepareParams.js';\n\nexport interface PopupOptions extends SharedFeatureOptions, WithVersion, WithRequest {\n}\n\n/**\n * @since Mini Apps v6.2\n */\nexport class Popup {\n constructor({ version, isTma, request }: PopupOptions) {\n const isOpened = signal(false);\n const toggleClosed = () => {\n isOpened.set(false);\n };\n\n const wrapSupportedTask = createWithChecksFp({\n version,\n isTma,\n requires: 'web_app_open_popup',\n returns: 'task',\n });\n\n this.isSupported = createIsSupportedSignal('web_app_open_popup', version);\n this.isOpened = computed(isOpened);\n this.showFp = wrapSupportedTask(options => {\n return pipe(\n this.isOpened()\n ? TE.left(new ConcurrentCallError('A popup is already opened'))\n : TE.right(undefined as never),\n TE.chainW(() => TE.fromEither(prepareParams(options))),\n TE.chain(preparedOptions => {\n isOpened.set(true);\n return request('web_app_open_popup', 'popup_closed', {\n ...options,\n params: preparedOptions,\n });\n }),\n TE.mapBoth(\n err => {\n toggleClosed();\n return err;\n },\n response => {\n toggleClosed();\n return response.button_id;\n },\n ),\n );\n });\n this.show = throwifyWithChecksFp(this.showFp);\n }\n\n /**\n * Signal indicating if any popup is currently opened.\n */\n readonly isOpened: Computed<boolean>;\n\n /**\n * Signal indicating if the component is supported.\n */\n readonly isSupported: Computed<boolean>;\n\n /**\n * A method that shows a native popup described by the `params` argument.\n * The promise will be resolved when the popup is closed. Resolved value will have\n * an identifier of the pressed button.\n *\n * If a user clicked outside the popup or clicked the top right popup close\n * button, null will be resolved.\n *\n * @param options - popup parameters.\n * @since Mini Apps v6.2\n * @example\n * pipe(\n * popup.showFp({\n * title: 'Confirm action',\n * message: 'Do you really want to buy this burger?',\n * buttons: [\n * { id: 'yes', text: 'Yes' },\n * { id: 'no', type: 'destructive', text: 'No' },\n * ],\n * }),\n * TE.map(buttonId => {\n * console.log('User clicked a button with ID', buttonId);\n * }),\n * );\n */\n readonly showFp: WithChecksFp<\n (options: ShowOptions) => TE.TaskEither<\n RequestError | InvalidArgumentsError | ConcurrentCallError,\n string | undefined\n >,\n true\n >;\n\n /**\n * @see showFp\n */\n readonly show: WithChecks<(options: ShowOptions) => BetterPromise<string | undefined>, true>;\n}\n","import { pipe } from 'fp-ts/function';\n\nimport { Popup } from '@/features/Popup/Popup.js';\nimport { sharedFeatureOptions } from '@/fn-options/sharedFeatureOptions.js';\nimport { withVersion } from '@/fn-options/withVersion.js';\nimport { withRequest } from '@/fn-options/withRequest.js';\n\nexport const popup = new Popup(pipe(sharedFeatureOptions(), withRequest, withVersion));\n","import { pipe } from 'fp-ts/function';\nimport * as TE from 'fp-ts/TaskEither';\nimport type { PhoneRequestedStatus, RequestError } from '@tma.js/bridge';\n\nimport {\n sharedFeatureOptions,\n type SharedFeatureOptions,\n} from '@/fn-options/sharedFeatureOptions.js';\nimport { withVersion, type WithVersion } from '@/fn-options/withVersion.js';\nimport { withChecksFp } from '@/with-checks/withChecksFp.js';\nimport { throwifyWithChecksFp } from '@/with-checks/throwifyWithChecksFp.js';\nimport { withRequest, type WithRequest } from '@/fn-options/withRequest.js';\nimport type { AsyncOptions } from '@/types.js';\n\ninterface CreateOptions extends SharedFeatureOptions, WithRequest, WithVersion {\n}\n\nexport type RequestPhoneAccessError = RequestError;\n\nfunction create({ request, ...rest }: CreateOptions) {\n return withChecksFp((\n options?: AsyncOptions,\n ): TE.TaskEither<RequestPhoneAccessError, PhoneRequestedStatus> => {\n return pipe(\n request('web_app_request_phone', 'phone_requested', options),\n TE.map(response => response.status),\n );\n }, { ...rest, requires: 'web_app_request_phone', returns: 'task' });\n}\n\n/**\n * Requests current user phone access. Method returns promise, which resolves\n * status of the request. In case, user accepted the request, Mini App bot will receive\n * the according notification.\n *\n * To obtain the retrieved information instead, utilize the `requestContact` method.\n * @param options - additional options.\n * @since Mini Apps v6.9\n * @see requestContact\n */\nexport const requestPhoneAccessFp = create(pipe(\n sharedFeatureOptions(),\n withVersion,\n withRequest,\n));\n\n/**\n * @see requestPhoneAccessFp\n */\nexport const requestPhoneAccess = throwifyWithChecksFp(requestPhoneAccessFp);\n","import * as TE from 'fp-ts/TaskEither';\nimport * as E from 'fp-ts/Either';\nimport { pipe } from 'fp-ts/function';\nimport {\n safeParse,\n pipe as valiPipe,\n date,\n looseObject,\n number,\n optional,\n string,\n transform,\n} from 'valibot';\nimport { pipeJsonToSchema, pipeQueryToSchema } from '@tma.js/transformers';\nimport { PhoneRequestedStatus } from '@tma.js/bridge';\nimport { BetterTaskEither, type BetterTaskEitherError } from '@tma.js/toolkit';\n\nimport { type RequestPhoneAccessError, requestPhoneAccessFp } from './requestPhoneAccess.js';\nimport {\n sharedFeatureOptions,\n type SharedFeatureOptions,\n} from '@/fn-options/sharedFeatureOptions.js';\nimport {\n withInvokeCustomMethod,\n type WithInvokeCustomMethod,\n InvokeCustomMethodError,\n} from '@/fn-options/withInvokeCustomMethod.js';\nimport { throwifyWithChecksFp } from '@/with-checks/throwifyWithChecksFp.js';\nimport { withChecksFp } from '@/with-checks/withChecksFp.js';\nimport { AccessDeniedError, ValidationError } from '@/errors.js';\nimport type { AsyncOptions } from '@/types.js';\nimport { withVersion, type WithVersion } from '@/fn-options/withVersion.js';\n\n/**\n * Requested contact information.\n */\nexport interface RequestedContact {\n contact: {\n user_id: number;\n phone_number: string;\n first_name: string;\n last_name?: string;\n [key: string]: unknown;\n };\n auth_date: Date;\n hash: string;\n [key: string]: unknown;\n}\n\n/**\n * Requested contact complete data.\n */\nexport interface RequestedContactCompleteData {\n /**\n * Raw original representation of the contact data returned from the Telegram server.\n */\n raw: string;\n /**\n * Parsed representation of the contact data.\n */\n parsed: RequestedContact;\n}\n\ninterface CreateCompleteOptions extends SharedFeatureOptions, WithInvokeCustomMethod, WithVersion {\n requestPhoneAccess: (options?: AsyncOptions) => (\n TE.TaskEither<RequestPhoneAccessError, PhoneRequestedStatus>\n );\n}\n\ninterface CreateParsedOptions extends SharedFeatureOptions, WithVersion {\n requestContact: (options?: AsyncOptions) => TE.TaskEither<RequestContactError, RequestedContact>;\n}\n\nexport type RequestContactError =\n | InvokeCustomMethodError\n | AccessDeniedError\n | ValidationError\n | BetterTaskEitherError;\n\nfunction createComplete({\n invokeCustomMethod,\n requestPhoneAccess,\n ...rest\n}: CreateCompleteOptions) {\n type GetRequestedContactError = InvokeCustomMethodError | ValidationError;\n\n // Attempts to get previously requested contact.\n const getContact = (\n options?: AsyncOptions,\n ): TE.TaskEither<GetRequestedContactError, RequestedContactCompleteData | undefined> => {\n return pipe(\n invokeCustomMethod('getRequestedContact', {}, {\n ...options,\n timeout: (options || {}).timeout || 5000,\n }),\n TE.chainW(response => {\n const toStringResult = safeParse(string(), response);\n if (!toStringResult.success) {\n return TE.left(new ValidationError(response, toStringResult.issues));\n }\n\n if (!toStringResult.output) {\n return TE.right(undefined);\n }\n\n const toParsedResult = safeParse(\n pipeQueryToSchema(\n looseObject({\n contact: pipeJsonToSchema(looseObject({\n user_id: number(),\n phone_number: string(),\n first_name: string(),\n last_name: optional(string()),\n })),\n auth_date: valiPipe(\n string(),\n transform(input => new Date(Number(input) * 1000)),\n date(),\n ),\n hash: string(),\n }),\n ),\n toStringResult.output,\n );\n return toParsedResult.success\n ? TE.right({ raw: toStringResult.output, parsed: toParsedResult.output })\n : TE.left(new ValidationError(toStringResult.output, toParsedResult.issues));\n }),\n );\n };\n\n // Attempts to get previously requested contact, but ignores all errors except validation error.\n const getContactWithErrorsIgnore = (\n options?: AsyncOptions,\n ): TE.TaskEither<ValidationError, RequestedContactCompleteData | undefined> => {\n return pipe(\n getContact(options),\n TE.match(\n // All other errors except validation ones should be ignored. Receiving validation error\n // means that we have some data, but we are unable to parse it properly. So, there is no\n // need to make some more requests further, the problem is local.\n error => (ValidationError.is(error) ? E.left(error) : E.right(undefined)),\n contact => E.right(contact),\n ),\n );\n };\n\n // Polls previously requested contact with increasing timeout between requests.\n const pollContact = (ctx: {\n isRejected: boolean;\n rejectReason: unknown;\n abortSignal: AbortSignal;\n }): TE.TaskEither<BetterTaskEitherError | ValidationError, RequestedContactCompleteData> => {\n return BetterTaskEither<ValidationError, RequestedContactCompleteData>(\n async (res, rej, context) => {\n // Time to wait before executing the next request.\n let sleepTime = 50;\n\n // We are trying to retrieve the requested contact until the deadline was reached.\n while (!context.isRejected) {\n const result = await getContactWithErrorsIgnore(context)();\n if (result._tag === 'Left') {\n return rej(result.left);\n }\n if (result.right) {\n return res(result.right);\n }\n await new Promise(resolve => setTimeout(resolve, sleepTime));\n sleepTime += 50;\n }\n },\n ctx,\n );\n };\n\n return withChecksFp((\n options?: AsyncOptions,\n ): TE.TaskEither<RequestContactError, RequestedContactCompleteData> => {\n return BetterTaskEither.fn(context => {\n return pipe(\n // Try to get the requested contact. Probably, we already requested it before.\n getContactWithErrorsIgnore(context),\n TE.chain(contact => {\n if (contact) {\n return TE.right(contact);\n }\n return pipe(\n requestPhoneAccess(context),\n TE.chainW(status => {\n return status === 'sent'\n ? pollContact(context)\n : TE.left(new AccessDeniedError('User denied access'));\n }),\n );\n }),\n );\n }, options);\n }, { ...rest, returns: 'task', requires: 'web_app_request_phone' });\n}\n\nfunction createParsed({ requestContact, ...rest }: CreateParsedOptions) {\n return withChecksFp(\n requestContact,\n { ...rest, returns: 'task', requires: 'web_app_request_phone' },\n );\n}\n\n/**\n * Requests current user contact information.\n *\n * This function returns an object, containing both raw and parsed representations of a response,\n * received from the Telegram client.\n * @param options - additional options.\n * @since Mini Apps v6.9\n */\nexport const requestContactCompleteFp = createComplete({\n ...pipe(sharedFeatureOptions(), withInvokeCustomMethod, withVersion),\n requestPhoneAccess: requestPhoneAccessFp,\n});\n\n/**\n * @see requestContactCompleteFp\n */\nexport const requestContactComplete = throwifyWithChecksFp(requestContactCompleteFp);\n\n/**\n * Works the same way as the `requestContactCompleteFp` function, but returns only parsed\n * representation of the contact data.\n * @see requestContactCompleteFp\n * @param options - additional options.\n * @since Mini Apps v6.9\n */\nexport const requestContactFp = createParsed({\n ...pipe(sharedFeatureOptions(), withVersion),\n requestContact(options) {\n return pipe(\n requestContactCompleteFp(options),\n TE.map(contact => contact.parsed),\n );\n },\n});\n\n/**\n * @see requestContactFp\n */\nexport const requestContact = throwifyWithChecksFp(requestContactFp);\n","import { pipe } from 'fp-ts/function';\nimport * as TE from 'fp-ts/TaskEither';\nimport type { WriteAccessRequestedStatus, RequestError } from '@tma.js/bridge';\n\nimport {\n sharedFeatureOptions,\n type SharedFeatureOptions,\n} from '@/fn-options/sharedFeatureOptions.js';\nimport { withVersion, type WithVersion } from '@/fn-options/withVersion.js';\nimport { withChecksFp } from '@/with-checks/withChecksFp.js';\nimport { throwifyWithChecksFp } from '@/with-checks/throwifyWithChecksFp.js';\nimport { withRequest, type WithRequest } from '@/fn-options/withRequest.js';\nimport type { AsyncOptions } from '@/types.js';\n\ninterface CreateOptions extends SharedFeatureOptions, WithRequest, WithVersion {\n}\n\nexport type RequestWriteAccessError = RequestError;\n\nfunction create({ request, ...rest }: CreateOptions) {\n return withChecksFp((\n options?: AsyncOptions,\n ): TE.TaskEither<RequestWriteAccessError, WriteAccessRequestedStatus> => {\n return pipe(\n request('web_app_request_write_access', 'write_access_requested', options),\n TE.map(response => response.status),\n );\n }, { ...rest, requires: 'web_app_request_write_access', returns: 'task' });\n}\n\n/**\n * Requests write message access to the current user.\n * @param options - additional options.\n * @since Mini Apps v6.9\n */\nexport const requestWriteAccessFp = create(pipe(\n sharedFeatureOptions(),\n withVersion,\n withRequest,\n));\n\n/**\n * @see requestWriteAccessFp\n */\nexport const requestWriteAccess = throwifyWithChecksFp(requestWriteAccessFp);\n","import { computed, type Computed, signal } from '@tma.js/signals';\nimport { createCbCollector, BetterTaskEither, type BetterTaskEitherError } from '@tma.js/toolkit';\nimport { BetterPromise } from 'better-promises';\nimport type { PostEventError } from '@tma.js/bridge';\nimport { pipe } from 'fp-ts/function';\nimport * as E from 'fp-ts/Either';\nimport * as TE from 'fp-ts/TaskEither';\n\nimport {\n createWithChecksFp,\n type WithChecks,\n type WithChecksFp,\n} from '@/with-checks/withChecksFp.js';\nimport { throwifyWithChecksFp } from '@/with-checks/throwifyWithChecksFp.js';\nimport { createIsSupportedSignal } from '@/helpers/createIsSupportedSignal.js';\nimport type { AsyncOptions } from '@/types.js';\nimport type { SharedFeatureOptions } from '@/fn-options/sharedFeatureOptions.js';\nimport { ConcurrentCallError } from '@/errors.js';\nimport type { WithVersion } from '@/fn-options/withVersion.js';\nimport type { WithPostEvent } from '@/fn-options/withPostEvent.js';\n\nexport interface QrScannerOptions extends WithVersion, WithPostEvent, SharedFeatureOptions {\n /**\n * A function to add a listener to the event determining if the QR scanner\n * was closed.\n * @param listener - a listener to add.\n * @returns A function to remove the listener.\n */\n onClosed: (listener: VoidFunction) => VoidFunction;\n /**\n * A function to add a listener to the event containing a scanned QR content.\n * @param listener - a listener to add.\n * @returns A function to remove the listener.\n */\n onTextReceived: (listener: (data: string) => void) => VoidFunction;\n}\n\ninterface SharedOptions extends AsyncOptions {\n /**\n * Title to be displayed in the scanner.\n */\n text?: string;\n}\n\ninterface CaptureOptions extends SharedOptions {\n /**\n * @returns True if the passed QR code should be captured.\n * @param qr - scanned QR content.\n */\n capture: (qr: string) => boolean;\n}\n\ninterface OpenOptions extends SharedOptions {\n /**\n * Function which will be called if a QR code was scanned.\n * @param qr - scanned QR content.\n */\n onCaptured: (qr: string) => void;\n}\n\n/**\n * @since Mini Apps v6.4\n */\nexport class QrScanner {\n constructor({\n version,\n onClosed,\n onTextReceived,\n isTma,\n postEvent,\n }: QrScannerOptions) {\n const wrapOptions = { version, requires: 'web_app_open_scan_qr_popup', isTma } as const;\n const wrapSupportedEither = createWithChecksFp({ ...wrapOptions, returns: 'either' });\n const wrapSupportedTask = createWithChecksFp({ ...wrapOptions, returns: 'task' });\n\n const isOpened = signal(false);\n const toggleClosed = () => {\n isOpened.set(false);\n };\n\n this.isSupported = createIsSupportedSignal('web_app_open_scan_qr_popup', version);\n this.isOpened = computed(isOpened);\n\n this.captureFp = wrapSupportedTask(options => {\n let captured: string | undefined;\n return pipe(\n this.openFp({\n ...options,\n onCaptured: qr => {\n if (options.capture(qr)) {\n captured = qr;\n this.close();\n }\n },\n }),\n TE.map(() => captured),\n );\n });\n this.closeFp = wrapSupportedEither(() => {\n return pipe(postEvent('web_app_close_scan_qr_popup'), E.map(toggleClosed));\n });\n this.openFp = wrapSupportedTask(options => {\n return pipe(\n this.isOpened()\n ? TE.left(new ConcurrentCallError('The QR Scanner is already opened'))\n : async () => postEvent('web_app_open_scan_qr_popup', { text: options.text }),\n TE.chainW(() => {\n const [addToCleanup, cleanup] = createCbCollector();\n const withCleanup = <T>(value: T): T => {\n cleanup();\n return value;\n };\n\n return pipe(\n BetterTaskEither<never, void>(resolve => {\n addToCleanup(onClosed(resolve), onTextReceived(options.onCaptured));\n }, options),\n TE.mapBoth(withCleanup, withCleanup),\n );\n }),\n );\n });\n\n this.open = throwifyWithChecksFp(this.openFp);\n this.capture = throwifyWithChecksFp(this.captureFp);\n this.close = throwifyWithChecksFp(this.closeFp);\n }\n\n /**\n * Signal indicating if the scanner is currently opened.\n */\n readonly isOpened: Computed<boolean>;\n\n /**\n * Signal indicating if the component is supported.\n */\n readonly isSupported: Computed<boolean>;\n\n /**\n * Opens the scanner and returns a task which will be completed with the QR content if the\n * passed `capture` function returned true.\n *\n * Task may also be completed with undefined if the scanner was closed.\n * @param options - method options.\n * @returns A promise with QR content presented as string or undefined if the scanner was closed.\n * @since Mini Apps v6.4\n * @example\n * pipe(\n * qrScanner.captureOneFp({\n * capture(scannedQr) {\n * return scannedQr === 'any expected by me qr';\n * }\n * }),\n * TE.match(\n * error => {\n * console.error(error);\n * },\n * qr => {\n * console.log('My QR:'), qr;\n * }\n * ),\n * );\n */\n readonly captureFp: WithChecksFp<\n (options: CaptureOptions) => (\n TE.TaskEither<PostEventError | BetterTaskEitherError, string | undefined>\n ),\n true\n >;\n\n /**\n * @see captureFp\n */\n readonly capture: WithChecks<\n (options: CaptureOptions) => BetterPromise<string | undefined>,\n true\n >;\n\n /**\n * Closes the scanner.\n * @since Mini Apps v6.4\n */\n readonly closeFp: WithChecksFp<() => E.Either<PostEventError, void>, true>;\n\n /**\n * @see close\n */\n readonly close: WithChecks<() => void, true>;\n\n /**\n * Opens the scanner and returns a task which will be completed when the scanner was closed.\n * @param options - method options.\n * @since Mini Apps v6.4\n * @example Without `capture` option\n * if (qrScanner.open.isAvailable()) {\n * const qr = await qrScanner.open({ text: 'Scan any QR' });\n * }\n * @example\n * pipe(\n * qrScanner.openFp({\n * onCaptured(scannedQr) {\n * if (scannedQr === 'any expected by me qr') {\n * qrScanner.close();\n * }\n * }\n * }),\n * TE.match(\n * error => {\n * console.error(error);\n * },\n * () => {\n * console.log('The scanner was closed');\n * }\n * ),\n * );\n */\n readonly openFp: WithChecksFp<\n (options: OpenOptions) => TE.TaskEither<PostEventError, void>,\n true\n >;\n\n /**\n * @see openFp\n */\n readonly open: WithChecks<(options: OpenOptions) => BetterPromise<void>, true>;\n}\n","import { on } from '@tma.js/bridge';\n\nimport { QrScanner } from '@/features/QrScanner/QrScanner.js';\nimport { pipe } from 'fp-ts/function';\nimport { sharedFeatureOptions } from '@/fn-options/sharedFeatureOptions.js';\nimport { withVersion } from '@/fn-options/withVersion.js';\nimport { withPostEvent } from '@/fn-options/withPostEvent.js';\n\nexport const qrScanner = new QrScanner({\n ...pipe(sharedFeatureOptions(), withPostEvent, withVersion),\n onClosed(listener) {\n return on('scan_qr_popup_closed', listener);\n },\n onTextReceived(listener) {\n return on('qr_text_received', event => {\n listener(event.data);\n });\n },\n});\n","import { computed, type Computed } from '@tma.js/signals';\nimport type { RGB } from '@tma.js/types';\nimport type { PostEventError, SecondaryButtonPosition } from '@tma.js/bridge';\nimport * as E from 'fp-ts/Either';\n\nimport type { WithChecks, WithChecksFp } from '@/with-checks/withChecksFp.js';\nimport { Button, type ButtonOptions } from '@/composables/Button.js';\nimport type { MaybeAccessor } from '@/types.js';\nimport { access } from '@/helpers/access.js';\nimport { createIsSupportedSignal } from '@/helpers/createIsSupportedSignal.js';\n\ntype SecondaryButtonEither = E.Either<PostEventError, void>;\n\nexport interface SecondaryButtonState {\n isVisible: boolean;\n bgColor?: RGB;\n hasShineEffect: boolean;\n isEnabled: boolean;\n isLoaderVisible: boolean;\n text: string;\n textColor?: RGB;\n position: SecondaryButtonPosition;\n}\n\nexport interface SecondaryButtonOptions extends Omit<\n ButtonOptions<SecondaryButtonState, 'web_app_setup_secondary_button'>,\n 'initialState' | 'method' | 'payload'\n> {\n /**\n * Default values for different kinds of the button properties.\n */\n defaults: {\n bgColor: MaybeAccessor<RGB>;\n textColor: MaybeAccessor<RGB>;\n };\n}\n\n/**\n * @since Mini Apps v7.10\n */\nexport class SecondaryButton {\n constructor({ defaults, ...options }: SecondaryButtonOptions) {\n const button = new Button({\n ...options,\n initialState: {\n hasShineEffect: false,\n isEnabled: true,\n isLoaderVisible: false,\n isVisible: false,\n text: 'Cancel',\n position: 'left',\n },\n method: 'web_app_setup_secondary_button',\n payload: state => ({\n has_shine_effect: state.hasShineEffect,\n is_visible: state.isVisible,\n is_active: state.isEnabled,\n is_progress_visible: state.isLoaderVisible,\n text: state.text,\n color: state.bgColor,\n text_color: state.textColor,\n position: state.position,\n }),\n });\n\n const withDefault = (\n field: 'bgColor' | 'textColor',\n getDefault: MaybeAccessor<RGB>,\n ) => {\n const fromState = button.stateGetter(field);\n return computed(() => fromState() || access(getDefault));\n };\n\n this.isSupported = createIsSupportedSignal('web_app_setup_secondary_button', options.version);\n this.bgColor = withDefault('bgColor', defaults.bgColor);\n this.textColor = withDefault('textColor', defaults.textColor);\n this.position = button.stateGetter('position');\n this.hasShineEffect = button.stateGetter('hasShineEffect');\n this.isEnabled = button.stateGetter('isEnabled');\n this.isLoaderVisible = button.stateGetter('isLoaderVisible');\n this.text = button.stateGetter('text');\n this.isVisible = button.stateGetter('isVisible');\n this.isMounted = button.isMounted;\n this.state = button.state;\n\n [this.setPosition, this.setPositionFp] = button.stateSetters('position');\n [this.setBgColor, this.setBgColorFp] = button.stateSetters('bgColor');\n [this.setTextColor, this.setTextColorFp] = button.stateSetters('textColor');\n [\n [this.disableShineEffect, this.disableShineEffectFp],\n [this.enableShineEffect, this.enableShineEffectFp],\n ] = button.stateBoolSetters('hasShineEffect');\n [\n [this.disable, this.disableFp],\n [this.enable, this.enableFp],\n ] = button.stateBoolSetters('isEnabled');\n [\n [this.hideLoader, this.hideLoaderFp],\n [this.showLoader, this.showLoaderFp],\n ] = button.stateBoolSetters('isLoaderVisible');\n\n [this.setText, this.setTextFp] = button.stateSetters('text');\n [[this.hide, this.hideFp], [this.show, this.showFp]] = button.stateBoolSetters('isVisible');\n this.setParams = button.setState;\n this.setParamsFp = button.setStateFp;\n this.onClick = button.onClick;\n this.onClickFp = button.onClickFp;\n this.offClick = button.offClick;\n this.offClickFp = button.offClickFp;\n this.mount = button.mount;\n this.mountFp = button.mountFp;\n this.unmount = button.unmount;\n }\n\n //#region Properties.\n /**\n * Signal indicating if the component is supported.\n */\n readonly isSupported: Computed<boolean>;\n\n /**\n * The button position relative to the main one.\n */\n readonly position: Computed<SecondaryButtonPosition>;\n\n /**\n * The button background color.\n */\n readonly bgColor: Computed<RGB>;\n\n /**\n * True if the button has a shining effect.\n */\n readonly hasShineEffect: Computed<boolean>;\n\n /**\n * True if the button is clickable.\n */\n readonly isEnabled: Computed<boolean>;\n\n /**\n * True if the button loader is visible.\n */\n readonly isLoaderVisible: Computed<boolean>;\n\n /**\n * True if the button is visible.\n */\n readonly isVisible: Computed<boolean>;\n\n /**\n * Signal indicating if the component is currently mounted.\n */\n readonly isMounted: Computed<boolean>;\n\n /**\n * The complete button state.\n */\n readonly state: Computed<SecondaryButtonState>;\n\n /**\n * The button displayed text.\n */\n readonly text: Computed<string>;\n\n /**\n * The button text color.\n *\n * Note that this value is computed based on the external defaults. For\n * example, if not explicitly set, this value may be equal to one of theme\n * params colors.\n */\n readonly textColor: Computed<RGB>;\n //#endregion\n\n //#region Methods.\n /**\n * Shows the button.\n * @since Mini Apps v7.10\n */\n readonly showFp: WithChecksFp<() => SecondaryButtonEither, true>;\n\n /**\n * @see showFp\n */\n readonly show: WithChecks<() => void, true>;\n\n /**\n * Hides the button.\n * @since Mini Apps v7.10\n */\n readonly hideFp: WithChecksFp<() => SecondaryButtonEither, true>;\n\n /**\n * @see hideFp\n */\n readonly hide: WithChecks<() => void, true>;\n\n /**\n * Enables the button.\n * @since Mini Apps v7.10\n */\n readonly enableFp: WithChecksFp<() => SecondaryButtonEither, true>;\n\n /**\n * @see enableFp\n */\n readonly enable: WithChecks<() => void, true>;\n\n /**\n * Enables the button.\n * @since Mini Apps v7.10\n */\n readonly enableShineEffectFp: WithChecksFp<() => SecondaryButtonEither, true>;\n\n /**\n * @see enableShineEffectFp\n */\n readonly enableShineEffect: WithChecks<() => void, true>;\n\n /**\n * Disables the button.\n * @since Mini Apps v7.10\n */\n readonly disableFp: WithChecksFp<() => SecondaryButtonEither, true>;\n\n /**\n * @see disableFp\n */\n readonly disable: WithChecks<() => void, true>;\n\n /**\n * Enables the button.\n * @since Mini Apps v7.10\n */\n readonly disableShineEffectFp: WithChecksFp<() => SecondaryButtonEither, true>;\n\n /**\n * @see disableShineEffectFp\n */\n readonly disableShineEffect: WithChecks<() => void, true>;\n\n /**\n * Updates the button background color.\n * @since Mini Apps v7.10\n */\n readonly setBgColorFp: WithChecksFp<(value: RGB) => SecondaryButtonEither, true>;\n\n /**\n * @see setBgColorFp\n */\n readonly setBgColor: WithChecks<(value: RGB) => void, true>;\n\n /**\n * Updates the button text color.\n * @since Mini Apps v7.10\n */\n readonly setTextColorFp: WithChecksFp<(value: RGB) => SecondaryButtonEither, true>;\n\n /**\n * @see setTextColorFp\n */\n readonly setTextColor: WithChecks<(value: RGB) => void, true>;\n\n /**\n * Updates the button text.\n * @since Mini Apps v7.10\n */\n readonly setTextFp: WithChecksFp<(value: string) => SecondaryButtonEither, true>;\n\n /**\n * @see setTextFp\n */\n readonly setText: WithChecks<(value: string) => void, true>;\n\n /**\n * Updates the button position.\n * @since Mini Apps v7.10\n */\n readonly setPositionFp: WithChecksFp<\n (position: SecondaryButtonPosition) => SecondaryButtonEither,\n true\n >;\n\n /**\n * @see setPositionFp\n */\n readonly setPosition: WithChecks<(position: SecondaryButtonPosition) => void, true>;\n\n /**\n * Shows the button loader.\n * @since Mini Apps v7.10\n */\n readonly showLoaderFp: WithChecksFp<() => SecondaryButtonEither, true>;\n\n /**\n * @see showLoaderFp\n */\n readonly showLoader: WithChecks<() => void, true>;\n\n /**\n * Hides the button loader.\n * @since Mini Apps v7.10\n */\n readonly hideLoaderFp: WithChecksFp<() => SecondaryButtonEither, true>;\n\n /**\n * @see hideLoaderFp\n */\n readonly hideLoader: WithChecks<() => void, true>;\n\n /**\n * Updates the button state.\n * @param state - updates to apply.\n * @since Mini Apps v7.10\n * @example\n * button.setParams({\n * text: 'Submit',\n * isEnabled: true,\n * hasShineEffect: true,\n * });\n */\n readonly setParamsFp: WithChecksFp<\n (state: Partial<SecondaryButtonState>) => SecondaryButtonEither,\n true\n >;\n\n /**\n * @see setParamsFp\n */\n readonly setParams: WithChecks<(state: Partial<SecondaryButtonState>) => void, true>;\n\n /**\n * Mounts the component restoring its state.\n * @since Mini Apps v7.10\n */\n readonly mountFp: WithChecksFp<() => void, true>;\n\n /**\n * @see mountFp\n */\n readonly mount: WithChecks<() => void, true>;\n\n /**\n * Unmounts the component.\n */\n readonly unmount: () => void;\n\n /**\n * Adds a new button listener.\n * @param listener - event listener.\n * @param once - should the listener be called only once.\n * @returns A function to remove bound listener.\n * @since Mini Apps v7.10\n * @example\n * const off = button.onClick(() => {\n * console.log('User clicked the button');\n * off();\n * });\n */\n readonly onClickFp: WithChecksFp<(listener: VoidFunction, once?: boolean) => VoidFunction, true>;\n\n /**\n * @see onClick\n */\n readonly onClick: WithChecks<(listener: VoidFunction, once?: boolean) => VoidFunction, true>;\n\n /**\n * Removes the button click listener.\n * @param listener - event listener.\n * @param once - should the listener be called only once.\n * @since Mini Apps v7.10\n * @example\n * function listener() {\n * console.log('User clicked the button');\n * button.offClick(listener);\n * }\n * button.onClick(listener);\n */\n readonly offClickFp: WithChecksFp<(listener: VoidFunction, once?: boolean) => void, true>;\n\n /**\n * @see offClick\n */\n readonly offClick: WithChecks<(listener: VoidFunction, once?: boolean) => void, true>;\n //#endregion\n}\n","import { computed } from '@tma.js/signals';\n\nimport { SecondaryButton } from '@/features/SecondaryButton/SecondaryButton.js';\nimport { bottomButtonOptions } from '@/fn-options/bottomButtonOptions.js';\nimport { themeParams } from '@/features/ThemeParams/instance.js';\nimport { miniApp } from '@/features/MiniApp/instance.js';\n\nexport const secondaryButton = new SecondaryButton(\n bottomButtonOptions('secondaryButton', 'secondary_button_pressed', {\n bgColor: computed(() => miniApp.bottomBarColorRgb() || '#000000'),\n textColor: computed(() => themeParams.buttonColor() || '#2481cc'),\n }),\n);\n","import type { Computed } from '@tma.js/signals';\nimport * as E from 'fp-ts/Either';\nimport type { PostEventError } from '@tma.js/bridge';\n\nimport { Button, type ButtonOptions } from '@/composables/Button.js';\nimport type { WithChecksFp, WithChecks } from '@/with-checks/withChecksFp.js';\n\nexport interface SettingsButtonState {\n isVisible: boolean;\n}\n\nexport type SettingsButtonOptions = Omit<\n ButtonOptions<SettingsButtonState, 'web_app_setup_settings_button'>,\n 'method' | 'payload' | 'initialState'\n>;\n\n/**\n * @since Mini Apps v6.10\n */\nexport class SettingsButton {\n constructor(options: SettingsButtonOptions) {\n const button = new Button({\n ...options,\n method: 'web_app_setup_settings_button',\n payload: state => ({ is_visible: state.isVisible }),\n initialState: { isVisible: false },\n });\n\n this.isVisible = button.stateGetter('isVisible');\n this.isMounted = button.isMounted;\n this.isSupported = button.isSupported;\n [[this.hide, this.hideFp], [this.show, this.showFp]] = button.stateBoolSetters('isVisible');\n this.onClick = button.onClick;\n this.onClickFp = button.onClickFp;\n this.offClick = button.offClick;\n this.offClickFp = button.offClickFp;\n this.mount = button.mount;\n this.mountFp = button.mountFp;\n this.unmount = button.unmount;\n }\n\n /**\n * Signal indicating if the component is currently visible.\n */\n readonly isVisible: Computed<boolean>;\n\n /**\n * Signal indicating if the component is currently mounted.\n */\n readonly isMounted: Computed<boolean>;\n\n /**\n * Signal indicating if the component is supported.\n */\n readonly isSupported: Computed<boolean>;\n\n /**\n * Hides the button.\n * @since Mini Apps v6.10\n */\n readonly hideFp: WithChecksFp<() => E.Either<PostEventError, void>, true>;\n\n /**\n * @see hideFp\n */\n readonly hide: WithChecks<() => void, true>;\n\n /**\n * Shows the button.\n * @since Mini Apps v6.10\n */\n readonly showFp: WithChecksFp<() => E.Either<PostEventError, void>, true>;\n\n /**\n * @see showFp\n */\n readonly show: WithChecks<() => void, true>;\n\n /**\n * Adds a new button listener.\n * @param listener - event listener.\n * @param once - should the listener be called only once.\n * @returns A function to remove bound listener.\n * @since Mini Apps v6.10\n * @example\n * const off = button.onClick(() => {\n * console.log('User clicked the button');\n * off();\n * });\n */\n readonly onClickFp: WithChecksFp<\n (listener: VoidFunction, once?: boolean) => VoidFunction,\n true\n >;\n\n /**\n * @see onClickFp\n */\n readonly onClick: WithChecks<(listener: VoidFunction, once?: boolean) => VoidFunction, true>;\n\n /**\n * Removes the button click listener.\n * @param listener - event listener.\n * @param once - should the listener be called only once.\n * @since Mini Apps v6.10\n * @example\n * function listener() {\n * console.log('User clicked the button');\n * button.offClick(listener);\n * }\n * button.onClick(listener);\n */\n readonly offClickFp: WithChecksFp<\n (listener: VoidFunction, once?: boolean) => void,\n true\n >;\n\n /**\n * @see offClickFp\n */\n readonly offClick: WithChecks<(listener: VoidFunction, once?: boolean) => void, true>;\n\n /**\n * Mounts the component restoring its state.\n * @since Mini Apps v6.10\n */\n readonly mountFp: WithChecksFp<() => void, true>;\n\n /**\n * @see mountFp\n */\n readonly mount: WithChecks<() => void, true>;\n\n /**\n * Unmounts the component.\n *\n * Note that this function does not remove listeners added via the `onClick`\n * function, so you have to remove them on your own.\n * @see onClick\n */\n readonly unmount: () => void;\n}\n","import { SettingsButton } from '@/features/SettingsButton/SettingsButton.js';\nimport { buttonOptions } from '@/fn-options/buttonOptions.js';\n\nexport const settingsButton = new SettingsButton(\n buttonOptions('settingsButton', 'settings_button_pressed'),\n);\n","import type { Computed } from '@tma.js/signals';\nimport * as E from 'fp-ts/Either';\nimport type { PostEventError } from '@tma.js/bridge';\nimport { pipe } from 'fp-ts/function';\n\nimport { createWithChecksFp, type WithChecksFp, type WithChecks } from '@/with-checks/withChecksFp.js';\nimport { throwifyWithChecksFp } from '@/with-checks/throwifyWithChecksFp.js';\nimport { Stateful } from '@/composables/Stateful.js';\nimport { Mountable } from '@/composables/Mountable.js';\nimport { createIsSupportedSignal } from '@/helpers/createIsSupportedSignal.js';\nimport type { WithStateRestore } from '@/fn-options/withStateRestore.js';\nimport type { SharedFeatureOptions } from '@/fn-options/sharedFeatureOptions.js';\nimport type { WithVersion } from '@/fn-options/withVersion.js';\nimport type { WithPostEvent } from '@/fn-options/withPostEvent.js';\n\nexport interface SwipeBehaviorState {\n isVerticalEnabled: boolean;\n}\n\nexport interface SwipeBehaviorOptions\n extends WithStateRestore<SwipeBehaviorState>,\n WithVersion,\n WithPostEvent,\n SharedFeatureOptions {\n}\n\n/**\n * @since Mini Apps v7.7\n */\nexport class SwipeBehavior {\n constructor({ postEvent, storage, isTma, isPageReload, version }: SwipeBehaviorOptions) {\n const stateful = new Stateful({\n initialState: { isVerticalEnabled: false },\n onChange(state) {\n storage.set(state);\n },\n });\n const mountable = new Mountable({\n initialState: { isVerticalEnabled: false },\n isPageReload,\n onMounted: stateful.setState,\n restoreState: storage.get,\n });\n\n const wrapOptions = { requires: 'web_app_setup_swipe_behavior', isTma, version } as const;\n const wrapSupportedPlain = createWithChecksFp({\n ...wrapOptions,\n returns: 'plain',\n });\n const wrapMountedEither = createWithChecksFp({\n ...wrapOptions,\n isMounted: mountable.isMounted,\n returns: 'either',\n });\n\n const setVerticalEnabled = (isVerticalEnabled: boolean) => {\n const update = { isVerticalEnabled };\n if (!stateful.hasDiff(update)) {\n return E.right(undefined);\n }\n return pipe(\n postEvent('web_app_setup_swipe_behavior', { allow_vertical_swipe: isVerticalEnabled }),\n E.map(() => {\n stateful.setState(update);\n }),\n );\n };\n\n this.isSupported = createIsSupportedSignal('web_app_setup_swipe_behavior', version);\n this.isVerticalEnabled = stateful.getter('isVerticalEnabled');\n this.isMounted = mountable.isMounted;\n this.disableVerticalFp = wrapMountedEither(() => {\n return setVerticalEnabled(false);\n });\n this.enableVerticalFp = wrapMountedEither(() => {\n return setVerticalEnabled(true);\n });\n this.mountFp = wrapSupportedPlain(() => {\n const nothing = () => undefined;\n return pipe(mountable.mount(), E.match(nothing, nothing));\n });\n this.unmount = mountable.unmount;\n\n this.disableVertical = throwifyWithChecksFp(this.disableVerticalFp);\n this.enableVertical = throwifyWithChecksFp(this.enableVerticalFp);\n this.mount = throwifyWithChecksFp(this.mountFp);\n }\n\n /**\n * Signal indicating if the component is supported.\n */\n readonly isSupported: Computed<boolean>;\n\n /**\n * Signal indicating if vertical swipes are enabled.\n */\n readonly isVerticalEnabled: Computed<boolean>;\n\n /**\n * Signal indicating if the component is currently mounted.\n */\n readonly isMounted: Computed<boolean>;\n\n /**\n * Mounts the component restoring its state.\n * @since Mini Apps v7.7\n */\n readonly mountFp: WithChecksFp<() => void, true>;\n\n /**\n * @see mountFp\n */\n readonly mount: WithChecks<() => void, true>;\n\n /**\n * Unmounts the component.\n */\n readonly unmount: () => void;\n\n /**\n * Disables the closing confirmation dialog.\n * @since Mini Apps v7.7\n */\n readonly disableVerticalFp: WithChecksFp<() => E.Either<PostEventError, void>, true>;\n\n /**\n * @see disableVerticalFp\n */\n readonly disableVertical: WithChecks<() => void, true>;\n\n /**\n * Enables the closing confirmation dialog.\n * @since Mini Apps v7.7\n */\n readonly enableVerticalFp: WithChecksFp<() => E.Either<PostEventError, void>, true>;\n\n /**\n * @see enableVerticalFp\n */\n readonly enableVertical: WithChecks<() => void, true>;\n}\n","import { pipe } from 'fp-ts/function';\n\nimport { SwipeBehavior, type SwipeBehaviorState } from '@/features/SwipeBehavior/SwipeBehavior.js';\nimport { sharedFeatureOptions } from '@/fn-options/sharedFeatureOptions.js';\nimport { withStateRestore } from '@/fn-options/withStateRestore.js';\nimport { withVersion } from '@/fn-options/withVersion.js';\nimport { withPostEvent } from '@/fn-options/withPostEvent.js';\n\nexport const swipeBehavior = new SwipeBehavior(pipe(\n sharedFeatureOptions(),\n withPostEvent,\n withVersion,\n withStateRestore<SwipeBehaviorState>('swipeBehavior'),\n));\n","/**\n * Copies specified text to the clipboard.\n * @param text - text to copy.\n */\nexport async function copyTextToClipboard(text: string): Promise<void> {\n try {\n const { clipboard } = navigator;\n if (clipboard) {\n return await clipboard.writeText(text);\n }\n } catch {\n }\n const textArea = document.createElement('textarea');\n textArea.value = text;\n\n // Avoid scrolling to bottom\n textArea.style.top = '0';\n textArea.style.left = '0';\n textArea.style.position = 'fixed';\n\n document.body.appendChild(textArea);\n textArea.focus();\n textArea.select();\n\n try {\n document.execCommand('copy');\n } finally {\n document.body.removeChild(textArea);\n }\n}\n","import * as TE from 'fp-ts/TaskEither';\nimport { pipe } from 'fp-ts/function';\nimport { RequestError } from '@tma.js/bridge';\n\nimport { AccessDeniedError } from '@/errors.js';\nimport type { AsyncOptions } from '@/types.js';\nimport {\n sharedFeatureOptions,\n type SharedFeatureOptions,\n} from '@/fn-options/sharedFeatureOptions.js';\nimport { withChecksFp } from '@/with-checks/withChecksFp.js';\nimport { withRequest, type WithRequest } from '@/fn-options/withRequest.js';\nimport { withVersion, type WithVersion } from '@/fn-options/withVersion.js';\nimport { throwifyWithChecksFp } from '@/with-checks/throwifyWithChecksFp.js';\n\ninterface CreateOptions extends SharedFeatureOptions, WithRequest, WithVersion {\n}\n\nexport type DownloadFileError = RequestError | AccessDeniedError;\n\nfunction create({ request, ...rest }: CreateOptions) {\n return withChecksFp((\n url: string,\n fileName: string,\n options?: AsyncOptions,\n ): TE.TaskEither<DownloadFileError, void> => {\n return pipe(\n request(\n 'web_app_request_file_download',\n 'file_download_requested',\n { ...options, params: { url, file_name: fileName } },\n ),\n TE.chain(response => {\n return response.status === 'downloading'\n ? TE.right(undefined)\n : TE.left(new AccessDeniedError('User denied the action'));\n }),\n );\n }, { ...rest, requires: 'web_app_request_file_download', returns: 'task' });\n}\n\n/**\n * Displays a native popup prompting the user to download a file.\n * @param url - the HTTPS URL of the file to be downloaded.\n * @param file - the suggested name for the downloaded file.\n * @param options - additional request execution options.\n * @since Mini Apps v8.0\n * @example\n * pipe(\n * downloadFileFp('https://telegram.org/js/telegram-web-app.js', 'telegram-sdk.js'),\n * TE.map(() => {\n * console.log('Downloading');\n * })\n * )\n */\nexport const downloadFileFp = create(pipe(\n sharedFeatureOptions(),\n withRequest,\n withVersion,\n));\n\nexport const downloadFile = throwifyWithChecksFp(downloadFileFp);\n","import { date, integer, number, transform, pipe as valiPipe, safeParse } from 'valibot';\nimport { pipe } from 'fp-ts/function';\nimport * as TE from 'fp-ts/TaskEither';\n\nimport { withChecksFp } from '@/with-checks/withChecksFp.js';\nimport {\n type SharedFeatureOptions,\n sharedFeatureOptions,\n} from '@/fn-options/sharedFeatureOptions.js';\nimport {\n type WithInvokeCustomMethod,\n withInvokeCustomMethod,\n type InvokeCustomMethodError,\n} from '@/fn-options/withInvokeCustomMethod.js';\nimport { type WithVersion, withVersion } from '@/fn-options/withVersion.js';\nimport type { AsyncOptions } from '@/types.js';\nimport { throwifyWithChecksFp } from '@/with-checks/throwifyWithChecksFp.js';\nimport { ValidationError } from '@/errors.js';\n\ninterface CreateOptions extends SharedFeatureOptions, WithInvokeCustomMethod, WithVersion {\n}\n\nexport type GetCurrentTimeError = InvokeCustomMethodError | ValidationError;\n\nfunction create({ invokeCustomMethod, ...rest }: CreateOptions) {\n return withChecksFp((options?: AsyncOptions): TE.TaskEither<GetCurrentTimeError, Date> => {\n return pipe(\n invokeCustomMethod('getCurrentTime', {}, options),\n TE.chain(response => {\n const parsed = safeParse(\n valiPipe(number(), integer(), transform(v => new Date(v * 1000)), date()),\n response,\n );\n return parsed.success\n ? TE.right(parsed.output)\n : TE.left(new ValidationError(response, parsed.issues));\n }),\n );\n }, { ...rest, requires: 'web_app_invoke_custom_method', returns: 'task' });\n}\n\n/**\n * @returns The current time according to the Telegram server time.\n * @param options - additional options.\n * @since Mini Apps v6.9\n */\nexport const getCurrentTimeFp = create(pipe(\n sharedFeatureOptions(),\n withInvokeCustomMethod,\n withVersion,\n));\n\n/**\n * @see getCurrentTimeFp\n */\nexport const getCurrentTime = throwifyWithChecksFp(getCurrentTimeFp);\n","import type { PostEventError } from '@tma.js/bridge';\nimport { pipe } from 'fp-ts/function';\nimport * as E from 'fp-ts/Either';\n\nimport {\n sharedFeatureOptions,\n type SharedFeatureOptions,\n} from '@/fn-options/sharedFeatureOptions.js';\nimport { withPostEvent, type WithPostEvent } from '@/fn-options/withPostEvent.js';\nimport { withVersion, type WithVersion } from '@/fn-options/withVersion.js';\nimport { withChecksFp } from '@/with-checks/withChecksFp.js';\nimport { throwifyWithChecksFp } from '@/with-checks/throwifyWithChecksFp.js';\n\ninterface CreateOptions extends SharedFeatureOptions, WithPostEvent, WithVersion {\n}\n\nexport type HideKeyboardError = PostEventError;\n\nfunction create({ postEvent, ...rest }: CreateOptions) {\n return withChecksFp((): E.Either<HideKeyboardError, void> => {\n return postEvent('web_app_hide_keyboard');\n }, { ...rest, returns: 'either', requires: 'web_app_hide_keyboard' });\n}\n\n/**\n * Hides the on-screen keyboard, if it is currently visible. Does nothing if the keyboard is\n * not active.\n * @since Mini Apps v9.1\n */\nexport const hideKeyboardFp = create(pipe(\n sharedFeatureOptions(),\n withPostEvent,\n withVersion,\n));\n\n/**\n * @see hideKeyboardFp\n */\nexport const hideKeyboard = throwifyWithChecksFp(hideKeyboardFp);\n","import { pipe } from 'fp-ts/function';\nimport * as TE from 'fp-ts/TaskEither';\nimport { captureSameReq, type RequestError } from '@tma.js/bridge';\n\nimport {\n sharedFeatureOptions,\n type SharedFeatureOptions,\n} from '@/fn-options/sharedFeatureOptions.js';\nimport { withVersion, type WithVersion } from '@/fn-options/withVersion.js';\nimport { withRequest, type WithRequest } from '@/fn-options/withRequest.js';\nimport { withChecksFp } from '@/with-checks/withChecksFp.js';\nimport type { AsyncOptions } from '@/types.js';\nimport { throwifyWithChecksFp } from '@/with-checks/throwifyWithChecksFp.js';\nimport { createRequestId } from '@/globals/createRequestId.js';\n\ninterface CreateOptions extends SharedFeatureOptions, WithVersion, WithRequest {\n createRequestId: () => string;\n}\n\nexport type ReadTextFromClipboardError = RequestError;\n\nfunction create({ request, createRequestId, ...rest }: CreateOptions) {\n return withChecksFp((\n options?: AsyncOptions,\n ): TE.TaskEither<ReadTextFromClipboardError, string | null> => {\n const reqId = createRequestId();\n return pipe(\n request('web_app_read_text_from_clipboard', 'clipboard_text_received', {\n ...options,\n params: { req_id: reqId },\n capture: captureSameReq(reqId),\n }),\n TE.map(({ data = null }) => data),\n );\n }, { ...rest, requires: 'web_app_read_text_from_clipboard', returns: 'task' });\n}\n\n/**\n * Reads a text from the clipboard and returns a `string` or `null`. `null` is returned\n * in one of the following cases:\n * - A value in the clipboard is not a text.\n * - Access to the clipboard is not granted.\n * @since Mini Apps v6.4\n */\nexport const readTextFromClipboardFp = create({\n ...pipe(\n sharedFeatureOptions(),\n withVersion,\n withRequest,\n ),\n createRequestId,\n});\n\nexport const readTextFromClipboard = throwifyWithChecksFp(readTextFromClipboardFp);\n","export interface AndroidDeviceData {\n appVersion?: string;\n manufacturer?: string;\n model?: string;\n androidVersion?: string;\n sdkVersion?: number;\n performanceClass?: 'LOW' | 'AVERAGE' | 'HIGH' | string;\n}\n\n/**\n * Retrieves Android device data from the specified User Agent.\n * @see https://core.telegram.org/bots/webapps#additional-data-in-user-agent\n * @param userAgent - user agent.\n */\nexport function retrieveAndroidDeviceDataFrom(userAgent: string): AndroidDeviceData {\n const result: AndroidDeviceData = {};\n const match = userAgent.match(/Telegram-Android(?:\\/([^ ]+))?(?: (\\([^)]+\\))?|$)/);\n if (match) {\n const [, appVersion, systemInfo] = match;\n appVersion && (result.appVersion = appVersion);\n systemInfo && systemInfo\n .slice(1, systemInfo.length - 1)\n .split(';')\n .forEach(item => {\n const [key, value] = item.trim().split(' ');\n if (key === 'Android') {\n result.androidVersion = value;\n } else if (key === 'SDK') {\n const parsed = parseInt(value, 10);\n parsed && (result.sdkVersion = parsed);\n } else if (value) {\n result.manufacturer = key;\n result.model = value;\n } else {\n result.performanceClass = key;\n }\n });\n }\n return result;\n}\n","import {\n type AndroidDeviceData,\n retrieveAndroidDeviceDataFrom,\n} from './retrieveAndroidDeviceDataFrom.js';\n\n/**\n * Retrieves Android device data from the navigator.userAgent.\n * @see https://core.telegram.org/bots/webapps#additional-data-in-user-agent\n */\nexport function retrieveAndroidDeviceData(): AndroidDeviceData {\n return retrieveAndroidDeviceDataFrom(navigator.userAgent);\n}\n","import type { PostEventError } from '@tma.js/bridge';\nimport { pipe } from 'fp-ts/function';\nimport * as E from 'fp-ts/Either';\n\nimport {\n sharedFeatureOptions,\n type SharedFeatureOptions,\n} from '@/fn-options/sharedFeatureOptions.js';\nimport { withPostEvent, type WithPostEvent } from '@/fn-options/withPostEvent.js';\nimport { withChecksFp } from '@/with-checks/withChecksFp.js';\nimport { InvalidArgumentsError } from '@/errors.js';\nimport { throwifyWithChecksFp } from '@/with-checks/throwifyWithChecksFp.js';\n\ninterface CreateOptions extends SharedFeatureOptions, WithPostEvent {\n}\n\nexport type SendDataError = PostEventError | InvalidArgumentsError;\n\nfunction create({ postEvent, ...rest }: CreateOptions) {\n return withChecksFp((data: string): E.Either<SendDataError, void> => {\n const { size } = new Blob([data]);\n if (!size || size > 4096) {\n return E.left(\n new InvalidArgumentsError(size\n ? 'Maximum size of data to send is 4096 bytes'\n : 'Attempted to send empty data'),\n );\n }\n return postEvent('web_app_data_send', { data });\n }, { ...rest, returns: 'either' });\n}\n\n/**\n * Sends data to the bot.\n *\n * When this method called, a service message sent to the bot containing the data of the length\n * up to 4096 bytes, and the Mini App closed.\n *\n * See the field `web_app_data` in the class [Message](https://core.telegram.org/bots/api#message).\n *\n * This method is only available for Mini Apps launched via a Keyboard button.\n * @param data - data to send to bot.\n */\nexport const sendDataFp = create(pipe(sharedFeatureOptions(), withPostEvent));\n\n/**\n * @see sendDataFp\n */\nexport const sendData = throwifyWithChecksFp(sendDataFp);\n","import { RequestError } from '@tma.js/bridge';\nimport { pipe } from 'fp-ts/function';\nimport * as TE from 'fp-ts/TaskEither';\n\nimport {\n sharedFeatureOptions,\n type SharedFeatureOptions,\n} from '@/fn-options/sharedFeatureOptions.js';\nimport { withRequest, type WithRequest } from '@/fn-options/withRequest.js';\nimport { withVersion, type WithVersion } from '@/fn-options/withVersion.js';\nimport { withChecksFp } from '@/with-checks/withChecksFp.js';\nimport { ShareMessageError } from '@/errors.js';\nimport type { AsyncOptions } from '@/types.js';\nimport { throwifyWithChecksFp } from '@/with-checks/throwifyWithChecksFp.js';\n\ninterface CreateOptions extends SharedFeatureOptions, WithRequest, WithVersion {\n}\n\nexport type ShareMessageFnError = RequestError | ShareMessageError;\n\nfunction create({ request, ...rest }: CreateOptions) {\n return withChecksFp((\n messageId: string,\n options?: AsyncOptions,\n ): TE.TaskEither<ShareMessageFnError, void> => {\n return pipe(\n request(\n 'web_app_send_prepared_message',\n ['prepared_message_failed', 'prepared_message_sent'],\n {\n ...options,\n params: { id: messageId },\n },\n ),\n TE.chain(response => {\n if (response && 'error' in response) {\n return TE.left(new ShareMessageError(response.error));\n }\n return TE.right(undefined);\n }),\n );\n }, { ...rest, requires: 'web_app_send_prepared_message', returns: 'task' });\n}\n\n/**\n * Opens a dialog allowing the user to share a message provided by the bot.\n * @since Mini Apps v8.0\n */\nexport const shareMessageFp = create(pipe(\n sharedFeatureOptions(),\n withRequest,\n withVersion,\n));\n\n/**\n * @see shareMessageFp\n */\nexport const shareMessage = throwifyWithChecksFp(shareMessageFp);\n","import { pipe } from 'fp-ts/function';\nimport type { PostEventError } from '@tma.js/bridge';\nimport * as E from 'fp-ts/Either';\n\nimport {\n sharedFeatureOptions,\n type SharedFeatureOptions,\n} from '@/fn-options/sharedFeatureOptions.js';\nimport { withPostEvent, type WithPostEvent } from '@/fn-options/withPostEvent.js';\nimport { withVersion, type WithVersion } from '@/fn-options/withVersion.js';\nimport { throwifyWithChecksFp } from '@/with-checks/throwifyWithChecksFp.js';\nimport { withChecksFp } from '@/with-checks/withChecksFp.js';\n\ninterface CreateOptions extends SharedFeatureOptions, WithPostEvent, WithVersion {\n}\n\nexport interface ShareStoryOptions {\n /**\n * The caption to be added to the media.\n * 0-200 characters for regular users and 0-2048 characters for premium subscribers.\n * @see https://telegram.org/faq_premium#telegram-premium\n */\n text?: string;\n /**\n * An object that describes a widget link to be included in the story.\n * Note that only premium subscribers can post stories with links.\n * @see https://telegram.org/faq_premium#telegram-premium\n */\n widgetLink?: {\n /**\n * The URL to be included in the story.\n */\n url: string;\n /**\n * The name to be displayed for the widget link, 0-48 characters.\n */\n name?: string;\n };\n}\n\nexport type ShareStoryError = PostEventError;\n\nfunction create({ postEvent, ...rest }: CreateOptions) {\n return withChecksFp((\n mediaUrl: string,\n options: ShareStoryOptions = {},\n ): E.Either<ShareStoryError, void> => {\n return postEvent('web_app_share_to_story', {\n text: options.text,\n media_url: mediaUrl,\n widget_link: options.widgetLink,\n });\n }, { ...rest, requires: 'web_app_share_to_story', returns: 'either' });\n}\n\n/**\n * Opens the native story editor.\n * @since Mini Apps v7.8\n * @example\n * pipe(\n * shareStory('https://example.com/background.png', {\n * text: 'Look at this cool group!',\n * widgetLink: {\n * url: 'https://t.me/heyqbnk',\n * name: 'Vlad\\'s community',\n * },\n * }),\n * TE.match(error => {\n * console.error('Something went wrong', error);\n * }, () => {\n * console.log('Call was successful');\n * }),\n * );\n */\nexport const shareStoryFp = create(pipe(\n sharedFeatureOptions(),\n withPostEvent,\n withVersion,\n));\n\n/**\n * @see shareStoryFp\n */\nexport const shareStory = throwifyWithChecksFp(shareStoryFp);\n","import { createSignal } from '@/globals/signals-registry.js';\n\n/**\n * True if the application is launched in inline mode.\n */\nexport const isInlineMode = createSignal(false);\n","import type { PostEventError, SwitchInlineQueryChatType } from '@tma.js/bridge';\nimport { pipe } from 'fp-ts/function';\nimport * as E from 'fp-ts/Either';\n\nimport {\n sharedFeatureOptions,\n type SharedFeatureOptions,\n} from '@/fn-options/sharedFeatureOptions.js';\nimport { withPostEvent, type WithPostEvent } from '@/fn-options/withPostEvent.js';\nimport { withVersion, type WithVersion } from '@/fn-options/withVersion.js';\nimport type { MaybeAccessor } from '@/types.js';\nimport { withChecksFp } from '@/with-checks/withChecksFp.js';\nimport { access } from '@/helpers/access.js';\nimport { throwifyWithChecksFp } from '@/with-checks/throwifyWithChecksFp.js';\nimport { isInlineMode } from '@/globals/inline-mode.js';\n\ninterface CreateOptions extends SharedFeatureOptions, WithPostEvent, WithVersion {\n isInlineMode: MaybeAccessor<boolean>;\n}\n\nexport type SwitchInlineQueryError = PostEventError;\n\nfunction create({ isInlineMode, postEvent, ...rest }: CreateOptions) {\n return withChecksFp((\n query: string,\n chatTypes?: SwitchInlineQueryChatType[],\n ): E.Either<SwitchInlineQueryError, void> => {\n return postEvent('web_app_switch_inline_query', {\n query: query,\n chat_types: chatTypes || [],\n });\n }, {\n ...rest,\n requires: {\n every: ['web_app_switch_inline_query', () => {\n return access(isInlineMode)\n ? undefined\n : 'The application must be launched in the inline mode';\n }],\n },\n returns: 'either',\n });\n}\n\n/**\n * Inserts the bot's username and the specified inline query in the current chat's input field.\n * Query may be empty, in which case only the bot's username will be inserted. The client prompts\n * the user to choose a specific chat, then opens that chat and inserts the bot's username and\n * the specified inline query in the input field.\n * @param query - text which should be inserted in the input after the current bot name. Max\n * length is 256 symbols.\n * @param chatTypes - List of chat types which could be chosen to send the message. Could be an\n * empty list.\n * @since Mini Apps v6.7\n * @example\n * pipe(\n * switchInlineQuery('my query goes here', ['users']),\n * E.match(error => {\n * console.error('Something went wrong', error);\n * }, () => {\n * console.log('Call was successful');\n * }),\n * );\n */\nexport const switchInlineQueryFp = create({\n ...pipe(\n sharedFeatureOptions(),\n withPostEvent,\n withVersion,\n ),\n isInlineMode,\n});\n\n/**\n * @see switchInlineQueryFp\n */\nexport const switchInlineQuery = throwifyWithChecksFp(switchInlineQueryFp);\n","import { BetterPromise } from 'better-promises';\nimport {\n type SafeAreaInsets,\n type EventListener,\n supports,\n type RequestError,\n type PostEventError,\n} from '@tma.js/bridge';\nimport { Computed, computed, signal } from '@tma.js/signals';\nimport * as E from 'fp-ts/Either';\nimport * as TE from 'fp-ts/TaskEither';\nimport { pipe } from 'fp-ts/function';\nimport { camelToKebab } from '@tma.js/toolkit';\n\nimport { Stateful } from '@/composables/Stateful.js';\nimport { WithStateRestore } from '@/fn-options/withStateRestore.js';\nimport { AsyncMountable } from '@/composables/AsyncMountable.js';\nimport { AsyncOptions } from '@/types.js';\nimport { createWithChecksFp, WithChecks, WithChecksFp } from '@/with-checks/withChecksFp.js';\nimport { throwifyWithChecksFp } from '@/with-checks/throwifyWithChecksFp.js';\nimport { SharedFeatureOptions } from '@/fn-options/sharedFeatureOptions.js';\nimport { WithVersion } from '@/fn-options/withVersion.js';\nimport { WithRequest } from '@/fn-options/withRequest.js';\nimport { access } from '@/helpers/access.js';\nimport { CSSVarsBoundError, FullscreenFailedError } from '@/errors.js';\nimport { WithPostEvent } from '@/fn-options/withPostEvent.js';\nimport { deleteCssVar, setCssVar } from '@/helpers/css-vars.js';\n\ntype FullscreenError = FullscreenFailedError | RequestError;\ntype ViewportChangedEventListener = EventListener<'viewport_changed'>;\ntype FullscreenChangedEventListener = EventListener<'fullscreen_changed'>;\ntype SafeAreaInsetsChangedEventListener = EventListener<'safe_area_changed'>;\ntype SafeAreaInsetCSSVarKey = `safeAreaInset${Capitalize<keyof SafeAreaInsets>}`;\n\nexport type GetCSSVarNameKey =\n | 'width'\n | 'height'\n | 'stableHeight'\n | SafeAreaInsetCSSVarKey\n | `content${Capitalize<SafeAreaInsetCSSVarKey>}`;\n\nexport type GetCSSVarNameFn = (key: GetCSSVarNameKey) => string | null | undefined | false;\n\nexport interface ViewportState {\n contentSafeAreaInsets: SafeAreaInsets;\n height: number;\n isExpanded: boolean;\n isFullscreen: boolean;\n safeAreaInsets: SafeAreaInsets;\n stableHeight: number;\n width: number;\n}\n\ntype WithListeners<On extends string, Off extends string, L> = {\n [K in On | Off]: (listener: L) => void;\n};\n\nexport interface ViewportOptions<EViewportStable, EFullscreen>\n extends WithStateRestore<ViewportState>,\n WithVersion,\n WithRequest,\n WithPostEvent,\n WithListeners<'onViewportChanged', 'offViewportChanged', ViewportChangedEventListener>,\n WithListeners<'onFullscreenChanged', 'offFullscreenChanged', FullscreenChangedEventListener>,\n WithListeners<'onSafeAreaInsetsChanged', 'offSafeAreaInsetsChanged', SafeAreaInsetsChangedEventListener>,\n WithListeners<'onContentSafeAreaInsetsChanged', 'offContentSafeAreaInsetsChanged', SafeAreaInsetsChangedEventListener>,\n SharedFeatureOptions {\n /**\n * True if the viewport is stable.\n */\n isViewportStable: boolean | (() => E.Either<EViewportStable, boolean>);\n /**\n * True if the application was opened in fullscreen initially.\n */\n isFullscreen: boolean | (() => E.Either<EFullscreen, boolean>);\n}\n\nexport class Viewport<EViewportStable, EFullscreen> {\n constructor({\n storage,\n isPageReload,\n onContentSafeAreaInsetsChanged,\n onSafeAreaInsetsChanged,\n onViewportChanged,\n onFullscreenChanged,\n offContentSafeAreaInsetsChanged,\n offFullscreenChanged,\n offSafeAreaInsetsChanged,\n offViewportChanged,\n request,\n isViewportStable,\n isFullscreen,\n isTma,\n version,\n postEvent,\n }: ViewportOptions<EViewportStable, EFullscreen>) {\n const initialInsets: SafeAreaInsets = { top: 0, right: 0, left: 0, bottom: 0 };\n const stateful = new Stateful<ViewportState>({\n initialState: {\n contentSafeAreaInsets: initialInsets,\n height: 0,\n isExpanded: false,\n isFullscreen: false,\n safeAreaInsets: initialInsets,\n stableHeight: 0,\n width: 0,\n },\n onChange: storage.set,\n });\n\n const viewportChangedListener: ViewportChangedEventListener = event => {\n stateful.setState({\n isExpanded: event.is_expanded,\n height: event.height,\n width: event.width,\n stableHeight: event.is_state_stable ? event.height : undefined,\n });\n };\n const fullscreenChangedListener: FullscreenChangedEventListener = event => {\n stateful.setState({ isFullscreen: event.is_fullscreen });\n };\n const safeAreaInsetsChangedListener: SafeAreaInsetsChangedEventListener = event => {\n stateful.setState({ safeAreaInsets: event });\n };\n const contentSafeAreaInsetsChangedListener: SafeAreaInsetsChangedEventListener = event => {\n stateful.setState({ contentSafeAreaInsets: event });\n };\n\n const mountable = new AsyncMountable({\n initialState(options) {\n const genRequestInsets = (kind: 'safe-area' | 'content-safe-area') => {\n return () => {\n const [method, event] = kind === 'safe-area'\n ? ['web_app_request_safe_area', 'safe_area_changed'] as const\n : ['web_app_request_content_safe_area', 'content_safe_area_changed'] as const;\n\n if (!supports(method, access(version))) {\n return TE.right({ top: 0, left: 0, right: 0, bottom: 0 });\n }\n return request(method, event, options);\n };\n };\n const genFlag = <E>(flag: boolean | (() => E.Either<E, boolean>)) => {\n return () => (\n typeof flag === 'boolean'\n ? TE.right(flag)\n : TE.fromEither(flag())\n );\n };\n\n return pipe(\n TE.Do,\n TE.bindW('safeAreaInsets', genRequestInsets('safe-area')),\n TE.bindW('contentSafeAreaInsets', genRequestInsets('content-safe-area')),\n TE.bindW('isFullscreen', genFlag(isFullscreen)),\n TE.bindW('isViewportStable', genFlag(isViewportStable)),\n TE.chainW(({ isViewportStable, ...shared }) => {\n if (isViewportStable) {\n return TE.right({\n ...shared,\n height: window.innerHeight,\n isExpanded: true,\n stableHeight: window.innerHeight,\n width: window.innerWidth,\n });\n }\n return pipe(\n request('web_app_request_viewport', 'viewport_changed', options),\n TE.map(viewport => ({\n ...shared,\n height: viewport.height,\n isExpanded: viewport.is_expanded,\n stableHeight: viewport.is_state_stable ? viewport.height : 0,\n width: viewport.width,\n })),\n );\n }),\n );\n },\n isPageReload,\n onMounted(state) {\n onViewportChanged(viewportChangedListener);\n onFullscreenChanged(fullscreenChangedListener);\n onSafeAreaInsetsChanged(safeAreaInsetsChangedListener);\n onContentSafeAreaInsetsChanged(contentSafeAreaInsetsChangedListener);\n stateful.setState(state);\n },\n onUnmounted() {\n offViewportChanged(viewportChangedListener);\n offFullscreenChanged(fullscreenChangedListener);\n offSafeAreaInsetsChanged(safeAreaInsetsChangedListener);\n offContentSafeAreaInsetsChanged(contentSafeAreaInsetsChangedListener);\n },\n restoreState: storage.get,\n });\n\n const saBased = <K extends keyof SafeAreaInsets>(key: K) => {\n return computed(() => this.safeAreaInsets()[key]);\n };\n const csaBased = <K extends keyof SafeAreaInsets>(key: K) => {\n return computed(() => this.contentSafeAreaInsets()[key]);\n };\n\n this.state = stateful.state;\n this.height = stateful.getter('height');\n this.stableHeight = stateful.getter('stableHeight');\n this.width = stateful.getter('width');\n this.isExpanded = stateful.getter('isExpanded');\n this.safeAreaInsets = stateful.getter('safeAreaInsets');\n this.safeAreaInsetTop = saBased('top');\n this.safeAreaInsetBottom = saBased('bottom');\n this.safeAreaInsetLeft = saBased('left');\n this.safeAreaInsetRight = saBased('right');\n this.contentSafeAreaInsets = stateful.getter('contentSafeAreaInsets');\n this.contentSafeAreaInsetTop = csaBased('top');\n this.contentSafeAreaInsetBottom = csaBased('bottom');\n this.contentSafeAreaInsetLeft = csaBased('left');\n this.contentSafeAreaInsetRight = csaBased('right');\n\n const wrapTask = createWithChecksFp({ isTma, returns: 'task' });\n const wrapMountedEither = createWithChecksFp({\n isTma,\n returns: 'either',\n });\n const wrapFullscreenTask = createWithChecksFp({\n isTma,\n requires: 'web_app_request_fullscreen',\n version,\n returns: 'task',\n });\n const genFullscreenFn = (enable: boolean) => {\n return wrapFullscreenTask((options?: AsyncOptions) => {\n return pipe(\n request(\n enable ? 'web_app_request_fullscreen' : 'web_app_exit_fullscreen',\n ['fullscreen_changed', 'fullscreen_failed'],\n options,\n ),\n TE.chain(data => {\n if ('error' in data && data.error !== 'ALREADY_FULLSCREEN') {\n return TE.left(new FullscreenFailedError(data.error));\n }\n stateful.setState({ isFullscreen: 'is_fullscreen' in data ? data.is_fullscreen : true });\n return TE.right(undefined);\n }),\n );\n });\n };\n\n // Mount.\n this.isMounted = mountable.isMounted;\n this.mountFp = wrapTask(mountable.mount);\n this.mount = throwifyWithChecksFp(this.mountFp);\n\n // Fullscreen.\n this.isFullscreen = stateful.getter('isFullscreen');\n this.requestFullscreenFp = genFullscreenFn(true);\n this.requestFullscreen = throwifyWithChecksFp(this.requestFullscreenFp);\n this.exitFullscreenFp = genFullscreenFn(false);\n this.exitFullscreen = throwifyWithChecksFp(this.exitFullscreenFp);\n\n // CSS vars.\n const isCssVarsBound = signal(false);\n this.isCssVarsBound = computed(isCssVarsBound);\n this.bindCssVarsFp = wrapMountedEither(\n (getCSSVarName?: GetCSSVarNameFn) => {\n if (isCssVarsBound()) {\n return E.left(new CSSVarsBoundError());\n }\n getCSSVarName ||= prop => `--tg-viewport-${camelToKebab(prop)}`;\n\n const settings = ([\n ['height', this.height],\n ['stableHeight', this.stableHeight],\n ['width', this.width],\n ['safeAreaInsetTop', this.safeAreaInsetTop],\n ['safeAreaInsetBottom', this.safeAreaInsetBottom],\n ['safeAreaInsetLeft', this.safeAreaInsetLeft],\n ['safeAreaInsetRight', this.safeAreaInsetRight],\n ['contentSafeAreaInsetTop', this.contentSafeAreaInsetTop],\n ['contentSafeAreaInsetBottom', this.contentSafeAreaInsetBottom],\n ['contentSafeAreaInsetLeft', this.contentSafeAreaInsetLeft],\n ['contentSafeAreaInsetRight', this.contentSafeAreaInsetRight],\n ] as const).reduce<{\n update: VoidFunction;\n removeListener: VoidFunction;\n cssVar: string;\n }[]>((acc, [key, signal]) => {\n const cssVar = getCSSVarName(key);\n if (cssVar) {\n const update = () => {\n setCssVar(cssVar, `${signal()}px`);\n };\n acc.push({ update, removeListener: signal.sub(update), cssVar });\n }\n return acc;\n }, []);\n\n settings.forEach(setting => {\n setting.update();\n });\n isCssVarsBound.set(true);\n\n return E.right(() => {\n settings.forEach(s => {\n s.removeListener();\n deleteCssVar(s.cssVar);\n });\n isCssVarsBound.set(false);\n });\n },\n );\n this.bindCssVars = throwifyWithChecksFp(this.bindCssVarsFp);\n\n // Other methods.\n this.expandFp = wrapMountedEither(() => postEvent('web_app_expand'));\n this.expand = throwifyWithChecksFp(this.expandFp);\n }\n\n //#region Other properties.\n /**\n * Complete component state.\n */\n readonly state: Computed<ViewportState>;\n\n /**\n * Signal containing the current height of the **visible area** of the Mini App.\n *\n * The application can display just the top part of the Mini App, with its\n * lower part remaining outside the screen area. From this position, the user\n * can \"pull\" the Mini App to its maximum height, while the bot can do the same\n * by calling `expand` method. As the position of the Mini App changes, the\n * current height value of the visible area will be updated in real time.\n *\n * Please note that the refresh rate of this value is not sufficient to\n * smoothly follow the lower border of the window. It should not be used to pin\n * interface elements to the bottom of the visible area. It's more appropriate\n * to use the value of the `stableHeight` field for this purpose.\n *\n * @see stableHeight\n */\n readonly height: Computed<number>;\n\n /**\n * Signal containing the height of the visible area of the Mini App in its last stable state.\n *\n * The application can display just the top part of the Mini App, with its\n * lower part remaining outside the screen area. From this position, the user\n * can \"pull\" the Mini App to its maximum height, while the application can do\n * the same by calling `expand` method.\n *\n * Unlike the value of `height`, the value of `stableHeight` does not change as\n * the position of the Mini App changes with user gestures or during\n * animations. The value of `stableHeight` will be updated after all gestures\n * and animations are completed and the Mini App reaches its final size.\n *\n * @see height\n */\n readonly stableHeight: Computed<number>;\n\n /**\n * Signal containing the currently visible area width.\n */\n readonly width: Computed<number>;\n\n /**\n * Signal indicating if the Mini App is expanded to the maximum available height. Otherwise,\n * if the Mini App occupies part of the screen and can be expanded to the full\n * height using the `expand` method.\n */\n readonly isExpanded: Computed<boolean>;\n\n /**\n * Signal indicating if the current viewport height is stable and is not going to change in\n * the next moment.\n */\n readonly isStable = computed(() => this.height() === this.stableHeight());\n //#endregion\n\n //#region Content safe area insets.\n /**\n * Signal containing content safe area insets.\n */\n readonly contentSafeAreaInsets: Computed<SafeAreaInsets>;\n\n /**\n * Signal containing top content safe area inset.\n */\n readonly contentSafeAreaInsetTop: Computed<number>;\n\n /**\n * Signal containing left content safe area inset.\n */\n readonly contentSafeAreaInsetLeft: Computed<number>;\n\n /**\n * Signal containing right content safe area inset.\n */\n readonly contentSafeAreaInsetRight: Computed<number>;\n\n /**\n * Signal containing bottom content safe area inset.\n */\n readonly contentSafeAreaInsetBottom: Computed<number>;\n //#endregion\n\n //#region Safe area insets.\n /**\n * Signal containing safe area insets.\n */\n readonly safeAreaInsets: Computed<SafeAreaInsets>;\n\n /**\n * Signal containing top safe area inset.\n */\n readonly safeAreaInsetTop: Computed<number>;\n\n /**\n * Signal containing left safe area inset.\n */\n readonly safeAreaInsetLeft: Computed<number>;\n\n /**\n * Signal containing right safe area inset.\n */\n readonly safeAreaInsetRight: Computed<number>;\n\n /**\n * Signal containing bottom safe area inset.\n */\n readonly safeAreaInsetBottom: Computed<number>;\n //#endregion\n\n //#region Fullscreen.\n /**\n * Signal indicating if the viewport is currently in fullscreen mode.\n */\n readonly isFullscreen: Computed<boolean>;\n\n /**\n * Requests fullscreen mode for the mini application.\n * @since Mini Apps v8.0\n */\n readonly requestFullscreenFp: WithChecksFp<\n (options?: AsyncOptions) => TE.TaskEither<FullscreenError, void>,\n true\n >;\n\n /**\n * @see requestFullscreenFp\n */\n readonly requestFullscreen: WithChecks<(options?: AsyncOptions) => BetterPromise<void>, true>;\n\n /**\n * Exits mini application from the fullscreen mode.\n * @since Mini Apps v8.0\n */\n readonly exitFullscreenFp: WithChecksFp<\n (options?: AsyncOptions) => TE.TaskEither<FullscreenError, void>,\n true\n >;\n\n /**\n * @see exitFullscreenFp\n */\n readonly exitFullscreen: WithChecks<(options?: AsyncOptions) => BetterPromise<void>, true>;\n //#endregion\n\n //#region CSS Vars.\n /**\n * Signal indicating if CSS variables are bound.\n */\n readonly isCssVarsBound: Computed<boolean>;\n\n /**\n * Creates CSS variables connected with the current viewport.\n *\n * By default, created CSS variables names are following the pattern \"--tg-theme-{name}\", where\n * {name} is a viewport property name converted from camel case to kebab case.\n *\n * Default variables:\n * - `--tg-viewport-height`\n * - `--tg-viewport-width`\n * - `--tg-viewport-stable-height`\n * - `--tg-viewport-content-safe-area-inset-top`\n * - `--tg-viewport-content-safe-area-inset-bottom`\n * - `--tg-viewport-content-safe-area-inset-left`\n * - `--tg-viewport-content-safe-area-inset-right`\n * - `--tg-viewport-safe-area-inset-top`\n * - `--tg-viewport-safe-area-inset-bottom`\n * - `--tg-viewport-safe-area-inset-left`\n * - `--tg-viewport-safe-area-inset-right`\n *\n * Variables are being automatically updated if the viewport was changed.\n *\n * @param getCSSVarName - function, returning computed complete CSS variable name. The CSS\n * variable will only be defined if the function returned non-empty string value.\n * @returns Function to stop updating variables.\n * @example Using no arguments\n * bindCssVarsFp();\n * @example Using custom CSS vars generator\n * bindCssVarsFp(key => `--my-prefix-${key}`);\n */\n readonly bindCssVarsFp: WithChecksFp<(getCSSVarName?: GetCSSVarNameFn) => (\n E.Either<CSSVarsBoundError, VoidFunction>\n ), false>;\n\n /**\n * @see bindCssVarsFp\n */\n readonly bindCssVars: WithChecks<(getCSSVarName?: GetCSSVarNameFn) => VoidFunction, false>;\n //#endregion\n\n //#region Mount.\n /**\n * Signal indicating if the component is currently mounted.\n */\n readonly isMounted: Computed<boolean>;\n\n /**\n * Mounts the component.\n */\n readonly mountFp: WithChecksFp<(options?: AsyncOptions) => (\n TE.TaskEither<EFullscreen | EViewportStable | RequestError, void>\n ), false>;\n\n /**\n * @see mountFp\n */\n readonly mount: WithChecks<(options?: AsyncOptions) => BetterPromise<void>, false>;\n //#endregion\n\n //#region Other methods.\n /**\n * A method that expands the Mini App to the maximum available height. To find\n * out if the Mini App is expanded to the maximum height, refer to the value of\n * the `isExpanded`.\n */\n readonly expandFp: WithChecksFp<() => E.Either<PostEventError, void>, false>;\n\n /**\n * @see expandFp\n */\n readonly expand: WithChecks<() => void, false>;\n //#endregion\n}\n","import { pipe } from 'fp-ts/function';\nimport * as E from 'fp-ts/Either';\nimport { retrieveLaunchParamsFp, on, off, type EventName, EventListener } from '@tma.js/bridge';\n\nimport { Viewport, type ViewportState } from '@/features/Viewport/Viewport.js';\nimport { sharedFeatureOptions } from '@/fn-options/sharedFeatureOptions.js';\nimport { withStateRestore } from '@/fn-options/withStateRestore.js';\nimport { withVersion } from '@/fn-options/withVersion.js';\nimport { withRequest } from '@/fn-options/withRequest.js';\nimport { withPostEvent } from '@/fn-options/withPostEvent.js';\n\nfunction create() {\n const createListeners = <E extends EventName>(event: E) => {\n return {\n on: (listener: EventListener<E>) => {\n on(event, listener);\n },\n off: (listener: EventListener<E>) => {\n off(event, listener);\n },\n };\n };\n const viewportListeners = createListeners('viewport_changed');\n const fullscreenListeners = createListeners('fullscreen_changed');\n const safeAreaListeners = createListeners('safe_area_changed');\n const contentSafeAreaListeners = createListeners('content_safe_area_changed');\n\n return new Viewport({\n ...pipe(\n sharedFeatureOptions(),\n withStateRestore<ViewportState>('viewport'),\n withVersion,\n withPostEvent,\n withRequest,\n ),\n isFullscreen() {\n return pipe(retrieveLaunchParamsFp(), E.map(lp => !!lp.tgWebAppFullscreen));\n },\n isViewportStable() {\n return pipe(retrieveLaunchParamsFp(), E.map(lp => {\n return ['macos', 'tdesktop', 'unigram', 'webk', 'weba', 'web'].includes(lp.tgWebAppPlatform);\n }));\n },\n offContentSafeAreaInsetsChanged: contentSafeAreaListeners.off,\n offFullscreenChanged: fullscreenListeners.off,\n offSafeAreaInsetsChanged: safeAreaListeners.off,\n offViewportChanged: viewportListeners.off,\n onContentSafeAreaInsetsChanged: contentSafeAreaListeners.on,\n onFullscreenChanged: fullscreenListeners.on,\n onSafeAreaInsetsChanged: safeAreaListeners.on,\n onViewportChanged: viewportListeners.on,\n });\n}\n\nexport const viewport = create();\n","import {\n on,\n logger,\n retrieveLaunchParamsFp,\n type RetrieveLaunchParamsError,\n type PostEventError,\n} from '@tma.js/bridge';\nimport { createCbCollector, throwifyFpFn } from '@tma.js/toolkit';\nimport type { Version, ThemeParams } from '@tma.js/types';\nimport type { PostEventFpFn } from '@tma.js/bridge';\nimport * as E from 'fp-ts/Either';\nimport { pipe } from 'fp-ts/function';\n\nimport { version } from '@/globals/version.js';\nimport { postEventFpSignal, postEventFp, postEvent } from '@/globals/post-event.js';\nimport { isInlineMode } from '@/globals/inline-mode.js';\nimport { themeParams } from '@/globals/themeParams.js';\n\nexport interface InitOptions {\n /**\n * True if SDK should accept styles sent from the Telegram application.\n * @default true\n */\n acceptCustomStyles?: boolean;\n /**\n * True if the application is launched in inline mode.\n * @default Will be calculated based on the launch parameters' tgWebAppBotInline field.\n */\n isInlineMode?: boolean;\n /**\n * A custom `postEvent` function to use across the package.\n * @default tma.js/bridge's postEventFp function will be used.\n */\n postEvent?: PostEventFpFn;\n /**\n * Mini application theme parameters.\n * @default Will be calculated based on the launch parameters' tgWebAppThemeParams field.\n */\n themeParams?: ThemeParams;\n /**\n * Telegram Mini Apps version supported by the Telegram client.\n * @default Will be calculated based on the launch parameters' tgWebAppVersion field.\n */\n version?: Version;\n}\n\n/**\n * Initializes the SDK allowing it to properly handle events, sent from the native Telegram\n * application. This function also configure the package's global dependencies (functions,\n * variables used across the package).\n * @param options - function options.\n * @returns A function, to perform a cleanup.\n */\nexport function initFp(\n options: InitOptions = {},\n): E.Either<RetrieveLaunchParamsError | PostEventError, VoidFunction> {\n const {\n version: optionsVersion,\n isInlineMode: optionsInlineMode,\n themeParams: optionsThemeParams,\n } = options;\n\n if (optionsVersion && typeof optionsInlineMode === 'boolean' && optionsThemeParams) {\n version.set(optionsVersion);\n isInlineMode.set(optionsInlineMode);\n themeParams.set(optionsThemeParams);\n } else {\n const error = pipe(retrieveLaunchParamsFp(), E.matchW(\n err => err,\n lp => {\n version.set(optionsVersion || lp.tgWebAppVersion);\n isInlineMode.set(typeof optionsInlineMode === 'boolean'\n ? optionsInlineMode\n : !!lp.tgWebAppBotInline);\n themeParams.set(optionsThemeParams || lp.tgWebAppThemeParams);\n },\n ));\n if (error) {\n return E.left(error);\n }\n }\n if (options.postEvent) {\n postEventFpSignal.set(options.postEvent);\n }\n\n const [addCleanup, cleanup] = createCbCollector(\n on('reload_iframe', () => {\n logger().log('Received a request to reload the page');\n postEvent('iframe_will_reload');\n window.location.reload();\n }),\n );\n\n const { acceptCustomStyles = true } = options;\n if (acceptCustomStyles) {\n const style = document.createElement('style');\n style.id = 'telegram-custom-styles';\n document.head.appendChild(style);\n\n addCleanup(\n on('set_custom_style', html => {\n // It is safe to use innerHTML here as long as style tag has a special behavior related\n // to the specified content.\n // In case any script will be passed here, it will not be executed, so XSS is not possible.\n style.innerHTML = html;\n }),\n () => {\n document.head.removeChild(style);\n },\n );\n }\n\n // Notify Telegram that the application is ready.\n //\n // This will result in sending style tag html content from the Telegram web application.\n // We should call this method also to start receiving \"reload_iframe\" events from the Telegram\n // application.\n //\n // It really has no effect outside non-Telegram web environment.\n return pipe(\n postEventFp('iframe_ready', { reload_supported: true }),\n E.map(() => {\n logger().log('The package was initialized');\n return cleanup;\n }),\n );\n}\n\n/**\n * @see initFp\n */\nexport const init = throwifyFpFn(initFp);\n"],"names":["__spreadArray","to","from","pack","i","l","ar","flow","ab","bc","cd","de","ef","fg","gh","hi","ij","pipe","a","ret","dual","arity","body","isDataFirst","args","self","none","some","isLeft","ma","left","e","right","emptyRecord","ap","F","G","fa","fab","gab","ga","map","f","bind","M","name","b","_a","_.left","_.right","flatMap","_map","_ap","URI","Functor","of","apW","Apply","Chain","bimap","g","_.isLeft","matchW","onLeft","onRight","match","tryCatch","onThrow","Do","_.emptyRecord","chainable.bind","bindW","access","value","createIsSupportedSignal","method","version","computed","supports","_.none","_.some","isNone","onNone","onSome","E.right","E.left","map_","E.Functor","ap_","E.Apply","E.isLeft","mapBoth","E.bimap","E.match","_apPar","Pointed","ApplyPar","Monad","__awaiter","thisArg","_arguments","P","generator","adopt","resolve","reject","fulfilled","step","rejected","result","__generator","_","t","y","verb","n","v","op","ET.left","T.Pointed","ET.right","fromEither","T.of","ET.match","T.Functor","onRejected","reason_1","ET.map","ET.mapBoth","ET.ap","T.ApplyPar","ET.flatMap","T.Monad","chain","chainW","msgToTuple","message","ValidationError","errorClassWithData","input","issues","CSSVarsBoundError","errorClass","NotAvailableError","InvalidEnvError","FunctionUnavailableError","InvalidArgumentsError","cause","ConcurrentCallError","SetEmojiStatusError","error","AccessDeniedError","FullscreenFailedError","ShareMessageError","UnknownThemeParamsKeyError","key","withChecksFp","fn","options","isTma","optionsIsSupported","isSupportedSimplified","isOptionSupported","optionName","optionSettings","calculateSupportError","mode","requirements","requirement","calculateOptionSupportError","k","isSupported","isInitialized","isMounted","isAvailable","wrapError","err","TE.left","errMessagePrefix","supportErr","supportsOptionErr","returns","E.tryCatch","TE.tryCatch","O.some","O.none","createWithChecksFp","throwifyWithChecksFp","throwifyFpFn","O.match","data","throwifyAnyEither","removeUndefined","shallowEqual","aKeys","bKeys","aKey","Stateful","initialState","onChange","__publicField","state","nextState","signal","Mountable","onMounted","restoreState","onUnmounted","isPageReload","restored","E.map","s","batch","Button","storage","onClick","offClick","postEvent","payload","stateful","mountable","wrapOptions","wrapSupportedPlain","wrapMountedEither","nothing","wrapped","setFp","setFalse","setTrue","BackButton","button","sharedFeatureOptions","isTMAFp","createComponentSessionStorage","getStorageValue","setStorageValue","getFirstNavigationEntry","entry","createFnOption","mix","obj","withStateRestore","storageName","createSignal","initialValue","postEventFpSignal","_postEventFp","postEventFp","withPostEvent","withVersion","buttonOptions","trackedClickEvent","listener","once","on","off","backButton","AsyncMountable","TE.right","TE.map","notAvailableError","eventToState","event","available","tokenSaved","deviceId","accessRequested","type","accessGranted","Biometry","request","onInfoReceived","offInfoReceived","wrapSupportedEither","wrapSupportedTask","wrapMountedTask","response","TE.chain","requestFp","events","_requestFp","BetterPromise","withRequest","biometry","ClosingBehavior","setClosingConfirmation","isConfirmationEnabled","closingBehavior","CloudStorage","invokeCustomMethod","keyOrKeys","keys","values","acc","parse","record","string","array","lastRequestId","createRequestId","params","invokeCustomMethodFp","withInvokeCustomMethod","cloudStorage","create","rest","requestEmojiStatusAccessFp","requestEmojiStatusAccess","customEmojiId","TE.chainW","setEmojiStatusFp","setEmojiStatus","HapticFeedback","HAPTIC_METHOD_NAME","wrapSupported","style","hapticFeedback","addToHomeScreenFp","addToHomeScreen","checkHomeScreenStatusFp","checkHomeScreenStatus","InitData","retrieveInitData","authDateValue","canSendAfterValue","raw","initData","E.Do","E.bindW","retrieveLaunchParamsFp","tgWebAppData","retrieveRawInitDataFp","O.Do","O.bind","Invoice","isOpened","toggleClosed","slug","TE.mapBoth","url","hostname","pathname","invoice","openLinkFp","openLink","urlString","openTelegramLinkFp","openTelegramLink","text","shareURLFp","shareURL","LocationManager","locationManager","MainButton","defaults","withDefault","field","getDefault","fromState","bottomButtonOptions","themeParams","setCssVar","deleteCssVar","isColorDarkFp","color","toRGBFullFp","rgb","modifier","idx","dec","isColorDark","ThemeParams","offChange","getCSSVarName","prop","snakeToKebab","forEachEntry","actualize","globalThemeParams","mainButton","MiniApp","theme","onVisibilityChanged","offVisibilityChanged","visibilityChangedListener","themeChangedListener","isRGB","tp","rgbBasedOn","computedRgbBasedOn","isCssVarsBound","addCleanup","cleanup","createCbCollector","cssVar","update","camelToKebab","genColorToolset","stateKey","rawColor","rgbColor","fp","withBasicEither","returnBack","miniApp","prepareParams","title","paramsButtons","buttons","id","Popup","TE.fromEither","preparedOptions","popup","requestPhoneAccessFp","requestPhoneAccess","createComplete","getContact","toStringResult","safeParse","toParsedResult","pipeQueryToSchema","looseObject","pipeJsonToSchema","number","optional","valiPipe","transform","date","getContactWithErrorsIgnore","TE.match","contact","pollContact","ctx","BetterTaskEither","res","rej","context","sleepTime","status","createParsed","requestContact","requestContactCompleteFp","requestContactComplete","requestContactFp","requestWriteAccessFp","requestWriteAccess","QrScanner","onClosed","onTextReceived","captured","qr","addToCleanup","withCleanup","qrScanner","SecondaryButton","secondaryButton","SettingsButton","settingsButton","SwipeBehavior","setVerticalEnabled","isVerticalEnabled","swipeBehavior","copyTextToClipboard","clipboard","textArea","fileName","downloadFileFp","downloadFile","parsed","integer","getCurrentTimeFp","getCurrentTime","hideKeyboardFp","hideKeyboard","reqId","captureSameReq","readTextFromClipboardFp","readTextFromClipboard","retrieveAndroidDeviceDataFrom","userAgent","appVersion","systemInfo","item","retrieveAndroidDeviceData","size","sendDataFp","sendData","messageId","shareMessageFp","shareMessage","mediaUrl","shareStoryFp","shareStory","isInlineMode","query","chatTypes","switchInlineQueryFp","switchInlineQuery","Viewport","onContentSafeAreaInsetsChanged","onSafeAreaInsetsChanged","onViewportChanged","onFullscreenChanged","offContentSafeAreaInsetsChanged","offFullscreenChanged","offSafeAreaInsetsChanged","offViewportChanged","isViewportStable","isFullscreen","initialInsets","viewportChangedListener","fullscreenChangedListener","safeAreaInsetsChangedListener","contentSafeAreaInsetsChangedListener","genRequestInsets","kind","genFlag","flag","TE.Do","TE.bindW","shared","viewport","saBased","csaBased","wrapTask","wrapFullscreenTask","genFullscreenFn","enable","settings","setting","createListeners","viewportListeners","fullscreenListeners","safeAreaListeners","contentSafeAreaListeners","lp","initFp","optionsVersion","optionsInlineMode","optionsThemeParams","E.matchW","logger","acceptCustomStyles","html","init"],"mappings":";;;;;;;;;;;;AAAA,IAAIA,KAAgD,SAAUC,GAAIC,GAAMC,GAAM;AAC1E,MAAIA,KAAQ,UAAU,WAAW,EAAG,UAASC,IAAI,GAAGC,IAAIH,EAAK,QAAQI,GAAIF,IAAIC,GAAGD;AAC5E,KAAIE,KAAM,EAAEF,KAAKF,QACRI,MAAIA,IAAK,MAAM,UAAU,MAAM,KAAKJ,GAAM,GAAGE,CAAC,IACnDE,EAAGF,CAAC,IAAIF,EAAKE,CAAC;AAGtB,SAAOH,EAAG,OAAOK,KAAM,MAAM,UAAU,MAAM,KAAKJ,CAAI,CAAC;AAC3D;AA0KO,SAASK,GAAKC,GAAIC,GAAIC,GAAIC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