@tma.js/sdk 1.3.0 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/dist/dts/launch-params/index.d.ts +1 -0
  2. package/dist/dts/launch-params/retrieveFromUrl.d.ts +6 -0
  3. package/dist/dts/launch-params/types.d.ts +12 -8
  4. package/dist/index.cjs +1 -1
  5. package/dist/index.cjs.map +1 -1
  6. package/dist/index.iife.js +1 -1
  7. package/dist/index.iife.js.map +1 -1
  8. package/dist/index.mjs +243 -238
  9. package/dist/index.mjs.map +1 -1
  10. package/package.json +2 -2
  11. package/src/__tests__/globals.ts +39 -0
  12. package/src/back-button/__tests__/BackButton.ts +129 -0
  13. package/src/bridge/__tests__/request.ts +236 -0
  14. package/src/bridge/env/__tests__/hasExternalNotify.ts +15 -0
  15. package/src/bridge/env/__tests__/hasWebviewProxy.ts +15 -0
  16. package/src/bridge/env/__tests__/isIframe.ts +30 -0
  17. package/src/bridge/events/__tests__/createEmitter.ts +143 -0
  18. package/src/bridge/events/__tests__/off.ts +34 -0
  19. package/src/bridge/events/__tests__/on.ts +49 -0
  20. package/src/bridge/events/__tests__/onTelegramEvent.ts +51 -0
  21. package/src/bridge/events/__tests__/once.ts +64 -0
  22. package/src/bridge/events/__tests__/singletonEmitter.ts +22 -0
  23. package/src/bridge/events/__tests__/subscribe.ts +49 -0
  24. package/src/bridge/events/__tests__/unsubscribe.ts +34 -0
  25. package/src/bridge/events/parsers/__tests__/clipboardTextReceived.ts +21 -0
  26. package/src/bridge/events/parsers/__tests__/invoiceClosed.ts +12 -0
  27. package/src/bridge/events/parsers/__tests__/popupClosed.ts +10 -0
  28. package/src/bridge/events/parsers/__tests__/qrTextReceived.ts +9 -0
  29. package/src/bridge/events/parsers/__tests__/theme-changed.ts +42 -0
  30. package/src/bridge/events/parsers/__tests__/viewportChanged.ts +49 -0
  31. package/src/bridge/methods/__tests__/createPostEvent.ts +37 -0
  32. package/src/bridge/methods/__tests__/postEvent.ts +137 -0
  33. package/src/classnames/__tests__/classNames.ts +20 -0
  34. package/src/classnames/__tests__/mergeClassNames.ts +21 -0
  35. package/src/closing-behavior/__tests__/ClosingBehavior.ts +86 -0
  36. package/src/colors/__tests__/isColorDark.ts +12 -0
  37. package/src/colors/__tests__/isRGB.ts +13 -0
  38. package/src/colors/__tests__/isRGBShort.ts +13 -0
  39. package/src/colors/__tests__/toRGB.ts +23 -0
  40. package/src/event-emitter/__tests__/EventEmitter.ts +145 -0
  41. package/src/haptic-feedback/__tests__/HapticFeedback.ts +68 -0
  42. package/src/init/creators/__tests__/createViewport.ts +96 -0
  43. package/src/init-data/__tests__/InitData.ts +98 -0
  44. package/src/init-data/__tests__/chatParser.ts +102 -0
  45. package/src/init-data/__tests__/initDataParser.ts +136 -0
  46. package/src/init-data/__tests__/parseInitData.ts +136 -0
  47. package/src/init-data/__tests__/userParser.ts +96 -0
  48. package/src/launch-params/__tests__/retrieveFromUrl.ts +19 -0
  49. package/src/launch-params/index.ts +1 -0
  50. package/src/launch-params/launchParamsParser.ts +4 -0
  51. package/src/launch-params/retrieveFromLocation.ts +2 -2
  52. package/src/launch-params/retrieveFromPerformance.ts +2 -7
  53. package/src/launch-params/retrieveFromUrl.ts +19 -0
  54. package/src/launch-params/types.ts +13 -8
  55. package/src/logger/__tests__/Logger.ts +107 -0
  56. package/src/main-button/__tests__/MainButton.ts +346 -0
  57. package/src/mini-app/__tests__/MiniApp.ts +140 -0
  58. package/src/misc/__tests__/isRecord.ts +21 -0
  59. package/src/navigation/HashNavigator/__tests__/HashNavigator.ts +144 -0
  60. package/src/navigation/HashNavigator/__tests__/drop.ts +42 -0
  61. package/src/navigation/HashNavigator/__tests__/go.ts +9 -0
  62. package/src/parsing/__tests__/ArrayValueParser.ts +18 -0
  63. package/src/parsing/__tests__/toRecord.ts +10 -0
  64. package/src/parsing/parsers/__tests__/array.ts +39 -0
  65. package/src/parsing/parsers/__tests__/boolean.ts +31 -0
  66. package/src/parsing/parsers/__tests__/date.ts +25 -0
  67. package/src/parsing/parsers/__tests__/json.ts +80 -0
  68. package/src/parsing/parsers/__tests__/number.ts +23 -0
  69. package/src/parsing/parsers/__tests__/rgb.ts +22 -0
  70. package/src/parsing/parsers/__tests__/searchParams.ts +105 -0
  71. package/src/parsing/parsers/__tests__/string.ts +25 -0
  72. package/src/popup/__tests__/Popup.ts +130 -0
  73. package/src/popup/__tests__/preparePopupParams.ts +85 -0
  74. package/src/supports/__tests__/supports.ts +123 -0
  75. package/src/theme-params/__tests__/keys.ts +19 -0
  76. package/src/theme-params/__tests__/parseThemeParams.ts +29 -0
  77. package/src/theme-params/__tests__/serializeThemeParams.ts +29 -0
  78. package/src/theme-params/__tests__/themeParamsParser.ts +29 -0
  79. package/src/timeout/__tests__/isTimeoutError.ts +9 -0
  80. package/src/timeout/__tests__/withTimeout.ts +28 -0
  81. package/src/version/__tests__/compareVersions.ts +19 -0
  82. package/src/viewport/__tests__/isStableViewportPlatform.ts +15 -0
  83. package/src/viewport/__tests__/utils.ts +12 -0
@@ -1,2 +1,2 @@
1
- var cr=Object.defineProperty;var ur=(a,g,P)=>g in a?cr(a,g,{enumerable:!0,configurable:!0,writable:!0,value:P}):a[g]=P;var o=(a,g,P)=>(ur(a,typeof g!="symbol"?g+"":g,P),P);this.tmajs=this.tmajs||{};this.tmajs.sdk=function(a){"use strict";function g(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}function P(){return performance.getEntriesByType("navigation")[0]||null}function re(){const r=P();return r?r.type==="reload":null}function B(){return new TypeError("Value has unexpected type")}class F extends Error{constructor(e,{cause:s,type:n}={}){super(`Unable to parse value${n?` as ${n}`:""}`,{cause:s});o(this,"type");this.value=e,Object.setPrototypeOf(this,F.prototype),this.type=n}}class z{constructor(t,e,s){this.parser=t,this.isOptional=e,this.type=s}parse(t){if(!(this.isOptional&&t===void 0))try{return this.parser(t)}catch(e){throw new F(t,{type:this.type,cause:e})}}optional(){return this.isOptional=!0,this}}function se(r){if(Array.isArray(r))return r;if(typeof r=="string")try{const t=JSON.parse(r);if(Array.isArray(t))return t}catch{}throw B()}class ne extends z{constructor(e,s,n){super(se,s,n);o(this,"itemParser");this.itemParser=typeof e=="function"?e:e.parse.bind(e)}parse(e){const s=super.parse(e);return s===void 0?s:s.map(this.itemParser)}of(e){return this.itemParser=typeof e=="function"?e:e.parse.bind(e),this}}function $(r,t){return()=>new z(r,!1,t)}class J extends Error{constructor(t,{cause:e,type:s}={}){super(`Unable to parse field "${t}"${s?` as ${s}`:""}`,{cause:e}),Object.setPrototypeOf(this,J.prototype)}}function bt(r,t){const e={};for(const s in r){const n=r[s];if(!n)continue;let i,c;if(typeof n=="function"||"parse"in n)i=s,c=typeof n=="function"?n:n.parse.bind(n);else{const{type:p}=n;i=n.from||s,c=typeof p=="function"?p:p.parse.bind(p)}let u;const l=t(i);try{u=c(l)}catch(p){throw p instanceof F?new J(i,{type:p.type,cause:p}):new J(i,{cause:p})}u!==void 0&&(e[s]=u)}return e}function ie(r){return new ne(t=>t,!1,r)}const S=$(r=>{if(typeof r=="boolean")return r;const t=String(r);if(t==="1"||t==="true")return!0;if(t==="0"||t==="false")return!1;throw B()},"boolean"),V=$(r=>{if(typeof r=="number")return r;if(typeof r=="string"){const t=Number(r);if(!Number.isNaN(t))return t}throw B()},"number"),mt=$(r=>r instanceof Date?r:new Date(V().parse(r)*1e3),"Date");function X(r){let t=r;if(typeof t=="string"&&(t=JSON.parse(t)),typeof t!="object"||t===null||Array.isArray(t))throw B();return t}function w(r,t){return new z(e=>{const s=X(e);return bt(r,n=>s[n])},!1,t)}function tt(r){return/^#[\da-f]{6}$/i.test(r)}function yt(r){return/^#[\da-f]{3}$/i.test(r)}function et(r){const t=r.replace(/\s/g,"").toLowerCase();if(tt(t))return t;if(yt(t)){let s="#";for(let n=0;n<3;n+=1)s+=t[1+n].repeat(2);return s}const e=t.match(/^rgb\((\d{1,3}),(\d{1,3}),(\d{1,3})\)$/)||t.match(/^rgba\((\d{1,3}),(\d{1,3}),(\d{1,3}),\d{1,3}\)$/);if(e===null)throw new Error(`Value "${r}" does not satisfy any of known RGB formats.`);return e.slice(1).reduce((s,n)=>{const i=parseInt(n,10).toString(16);return s+(i.length===1?"0":"")+i},"#")}function rt(r){const t=et(r);return Math.sqrt([.299,.587,.114].reduce((s,n,i)=>{const c=parseInt(t.slice(1+i*2,1+(i+1)*2),16);return s+c*c*n},0))<120}const h=$(r=>{if(typeof r=="string"||typeof r=="number")return r.toString();throw B()},"string"),Et=$(r=>et(h().parse(r)),"rgb");function st(r,t){return new z(e=>{if(typeof e!="string"&&!(e instanceof URLSearchParams))throw B();const s=typeof e=="string"?new URLSearchParams(e):e;return bt(r,n=>{const i=s.get(n);return i===null?void 0:i})},!1,t)}function Ct(){return w({id:V(),type:h(),title:h(),photoUrl:{type:h().optional(),from:"photo_url"},username:h().optional()},"Chat")}class vt{constructor(t){this.initData=t}get authDate(){return this.initData.authDate}get canSendAfter(){return this.initData.canSendAfter}get canSendAfterDate(){const{canSendAfter:t}=this;return t===void 0?void 0:new Date(this.authDate.getTime()+t*1e3)}get chat(){return this.initData.chat}get chatType(){return this.initData.chatType}get chatInstance(){return this.initData.chatInstance}get hash(){return this.initData.hash}get queryId(){return this.initData.queryId}get receiver(){return this.initData.receiver}get startParam(){return this.initData.startParam}get user(){return this.initData.user}}function nt(){return w({addedToAttachmentMenu:{type:S().optional(),from:"added_to_attachment_menu"},allowsWriteToPm:{type:S().optional(),from:"allows_write_to_pm"},firstName:{type:h(),from:"first_name"},id:V(),isBot:{type:S().optional(),from:"is_bot"},isPremium:{type:S().optional(),from:"is_premium"},languageCode:{type:h().optional(),from:"language_code"},lastName:{type:h().optional(),from:"last_name"},photoUrl:{type:h().optional(),from:"photo_url"},username:h().optional()},"User")}function it(){return st({authDate:{type:mt(),from:"auth_date"},canSendAfter:{type:V().optional(),from:"can_send_after"},chat:Ct().optional(),chatInstance:{type:h().optional(),from:"chat_instance"},chatType:{type:h().optional(),from:"chat_type"},hash:h(),queryId:{type:h().optional(),from:"query_id"},receiver:nt().optional(),startParam:{type:h().optional(),from:"start_param"},user:nt().optional()},"InitData")}function oe(r){return it().parse(r)}function ae(r){return r.replace(/(^|_)bg/,(t,e)=>`${e}background`).replace(/_([a-z])/g,(t,e)=>e.toUpperCase())}function ce(r){return r.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`).replace(/(^|_)background/,(t,e)=>`${e}bg`)}const ot=$(r=>{const t=Et().optional();return Object.entries(X(r)).reduce((e,[s,n])=>(e[ae(s)]=t.parse(n),e),{})},"ThemeParams");function at(r){return ot().parse(r)}function ue(r={}){return C("web_app_request_theme","theme_changed",r).then(at)}function Pt(r){return JSON.stringify(Object.entries(r).reduce((t,[e,s])=>(s&&(t[ce(e)]=s),t),{}))}class b{constructor(){o(this,"listeners",new Map);o(this,"subscribeListeners",[])}addListener(t,e,s){let n=this.listeners.get(t);return n||(n=[],this.listeners.set(t,n)),n.push([e,s]),()=>this.off(t,e)}emit(t,...e){this.subscribeListeners.forEach(n=>n(t,...e));const s=this.listeners.get(t);s&&s.forEach(([n,i],c)=>{n(...e),i&&s.splice(c,1)})}on(t,e){return this.addListener(t,e,!1)}once(t,e){return this.addListener(t,e,!0)}off(t,e){const s=this.listeners.get(t);if(s){for(let n=0;n<s.length;n+=1)if(e===s[n][0]){s.splice(n,1);return}}}subscribe(t){return this.subscribeListeners.push(t),()=>this.unsubscribe(t)}unsubscribe(t){for(let e=0;e<this.subscribeListeners.length;e+=1)if(this.subscribeListeners[e]===t){this.subscribeListeners.splice(e,1);return}}}class y{constructor(t,e){this.state=t,this.ee=e}internalSet(t,e){return this.state[t]===e||e===void 0?!1:(this.state[t]=e,this.ee.emit(`change:${t}`,e),!0)}clone(){return{...this.state}}set(t,e){let s=!1;if(typeof t=="string")s=this.internalSet(t,e);else for(const n in t)this.internalSet(n,t[n])&&(s=!0);s&&this.ee.emit("change")}get(t){return this.state[t]}}class St{constructor(t){o(this,"ee",new b);o(this,"state");o(this,"on",this.ee.on.bind(this.ee));o(this,"off",this.ee.off.bind(this.ee));this.state=new y(t,this.ee)}get accentTextColor(){return this.get("accentTextColor")}get backgroundColor(){return this.get("backgroundColor")}get buttonColor(){return this.get("buttonColor")}get buttonTextColor(){return this.get("buttonTextColor")}get destructiveTextColor(){return this.get("destructiveTextColor")}get(t){return this.state.get(t)}getState(){return this.state.clone()}get headerBackgroundColor(){return this.get("headerBackgroundColor")}get hintColor(){return this.get("hintColor")}get isDark(){return!this.backgroundColor||rt(this.backgroundColor)}get linkColor(){return this.get("linkColor")}get secondaryBackgroundColor(){return this.get("secondaryBackgroundColor")}get sectionBackgroundColor(){return this.get("sectionBackgroundColor")}get sectionHeaderTextColor(){return this.get("sectionHeaderTextColor")}listen(){return E("theme_changed",t=>{this.state.set(at(t.theme_params))})}get subtitleTextColor(){return this.get("subtitleTextColor")}get textColor(){return this.get("textColor")}}function ct(){return st({botInline:{type:S().optional(),from:"tgWebAppBotInline"},initData:{type:it().optional(),from:"tgWebAppData"},initDataRaw:{type:h().optional(),from:"tgWebAppData"},platform:{type:h(),from:"tgWebAppPlatform"},showSettings:{type:S().optional(),from:"tgWebAppShowSettings"},themeParams:{type:ot(),from:"tgWebAppThemeParams"},version:{type:h(),from:"tgWebAppVersion"}},"LaunchParams")}function ut(r){return ct().parse(r)}function he(){return ut(window.location.hash.slice(1))}function pe(){const r=P();if(!r)throw new Error("Unable to get first navigation entry.");const t=r.name.match(/#(.*)/);if(!t)throw new Error("First navigation entry does not contain hash part.");return ut(t[1])}function le(){try{return pe()}catch{}try{return he()}catch{}return null}function kt(r){const{initDataRaw:t,themeParams:e,platform:s,version:n,showSettings:i,botInline:c}=r,u=new URLSearchParams;return t&&u.set("tgWebAppData",t),u.set("tgWebAppPlatform",s),u.set("tgWebAppThemeParams",Pt(e)),u.set("tgWebAppVersion",n),typeof i=="boolean"&&u.set("tgWebAppShowSettings",i?"1":"0"),typeof c=="boolean"&&u.set("tgWebAppBotInline",c?"1":"0"),u.toString()}const qt="telegram-mini-apps-launch-params";function de(){const r=sessionStorage.getItem(qt);return r?ct().parse(r):null}function fe(r){sessionStorage.setItem(qt,kt(r))}function ge(){try{return window.self!==window.top}catch{return!0}}function we(){const r=de(),t=le(),e=re();if(r){if(t)return{launchParams:t,isPageReload:ge()?e||r.initDataRaw===t.initDataRaw:!0};if(e)return{launchParams:r,isPageReload:e};throw new Error("Unable to retrieve current launch parameters, which must exist.")}if(t)return{launchParams:t,isPageReload:!1};throw new Error("Unable to retrieve any launch parameters.")}const At="tmajsLaunchData";function ht(){const r=window[At];if(r)return r;const t=we();return window[At]=t,fe(t.launchParams),t}function _e(){try{return ht(),!0}catch{return!1}}function be(r){return"external"in r&&g(r.external)&&"notify"in r.external&&typeof r.external.notify=="function"}function me(r){return"TelegramWebviewProxy"in r&&g(r.TelegramWebviewProxy)&&"postEvent"in r.TelegramWebviewProxy&&typeof r.TelegramWebviewProxy.postEvent=="function"}function pt(){try{return window.self!==window.top}catch{return!0}}class Q extends Error{constructor(t,e){super(`Method "${t}" is unsupported in the Mini Apps version ${e}.`),Object.setPrototypeOf(this,Q.prototype)}}class Z extends Error{constructor(t,e,s){super(`Parameter "${e}" in method "${t}" is unsupported in the Mini Apps version ${s}.`),Object.setPrototypeOf(this,Z.prototype)}}class Rt{constructor(t,e){this.prefix=t,this.enabled=e}print(t,...e){if(!this.enabled)return;const s=new Date,n=Intl.DateTimeFormat("en-GB",{hour:"2-digit",minute:"2-digit",second:"2-digit",fractionalSecondDigits:3,timeZone:"UTC"}).format(s);console[t](`[${n}]`,this.prefix,...e)}disable(){this.enabled=!1}error(...t){this.print("error",...t)}enable(){this.enabled=!0}log(...t){this.print("log",...t)}warn(...t){this.print("warn",...t)}}let Vt="https://web.telegram.org";const D=new Rt("[SDK]",!1);function ye(r){if(r){D.enable();return}D.disable()}function Ee(r){Vt=r}function Ce(){return Vt}const ve=w({eventType:h(),eventData:r=>r});function Pe(r,t){window.dispatchEvent(new MessageEvent("message",{data:JSON.stringify({eventType:r,eventData:t})}))}function Se(){const r=window;"TelegramGameProxy_receiveEvent"in r||[["TelegramGameProxy_receiveEvent"],["TelegramGameProxy","receiveEvent"],["Telegram","WebView","receiveEvent"]].forEach(t=>{let e=r;t.forEach((s,n,i)=>{if(n===i.length-1){e[s]=Pe;return}s in e||(e[s]={}),e=e[s]})})}function ke(r){Se(),window.addEventListener("message",t=>{try{const{eventType:e,eventData:s}=ve.parse(t.data);r(e,s)}catch{}})}function qe(){return w({req_id:h(),data:r=>r===null?r:h().optional().parse(r)})}function Ae(){return w({req_id:h(),result:r=>r,error:h().optional()})}function Re(){return w({slug:h(),status:h()})}function Ve(){return w({status:h()})}function Te(){return w({button_id:r=>r==null?void 0:h().parse(r)})}function Ie(){return w({data:h().optional()})}function Le(){return w({theme_params:r=>{const t=Et().optional();return Object.entries(X(r)).reduce((e,[s,n])=>(e[s]=t.parse(n),e),{})}})}function Be(){return w({height:V(),width:r=>r==null?window.innerWidth:V().parse(r),is_state_stable:S(),is_expanded:S()})}function $e(){return w({status:h()})}function De(){const r=new b,t=(e,...s)=>{D.log("Emitting processed event:",e,...s),r.emit(e,...s)};return window.addEventListener("resize",()=>{t("viewport_changed",{width:window.innerWidth,height:window.innerHeight,is_state_stable:!0,is_expanded:!0})}),ke((e,s)=>{D.log("Received raw event:",e,s);try{switch(e){case"viewport_changed":return t(e,Be().parse(s));case"theme_changed":return t(e,Le().parse(s));case"popup_closed":return s==null?t(e,{}):t(e,Te().parse(s));case"set_custom_style":return t(e,h().parse(s));case"qr_text_received":return t(e,Ie().parse(s));case"clipboard_text_received":return t(e,qe().parse(s));case"invoice_closed":return t(e,Re().parse(s));case"phone_requested":return t("phone_requested",Ve().parse(s));case"custom_method_invoked":return t("custom_method_invoked",Ae().parse(s));case"write_access_requested":return t("write_access_requested",$e().parse(s));case"main_button_pressed":case"back_button_pressed":case"settings_button_pressed":case"scan_qr_popup_closed":case"reload_iframe":return t(e);default:return t(e,s)}}catch(n){D.error("Error processing event:",n)}}),r}const lt="telegram-mini-apps-cached-emitter";function W(){const r=window;return r[lt]===void 0&&(r[lt]=De()),r[lt]}function T(r,t){W().off(r,t)}function E(r,t){return W().on(r,t),()=>T(r,t)}function xe(r,t){return W().once(r,t),()=>T(r,t)}function Tt(r){W().unsubscribe(r)}function Ne(r){return W().subscribe(r),()=>Tt(r)}function It(r,t){const e=r.split("."),s=t.split("."),n=Math.max(e.length,s.length);for(let i=0;i<n;i+=1){const c=parseInt(e[i]||"0",10),u=parseInt(s[i]||"0",10);if(c!==u)return c>u?1:-1}return 0}function k(r,t){return It(r,t)<=0}function I(r,t,e){if(typeof e=="string"){if(r==="web_app_open_link"&&t==="try_instant_view")return k("6.4",e);if(r==="web_app_set_header_color"&&t==="color")return k("6.9",e)}switch(r){case"web_app_open_tg_link":case"web_app_open_invoice":case"web_app_setup_back_button":case"web_app_set_background_color":case"web_app_set_header_color":case"web_app_trigger_haptic_feedback":return k("6.1",t);case"web_app_open_popup":return k("6.2",t);case"web_app_close_scan_qr_popup":case"web_app_open_scan_qr_popup":case"web_app_read_text_from_clipboard":return k("6.4",t);case"web_app_switch_inline_query":return k("6.7",t);case"web_app_invoke_custom_method":case"web_app_request_write_access":case"web_app_request_phone":return k("6.9",t);case"web_app_setup_settings_button":return k("6.10",t);default:return!0}}function v(r,t){return e=>I(t[e],r)}function Lt(r,t){return e=>{const[s,n]=t[e];return I(s,n,r)}}function d(r,t,e){let s={},n;t===void 0&&e===void 0?s={}:t!==void 0&&e!==void 0?(s=e,n=t):t!==void 0&&("targetOrigin"in t?s=t:n=t);const{targetOrigin:i=Ce()}=s;if(D.log(`Calling method "${r}"`,n),pt()){window.parent.postMessage(JSON.stringify({eventType:r,eventData:n}),i);return}if(be(window)){window.external.notify(JSON.stringify({eventType:r,eventData:n}));return}if(me(window)){window.TelegramWebviewProxy.postEvent(r,JSON.stringify(n));return}throw new Error("Unable to determine current environment and possible way to send event.")}function Bt(r){return(t,e)=>{if(!I(t,r))throw new Q(t,r);if(g(e)){let s;if(t==="web_app_open_link"&&"try_instant_view"in e?s="try_instant_view":t==="web_app_set_header_color"&&"color"in e&&(s="color"),s&&!I(t,s,r))throw new Z(t,s,r)}return d(t,e)}}class M extends Error{constructor(t){super(`Async call timeout exceeded. Timeout: ${t}`),Object.setPrototypeOf(this,M.prototype)}}function He(r){return r instanceof M}function Oe(r){return new Promise(t=>{setTimeout(t,r)})}function We(r){return new Promise((t,e)=>{setTimeout(e,r,new M(r))})}function dt(r,t){return Promise.race([r(),We(t)])}function C(r,t,e,s){let n,i,c,u;typeof t=="string"||Array.isArray(t)?(c=Array.isArray(t)?t:[t],n=e):(i=t,c=Array.isArray(e)?e:[e],n=s),g(i)&&typeof i.req_id=="string"&&(u=i.req_id);const{postEvent:l=d,timeout:p}=n||{},_=n&&"capture"in n?n.capture:null,m=()=>new Promise((O,f)=>{const A=c.map(R=>E(R,Y=>{u&&(!g(Y)||Y.req_id!==u)||typeof _=="function"&&!_(Y)||(L(),O(Y))})),L=()=>A.forEach(R=>R());try{l(r,i)}catch(R){L(),f(R)}});return typeof p=="number"?dt(m,p):m()}async function x(r,t,e,s={}){const{result:n,error:i}=await C("web_app_invoke_custom_method",{method:r,params:t,req_id:e},"custom_method_invoked",s);if(i)throw new Error(i);return n}class $t{constructor(t,e,s=d){o(this,"ee",new b);o(this,"state");o(this,"on",(t,e)=>t==="click"?E("back_button_pressed",e):this.ee.on(t,e));o(this,"off",(t,e)=>t==="click"?T("back_button_pressed",e):this.ee.off(t,e));o(this,"supports");this.postEvent=s,this.state=new y({isVisible:t},this.ee),this.supports=v(e,{show:"web_app_setup_back_button",hide:"web_app_setup_back_button"})}set isVisible(t){this.state.set("isVisible",t),this.postEvent("web_app_setup_back_button",{is_visible:t})}get isVisible(){return this.state.get("isVisible")}hide(){this.isVisible=!1}show(){this.isVisible=!0}}function Dt(r,t){return r+(r.length>0&&t.length>0?` ${t}`:t)}function xt(...r){return r.reduce((t,e)=>{let s="";return typeof e=="string"?s=e:typeof e=="object"&&e!==null&&(s=Object.entries(e).reduce((n,[i,c])=>c?Dt(n,i):n,"")),Dt(t,s)},"")}function Me(r){return typeof r=="object"&&r!==null&&!Array.isArray(null)}function Ue(...r){return r.reduce((t,e)=>(Me(e)&&Object.entries(e).forEach(([s,n])=>{const i=xt(t[s],n);i.length>0&&(t[s]=i)}),t),{})}class Nt{constructor(t,e=d){o(this,"ee",new b);o(this,"state");o(this,"on",this.ee.on.bind(this.ee));o(this,"off",this.ee.off.bind(this.ee));this.postEvent=e,this.state=new y({isConfirmationNeeded:t},this.ee)}set isConfirmationNeeded(t){this.state.set("isConfirmationNeeded",t),this.postEvent("web_app_setup_closing_behavior",{need_confirmation:t})}get isConfirmationNeeded(){return this.state.get("isConfirmationNeeded")}disableConfirmation(){this.isConfirmationNeeded=!1}enableConfirmation(){this.isConfirmationNeeded=!0}}function Ht(r,t){return r.reduce((e,s)=>(e[s]=t,e),{})}class Ot{constructor(t,e,s=d){o(this,"supports");this.createRequestId=e,this.postEvent=s,this.supports=v(t,{delete:"web_app_invoke_custom_method",get:"web_app_invoke_custom_method",getKeys:"web_app_invoke_custom_method",set:"web_app_invoke_custom_method"})}async delete(t,e={}){const s=Array.isArray(t)?t:[t];s.length!==0&&await x("deleteStorageValues",{keys:s},this.createRequestId(),{...e,postEvent:this.postEvent})}async getKeys(t={}){const e=await x("getStorageKeys",{},this.createRequestId(),{...t,postEvent:this.postEvent});return ie().of(h()).parse(e)}async get(t,e={}){const s=Array.isArray(t)?t:[t];if(s.length===0)return Ht(s,"");const n=w(Ht(s,h())),i=await x("getStorageValues",{keys:s},this.createRequestId(),{...e,postEvent:this.postEvent}).then(c=>n.parse(c));return Array.isArray(t)?i:i[t]}async set(t,e,s={}){await x("saveStorageValue",{key:t,value:e},this.createRequestId(),{...s,postEvent:this.postEvent})}}class Wt{constructor(t,e=d){o(this,"supports");this.postEvent=e,this.supports=v(t,{impactOccurred:"web_app_trigger_haptic_feedback",notificationOccurred:"web_app_trigger_haptic_feedback",selectionChanged:"web_app_trigger_haptic_feedback"})}impactOccurred(t){this.postEvent("web_app_trigger_haptic_feedback",{type:"impact",impact_style:t})}notificationOccurred(t){this.postEvent("web_app_trigger_haptic_feedback",{type:"notification",notification_type:t})}selectionChanged(){this.postEvent("web_app_trigger_haptic_feedback",{type:"selection_change"})}}function je(){const r=document.createElement("style");r.id="telegram-custom-styles",document.head.appendChild(r),E("set_custom_style",t=>{r.innerHTML=t})}function Mt(r){return`telegram-mini-apps-${r}`}function N(r,t){sessionStorage.setItem(Mt(r),JSON.stringify(t))}function H(r){const t=sessionStorage.getItem(Mt(r));return t?JSON.parse(t):null}function Ge(r,t,e){const{isVisible:s=!1}=r?H("back-button")||{}:{},n=new $t(s,t,e);return n.on("change",()=>{N("back-button",{isVisible:n.isVisible})}),n}function Fe(r,t){const{isConfirmationNeeded:e=!1}=r?H("closing-behavior")||{}:{},s=new Nt(e,t);return s.on("change",()=>N("closing-behavior",{isConfirmationNeeded:s.isConfirmationNeeded})),s}class Ut{constructor(t){o(this,"ee",new b);o(this,"state");o(this,"postEvent");o(this,"on",(t,e)=>t==="click"?E("main_button_pressed",e):this.ee.on(t,e));o(this,"off",(t,e)=>t==="click"?T("main_button_pressed",e):this.ee.off(t,e));const{postEvent:e=d,text:s,textColor:n,backgroundColor:i,isEnabled:c,isVisible:u,isLoaderVisible:l}=t;this.postEvent=e,this.state=new y({backgroundColor:i,isEnabled:c,isVisible:u,isLoaderVisible:l,text:s,textColor:n},this.ee)}commit(){this.text!==""&&this.postEvent("web_app_setup_main_button",{is_visible:this.isVisible,is_active:this.isEnabled,is_progress_visible:this.isLoaderVisible,text:this.text,color:this.backgroundColor,text_color:this.textColor})}set isEnabled(t){this.setParams({isEnabled:t})}get isEnabled(){return this.state.get("isEnabled")}set isLoaderVisible(t){this.setParams({isLoaderVisible:t})}get isLoaderVisible(){return this.state.get("isLoaderVisible")}set isVisible(t){this.setParams({isVisible:t})}get isVisible(){return this.state.get("isVisible")}get backgroundColor(){return this.state.get("backgroundColor")}get text(){return this.state.get("text")}get textColor(){return this.state.get("textColor")}disable(){return this.isEnabled=!1,this}enable(){return this.isEnabled=!0,this}hide(){return this.isVisible=!1,this}hideLoader(){return this.isLoaderVisible=!1,this}show(){return this.isVisible=!0,this}showLoader(){return this.isLoaderVisible=!0,this}setText(t){return this.setParams({text:t})}setTextColor(t){return this.setParams({textColor:t})}setBackgroundColor(t){return this.setParams({backgroundColor:t})}setParams(t){return this.state.set(t),this.commit(),this}}function ze(r,t,e,s){const{backgroundColor:n=t,isEnabled:i=!1,isVisible:c=!1,isLoaderVisible:u=!1,textColor:l=e,text:p=""}=r?H("main-button")||{}:{},_=new Ut({backgroundColor:n,isEnabled:i,isLoaderVisible:u,isVisible:c,postEvent:s,text:p,textColor:l}),m=()=>N("main-button",{backgroundColor:_.backgroundColor,isEnabled:_.isEnabled,isLoaderVisible:_.isLoaderVisible,isVisible:_.isVisible,text:_.text,textColor:_.textColor});return _.on("change",m),_}const Je=st({contact:w({userId:{type:V(),from:"user_id"},phoneNumber:{type:h(),from:"phone_number"},firstName:{type:h(),from:"first_name"},lastName:{type:h().optional(),from:"last_name"}}),authDate:{type:mt(),from:"auth_date"},hash:h()});class jt{constructor(t){o(this,"ee",new b);o(this,"state");o(this,"botInline");o(this,"postEvent");o(this,"createRequestId");o(this,"requestingPhoneAccess",!1);o(this,"requestingWriteAccess",!1);o(this,"on",this.ee.on.bind(this.ee));o(this,"off",this.ee.off.bind(this.ee));o(this,"supports");o(this,"supportsParam");const{postEvent:e=d,headerColor:s,backgroundColor:n,version:i,botInline:c,createRequestId:u}=t,l=v(i,{requestPhoneAccess:"web_app_request_phone",requestWriteAccess:"web_app_request_write_access",switchInlineQuery:"web_app_switch_inline_query",setHeaderColor:"web_app_set_header_color",setBackgroundColor:"web_app_set_background_color"});this.postEvent=e,this.botInline=c,this.createRequestId=u,this.supports=p=>!(!l(p)||p==="switchInlineQuery"&&!c),this.state=new y({backgroundColor:n,headerColor:s},this.ee),this.supportsParam=Lt(i,{"setHeaderColor.color":["web_app_set_header_color","color"]})}async getRequestedContact(){return x("getRequestedContact",{},this.createRequestId(),{postEvent:this.postEvent,timeout:1e4}).then(t=>Je.parse(t))}get backgroundColor(){return this.state.get("backgroundColor")}close(){this.postEvent("web_app_close")}get headerColor(){return this.state.get("headerColor")}get isBotInline(){return this.botInline}get isDark(){return rt(this.backgroundColor)}get isRequestingPhoneAccess(){return this.requestingPhoneAccess}get isRequestingWriteAccess(){return this.requestingWriteAccess}ready(){this.postEvent("web_app_ready")}async requestContact({timeout:t=5e3}={}){try{return await this.getRequestedContact()}catch{}if(await this.requestPhoneAccess()!=="sent")throw new Error("Access denied.");const s=Date.now()+t;let n=50;return dt(async()=>{for(;Date.now()<s;){try{return await this.getRequestedContact()}catch{}await Oe(n),n+=50}throw new Error("Unable to retrieve requested contact.")},t)}requestPhoneAccess(t={}){if(this.requestingPhoneAccess)throw new Error("Phone access is already being requested.");return this.requestingPhoneAccess=!0,C("web_app_request_phone","phone_requested",{...t,postEvent:this.postEvent}).then(e=>e.status).finally(()=>{this.requestingPhoneAccess=!1})}requestWriteAccess(t={}){if(this.requestingWriteAccess)throw new Error("Write access is already being requested.");return this.requestingWriteAccess=!0,C("web_app_request_write_access","write_access_requested",{...t,postEvent:this.postEvent}).then(e=>e.status).finally(()=>{this.requestingWriteAccess=!1})}sendData(t){const{size:e}=new Blob([t]);if(e===0||e>4096)throw new Error(`Passed data has incorrect size: ${e}`);this.postEvent("web_app_data_send",{data:t})}setHeaderColor(t){this.postEvent("web_app_set_header_color",tt(t)?{color:t}:{color_key:t}),this.state.set("headerColor",t)}setBackgroundColor(t){this.postEvent("web_app_set_background_color",{color:t}),this.state.set("backgroundColor",t)}switchInlineQuery(t,e=[]){if(!this.supports("switchInlineQuery")&&!this.isBotInline)throw new Error("Method is unsupported because Mini App should be launched in inline mode.");this.postEvent("web_app_switch_inline_query",{query:t,chat_types:e})}}function Qe(r,t,e,s,n,i){const{backgroundColor:c=t,headerColor:u="bg_color"}=r?H("mini-app")||{}:{},l=new jt({headerColor:u,backgroundColor:c,version:e,botInline:s,createRequestId:n,postEvent:i}),p=()=>N("mini-app",{backgroundColor:l.backgroundColor,headerColor:l.headerColor});return l.on("change",p),l}function Ze(){let r=0;return()=>(r+=1,r.toString())}class Gt{constructor(t,e,s=d){o(this,"ee",new b);o(this,"state");o(this,"on",(t,e)=>t==="click"?E("settings_button_pressed",e):this.ee.on(t,e));o(this,"off",(t,e)=>t==="click"?T("settings_button_pressed",e):this.ee.off(t,e));o(this,"supports");this.postEvent=s,this.state=new y({isVisible:t},this.ee),this.supports=v(e,{show:"web_app_setup_settings_button",hide:"web_app_setup_settings_button"})}set isVisible(t){this.state.set("isVisible",t),this.postEvent("web_app_setup_settings_button",{is_visible:t})}get isVisible(){return this.state.get("isVisible")}hide(){this.isVisible=!1}show(){this.isVisible=!0}}function Ke(r,t,e){const{isVisible:s=!1}=r?H("settings-button")||{}:{},n=new Gt(s,t,e);return n.on("change",()=>{N("settings-button",{isVisible:n.isVisible})}),n}function Ye(r){const t=new St(r);return t.listen(),t}function Ft(r){return["macos","tdesktop","unigram","web","weba"].includes(r)}async function ft(r){const t=await C("web_app_request_viewport","viewport_changed",r);return{height:t.height,width:t.width,isExpanded:t.is_expanded,isStateStable:t.is_state_stable}}function U(r){return r<0?0:r}class zt{constructor(t){o(this,"ee",new b);o(this,"state");o(this,"postEvent");o(this,"on",this.ee.on.bind(this.ee));o(this,"off",this.ee.off.bind(this.ee));const{height:e,isExpanded:s,width:n,stableHeight:i,postEvent:c=d}=t;this.postEvent=c,this.state=new y({height:U(e),isExpanded:s,stableHeight:U(i),width:U(n)},this.ee)}sync(t){return ft(t).then(({height:e,isExpanded:s,width:n,isStateStable:i})=>{this.state.set({height:e,width:n,isExpanded:s,stableHeight:i?e:this.state.get("stableHeight")})})}get height(){return this.state.get("height")}get stableHeight(){return this.state.get("stableHeight")}listen(){return E("viewport_changed",t=>{const{height:e,width:s,is_expanded:n,is_state_stable:i}=t,c={height:U(e),isExpanded:n,width:U(s)};i&&(c.stableHeight=c.height),this.state.set(c)})}get isExpanded(){return this.state.get("isExpanded")}get width(){return this.state.get("width")}expand(){this.postEvent("web_app_expand"),this.state.set("isExpanded",!0)}get isStable(){return this.stableHeight===this.height}}function K(r){const t=new zt(r);return t.on("change",()=>N("viewport",{height:t.height,isExpanded:t.isExpanded,stableHeight:t.stableHeight,width:t.width})),t.listen(),t}function Xe(r,t,e,s){const n=r?H("viewport"):null;if(n)return K({...n,postEvent:e});if(Ft(t))return K({height:window.innerHeight,isExpanded:!0,postEvent:e,stableHeight:window.innerHeight,width:window.innerWidth});if(s)return ft({postEvent:e,timeout:5e3}).then(({height:c,isStateStable:u,...l})=>K({...l,height:c,stableHeight:u?c:0}));const i=K({width:0,height:0,isExpanded:!1,postEvent:e,stableHeight:0});return i.sync({postEvent:e,timeout:5e3}).catch(c=>{console.error("Unable to actualize viewport state",c)}),i}function q(r,t){document.documentElement.style.setProperty(r,t)}function tr(r,t){const e=()=>{q("--tg-background-color",r.backgroundColor)},s=()=>{const{backgroundColor:n,secondaryBackgroundColor:i}=t;r.headerColor==="bg_color"?n&&q("--tg-header-color",n):r.headerColor==="secondary_bg_color"?i&&q("--tg-header-color",i):q("--tg-header-color",r.headerColor)};t.on("change",s),r.on("change:backgroundColor",e),r.on("change:headerColor",s),e(),s()}function er(r){const t=()=>{const e=r.getState();Object.entries(e).forEach(([s,n])=>{if(n){const i=s.replace(/[A-Z]/g,c=>`-${c.toLowerCase()}`);q(`--tg-theme-${i}`,n)}})};r.on("change",t),t()}function Jt(r){const t=()=>q("--tg-viewport-height",`${r.height}px`),e=()=>q("--tg-viewport-width",`${r.width}px`),s=()=>q("--tg-viewport-height",`${r.stableHeight}px`);r.on("change:height",t),r.on("change:width",e),r.on("change:stableHeight",s),t(),e(),s()}function rr(r){return typeof r=="object"?r:r?{themeParams:!0,viewport:!0,miniApp:!0}:{}}function Qt(r,t,e,s){const n=rr(r);n.miniApp&&tr(t,e),n.themeParams&&er(e),n.viewport&&(s instanceof Promise?s.then(Jt):Jt(s))}function sr(r){const{hostname:t,pathname:e}=new URL(r,window.location.href);if(t!=="t.me")throw new Error(`Incorrect hostname: ${t}`);const s=e.match(/^\/(\$|invoice\/)([A-Za-z0-9\-_=]+)$/);if(s===null)throw new Error('Link pathname has incorrect format. Expected to receive "/invoice/{slug}" or "/${slug}"');return s[2]}class Zt{constructor(t,e=d){o(this,"ee",new b);o(this,"state");o(this,"on",this.ee.on.bind(this.ee));o(this,"off",this.ee.off.bind(this.ee));o(this,"supports");this.postEvent=e,this.state=new y({isOpened:!1},this.ee),this.supports=v(t,{open:"web_app_open_invoice"})}set isOpened(t){this.state.set("isOpened",t)}get isOpened(){return this.state.get("isOpened")}async open(t,e){if(this.isOpened)throw new Error("Invoice is already opened");const s=e?sr(t):t;this.isOpened=!0;try{return(await C("web_app_open_invoice",{slug:s},"invoice_closed",{postEvent:this.postEvent,capture(i){return s===i.slug}})).status}finally{this.isOpened=!1}}}function nr(r){const t=r.message.trim(),e=(r.title||"").trim(),s=r.buttons||[];let n;if(e.length>64)throw new Error(`Title has incorrect size: ${e.length}`);if(t.length===0||t.length>256)throw new Error(`Message has incorrect size: ${t.length}`);if(s.length>3)throw new Error(`Buttons have incorrect size: ${s.length}`);return s.length===0?n=[{type:"close",id:""}]:n=s.map(i=>{const{id:c=""}=i;if(c.length>64)throw new Error(`Button ID has incorrect size: ${c}`);if(i.type===void 0||i.type==="default"||i.type==="destructive"){const u=i.text.trim();if(u.length===0||u.length>64){const l=i.type||"default";throw new Error(`Button text with type "${l}" has incorrect size: ${i.text.length}`)}return{...i,text:u,id:c}}return{...i,id:c}}),{title:e,message:t,buttons:n}}class Kt{constructor(t,e=d){o(this,"ee",new b);o(this,"state");o(this,"on",this.ee.on.bind(this.ee));o(this,"off",this.ee.off.bind(this.ee));o(this,"supports");this.postEvent=e,this.state=new y({isOpened:!1},this.ee),this.supports=v(t,{open:"web_app_open_popup"})}set isOpened(t){this.state.set("isOpened",t)}get isOpened(){return this.state.get("isOpened")}open(t){if(this.isOpened)throw new Error("Popup is already opened.");return this.isOpened=!0,C("web_app_open_popup",nr(t),"popup_closed",{postEvent:this.postEvent}).then(({button_id:e=null})=>e).finally(()=>{this.isOpened=!1})}}class Yt{constructor(t,e=d){o(this,"ee",new b);o(this,"state");o(this,"on",this.ee.on.bind(this.ee));o(this,"off",this.ee.off.bind(this.ee));o(this,"supports");this.postEvent=e,this.state=new y({isOpened:!1},this.ee),this.supports=v(t,{close:"web_app_close_scan_qr_popup",open:"web_app_open_scan_qr_popup"})}close(){this.postEvent("web_app_close_scan_qr_popup"),this.isOpened=!1}set isOpened(t){this.state.set("isOpened",t)}get isOpened(){return this.state.get("isOpened")}async open(t){if(this.isOpened)throw new Error("QR scanner is already opened.");this.isOpened=!0;try{const e=await C("web_app_open_scan_qr_popup",{text:t},["qr_text_received","scan_qr_popup_closed"],{postEvent:this.postEvent});return typeof e=="object"&&typeof e.data=="string"?e.data:null}finally{this.isOpened=!1}}}class Xt{constructor(t,e,s=d){o(this,"supports");o(this,"supportsParam");this.version=t,this.createRequestId=e,this.postEvent=s,this.supports=v(t,{readTextFromClipboard:"web_app_read_text_from_clipboard"}),this.supportsParam=Lt(t,{"openLink.tryInstantView":["web_app_open_link","try_instant_view"]})}openLink(t,e){const s=new URL(t,window.location.href).toString();if(!I("web_app_open_link",this.version)){window.open(s,"_blank");return}this.postEvent("web_app_open_link",{url:s,...typeof e=="boolean"?{try_instant_view:e}:{}})}openTelegramLink(t){const{hostname:e,pathname:s,search:n}=new URL(t,window.location.href);if(e!=="t.me")throw new Error(`URL has not allowed hostname: ${e}. Only "t.me" is allowed`);if(!I("web_app_open_tg_link",this.version)){window.location.href=t;return}this.postEvent("web_app_open_tg_link",{path_full:s+n})}readTextFromClipboard(){return C("web_app_read_text_from_clipboard",{req_id:this.createRequestId()},"clipboard_text_received",{postEvent:this.postEvent}).then(({data:t=null})=>t)}}function ir(r={}){const{async:t=!1,complete:e=t,cssVars:s=!1,acceptCustomStyles:n=!1}=r;try{const{launchParams:{initData:i,initDataRaw:c,version:u,platform:l,themeParams:p,botInline:_=!1},isPageReload:m}=ht(),O=Ze(),f=Bt(u);pt()&&(n&&je(),f("iframe_ready",{reload_supported:!0}),E("reload_iframe",()=>window.location.reload()));const A={backButton:Ge(m,u,f),closingBehavior:Fe(m,f),cloudStorage:new Ot(u,O,f),createRequestId:O,hapticFeedback:new Wt(u,f),invoice:new Zt(u,f),mainButton:ze(m,p.buttonColor||"#000000",p.buttonTextColor||"#ffffff",f),miniApp:Qe(m,p.backgroundColor||"#ffffff",u,_,O,f),popup:new Kt(u,f),postEvent:f,qrScanner:new Yt(u,f),settingsButton:Ke(m,u,f),themeParams:Ye(p),utils:new Xt(u,O,f),...i?{initData:new vt(i),initDataRaw:c}:{}},L=Xe(m,l,f,e);return L instanceof Promise||e?Promise.resolve(L).then(R=>(Qt(s,A.miniApp,A.themeParams,R),{...A,viewport:R})):(Qt(s,A.miniApp,A.themeParams,L),{...A,viewport:L})}catch(i){if(e)return Promise.reject(i);throw i}}function j(r,t){return r.startsWith(t)?r:`${t}${r}`}function or(r){const t=r.match(/#(.+)/);return t?t[1]:null}async function G(r){return r===0?!0:Promise.race([new Promise(t=>{window.addEventListener("popstate",function e(){window.removeEventListener("popstate",e),t(!0)}),window.history.go(r)}),new Promise(t=>{setTimeout(t,50,!1)})])}async function ar(){if(window.history.length<=1||(window.history.pushState(null,""),await G(1-window.history.length)))return;let t=await G(-1);for(;t;)t=await G(-1)}class te{constructor(t,e,{debug:s=!1,loggerPrefix:n="Navigator"}){o(this,"logger");o(this,"entries");if(this.entriesCursor=e,t.length===0)throw new Error("Entries list should not be empty.");if(e>=t.length)throw new Error("Cursor should be less than entries count.");this.entries=t.map(({pathname:i="",search:c,hash:u})=>{if(!i.startsWith("/")&&i.length>0)throw new Error('Pathname should start with "/"');return{pathname:j(i,"/"),search:c?j(c,"?"):"",hash:u?j(u,"#"):""}}),this.logger=new Rt(`[${n}]`,s)}formatEntry(t){let e;if(typeof t=="string")e=t;else{const{pathname:c="",search:u,hash:l}=t;e=c+(u?j(u,"?"):"")+(l?j(l,"#"):"")}const{pathname:s,search:n,hash:i}=new URL(e,`https://localhost${this.path}`);return{pathname:s,search:n,hash:i}}get entry(){return this.entries[this.entriesCursor]}back(){return this.go(-1)}get cursor(){return this.entriesCursor}get canGoBack(){return this.entriesCursor>0}get canGoForward(){return this.entriesCursor!==this.entries.length-1}forward(){return this.go(1)}go(t){this.logger.log(`called go(${t})`);const e=Math.min(this.entries.length-1,Math.max(this.entriesCursor+t,0));if(this.entriesCursor===e)return this.performGo({updated:!1,delta:t});const s=this.entry;this.entriesCursor=e;const n=this.entry;return this.logger.log("State changed",{before:s,after:n}),this.performGo({updated:!0,delta:t,before:s,after:n})}getEntries(){return this.entries.map(t=>({...t}))}get hash(){return this.entry.hash}push(t){this.entriesCursor!==this.entries.length-1&&this.entries.splice(this.entriesCursor+1);const e=this.formatEntry(t),s=this.entry;this.entriesCursor+=1,this.entries[this.entriesCursor]=e;const n=this.entry;return this.logger.log("State changed",{before:s,after:n}),this.performPush({before:s,after:n})}get path(){return`${this.pathname}${this.search}${this.hash}`}get pathname(){return this.entry.pathname}replace(t){const e=this.formatEntry(t);if(this.search===e.search&&this.pathname===e.pathname&&this.hash===e.hash)return this.performReplace({updated:!1,entry:e});const s=this.entry;this.entries[this.entriesCursor]=e;const n=this.entry;return this.logger.log("State changed",{before:s,after:n}),this.performReplace({updated:!0,before:s,after:n})}get search(){return this.entry.search}}const ee=0,gt=1,wt=2;class _t extends te{constructor(e,s,n={}){super(e,s,{...n,loggerPrefix:"HashNavigator"});o(this,"ee",new b);o(this,"attached",!1);o(this,"onPopState",async({state:e})=>{if(this.logger.log('"popstate" event received. State:',e),e===null)return this.push(window.location.hash.slice(1));if(e===ee){this.logger.log("Void reached. Moving history forward"),window.history.forward();return}if(e===gt)return this.back();if(e===wt)return this.forward()});o(this,"back",()=>super.back());o(this,"on",this.ee.on.bind(this.ee));o(this,"off",this.ee.off.bind(this.ee))}static fromLocation(e){const{search:s,pathname:n,hash:i}=new URL(window.location.hash.slice(1),window.location.href);return new _t([{search:s,pathname:n,hash:i}],0,e)}async performGo(e){e.updated&&(this.attached&&await this.syncHistory(),this.emitChanged(e.before,e.after))}async performPush({before:e,after:s}){this.attached&&await this.syncHistory(),this.emitChanged(e,s)}async performReplace(e){e.updated&&(this.attached&&window.history.replaceState(null,"",`#${this.path}`),this.emitChanged(e.before,e.after))}async syncHistory(){window.removeEventListener("popstate",this.onPopState);const e=`#${this.path}`;await ar(),d("web_app_setup_back_button",{is_visible:this.canGoBack}),this.canGoBack&&this.canGoForward?(this.logger.log("Setting up history: [<-, *, ->]"),window.history.replaceState(gt,""),window.history.pushState(null,"",e),window.history.pushState(wt,""),await G(-1)):this.canGoBack?(this.logger.log("Setting up history: [<-, *]"),window.history.replaceState(gt,""),window.history.pushState(null,"",e)):this.canGoForward?(this.logger.log("Setting up history: [*, ->]"),window.history.replaceState(null,e),window.history.pushState(wt,""),await G(-1)):(this.logger.log("Setting up history: [~, *]"),window.history.replaceState(ee,""),window.history.pushState(null,"",e)),window.addEventListener("popstate",this.onPopState)}emitChanged(e,s){this.ee.emit("change",{navigator:this,from:e,to:s})}async attach(){if(!this.attached)return this.logger.log("Attaching",this),this.attached=!0,E("back_button_pressed",this.back),this.syncHistory()}detach(){this.attached&&(this.logger.log("Detaching",this),this.attached=!1,window.removeEventListener("popstate",this.onPopState),T("back_button_pressed",this.back))}}return a.BackButton=$t,a.ClosingBehavior=Nt,a.CloudStorage=Ot,a.HapticFeedback=Wt,a.HashNavigator=_t,a.InitData=vt,a.Invoice=Zt,a.MainButton=Ut,a.MethodUnsupportedError=Q,a.MiniApp=jt,a.Navigator=te,a.ParameterUnsupportedError=Z,a.Popup=Kt,a.QRScanner=Yt,a.SettingsButton=Gt,a.ThemeParams=St,a.TimeoutError=M,a.Utils=Xt,a.Viewport=zt,a.chatParser=Ct,a.classNames=xt,a.compareVersions=It,a.createPostEvent=Bt,a.getHash=or,a.init=ir,a.initDataParser=it,a.invokeCustomMethod=x,a.isColorDark=rt,a.isIframe=pt,a.isRGB=tt,a.isRGBShort=yt,a.isRecord=g,a.isStableViewportPlatform=Ft,a.isTMA=_e,a.isTimeoutError=He,a.launchParamsParser=ct,a.mergeClassNames=Ue,a.off=T,a.on=E,a.once=xe,a.parseInitData=oe,a.parseLaunchParams=ut,a.parseThemeParams=at,a.postEvent=d,a.request=C,a.requestThemeParams=ue,a.requestViewport=ft,a.retrieveLaunchData=ht,a.serializeLaunchParams=kt,a.serializeThemeParams=Pt,a.setDebug=ye,a.setTargetOrigin=Ee,a.subscribe=Ne,a.supports=I,a.themeParamsParser=ot,a.toRGB=et,a.unsubscribe=Tt,a.userParser=nt,a.withTimeout=dt,Object.defineProperty(a,Symbol.toStringTag,{value:"Module"}),a}({});
1
+ var ur=Object.defineProperty;var hr=(a,g,P)=>g in a?ur(a,g,{enumerable:!0,configurable:!0,writable:!0,value:P}):a[g]=P;var o=(a,g,P)=>(hr(a,typeof g!="symbol"?g+"":g,P),P);this.tmajs=this.tmajs||{};this.tmajs.sdk=function(a){"use strict";function g(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}function P(){return performance.getEntriesByType("navigation")[0]||null}function st(){const r=P();return r?r.type==="reload":null}function B(){return new TypeError("Value has unexpected type")}class F extends Error{constructor(t,{cause:s,type:n}={}){super(`Unable to parse value${n?` as ${n}`:""}`,{cause:s});o(this,"type");this.value=t,Object.setPrototypeOf(this,F.prototype),this.type=n}}class z{constructor(e,t,s){this.parser=e,this.isOptional=t,this.type=s}parse(e){if(!(this.isOptional&&e===void 0))try{return this.parser(e)}catch(t){throw new F(e,{type:this.type,cause:t})}}optional(){return this.isOptional=!0,this}}function nt(r){if(Array.isArray(r))return r;if(typeof r=="string")try{const e=JSON.parse(r);if(Array.isArray(e))return e}catch{}throw B()}class it extends z{constructor(t,s,n){super(nt,s,n);o(this,"itemParser");this.itemParser=typeof t=="function"?t:t.parse.bind(t)}parse(t){const s=super.parse(t);return s===void 0?s:s.map(this.itemParser)}of(t){return this.itemParser=typeof t=="function"?t:t.parse.bind(t),this}}function $(r,e){return()=>new z(r,!1,e)}class J extends Error{constructor(e,{cause:t,type:s}={}){super(`Unable to parse field "${e}"${s?` as ${s}`:""}`,{cause:t}),Object.setPrototypeOf(this,J.prototype)}}function _e(r,e){const t={};for(const s in r){const n=r[s];if(!n)continue;let i,c;if(typeof n=="function"||"parse"in n)i=s,c=typeof n=="function"?n:n.parse.bind(n);else{const{type:p}=n;i=n.from||s,c=typeof p=="function"?p:p.parse.bind(p)}let u;const l=e(i);try{u=c(l)}catch(p){throw p instanceof F?new J(i,{type:p.type,cause:p}):new J(i,{cause:p})}u!==void 0&&(t[s]=u)}return t}function ot(r){return new it(e=>e,!1,r)}const S=$(r=>{if(typeof r=="boolean")return r;const e=String(r);if(e==="1"||e==="true")return!0;if(e==="0"||e==="false")return!1;throw B()},"boolean"),V=$(r=>{if(typeof r=="number")return r;if(typeof r=="string"){const e=Number(r);if(!Number.isNaN(e))return e}throw B()},"number"),be=$(r=>r instanceof Date?r:new Date(V().parse(r)*1e3),"Date");function X(r){let e=r;if(typeof e=="string"&&(e=JSON.parse(e)),typeof e!="object"||e===null||Array.isArray(e))throw B();return e}function w(r,e){return new z(t=>{const s=X(t);return _e(r,n=>s[n])},!1,e)}function ee(r){return/^#[\da-f]{6}$/i.test(r)}function me(r){return/^#[\da-f]{3}$/i.test(r)}function te(r){const e=r.replace(/\s/g,"").toLowerCase();if(ee(e))return e;if(me(e)){let s="#";for(let n=0;n<3;n+=1)s+=e[1+n].repeat(2);return s}const t=e.match(/^rgb\((\d{1,3}),(\d{1,3}),(\d{1,3})\)$/)||e.match(/^rgba\((\d{1,3}),(\d{1,3}),(\d{1,3}),\d{1,3}\)$/);if(t===null)throw new Error(`Value "${r}" does not satisfy any of known RGB formats.`);return t.slice(1).reduce((s,n)=>{const i=parseInt(n,10).toString(16);return s+(i.length===1?"0":"")+i},"#")}function re(r){const e=te(r);return Math.sqrt([.299,.587,.114].reduce((s,n,i)=>{const c=parseInt(e.slice(1+i*2,1+(i+1)*2),16);return s+c*c*n},0))<120}const h=$(r=>{if(typeof r=="string"||typeof r=="number")return r.toString();throw B()},"string"),ye=$(r=>te(h().parse(r)),"rgb");function se(r,e){return new z(t=>{if(typeof t!="string"&&!(t instanceof URLSearchParams))throw B();const s=typeof t=="string"?new URLSearchParams(t):t;return _e(r,n=>{const i=s.get(n);return i===null?void 0:i})},!1,e)}function Ee(){return w({id:V(),type:h(),title:h(),photoUrl:{type:h().optional(),from:"photo_url"},username:h().optional()},"Chat")}class Ce{constructor(e){this.initData=e}get authDate(){return this.initData.authDate}get canSendAfter(){return this.initData.canSendAfter}get canSendAfterDate(){const{canSendAfter:e}=this;return e===void 0?void 0:new Date(this.authDate.getTime()+e*1e3)}get chat(){return this.initData.chat}get chatType(){return this.initData.chatType}get chatInstance(){return this.initData.chatInstance}get hash(){return this.initData.hash}get queryId(){return this.initData.queryId}get receiver(){return this.initData.receiver}get startParam(){return this.initData.startParam}get user(){return this.initData.user}}function ne(){return w({addedToAttachmentMenu:{type:S().optional(),from:"added_to_attachment_menu"},allowsWriteToPm:{type:S().optional(),from:"allows_write_to_pm"},firstName:{type:h(),from:"first_name"},id:V(),isBot:{type:S().optional(),from:"is_bot"},isPremium:{type:S().optional(),from:"is_premium"},languageCode:{type:h().optional(),from:"language_code"},lastName:{type:h().optional(),from:"last_name"},photoUrl:{type:h().optional(),from:"photo_url"},username:h().optional()},"User")}function ie(){return se({authDate:{type:be(),from:"auth_date"},canSendAfter:{type:V().optional(),from:"can_send_after"},chat:Ee().optional(),chatInstance:{type:h().optional(),from:"chat_instance"},chatType:{type:h().optional(),from:"chat_type"},hash:h(),queryId:{type:h().optional(),from:"query_id"},receiver:ne().optional(),startParam:{type:h().optional(),from:"start_param"},user:ne().optional()},"InitData")}function at(r){return ie().parse(r)}function ct(r){return r.replace(/(^|_)bg/,(e,t)=>`${t}background`).replace(/_([a-z])/g,(e,t)=>t.toUpperCase())}function ut(r){return r.replace(/[A-Z]/g,e=>`_${e.toLowerCase()}`).replace(/(^|_)background/,(e,t)=>`${t}bg`)}const oe=$(r=>{const e=ye().optional();return Object.entries(X(r)).reduce((t,[s,n])=>(t[ct(s)]=e.parse(n),t),{})},"ThemeParams");function ae(r){return oe().parse(r)}function ht(r={}){return C("web_app_request_theme","theme_changed",r).then(ae)}function ve(r){return JSON.stringify(Object.entries(r).reduce((e,[t,s])=>(s&&(e[ut(t)]=s),e),{}))}class b{constructor(){o(this,"listeners",new Map);o(this,"subscribeListeners",[])}addListener(e,t,s){let n=this.listeners.get(e);return n||(n=[],this.listeners.set(e,n)),n.push([t,s]),()=>this.off(e,t)}emit(e,...t){this.subscribeListeners.forEach(n=>n(e,...t));const s=this.listeners.get(e);s&&s.forEach(([n,i],c)=>{n(...t),i&&s.splice(c,1)})}on(e,t){return this.addListener(e,t,!1)}once(e,t){return this.addListener(e,t,!0)}off(e,t){const s=this.listeners.get(e);if(s){for(let n=0;n<s.length;n+=1)if(t===s[n][0]){s.splice(n,1);return}}}subscribe(e){return this.subscribeListeners.push(e),()=>this.unsubscribe(e)}unsubscribe(e){for(let t=0;t<this.subscribeListeners.length;t+=1)if(this.subscribeListeners[t]===e){this.subscribeListeners.splice(t,1);return}}}class y{constructor(e,t){this.state=e,this.ee=t}internalSet(e,t){return this.state[e]===t||t===void 0?!1:(this.state[e]=t,this.ee.emit(`change:${e}`,t),!0)}clone(){return{...this.state}}set(e,t){let s=!1;if(typeof e=="string")s=this.internalSet(e,t);else for(const n in e)this.internalSet(n,e[n])&&(s=!0);s&&this.ee.emit("change")}get(e){return this.state[e]}}class Pe{constructor(e){o(this,"ee",new b);o(this,"state");o(this,"on",this.ee.on.bind(this.ee));o(this,"off",this.ee.off.bind(this.ee));this.state=new y(e,this.ee)}get accentTextColor(){return this.get("accentTextColor")}get backgroundColor(){return this.get("backgroundColor")}get buttonColor(){return this.get("buttonColor")}get buttonTextColor(){return this.get("buttonTextColor")}get destructiveTextColor(){return this.get("destructiveTextColor")}get(e){return this.state.get(e)}getState(){return this.state.clone()}get headerBackgroundColor(){return this.get("headerBackgroundColor")}get hintColor(){return this.get("hintColor")}get isDark(){return!this.backgroundColor||re(this.backgroundColor)}get linkColor(){return this.get("linkColor")}get secondaryBackgroundColor(){return this.get("secondaryBackgroundColor")}get sectionBackgroundColor(){return this.get("sectionBackgroundColor")}get sectionHeaderTextColor(){return this.get("sectionHeaderTextColor")}listen(){return E("theme_changed",e=>{this.state.set(ae(e.theme_params))})}get subtitleTextColor(){return this.get("subtitleTextColor")}get textColor(){return this.get("textColor")}}function ce(){return se({botInline:{type:S().optional(),from:"tgWebAppBotInline"},initData:{type:ie().optional(),from:"tgWebAppData"},initDataRaw:{type:h().optional(),from:"tgWebAppData"},platform:{type:h(),from:"tgWebAppPlatform"},showSettings:{type:S().optional(),from:"tgWebAppShowSettings"},startParam:{type:h().optional(),from:"tgWebAppStartParam"},themeParams:{type:oe(),from:"tgWebAppThemeParams"},version:{type:h(),from:"tgWebAppVersion"}},"LaunchParams")}function Se(r){return ce().parse(r)}function ke(r){const e=r.includes("?")?r.replace("#","&").slice(r.indexOf("?")+1):r.slice(r.indexOf("#")+1);return Se(e)}function pt(){return ke(window.location.href)}function lt(){const r=P();if(!r)throw new Error("Unable to get first navigation entry.");return ke(r.name)}function dt(){try{return lt()}catch{}try{return pt()}catch{}return null}function qe(r){const{initDataRaw:e,themeParams:t,platform:s,version:n,showSettings:i,botInline:c}=r,u=new URLSearchParams;return e&&u.set("tgWebAppData",e),u.set("tgWebAppPlatform",s),u.set("tgWebAppThemeParams",ve(t)),u.set("tgWebAppVersion",n),typeof i=="boolean"&&u.set("tgWebAppShowSettings",i?"1":"0"),typeof c=="boolean"&&u.set("tgWebAppBotInline",c?"1":"0"),u.toString()}const Ae="telegram-mini-apps-launch-params";function ft(){const r=sessionStorage.getItem(Ae);return r?ce().parse(r):null}function gt(r){sessionStorage.setItem(Ae,qe(r))}function wt(){try{return window.self!==window.top}catch{return!0}}function _t(){const r=ft(),e=dt(),t=st();if(r){if(e)return{launchParams:e,isPageReload:wt()?t||r.initDataRaw===e.initDataRaw:!0};if(t)return{launchParams:r,isPageReload:t};throw new Error("Unable to retrieve current launch parameters, which must exist.")}if(e)return{launchParams:e,isPageReload:!1};throw new Error("Unable to retrieve any launch parameters.")}const Re="tmajsLaunchData";function ue(){const r=window[Re];if(r)return r;const e=_t();return window[Re]=e,gt(e.launchParams),e}function bt(){try{return ue(),!0}catch{return!1}}function mt(r){return"external"in r&&g(r.external)&&"notify"in r.external&&typeof r.external.notify=="function"}function yt(r){return"TelegramWebviewProxy"in r&&g(r.TelegramWebviewProxy)&&"postEvent"in r.TelegramWebviewProxy&&typeof r.TelegramWebviewProxy.postEvent=="function"}function he(){try{return window.self!==window.top}catch{return!0}}class Q extends Error{constructor(e,t){super(`Method "${e}" is unsupported in the Mini Apps version ${t}.`),Object.setPrototypeOf(this,Q.prototype)}}class Z extends Error{constructor(e,t,s){super(`Parameter "${t}" in method "${e}" is unsupported in the Mini Apps version ${s}.`),Object.setPrototypeOf(this,Z.prototype)}}class Ve{constructor(e,t){this.prefix=e,this.enabled=t}print(e,...t){if(!this.enabled)return;const s=new Date,n=Intl.DateTimeFormat("en-GB",{hour:"2-digit",minute:"2-digit",second:"2-digit",fractionalSecondDigits:3,timeZone:"UTC"}).format(s);console[e](`[${n}]`,this.prefix,...t)}disable(){this.enabled=!1}error(...e){this.print("error",...e)}enable(){this.enabled=!0}log(...e){this.print("log",...e)}warn(...e){this.print("warn",...e)}}let Te="https://web.telegram.org";const D=new Ve("[SDK]",!1);function Et(r){if(r){D.enable();return}D.disable()}function Ct(r){Te=r}function vt(){return Te}const Pt=w({eventType:h(),eventData:r=>r});function St(r,e){window.dispatchEvent(new MessageEvent("message",{data:JSON.stringify({eventType:r,eventData:e})}))}function kt(){const r=window;"TelegramGameProxy_receiveEvent"in r||[["TelegramGameProxy_receiveEvent"],["TelegramGameProxy","receiveEvent"],["Telegram","WebView","receiveEvent"]].forEach(e=>{let t=r;e.forEach((s,n,i)=>{if(n===i.length-1){t[s]=St;return}s in t||(t[s]={}),t=t[s]})})}function qt(r){kt(),window.addEventListener("message",e=>{try{const{eventType:t,eventData:s}=Pt.parse(e.data);r(t,s)}catch{}})}function At(){return w({req_id:h(),data:r=>r===null?r:h().optional().parse(r)})}function Rt(){return w({req_id:h(),result:r=>r,error:h().optional()})}function Vt(){return w({slug:h(),status:h()})}function Tt(){return w({status:h()})}function It(){return w({button_id:r=>r==null?void 0:h().parse(r)})}function Lt(){return w({data:h().optional()})}function Bt(){return w({theme_params:r=>{const e=ye().optional();return Object.entries(X(r)).reduce((t,[s,n])=>(t[s]=e.parse(n),t),{})}})}function $t(){return w({height:V(),width:r=>r==null?window.innerWidth:V().parse(r),is_state_stable:S(),is_expanded:S()})}function Dt(){return w({status:h()})}function xt(){const r=new b,e=(t,...s)=>{D.log("Emitting processed event:",t,...s),r.emit(t,...s)};return window.addEventListener("resize",()=>{e("viewport_changed",{width:window.innerWidth,height:window.innerHeight,is_state_stable:!0,is_expanded:!0})}),qt((t,s)=>{D.log("Received raw event:",t,s);try{switch(t){case"viewport_changed":return e(t,$t().parse(s));case"theme_changed":return e(t,Bt().parse(s));case"popup_closed":return s==null?e(t,{}):e(t,It().parse(s));case"set_custom_style":return e(t,h().parse(s));case"qr_text_received":return e(t,Lt().parse(s));case"clipboard_text_received":return e(t,At().parse(s));case"invoice_closed":return e(t,Vt().parse(s));case"phone_requested":return e("phone_requested",Tt().parse(s));case"custom_method_invoked":return e("custom_method_invoked",Rt().parse(s));case"write_access_requested":return e("write_access_requested",Dt().parse(s));case"main_button_pressed":case"back_button_pressed":case"settings_button_pressed":case"scan_qr_popup_closed":case"reload_iframe":return e(t);default:return e(t,s)}}catch(n){D.error("Error processing event:",n)}}),r}const pe="telegram-mini-apps-cached-emitter";function H(){const r=window;return r[pe]===void 0&&(r[pe]=xt()),r[pe]}function T(r,e){H().off(r,e)}function E(r,e){return H().on(r,e),()=>T(r,e)}function Nt(r,e){return H().once(r,e),()=>T(r,e)}function Ie(r){H().unsubscribe(r)}function Ot(r){return H().subscribe(r),()=>Ie(r)}function Le(r,e){const t=r.split("."),s=e.split("."),n=Math.max(t.length,s.length);for(let i=0;i<n;i+=1){const c=parseInt(t[i]||"0",10),u=parseInt(s[i]||"0",10);if(c!==u)return c>u?1:-1}return 0}function k(r,e){return Le(r,e)<=0}function I(r,e,t){if(typeof t=="string"){if(r==="web_app_open_link"&&e==="try_instant_view")return k("6.4",t);if(r==="web_app_set_header_color"&&e==="color")return k("6.9",t)}switch(r){case"web_app_open_tg_link":case"web_app_open_invoice":case"web_app_setup_back_button":case"web_app_set_background_color":case"web_app_set_header_color":case"web_app_trigger_haptic_feedback":return k("6.1",e);case"web_app_open_popup":return k("6.2",e);case"web_app_close_scan_qr_popup":case"web_app_open_scan_qr_popup":case"web_app_read_text_from_clipboard":return k("6.4",e);case"web_app_switch_inline_query":return k("6.7",e);case"web_app_invoke_custom_method":case"web_app_request_write_access":case"web_app_request_phone":return k("6.9",e);case"web_app_setup_settings_button":return k("6.10",e);default:return!0}}function v(r,e){return t=>I(e[t],r)}function Be(r,e){return t=>{const[s,n]=e[t];return I(s,n,r)}}function d(r,e,t){let s={},n;e===void 0&&t===void 0?s={}:e!==void 0&&t!==void 0?(s=t,n=e):e!==void 0&&("targetOrigin"in e?s=e:n=e);const{targetOrigin:i=vt()}=s;if(D.log(`Calling method "${r}"`,n),he()){window.parent.postMessage(JSON.stringify({eventType:r,eventData:n}),i);return}if(mt(window)){window.external.notify(JSON.stringify({eventType:r,eventData:n}));return}if(yt(window)){window.TelegramWebviewProxy.postEvent(r,JSON.stringify(n));return}throw new Error("Unable to determine current environment and possible way to send event.")}function $e(r){return(e,t)=>{if(!I(e,r))throw new Q(e,r);if(g(t)){let s;if(e==="web_app_open_link"&&"try_instant_view"in t?s="try_instant_view":e==="web_app_set_header_color"&&"color"in t&&(s="color"),s&&!I(e,s,r))throw new Z(e,s,r)}return d(e,t)}}class M extends Error{constructor(e){super(`Async call timeout exceeded. Timeout: ${e}`),Object.setPrototypeOf(this,M.prototype)}}function Wt(r){return r instanceof M}function Ht(r){return new Promise(e=>{setTimeout(e,r)})}function Mt(r){return new Promise((e,t)=>{setTimeout(t,r,new M(r))})}function le(r,e){return Promise.race([r(),Mt(e)])}function C(r,e,t,s){let n,i,c,u;typeof e=="string"||Array.isArray(e)?(c=Array.isArray(e)?e:[e],n=t):(i=e,c=Array.isArray(t)?t:[t],n=s),g(i)&&typeof i.req_id=="string"&&(u=i.req_id);const{postEvent:l=d,timeout:p}=n||{},_=n&&"capture"in n?n.capture:null,m=()=>new Promise((W,f)=>{const A=c.map(R=>E(R,Y=>{u&&(!g(Y)||Y.req_id!==u)||typeof _=="function"&&!_(Y)||(L(),W(Y))})),L=()=>A.forEach(R=>R());try{l(r,i)}catch(R){L(),f(R)}});return typeof p=="number"?le(m,p):m()}async function x(r,e,t,s={}){const{result:n,error:i}=await C("web_app_invoke_custom_method",{method:r,params:e,req_id:t},"custom_method_invoked",s);if(i)throw new Error(i);return n}class De{constructor(e,t,s=d){o(this,"ee",new b);o(this,"state");o(this,"on",(e,t)=>e==="click"?E("back_button_pressed",t):this.ee.on(e,t));o(this,"off",(e,t)=>e==="click"?T("back_button_pressed",t):this.ee.off(e,t));o(this,"supports");this.postEvent=s,this.state=new y({isVisible:e},this.ee),this.supports=v(t,{show:"web_app_setup_back_button",hide:"web_app_setup_back_button"})}set isVisible(e){this.state.set("isVisible",e),this.postEvent("web_app_setup_back_button",{is_visible:e})}get isVisible(){return this.state.get("isVisible")}hide(){this.isVisible=!1}show(){this.isVisible=!0}}function xe(r,e){return r+(r.length>0&&e.length>0?` ${e}`:e)}function Ne(...r){return r.reduce((e,t)=>{let s="";return typeof t=="string"?s=t:typeof t=="object"&&t!==null&&(s=Object.entries(t).reduce((n,[i,c])=>c?xe(n,i):n,"")),xe(e,s)},"")}function Ut(r){return typeof r=="object"&&r!==null&&!Array.isArray(null)}function jt(...r){return r.reduce((e,t)=>(Ut(t)&&Object.entries(t).forEach(([s,n])=>{const i=Ne(e[s],n);i.length>0&&(e[s]=i)}),e),{})}class Oe{constructor(e,t=d){o(this,"ee",new b);o(this,"state");o(this,"on",this.ee.on.bind(this.ee));o(this,"off",this.ee.off.bind(this.ee));this.postEvent=t,this.state=new y({isConfirmationNeeded:e},this.ee)}set isConfirmationNeeded(e){this.state.set("isConfirmationNeeded",e),this.postEvent("web_app_setup_closing_behavior",{need_confirmation:e})}get isConfirmationNeeded(){return this.state.get("isConfirmationNeeded")}disableConfirmation(){this.isConfirmationNeeded=!1}enableConfirmation(){this.isConfirmationNeeded=!0}}function We(r,e){return r.reduce((t,s)=>(t[s]=e,t),{})}class He{constructor(e,t,s=d){o(this,"supports");this.createRequestId=t,this.postEvent=s,this.supports=v(e,{delete:"web_app_invoke_custom_method",get:"web_app_invoke_custom_method",getKeys:"web_app_invoke_custom_method",set:"web_app_invoke_custom_method"})}async delete(e,t={}){const s=Array.isArray(e)?e:[e];s.length!==0&&await x("deleteStorageValues",{keys:s},this.createRequestId(),{...t,postEvent:this.postEvent})}async getKeys(e={}){const t=await x("getStorageKeys",{},this.createRequestId(),{...e,postEvent:this.postEvent});return ot().of(h()).parse(t)}async get(e,t={}){const s=Array.isArray(e)?e:[e];if(s.length===0)return We(s,"");const n=w(We(s,h())),i=await x("getStorageValues",{keys:s},this.createRequestId(),{...t,postEvent:this.postEvent}).then(c=>n.parse(c));return Array.isArray(e)?i:i[e]}async set(e,t,s={}){await x("saveStorageValue",{key:e,value:t},this.createRequestId(),{...s,postEvent:this.postEvent})}}class Me{constructor(e,t=d){o(this,"supports");this.postEvent=t,this.supports=v(e,{impactOccurred:"web_app_trigger_haptic_feedback",notificationOccurred:"web_app_trigger_haptic_feedback",selectionChanged:"web_app_trigger_haptic_feedback"})}impactOccurred(e){this.postEvent("web_app_trigger_haptic_feedback",{type:"impact",impact_style:e})}notificationOccurred(e){this.postEvent("web_app_trigger_haptic_feedback",{type:"notification",notification_type:e})}selectionChanged(){this.postEvent("web_app_trigger_haptic_feedback",{type:"selection_change"})}}function Gt(){const r=document.createElement("style");r.id="telegram-custom-styles",document.head.appendChild(r),E("set_custom_style",e=>{r.innerHTML=e})}function Ue(r){return`telegram-mini-apps-${r}`}function N(r,e){sessionStorage.setItem(Ue(r),JSON.stringify(e))}function O(r){const e=sessionStorage.getItem(Ue(r));return e?JSON.parse(e):null}function Ft(r,e,t){const{isVisible:s=!1}=r?O("back-button")||{}:{},n=new De(s,e,t);return n.on("change",()=>{N("back-button",{isVisible:n.isVisible})}),n}function zt(r,e){const{isConfirmationNeeded:t=!1}=r?O("closing-behavior")||{}:{},s=new Oe(t,e);return s.on("change",()=>N("closing-behavior",{isConfirmationNeeded:s.isConfirmationNeeded})),s}class je{constructor(e){o(this,"ee",new b);o(this,"state");o(this,"postEvent");o(this,"on",(e,t)=>e==="click"?E("main_button_pressed",t):this.ee.on(e,t));o(this,"off",(e,t)=>e==="click"?T("main_button_pressed",t):this.ee.off(e,t));const{postEvent:t=d,text:s,textColor:n,backgroundColor:i,isEnabled:c,isVisible:u,isLoaderVisible:l}=e;this.postEvent=t,this.state=new y({backgroundColor:i,isEnabled:c,isVisible:u,isLoaderVisible:l,text:s,textColor:n},this.ee)}commit(){this.text!==""&&this.postEvent("web_app_setup_main_button",{is_visible:this.isVisible,is_active:this.isEnabled,is_progress_visible:this.isLoaderVisible,text:this.text,color:this.backgroundColor,text_color:this.textColor})}set isEnabled(e){this.setParams({isEnabled:e})}get isEnabled(){return this.state.get("isEnabled")}set isLoaderVisible(e){this.setParams({isLoaderVisible:e})}get isLoaderVisible(){return this.state.get("isLoaderVisible")}set isVisible(e){this.setParams({isVisible:e})}get isVisible(){return this.state.get("isVisible")}get backgroundColor(){return this.state.get("backgroundColor")}get text(){return this.state.get("text")}get textColor(){return this.state.get("textColor")}disable(){return this.isEnabled=!1,this}enable(){return this.isEnabled=!0,this}hide(){return this.isVisible=!1,this}hideLoader(){return this.isLoaderVisible=!1,this}show(){return this.isVisible=!0,this}showLoader(){return this.isLoaderVisible=!0,this}setText(e){return this.setParams({text:e})}setTextColor(e){return this.setParams({textColor:e})}setBackgroundColor(e){return this.setParams({backgroundColor:e})}setParams(e){return this.state.set(e),this.commit(),this}}function Jt(r,e,t,s){const{backgroundColor:n=e,isEnabled:i=!1,isVisible:c=!1,isLoaderVisible:u=!1,textColor:l=t,text:p=""}=r?O("main-button")||{}:{},_=new je({backgroundColor:n,isEnabled:i,isLoaderVisible:u,isVisible:c,postEvent:s,text:p,textColor:l}),m=()=>N("main-button",{backgroundColor:_.backgroundColor,isEnabled:_.isEnabled,isLoaderVisible:_.isLoaderVisible,isVisible:_.isVisible,text:_.text,textColor:_.textColor});return _.on("change",m),_}const Qt=se({contact:w({userId:{type:V(),from:"user_id"},phoneNumber:{type:h(),from:"phone_number"},firstName:{type:h(),from:"first_name"},lastName:{type:h().optional(),from:"last_name"}}),authDate:{type:be(),from:"auth_date"},hash:h()});class Ge{constructor(e){o(this,"ee",new b);o(this,"state");o(this,"botInline");o(this,"postEvent");o(this,"createRequestId");o(this,"requestingPhoneAccess",!1);o(this,"requestingWriteAccess",!1);o(this,"on",this.ee.on.bind(this.ee));o(this,"off",this.ee.off.bind(this.ee));o(this,"supports");o(this,"supportsParam");const{postEvent:t=d,headerColor:s,backgroundColor:n,version:i,botInline:c,createRequestId:u}=e,l=v(i,{requestPhoneAccess:"web_app_request_phone",requestWriteAccess:"web_app_request_write_access",switchInlineQuery:"web_app_switch_inline_query",setHeaderColor:"web_app_set_header_color",setBackgroundColor:"web_app_set_background_color"});this.postEvent=t,this.botInline=c,this.createRequestId=u,this.supports=p=>!(!l(p)||p==="switchInlineQuery"&&!c),this.state=new y({backgroundColor:n,headerColor:s},this.ee),this.supportsParam=Be(i,{"setHeaderColor.color":["web_app_set_header_color","color"]})}async getRequestedContact(){return x("getRequestedContact",{},this.createRequestId(),{postEvent:this.postEvent,timeout:1e4}).then(e=>Qt.parse(e))}get backgroundColor(){return this.state.get("backgroundColor")}close(){this.postEvent("web_app_close")}get headerColor(){return this.state.get("headerColor")}get isBotInline(){return this.botInline}get isDark(){return re(this.backgroundColor)}get isRequestingPhoneAccess(){return this.requestingPhoneAccess}get isRequestingWriteAccess(){return this.requestingWriteAccess}ready(){this.postEvent("web_app_ready")}async requestContact({timeout:e=5e3}={}){try{return await this.getRequestedContact()}catch{}if(await this.requestPhoneAccess()!=="sent")throw new Error("Access denied.");const s=Date.now()+e;let n=50;return le(async()=>{for(;Date.now()<s;){try{return await this.getRequestedContact()}catch{}await Ht(n),n+=50}throw new Error("Unable to retrieve requested contact.")},e)}requestPhoneAccess(e={}){if(this.requestingPhoneAccess)throw new Error("Phone access is already being requested.");return this.requestingPhoneAccess=!0,C("web_app_request_phone","phone_requested",{...e,postEvent:this.postEvent}).then(t=>t.status).finally(()=>{this.requestingPhoneAccess=!1})}requestWriteAccess(e={}){if(this.requestingWriteAccess)throw new Error("Write access is already being requested.");return this.requestingWriteAccess=!0,C("web_app_request_write_access","write_access_requested",{...e,postEvent:this.postEvent}).then(t=>t.status).finally(()=>{this.requestingWriteAccess=!1})}sendData(e){const{size:t}=new Blob([e]);if(t===0||t>4096)throw new Error(`Passed data has incorrect size: ${t}`);this.postEvent("web_app_data_send",{data:e})}setHeaderColor(e){this.postEvent("web_app_set_header_color",ee(e)?{color:e}:{color_key:e}),this.state.set("headerColor",e)}setBackgroundColor(e){this.postEvent("web_app_set_background_color",{color:e}),this.state.set("backgroundColor",e)}switchInlineQuery(e,t=[]){if(!this.supports("switchInlineQuery")&&!this.isBotInline)throw new Error("Method is unsupported because Mini App should be launched in inline mode.");this.postEvent("web_app_switch_inline_query",{query:e,chat_types:t})}}function Zt(r,e,t,s,n,i){const{backgroundColor:c=e,headerColor:u="bg_color"}=r?O("mini-app")||{}:{},l=new Ge({headerColor:u,backgroundColor:c,version:t,botInline:s,createRequestId:n,postEvent:i}),p=()=>N("mini-app",{backgroundColor:l.backgroundColor,headerColor:l.headerColor});return l.on("change",p),l}function Kt(){let r=0;return()=>(r+=1,r.toString())}class Fe{constructor(e,t,s=d){o(this,"ee",new b);o(this,"state");o(this,"on",(e,t)=>e==="click"?E("settings_button_pressed",t):this.ee.on(e,t));o(this,"off",(e,t)=>e==="click"?T("settings_button_pressed",t):this.ee.off(e,t));o(this,"supports");this.postEvent=s,this.state=new y({isVisible:e},this.ee),this.supports=v(t,{show:"web_app_setup_settings_button",hide:"web_app_setup_settings_button"})}set isVisible(e){this.state.set("isVisible",e),this.postEvent("web_app_setup_settings_button",{is_visible:e})}get isVisible(){return this.state.get("isVisible")}hide(){this.isVisible=!1}show(){this.isVisible=!0}}function Yt(r,e,t){const{isVisible:s=!1}=r?O("settings-button")||{}:{},n=new Fe(s,e,t);return n.on("change",()=>{N("settings-button",{isVisible:n.isVisible})}),n}function Xt(r){const e=new Pe(r);return e.listen(),e}function ze(r){return["macos","tdesktop","unigram","web","weba"].includes(r)}async function de(r){const e=await C("web_app_request_viewport","viewport_changed",r);return{height:e.height,width:e.width,isExpanded:e.is_expanded,isStateStable:e.is_state_stable}}function U(r){return r<0?0:r}class Je{constructor(e){o(this,"ee",new b);o(this,"state");o(this,"postEvent");o(this,"on",this.ee.on.bind(this.ee));o(this,"off",this.ee.off.bind(this.ee));const{height:t,isExpanded:s,width:n,stableHeight:i,postEvent:c=d}=e;this.postEvent=c,this.state=new y({height:U(t),isExpanded:s,stableHeight:U(i),width:U(n)},this.ee)}sync(e){return de(e).then(({height:t,isExpanded:s,width:n,isStateStable:i})=>{this.state.set({height:t,width:n,isExpanded:s,stableHeight:i?t:this.state.get("stableHeight")})})}get height(){return this.state.get("height")}get stableHeight(){return this.state.get("stableHeight")}listen(){return E("viewport_changed",e=>{const{height:t,width:s,is_expanded:n,is_state_stable:i}=e,c={height:U(t),isExpanded:n,width:U(s)};i&&(c.stableHeight=c.height),this.state.set(c)})}get isExpanded(){return this.state.get("isExpanded")}get width(){return this.state.get("width")}expand(){this.postEvent("web_app_expand"),this.state.set("isExpanded",!0)}get isStable(){return this.stableHeight===this.height}}function K(r){const e=new Je(r);return e.on("change",()=>N("viewport",{height:e.height,isExpanded:e.isExpanded,stableHeight:e.stableHeight,width:e.width})),e.listen(),e}function er(r,e,t,s){const n=r?O("viewport"):null;if(n)return K({...n,postEvent:t});if(ze(e))return K({height:window.innerHeight,isExpanded:!0,postEvent:t,stableHeight:window.innerHeight,width:window.innerWidth});if(s)return de({postEvent:t,timeout:5e3}).then(({height:c,isStateStable:u,...l})=>K({...l,height:c,stableHeight:u?c:0}));const i=K({width:0,height:0,isExpanded:!1,postEvent:t,stableHeight:0});return i.sync({postEvent:t,timeout:5e3}).catch(c=>{console.error("Unable to actualize viewport state",c)}),i}function q(r,e){document.documentElement.style.setProperty(r,e)}function tr(r,e){const t=()=>{q("--tg-background-color",r.backgroundColor)},s=()=>{const{backgroundColor:n,secondaryBackgroundColor:i}=e;r.headerColor==="bg_color"?n&&q("--tg-header-color",n):r.headerColor==="secondary_bg_color"?i&&q("--tg-header-color",i):q("--tg-header-color",r.headerColor)};e.on("change",s),r.on("change:backgroundColor",t),r.on("change:headerColor",s),t(),s()}function rr(r){const e=()=>{const t=r.getState();Object.entries(t).forEach(([s,n])=>{if(n){const i=s.replace(/[A-Z]/g,c=>`-${c.toLowerCase()}`);q(`--tg-theme-${i}`,n)}})};r.on("change",e),e()}function Qe(r){const e=()=>q("--tg-viewport-height",`${r.height}px`),t=()=>q("--tg-viewport-width",`${r.width}px`),s=()=>q("--tg-viewport-height",`${r.stableHeight}px`);r.on("change:height",e),r.on("change:width",t),r.on("change:stableHeight",s),e(),t(),s()}function sr(r){return typeof r=="object"?r:r?{themeParams:!0,viewport:!0,miniApp:!0}:{}}function Ze(r,e,t,s){const n=sr(r);n.miniApp&&tr(e,t),n.themeParams&&rr(t),n.viewport&&(s instanceof Promise?s.then(Qe):Qe(s))}function nr(r){const{hostname:e,pathname:t}=new URL(r,window.location.href);if(e!=="t.me")throw new Error(`Incorrect hostname: ${e}`);const s=t.match(/^\/(\$|invoice\/)([A-Za-z0-9\-_=]+)$/);if(s===null)throw new Error('Link pathname has incorrect format. Expected to receive "/invoice/{slug}" or "/${slug}"');return s[2]}class Ke{constructor(e,t=d){o(this,"ee",new b);o(this,"state");o(this,"on",this.ee.on.bind(this.ee));o(this,"off",this.ee.off.bind(this.ee));o(this,"supports");this.postEvent=t,this.state=new y({isOpened:!1},this.ee),this.supports=v(e,{open:"web_app_open_invoice"})}set isOpened(e){this.state.set("isOpened",e)}get isOpened(){return this.state.get("isOpened")}async open(e,t){if(this.isOpened)throw new Error("Invoice is already opened");const s=t?nr(e):e;this.isOpened=!0;try{return(await C("web_app_open_invoice",{slug:s},"invoice_closed",{postEvent:this.postEvent,capture(i){return s===i.slug}})).status}finally{this.isOpened=!1}}}function ir(r){const e=r.message.trim(),t=(r.title||"").trim(),s=r.buttons||[];let n;if(t.length>64)throw new Error(`Title has incorrect size: ${t.length}`);if(e.length===0||e.length>256)throw new Error(`Message has incorrect size: ${e.length}`);if(s.length>3)throw new Error(`Buttons have incorrect size: ${s.length}`);return s.length===0?n=[{type:"close",id:""}]:n=s.map(i=>{const{id:c=""}=i;if(c.length>64)throw new Error(`Button ID has incorrect size: ${c}`);if(i.type===void 0||i.type==="default"||i.type==="destructive"){const u=i.text.trim();if(u.length===0||u.length>64){const l=i.type||"default";throw new Error(`Button text with type "${l}" has incorrect size: ${i.text.length}`)}return{...i,text:u,id:c}}return{...i,id:c}}),{title:t,message:e,buttons:n}}class Ye{constructor(e,t=d){o(this,"ee",new b);o(this,"state");o(this,"on",this.ee.on.bind(this.ee));o(this,"off",this.ee.off.bind(this.ee));o(this,"supports");this.postEvent=t,this.state=new y({isOpened:!1},this.ee),this.supports=v(e,{open:"web_app_open_popup"})}set isOpened(e){this.state.set("isOpened",e)}get isOpened(){return this.state.get("isOpened")}open(e){if(this.isOpened)throw new Error("Popup is already opened.");return this.isOpened=!0,C("web_app_open_popup",ir(e),"popup_closed",{postEvent:this.postEvent}).then(({button_id:t=null})=>t).finally(()=>{this.isOpened=!1})}}class Xe{constructor(e,t=d){o(this,"ee",new b);o(this,"state");o(this,"on",this.ee.on.bind(this.ee));o(this,"off",this.ee.off.bind(this.ee));o(this,"supports");this.postEvent=t,this.state=new y({isOpened:!1},this.ee),this.supports=v(e,{close:"web_app_close_scan_qr_popup",open:"web_app_open_scan_qr_popup"})}close(){this.postEvent("web_app_close_scan_qr_popup"),this.isOpened=!1}set isOpened(e){this.state.set("isOpened",e)}get isOpened(){return this.state.get("isOpened")}async open(e){if(this.isOpened)throw new Error("QR scanner is already opened.");this.isOpened=!0;try{const t=await C("web_app_open_scan_qr_popup",{text:e},["qr_text_received","scan_qr_popup_closed"],{postEvent:this.postEvent});return typeof t=="object"&&typeof t.data=="string"?t.data:null}finally{this.isOpened=!1}}}class et{constructor(e,t,s=d){o(this,"supports");o(this,"supportsParam");this.version=e,this.createRequestId=t,this.postEvent=s,this.supports=v(e,{readTextFromClipboard:"web_app_read_text_from_clipboard"}),this.supportsParam=Be(e,{"openLink.tryInstantView":["web_app_open_link","try_instant_view"]})}openLink(e,t){const s=new URL(e,window.location.href).toString();if(!I("web_app_open_link",this.version)){window.open(s,"_blank");return}this.postEvent("web_app_open_link",{url:s,...typeof t=="boolean"?{try_instant_view:t}:{}})}openTelegramLink(e){const{hostname:t,pathname:s,search:n}=new URL(e,window.location.href);if(t!=="t.me")throw new Error(`URL has not allowed hostname: ${t}. Only "t.me" is allowed`);if(!I("web_app_open_tg_link",this.version)){window.location.href=e;return}this.postEvent("web_app_open_tg_link",{path_full:s+n})}readTextFromClipboard(){return C("web_app_read_text_from_clipboard",{req_id:this.createRequestId()},"clipboard_text_received",{postEvent:this.postEvent}).then(({data:e=null})=>e)}}function or(r={}){const{async:e=!1,complete:t=e,cssVars:s=!1,acceptCustomStyles:n=!1}=r;try{const{launchParams:{initData:i,initDataRaw:c,version:u,platform:l,themeParams:p,botInline:_=!1},isPageReload:m}=ue(),W=Kt(),f=$e(u);he()&&(n&&Gt(),f("iframe_ready",{reload_supported:!0}),E("reload_iframe",()=>window.location.reload()));const A={backButton:Ft(m,u,f),closingBehavior:zt(m,f),cloudStorage:new He(u,W,f),createRequestId:W,hapticFeedback:new Me(u,f),invoice:new Ke(u,f),mainButton:Jt(m,p.buttonColor||"#000000",p.buttonTextColor||"#ffffff",f),miniApp:Zt(m,p.backgroundColor||"#ffffff",u,_,W,f),popup:new Ye(u,f),postEvent:f,qrScanner:new Xe(u,f),settingsButton:Yt(m,u,f),themeParams:Xt(p),utils:new et(u,W,f),...i?{initData:new Ce(i),initDataRaw:c}:{}},L=er(m,l,f,t);return L instanceof Promise||t?Promise.resolve(L).then(R=>(Ze(s,A.miniApp,A.themeParams,R),{...A,viewport:R})):(Ze(s,A.miniApp,A.themeParams,L),{...A,viewport:L})}catch(i){if(t)return Promise.reject(i);throw i}}function j(r,e){return r.startsWith(e)?r:`${e}${r}`}function ar(r){const e=r.match(/#(.+)/);return e?e[1]:null}async function G(r){return r===0?!0:Promise.race([new Promise(e=>{window.addEventListener("popstate",function t(){window.removeEventListener("popstate",t),e(!0)}),window.history.go(r)}),new Promise(e=>{setTimeout(e,50,!1)})])}async function cr(){if(window.history.length<=1||(window.history.pushState(null,""),await G(1-window.history.length)))return;let e=await G(-1);for(;e;)e=await G(-1)}class tt{constructor(e,t,{debug:s=!1,loggerPrefix:n="Navigator"}){o(this,"logger");o(this,"entries");if(this.entriesCursor=t,e.length===0)throw new Error("Entries list should not be empty.");if(t>=e.length)throw new Error("Cursor should be less than entries count.");this.entries=e.map(({pathname:i="",search:c,hash:u})=>{if(!i.startsWith("/")&&i.length>0)throw new Error('Pathname should start with "/"');return{pathname:j(i,"/"),search:c?j(c,"?"):"",hash:u?j(u,"#"):""}}),this.logger=new Ve(`[${n}]`,s)}formatEntry(e){let t;if(typeof e=="string")t=e;else{const{pathname:c="",search:u,hash:l}=e;t=c+(u?j(u,"?"):"")+(l?j(l,"#"):"")}const{pathname:s,search:n,hash:i}=new URL(t,`https://localhost${this.path}`);return{pathname:s,search:n,hash:i}}get entry(){return this.entries[this.entriesCursor]}back(){return this.go(-1)}get cursor(){return this.entriesCursor}get canGoBack(){return this.entriesCursor>0}get canGoForward(){return this.entriesCursor!==this.entries.length-1}forward(){return this.go(1)}go(e){this.logger.log(`called go(${e})`);const t=Math.min(this.entries.length-1,Math.max(this.entriesCursor+e,0));if(this.entriesCursor===t)return this.performGo({updated:!1,delta:e});const s=this.entry;this.entriesCursor=t;const n=this.entry;return this.logger.log("State changed",{before:s,after:n}),this.performGo({updated:!0,delta:e,before:s,after:n})}getEntries(){return this.entries.map(e=>({...e}))}get hash(){return this.entry.hash}push(e){this.entriesCursor!==this.entries.length-1&&this.entries.splice(this.entriesCursor+1);const t=this.formatEntry(e),s=this.entry;this.entriesCursor+=1,this.entries[this.entriesCursor]=t;const n=this.entry;return this.logger.log("State changed",{before:s,after:n}),this.performPush({before:s,after:n})}get path(){return`${this.pathname}${this.search}${this.hash}`}get pathname(){return this.entry.pathname}replace(e){const t=this.formatEntry(e);if(this.search===t.search&&this.pathname===t.pathname&&this.hash===t.hash)return this.performReplace({updated:!1,entry:t});const s=this.entry;this.entries[this.entriesCursor]=t;const n=this.entry;return this.logger.log("State changed",{before:s,after:n}),this.performReplace({updated:!0,before:s,after:n})}get search(){return this.entry.search}}const rt=0,fe=1,ge=2;class we extends tt{constructor(t,s,n={}){super(t,s,{...n,loggerPrefix:"HashNavigator"});o(this,"ee",new b);o(this,"attached",!1);o(this,"onPopState",async({state:t})=>{if(this.logger.log('"popstate" event received. State:',t),t===null)return this.push(window.location.hash.slice(1));if(t===rt){this.logger.log("Void reached. Moving history forward"),window.history.forward();return}if(t===fe)return this.back();if(t===ge)return this.forward()});o(this,"back",()=>super.back());o(this,"on",this.ee.on.bind(this.ee));o(this,"off",this.ee.off.bind(this.ee))}static fromLocation(t){const{search:s,pathname:n,hash:i}=new URL(window.location.hash.slice(1),window.location.href);return new we([{search:s,pathname:n,hash:i}],0,t)}async performGo(t){t.updated&&(this.attached&&await this.syncHistory(),this.emitChanged(t.before,t.after))}async performPush({before:t,after:s}){this.attached&&await this.syncHistory(),this.emitChanged(t,s)}async performReplace(t){t.updated&&(this.attached&&window.history.replaceState(null,"",`#${this.path}`),this.emitChanged(t.before,t.after))}async syncHistory(){window.removeEventListener("popstate",this.onPopState);const t=`#${this.path}`;await cr(),d("web_app_setup_back_button",{is_visible:this.canGoBack}),this.canGoBack&&this.canGoForward?(this.logger.log("Setting up history: [<-, *, ->]"),window.history.replaceState(fe,""),window.history.pushState(null,"",t),window.history.pushState(ge,""),await G(-1)):this.canGoBack?(this.logger.log("Setting up history: [<-, *]"),window.history.replaceState(fe,""),window.history.pushState(null,"",t)):this.canGoForward?(this.logger.log("Setting up history: [*, ->]"),window.history.replaceState(null,t),window.history.pushState(ge,""),await G(-1)):(this.logger.log("Setting up history: [~, *]"),window.history.replaceState(rt,""),window.history.pushState(null,"",t)),window.addEventListener("popstate",this.onPopState)}emitChanged(t,s){this.ee.emit("change",{navigator:this,from:t,to:s})}async attach(){if(!this.attached)return this.logger.log("Attaching",this),this.attached=!0,E("back_button_pressed",this.back),this.syncHistory()}detach(){this.attached&&(this.logger.log("Detaching",this),this.attached=!1,window.removeEventListener("popstate",this.onPopState),T("back_button_pressed",this.back))}}return a.BackButton=De,a.ClosingBehavior=Oe,a.CloudStorage=He,a.HapticFeedback=Me,a.HashNavigator=we,a.InitData=Ce,a.Invoice=Ke,a.MainButton=je,a.MethodUnsupportedError=Q,a.MiniApp=Ge,a.Navigator=tt,a.ParameterUnsupportedError=Z,a.Popup=Ye,a.QRScanner=Xe,a.SettingsButton=Fe,a.ThemeParams=Pe,a.TimeoutError=M,a.Utils=et,a.Viewport=Je,a.chatParser=Ee,a.classNames=Ne,a.compareVersions=Le,a.createPostEvent=$e,a.getHash=ar,a.init=or,a.initDataParser=ie,a.invokeCustomMethod=x,a.isColorDark=re,a.isIframe=he,a.isRGB=ee,a.isRGBShort=me,a.isRecord=g,a.isStableViewportPlatform=ze,a.isTMA=bt,a.isTimeoutError=Wt,a.launchParamsParser=ce,a.mergeClassNames=jt,a.off=T,a.on=E,a.once=Nt,a.parseInitData=at,a.parseLaunchParams=Se,a.parseThemeParams=ae,a.postEvent=d,a.request=C,a.requestThemeParams=ht,a.requestViewport=de,a.retrieveLaunchData=ue,a.serializeLaunchParams=qe,a.serializeThemeParams=ve,a.setDebug=Et,a.setTargetOrigin=Ct,a.subscribe=Ot,a.supports=I,a.themeParamsParser=oe,a.toRGB=te,a.unsubscribe=Ie,a.userParser=ne,a.withTimeout=le,Object.defineProperty(a,Symbol.toStringTag,{value:"Module"}),a}({});
2
2
  //# sourceMappingURL=index.iife.js.map