@tma.js/sdk 2.6.0 → 2.7.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.
- package/dist/dts/bridge/{utils/invokeCustomMethod.d.ts → invokeCustomMethod.d.ts} +2 -2
- package/dist/dts/bridge/methods/createPostEvent.d.ts +3 -2
- package/dist/dts/bridge/methods/postEvent.d.ts +5 -3
- package/dist/dts/bridge/request.d.ts +53 -0
- package/dist/dts/bridge/target-origin.d.ts +8 -3
- package/dist/dts/components/MiniApp/MiniApp.d.ts +3 -2
- package/dist/dts/components/QRScanner/QRScanner.d.ts +6 -8
- package/dist/dts/components/QRScanner/types.d.ts +2 -2
- package/dist/dts/components/Utils/Utils.d.ts +27 -4
- package/dist/dts/env/hasWebviewProxy.d.ts +1 -1
- package/dist/dts/index.d.ts +4 -4
- package/dist/dts/index.low-level.d.ts +3 -3
- package/dist/dts/misc/createCleanup.d.ts +2 -2
- package/dist/index.cjs +3 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.iife.js +3 -1
- package/dist/index.iife.js.map +1 -1
- package/dist/index.js +505 -519
- package/dist/index.js.map +1 -1
- package/dist/index.low-level.iife.js +3 -1
- package/dist/index.low-level.iife.js.map +1 -1
- package/package.json +1 -1
- package/dist/dts/bridge/utils/request.d.ts +0 -47
- /package/dist/dts/bridge/{utils/captureSameReq.d.ts → captureSameReq.d.ts} +0 -0
package/dist/index.iife.js
CHANGED
|
@@ -1,2 +1,4 @@
|
|
|
1
|
-
var Cn=Object.defineProperty;var An=(o,w,v)=>w in o?Cn(o,w,{enumerable:!0,configurable:!0,writable:!0,value:v}):o[w]=v;var h=(o,w,v)=>An(o,typeof w!="symbol"?w+"":w,v);this.tmajs=this.tmajs||{};this.tmajs.sdk=function(o){"use strict";function w(e,t){let n;const s=()=>{n!==void 0&&t&&t(n),n=void 0};return[()=>n===void 0?n=e(s):n,s]}function v(e){const t=W(),{count:n}=t;t.unsubscribe(e),n&&!t.count&&De()}function yt(e){return W().subscribe(e),()=>v(e)}class Se{constructor(t,n={}){this.scope=t,this.options=n}print(t,...n){const s=new Date,i=Intl.DateTimeFormat("en-GB",{hour:"2-digit",minute:"2-digit",second:"2-digit",fractionalSecondDigits:3,timeZone:"UTC"}).format(s),{textColor:r,bgColor:a}=this.options,c="font-weight: bold;padding: 0 5px;border-radius:5px";console[t](`%c${i}%c / %c${this.scope}`,`${c};background-color: lightblue;color:black`,"",`${c};${r?`color:${r};`:""}${a?`background-color:${a}`:""}`,...n)}error(...t){this.print("error",...t)}log(...t){this.print("log",...t)}}const j=new Se("SDK",{bgColor:"forestgreen",textColor:"white"});let z=!1;const Et=({name:e,payload:t})=>{j.log("Event received:",t?{name:e,payload:t}:{name:e})};function Pe(e){z!==e&&(z=e,e?yt(Et):v(Et))}function Re(...e){z&&j.log(...e)}class R{constructor(){h(this,"listeners",new Map);h(this,"listenersCount",0);h(this,"subscribeListeners",[])}clear(){this.listeners.clear(),this.subscribeListeners=[]}get count(){return this.listenersCount+this.subscribeListeners.length}emit(t,...n){this.subscribeListeners.forEach(i=>i({event:t,args:n})),(this.listeners.get(t)||[]).forEach(([i,r])=>{i(...n),r&&this.off(t,i)})}on(t,n,s){let i=this.listeners.get(t);return i||this.listeners.set(t,i=[]),i.push([n,s]),this.listenersCount+=1,()=>this.off(t,n)}off(t,n){const s=this.listeners.get(t)||[];for(let i=0;i<s.length;i+=1)if(n===s[i][0]){s.splice(i,1),this.listenersCount-=1;return}}subscribe(t){return this.subscribeListeners.push(t),()=>this.unsubscribe(t)}unsubscribe(t){for(let n=0;n<this.subscribeListeners.length;n+=1)if(this.subscribeListeners[n]===t){this.subscribeListeners.splice(n,1);return}}}function F(e,t,n){return window.addEventListener(e,t,n),()=>window.removeEventListener(e,t,n)}function J(...e){let t=!1;const n=[...e];return[s=>!t&&n.push(s),()=>{t||(t=!0,n.forEach(s=>s()))},t]}class N extends Error{constructor(t,n,s){super(n,{cause:s}),this.type=t,Object.setPrototypeOf(this,N.prototype)}}function g(e,t,n){return new N(e,t,n)}const vt="ERR_METHOD_UNSUPPORTED",St="ERR_METHOD_PARAMETER_UNSUPPORTED",Pt="ERR_UNKNOWN_ENV",Rt="ERR_INVOKE_CUSTOM_METHOD_RESPONSE",Tt="ERR_TIMED_OUT",Ct="ERR_UNEXPECTED_TYPE",Q="ERR_PARSE",At="ERR_NAVIGATION_LIST_EMPTY",It="ERR_NAVIGATION_CURSOR_INVALID",Te="ERR_NAVIGATION_ITEM_INVALID",Ce="ERR_SSR_INIT",Nt="ERR_INVALID_PATH_BASE";function T(){return g(Ct,"Value has unexpected type")}class U{constructor(t,n,s){this.parser=t,this.isOptional=n,this.type=s}parse(t){if(!(this.isOptional&&t===void 0))try{return this.parser(t)}catch(n){throw g(Q,`Unable to parse value${this.type?` as ${this.type}`:""}`,n)}}optional(){return this.isOptional=!0,this}}function C(e,t){return()=>new U(e,!1,t)}const y=C(e=>{if(typeof e=="boolean")return e;const t=String(e);if(t==="1"||t==="true")return!0;if(t==="0"||t==="false")return!1;throw T()},"boolean");function qt(e,t){const n={};for(const s in e){const i=e[s];if(!i)continue;let r,a;if(typeof i=="function"||"parse"in i)r=s,a=typeof i=="function"?i:i.parse.bind(i);else{const{type:c}=i;r=i.from||s,a=typeof c=="function"?c:c.parse.bind(c)}try{const c=a(t(r));c!==void 0&&(n[s]=c)}catch(c){throw g(Q,`Unable to parse field "${s}"`,c)}}return n}function Y(e){let t=e;if(typeof t=="string"&&(t=JSON.parse(t)),typeof t!="object"||t===null||Array.isArray(t))throw T();return t}function d(e,t){return new U(n=>{const s=Y(n);return qt(e,i=>s[i])},!1,t)}const S=C(e=>{if(typeof e=="number")return e;if(typeof e=="string"){const t=Number(e);if(!Number.isNaN(t))return t}throw T()},"number");function $(e){return/^#[\da-f]{6}$/i.test(e)}function kt(e){return/^#[\da-f]{3}$/i.test(e)}function K(e){const t=e.replace(/\s/g,"").toLowerCase();if($(t))return t;if(kt(t)){let s="#";for(let i=0;i<3;i+=1)s+=t[1+i].repeat(2);return s}const n=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(!n)throw new Error(`Value "${e}" does not satisfy any of known RGB formats.`);return n.slice(1).reduce((s,i)=>{const r=parseInt(i,10).toString(16);return s+(r.length===1?"0":"")+r},"#")}const u=C(e=>{if(typeof e=="string"||typeof e=="number")return e.toString();throw T()},"string"),X=C(e=>K(u().parse(e)),"rgb");function Dt(e){return d({eventType:u(),eventData:t=>t}).parse(e)}function Ae(){["TelegramGameProxy_receiveEvent","TelegramGameProxy","Telegram"].forEach(e=>{delete window[e]})}function Z(e,t){window.dispatchEvent(new MessageEvent("message",{data:JSON.stringify({eventType:e,eventData:t}),source:window.parent}))}function Ie(){[["TelegramGameProxy_receiveEvent"],["TelegramGameProxy","receiveEvent"],["Telegram","WebView","receiveEvent"]].forEach(e=>{let t=window;e.forEach((n,s,i)=>{if(s===i.length-1){t[n]=Z;return}n in t||(t[n]={}),t=t[n]})})}const Ne={clipboard_text_received:d({req_id:u(),data:e=>e===null?e:u().optional().parse(e)}),custom_method_invoked:d({req_id:u(),result:e=>e,error:u().optional()}),invoice_closed:d({slug:u(),status:u()}),phone_requested:d({status:u()}),popup_closed:{parse(e){return d({button_id:t=>t==null?void 0:u().parse(t)}).parse(e??{})}},qr_text_received:d({data:u().optional()}),theme_changed:d({theme_params:e=>{const t=X().optional();return Object.entries(Y(e)).reduce((n,[s,i])=>(n[s]=t.parse(i),n),{})}}),viewport_changed:d({height:S(),width:e=>e==null?window.innerWidth:S().parse(e),is_state_stable:y(),is_expanded:y()}),write_access_requested:d({status:u()})};function qe(){const e=new R,t=new R;t.subscribe(s=>{e.emit("event",{name:s.event,payload:s.args[0]})}),Ie();const[,n]=J(Ae,F("resize",()=>{t.emit("viewport_changed",{width:window.innerWidth,height:window.innerHeight,is_state_stable:!0,is_expanded:!0})}),F("message",s=>{if(s.source!==window.parent)return;let i;try{i=Dt(s.data)}catch{return}const{eventType:r,eventData:a}=i,c=Ne[r];try{const p=c?c.parse(a):a;t.emit(...p?[r,p]:[r])}catch(p){j.error(`An error occurred processing the "${r}" event from the Telegram application. Please, file an issue here: https://github.com/Telegram-Mini-Apps/tma.js/issues/new/choose`,i,p)}}),()=>e.clear(),()=>t.clear());return[{on:t.on.bind(t),off:t.off.bind(t),subscribe(s){return e.on("event",s)},unsubscribe(s){e.off("event",s)},get count(){return t.count+e.count}},n]}const[ke,De]=w(e=>{const[t,n]=qe(),s=t.off.bind(t);return t.off=(i,r)=>{const{count:a}=t;s(i,r),a&&!t.count&&e()},[t,n]},([,e])=>e());function W(){return ke()[0]}function q(e,t){W().off(e,t)}function m(e,t,n){return W().on(e,t,n)}function k(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Mt(e,t){const n=e.split("."),s=t.split("."),i=Math.max(n.length,s.length);for(let r=0;r<i;r+=1){const a=parseInt(n[r]||"0",10),c=parseInt(s[r]||"0",10);if(a!==c)return a>c?1:-1}return 0}function b(e,t){return Mt(e,t)<=0}function P(e,t,n){if(typeof n=="string"){if(e==="web_app_open_link"){if(t==="try_instant_view")return b("6.4",n);if(t==="try_browser")return b("7.6",n)}if(e==="web_app_set_header_color"&&t==="color")return b("6.9",n);if(e==="web_app_close"&&t==="return_back")return b("7.6",n)}switch(e){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 b("6.1",t);case"web_app_open_popup":return b("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 b("6.4",t);case"web_app_switch_inline_query":return b("6.7",t);case"web_app_invoke_custom_method":case"web_app_request_write_access":case"web_app_request_phone":return b("6.9",t);case"web_app_setup_settings_button":return b("6.10",t);case"web_app_biometry_get_info":case"web_app_biometry_open_settings":case"web_app_biometry_request_access":case"web_app_biometry_request_auth":case"web_app_biometry_update_token":return b("7.2",t);default:return["iframe_ready","iframe_will_reload","web_app_close","web_app_data_send","web_app_expand","web_app_open_link","web_app_ready","web_app_request_theme","web_app_request_viewport","web_app_setup_main_button","web_app_setup_closing_behavior"].includes(e)}}function Vt(e){return"external"in e&&k(e.external)&&"notify"in e.external&&typeof e.external.notify=="function"}function Bt(e){return"TelegramWebviewProxy"in e&&k(e.TelegramWebviewProxy)&&"postEvent"in e.TelegramWebviewProxy&&typeof e.TelegramWebviewProxy.postEvent=="function"}function tt(){try{return window.self!==window.top}catch{return!0}}let Lt="https://web.telegram.org";function Me(e){Lt=e}function Ot(){return Lt}function A(e,t,n){let s={},i;t===void 0&&n===void 0?s={}:t!==void 0&&n!==void 0?(s=n,i=t):t!==void 0&&("targetOrigin"in t?s=t:i=t);const{targetOrigin:r=Ot()}=s;if(Re("Posting event:",i?{event:e,data:i}:{event:e}),tt()){window.parent.postMessage(JSON.stringify({eventType:e,eventData:i}),r);return}if(Vt(window)){window.external.notify(JSON.stringify({eventType:e,eventData:i}));return}if(Bt(window)){window.TelegramWebviewProxy.postEvent(e,JSON.stringify(i));return}throw g(Pt,"Unable to determine current environment and possible way to send event. You are probably trying to use Mini Apps method outside of Telegram application environment.")}function Ut(e){return(t,n)=>{if(!P(t,e))throw g(vt,`Method "${t}" is unsupported in Mini Apps version ${e}`);if(k(n)){let s;if(t==="web_app_open_link"&&"try_instant_view"in n?s="try_instant_view":t==="web_app_set_header_color"&&"color"in n&&(s="color"),s&&!P(t,s,e))throw g(St,`Parameter "${s}" of "${t}" method is unsupported in Mini Apps version ${e}`)}return A(t,n)}}function et(e){return({req_id:t})=>t===e}function $t(e){return g(Tt,`Timeout reached: ${e}ms`)}function nt(e,t){return Promise.race([typeof e=="function"?e():e,new Promise((n,s)=>{setTimeout(()=>{s($t(t))},t)})])}async function _(e){let t;const n=new Promise(c=>{t=c}),{event:s,capture:i,timeout:r}=e,[,a]=J(...(Array.isArray(s)?s:[s]).map(c=>m(c,p=>(!i||i(p))&&t(p))));try{return(e.postEvent||A)(e.method,e.params),await(r?nt(n,r):n)}finally{a()}}async function I(e,t,n,s={}){const{result:i,error:r}=await _({...s,method:"web_app_invoke_custom_method",event:"custom_method_invoked",params:{method:e,params:t,req_id:n},capture:et(n)});if(r)throw g(Rt,r);return i}function H(...e){return e.map(t=>{if(typeof t=="string")return t;if(k(t))return H(Object.entries(t).map(n=>n[1]&&n[0]));if(Array.isArray(t))return H(...t)}).filter(Boolean).join(" ")}function Ve(...e){return e.reduce((t,n)=>(k(n)&&Object.entries(n).forEach(([s,i])=>{const r=H(t[s],i);r.length&&(t[s]=r)}),t),{})}function st(e){const t=K(e);return Math.sqrt([.299,.587,.114].reduce((n,s,i)=>{const r=parseInt(t.slice(1+i*2,1+(i+1)*2),16);return n+r*r*s},0))<120}class Be{constructor(t){h(this,"ee",new R);h(this,"on",this.ee.on.bind(this.ee));h(this,"off",this.ee.off.bind(this.ee));this.state=t}clone(){return{...this.state}}set(t,n){Object.entries(typeof t=="string"?{[t]:n}:t).reduce((i,[r,a])=>this.state[r]===a||a===void 0?i:(this.state[r]=a,this.ee.emit(`change:${r}`,a),!0),!1)&&this.ee.emit("change",this.state)}get(t){return this.state[t]}}class it{constructor(t){h(this,"state");h(this,"get");h(this,"set");h(this,"clone");this.state=new Be(t),this.set=this.state.set.bind(this.state),this.get=this.state.get.bind(this.state),this.clone=this.state.clone.bind(this.state)}}function Wt(e,t){return n=>P(t[n],e)}class rt extends it{constructor(n,s,i){super(n);h(this,"supports");this.supports=Wt(s,i)}}class Ht extends rt{constructor(n,s,i){super({isVisible:n},s,{show:"web_app_setup_back_button",hide:"web_app_setup_back_button"});h(this,"on",(n,s)=>n==="click"?m("back_button_pressed",s):this.state.on(n,s));h(this,"off",(n,s)=>n==="click"?q("back_button_pressed",s):this.state.off(n,s));this.postEvent=i}set isVisible(n){this.set("isVisible",n),this.postEvent("web_app_setup_back_button",{is_visible:n})}get isVisible(){return this.get("isVisible")}hide(){this.isVisible=!1}show(){this.isVisible=!0}}const ot=C(e=>e instanceof Date?e:new Date(S().parse(e)*1e3),"Date");function x(e,t){return new U(n=>{if(typeof n!="string"&&!(n instanceof URLSearchParams))throw T();const s=typeof n=="string"?new URLSearchParams(n):n;return qt(e,i=>{const r=s.get(i);return r===null?void 0:r})},!1,t)}const Le=d({id:S(),type:u(),title:u(),photoUrl:{type:u().optional(),from:"photo_url"},username:u().optional()},"Chat").optional(),xt=d({addedToAttachmentMenu:{type:y().optional(),from:"added_to_attachment_menu"},allowsWriteToPm:{type:y().optional(),from:"allows_write_to_pm"},firstName:{type:u(),from:"first_name"},id:S(),isBot:{type:y().optional(),from:"is_bot"},isPremium:{type:y().optional(),from:"is_premium"},languageCode:{type:u().optional(),from:"language_code"},lastName:{type:u().optional(),from:"last_name"},photoUrl:{type:u().optional(),from:"photo_url"},username:u().optional()},"User").optional();function Gt(){return x({authDate:{type:ot(),from:"auth_date"},canSendAfter:{type:S().optional(),from:"can_send_after"},chat:Le,chatInstance:{type:u().optional(),from:"chat_instance"},chatType:{type:u().optional(),from:"chat_type"},hash:u(),queryId:{type:u().optional(),from:"query_id"},receiver:xt,startParam:{type:u().optional(),from:"start_param"},user:xt},"InitData")}function Oe(e){return e.replace(/_[a-z]/g,t=>t[1].toUpperCase())}function Ue(e){return e.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}const jt=C(e=>{const t=X().optional();return Object.entries(Y(e)).reduce((n,[s,i])=>(n[Oe(s)]=t.parse(i),n),{})},"ThemeParams");function G(e){return x({botInline:{type:y().optional(),from:"tgWebAppBotInline"},initData:{type:Gt().optional(),from:"tgWebAppData"},initDataRaw:{type:u().optional(),from:"tgWebAppData"},platform:{type:u(),from:"tgWebAppPlatform"},showSettings:{type:y().optional(),from:"tgWebAppShowSettings"},startParam:{type:u().optional(),from:"tgWebAppStartParam"},themeParams:{type:jt(),from:"tgWebAppThemeParams"},version:{type:u(),from:"tgWebAppVersion"}}).parse(e)}function zt(e){return G(e.replace(/^[^?#]*[?#]/,"").replace(/[?#]/g,"&"))}function $e(){return zt(window.location.href)}function Ft(){return performance.getEntriesByType("navigation")[0]}function We(){const e=Ft();if(!e)throw new Error("Unable to get first navigation entry.");return zt(e.name)}function Jt(e){return`tma.js/${e.replace(/[A-Z]/g,t=>`-${t.toLowerCase()}`)}`}function Qt(e,t){sessionStorage.setItem(Jt(e),JSON.stringify(t))}function Yt(e){const t=sessionStorage.getItem(Jt(e));try{return t?JSON.parse(t):void 0}catch{}}function He(){return G(Yt("launchParams")||"")}function at(e){return JSON.stringify(Object.fromEntries(Object.entries(e).map(([t,n])=>[Ue(t),n])))}function Kt(e){const{initDataRaw:t,themeParams:n,platform:s,version:i,showSettings:r,startParam:a,botInline:c}=e,p=new URLSearchParams;return p.set("tgWebAppPlatform",s),p.set("tgWebAppThemeParams",at(n)),p.set("tgWebAppVersion",i),t&&p.set("tgWebAppData",t),a&&p.set("tgWebAppStartParam",a),typeof r=="boolean"&&p.set("tgWebAppShowSettings",r?"1":"0"),typeof c=="boolean"&&p.set("tgWebAppBotInline",c?"1":"0"),p.toString()}function Xt(e){Qt("launchParams",Kt(e))}function Zt(){for(const e of[$e,We,He])try{const t=e();return Xt(t),t}catch{}throw new Error("Unable to retrieve launch parameters from any known source.")}function ct(){const e=Ft();return!!(e&&e.type==="reload")}function xe(){let e=0;return()=>(e+=1).toString()}const[Ge]=w(xe);function f(e,t){return()=>{const n=Zt(),s={...n,postEvent:Ut(n.version),createRequestId:Ge()};if(typeof e=="function")return e(s);const[i,r,a]=J(),c=t({...s,state:ct()?Yt(e):void 0,addCleanup:i}),p=l=>(a||i(l.on("change",Tn=>{Qt(e,Tn)})),l);return[c instanceof Promise?c.then(p):p(c),r]}}const je=f("backButton",({postEvent:e,version:t,state:n={isVisible:!1}})=>new Ht(n.isVisible,t,e));class D extends rt{constructor(){super(...arguments);h(this,"on",this.state.on.bind(this.state));h(this,"off",this.state.off.bind(this.state))}}function te(e){const t=e.available?e:{available:!1,device_id:"",token_saved:!1,access_requested:!1,access_granted:!1,type:""};return{available:!0,type:t.type,deviceId:t.device_id,tokenSaved:t.token_saved,accessRequested:t.access_requested,accessGranted:t.access_granted}}class ee extends D{constructor({postEvent:n,version:s,...i}){super(i,s,{auth:"web_app_biometry_request_auth",openSettings:"web_app_biometry_open_settings",requestAccess:"web_app_biometry_request_access",updateToken:"web_app_biometry_update_token"});h(this,"postEvent");h(this,"authPromise");h(this,"accessPromise");this.postEvent=n}get available(){return this.get("available")}get accessGranted(){return this.get("accessGranted")}get accessRequested(){return this.get("accessRequested")}async authenticate({reason:n,...s}){return this.authPromise||(this.authPromise=_({...s,method:"web_app_biometry_request_auth",event:"biometry_auth_requested",postEvent:this.postEvent,params:{reason:(n||"").trim()}}).then(({token:i})=>i).finally(()=>this.authPromise=void 0)),this.authPromise}get deviceId(){return this.get("deviceId")}openSettings(){this.postEvent("web_app_biometry_open_settings")}requestAccess({reason:n,...s}={}){return this.accessPromise||(this.accessPromise=_({...s,postEvent:this.postEvent,method:"web_app_biometry_request_access",event:"biometry_info_received",params:{reason:n||""}}).then(i=>{const r=te(i);return this.set(r),r.accessGranted}).finally(()=>this.accessPromise=void 0)),this.accessPromise}get biometryType(){return this.get("biometryType")}get tokenSaved(){return this.get("tokenSaved")}async updateToken({token:n,...s}={}){return["removed","updated"].includes((await _({...s,postEvent:this.postEvent,method:"web_app_biometry_update_token",event:"biometry_token_updated",params:{token:n||""}})).status)}}async function ne(e){return te(await _({...e||{},method:"web_app_biometry_get_info",event:"biometry_info_received"}))}const ze=f("biometryManager",async({postEvent:e,version:t,state:n})=>new ee({...n||P("web_app_biometry_get_info",t)?n||await ne({timeout:1e3}):{available:!1,accessGranted:!1,accessRequested:!1,tokenSaved:!1,deviceId:""},version:t,postEvent:e}));class ht extends it{constructor(){super(...arguments);h(this,"on",this.state.on.bind(this.state));h(this,"off",this.state.off.bind(this.state))}}class se extends ht{constructor(t,n){super({isConfirmationNeeded:t}),this.postEvent=n}set isConfirmationNeeded(t){this.set("isConfirmationNeeded",t),this.postEvent("web_app_setup_closing_behavior",{need_confirmation:t})}get isConfirmationNeeded(){return this.get("isConfirmationNeeded")}disableConfirmation(){this.isConfirmationNeeded=!1}enableConfirmation(){this.isConfirmationNeeded=!0}}const Fe=f("closingBehavior",({postEvent:e,state:t={isConfirmationNeeded:!1}})=>new se(t.isConfirmationNeeded,e));class ut{constructor(t,n){h(this,"supports");this.supports=Wt(t,n)}}function Je(e){if(Array.isArray(e))return e;if(typeof e=="string")try{const t=JSON.parse(e);if(Array.isArray(t))return t}catch{}throw T()}class Qe extends U{constructor(n,s,i){super(Je,s,i);h(this,"itemParser");this.itemParser=typeof n=="function"?n:n.parse.bind(n)}parse(n){const s=super.parse(n);return s===void 0?s:s.map(this.itemParser)}of(n){return this.itemParser=typeof n=="function"?n:n.parse.bind(n),this}}function ie(e){return new Qe(t=>t,!1,e)}function re(e,t){return Object.fromEntries(e.map(n=>[n,t]))}class oe extends ut{constructor(t,n,s){super(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"}),this.createRequestId=n,this.postEvent=s}async delete(t,n={}){const s=Array.isArray(t)?t:[t];s.length&&await I("deleteStorageValues",{keys:s},this.createRequestId(),{...n,postEvent:this.postEvent})}async getKeys(t={}){return ie().of(u()).parse(await I("getStorageKeys",{},this.createRequestId(),{...t,postEvent:this.postEvent}))}async get(t,n={}){const s=Array.isArray(t)?t:[t];if(!s.length)return re(s,"");const i=await I("getStorageValues",{keys:s},this.createRequestId(),{...n,postEvent:this.postEvent}),r=d(re(s,u()),"CloudStorageData").parse(i);return Array.isArray(t)?r:r[t]}async set(t,n,s={}){await I("saveStorageValue",{key:t,value:n},this.createRequestId(),{...s,postEvent:this.postEvent})}}const Ye=f(({createRequestId:e,postEvent:t,version:n})=>new oe(n,e,t));class ae extends ut{constructor(t,n){super(t,{impactOccurred:"web_app_trigger_haptic_feedback",notificationOccurred:"web_app_trigger_haptic_feedback",selectionChanged:"web_app_trigger_haptic_feedback"}),this.postEvent=n}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"})}}const Ke=f(({version:e,postEvent:t})=>new ae(e,t));class ce{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?new Date(this.authDate.getTime()+t*1e3):void 0}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}}const Xe=f(({initData:e})=>e?new ce(e):void 0);function Ze(e){return Gt().parse(e)}class he extends D{constructor(t,n,s){super({isOpened:t},n,{open:"web_app_open_invoice"}),this.postEvent=s}set isOpened(t){this.set("isOpened",t)}get isOpened(){return this.get("isOpened")}async open(t,n){if(this.isOpened)throw new Error("Invoice is already opened");let s;if(!n)s=t;else{const{hostname:i,pathname:r}=new URL(t,window.location.href);if(i!=="t.me")throw new Error(`Incorrect hostname: ${i}`);const a=r.match(/^\/(\$|invoice\/)([A-Za-z0-9\-_=]+)$/);if(!a)throw new Error('Link pathname has incorrect format. Expected to receive "/invoice/{slug}" or "/${slug}"');[,,s]=a}this.isOpened=!0;try{return(await _({method:"web_app_open_invoice",event:"invoice_closed",params:{slug:s},postEvent:this.postEvent,capture(r){return s===r.slug}})).status}finally{this.isOpened=!1}}}const tn=f(({version:e,postEvent:t})=>new he(!1,e,t));class ue extends it{constructor({postEvent:n,...s}){super(s);h(this,"postEvent");h(this,"on",(n,s)=>n==="click"?m("main_button_pressed",s):this.state.on(n,s));h(this,"off",(n,s)=>n==="click"?q("main_button_pressed",s):this.state.off(n,s));this.postEvent=n}get bgColor(){return this.get("bgColor")}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.bgColor,text_color:this.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}set isEnabled(n){this.setParams({isEnabled:n})}get isEnabled(){return this.get("isEnabled")}set isLoaderVisible(n){this.setParams({isLoaderVisible:n})}get isLoaderVisible(){return this.get("isLoaderVisible")}set isVisible(n){this.setParams({isVisible:n})}get isVisible(){return this.get("isVisible")}show(){return this.isVisible=!0,this}showLoader(){return this.isLoaderVisible=!0,this}setText(n){return this.setParams({text:n})}setTextColor(n){return this.setParams({textColor:n})}setBgColor(n){return this.setParams({bgColor:n})}setParams(n){return this.set(n),this.commit(),this}get text(){return this.get("text")}get textColor(){return this.get("textColor")}}const en=f("mainButton",({postEvent:e,themeParams:t,state:n={isVisible:!1,isEnabled:!1,text:"",isLoaderVisible:!1,textColor:t.buttonTextColor||"#ffffff",bgColor:t.buttonColor||"#000000"}})=>new ue({...n,postEvent:e}));function nn(){return x({contact:d({userId:{type:S(),from:"user_id"},phoneNumber:{type:u(),from:"phone_number"},firstName:{type:u(),from:"first_name"},lastName:{type:u().optional(),from:"last_name"}}),authDate:{type:ot(),from:"auth_date"},hash:u()},"RequestedContact")}function pe(e,t){return n=>{const[s,i]=t[n];return P(s,i,e)}}function sn(e){return new Promise(t=>{setTimeout(t,e)})}class le extends D{constructor({postEvent:n,createRequestId:s,version:i,botInline:r,...a}){super(a,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"});h(this,"botInline");h(this,"postEvent");h(this,"createRequestId");h(this,"requestPhoneAccessPromise");h(this,"requestWriteAccessPromise");h(this,"supportsParam");this.createRequestId=s,this.postEvent=n,this.botInline=r;const c=this.supports.bind(this);this.supports=p=>c(p)?p!=="switchInlineQuery"||r:!1,this.supportsParam=pe(i,{"setHeaderColor.color":["web_app_set_header_color","color"]})}async getRequestedContact({timeout:n=1e4}={}){return nn().parse(await I("getRequestedContact",{},this.createRequestId(),{postEvent:this.postEvent,timeout:n}))}get bgColor(){return this.get("bgColor")}close(){this.postEvent("web_app_close")}get headerColor(){return this.get("headerColor")}get isBotInline(){return this.botInline}get isDark(){return st(this.bgColor)}ready(){this.postEvent("web_app_ready")}async requestContact({timeout:n=5e3}={}){try{return await this.getRequestedContact()}catch{}if(await this.requestPhoneAccess()!=="sent")throw new Error("Access denied.");const i=Date.now()+n;let r=50;return nt(async()=>{for(;Date.now()<i;){try{return await this.getRequestedContact()}catch{}await sn(r),r+=50}throw $t(n)},n)}async requestPhoneAccess(n={}){return this.requestPhoneAccessPromise||(this.requestPhoneAccessPromise=_({...n,method:"web_app_request_phone",event:"phone_requested",postEvent:this.postEvent}).then(({status:s})=>s).finally(()=>this.requestPhoneAccessPromise=void 0)),this.requestPhoneAccessPromise}async requestWriteAccess(n={}){return this.requestWriteAccessPromise||(this.requestWriteAccessPromise=_({...n,method:"web_app_request_write_access",event:"write_access_requested",postEvent:this.postEvent}).then(({status:s})=>s).finally(()=>this.requestWriteAccessPromise=void 0)),this.requestWriteAccessPromise}sendData(n){const{size:s}=new Blob([n]);if(!s||s>4096)throw new Error(`Passed data has incorrect size: ${s}`);this.postEvent("web_app_data_send",{data:n})}setHeaderColor(n){this.postEvent("web_app_set_header_color",$(n)?{color:n}:{color_key:n}),this.set("headerColor",n)}setBgColor(n){this.postEvent("web_app_set_background_color",{color:n}),this.set("bgColor",n)}switchInlineQuery(n,s=[]){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:n,chat_types:s})}}const rn=f("miniApp",({themeParams:e,botInline:t=!1,state:n={bgColor:e.bgColor||"#ffffff",headerColor:e.headerBgColor||"#000000"},...s})=>new le({...s,...n,botInline:t}));function on(e){const t=e.message.trim(),n=(e.title||"").trim(),s=e.buttons||[];let i;if(n.length>64)throw new Error(`Title has incorrect size: ${n.length}`);if(!t.length||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?i=s.map(r=>{const{id:a=""}=r;if(a.length>64)throw new Error(`Button ID has incorrect size: ${a}`);if(!r.type||r.type==="default"||r.type==="destructive"){const c=r.text.trim();if(!c.length||c.length>64){const p=r.type||"default";throw new Error(`Button text with type "${p}" has incorrect size: ${r.text.length}`)}return{...r,text:c,id:a}}return{...r,id:a}}):i=[{type:"close",id:""}],{title:n,message:t,buttons:i}}class de extends D{constructor(t,n,s){super({isOpened:t},n,{open:"web_app_open_popup"}),this.postEvent=s}set isOpened(t){this.set("isOpened",t)}get isOpened(){return this.get("isOpened")}async open(t){if(this.isOpened)throw new Error("Popup is already opened.");this.isOpened=!0;try{const{button_id:n=null}=await _({event:"popup_closed",method:"web_app_open_popup",postEvent:this.postEvent,params:on(t)});return n}finally{this.isOpened=!1}}}const an=f(({postEvent:e,version:t})=>new de(!1,t,e));class _e extends D{constructor(t,n,s){super({isOpened:t},n,{close:"web_app_close_scan_qr_popup",open:"web_app_open_scan_qr_popup"}),this.postEvent=s}close(){this.postEvent("web_app_close_scan_qr_popup"),this.isOpened=!1}set isOpened(t){this.set("isOpened",t)}get isOpened(){return this.get("isOpened")}async open(t){if(this.isOpened)throw new Error("QR scanner is already opened.");const{text:n,capture:s}=(typeof t=="string"?{text:t}:t)||{};this.isOpened=!0;try{const r=(await _({method:"web_app_open_scan_qr_popup",event:["qr_text_received","scan_qr_popup_closed"],postEvent:this.postEvent,params:{text:n},capture(a){return a.event==="scan_qr_popup_closed"||!s||s(a.payload)}})||{}).data||null;return r&&this.close(),r}catch(i){throw this.isOpened=!1,i}}}const cn=f(({version:e,postEvent:t})=>new _e(!1,e,t));class fe extends rt{constructor(n,s,i){super({isVisible:n},s,{show:"web_app_setup_settings_button",hide:"web_app_setup_settings_button"});h(this,"on",(n,s)=>n==="click"?m("settings_button_pressed",s):this.state.on(n,s));h(this,"off",(n,s)=>n==="click"?q("settings_button_pressed",s):this.state.off(n,s));this.postEvent=i}set isVisible(n){this.set("isVisible",n),this.postEvent("web_app_setup_settings_button",{is_visible:n})}get isVisible(){return this.get("isVisible")}hide(){this.isVisible=!1}show(){this.isVisible=!0}}const hn=f("settingsButton",({version:e,postEvent:t,state:n={isVisible:!1}})=>new fe(n.isVisible,e,t));function pt(e){return jt().parse(e)}class ge extends ht{get accentTextColor(){return this.get("accentTextColor")}get bgColor(){return this.get("bgColor")}get buttonColor(){return this.get("buttonColor")}get buttonTextColor(){return this.get("buttonTextColor")}get destructiveTextColor(){return this.get("destructiveTextColor")}getState(){return this.clone()}get headerBgColor(){return this.get("headerBgColor")}get hintColor(){return this.get("hintColor")}get isDark(){return!this.bgColor||st(this.bgColor)}get linkColor(){return this.get("linkColor")}get secondaryBgColor(){return this.get("secondaryBgColor")}get sectionBgColor(){return this.get("sectionBgColor")}get sectionHeaderTextColor(){return this.get("sectionHeaderTextColor")}get sectionSeparatorColor(){return this.get("sectionHeaderTextColor")}listen(){return m("theme_changed",t=>{this.set(pt(t.theme_params))})}get subtitleTextColor(){return this.get("subtitleTextColor")}get textColor(){return this.get("textColor")}}const un=f("themeParams",({themeParams:e,state:t=e,addCleanup:n})=>{const s=new ge(t);return n(s.listen()),s});function pn(e={}){return _({...e,method:"web_app_request_theme",event:"theme_changed"}).then(pt)}class be extends ut{constructor(n,s,i){super(n,{readTextFromClipboard:"web_app_read_text_from_clipboard"});h(this,"supportsParam");this.version=n,this.createRequestId=s,this.postEvent=i,this.supportsParam=pe(n,{"openLink.tryInstantView":["web_app_open_link","try_instant_view"]})}openLink(n,s){const i=new URL(n,window.location.href).toString();if(!P("web_app_open_link",this.version)){window.open(i,"_blank");return}this.postEvent("web_app_open_link",{url:i,...typeof s=="boolean"?{try_instant_view:s}:{}})}openTelegramLink(n){const{hostname:s,pathname:i,search:r}=new URL(n,"https://t.me");if(s!=="t.me")throw new Error(`URL has not allowed hostname: ${s}. Only "t.me" is allowed`);if(!P("web_app_open_tg_link",this.version)){window.location.href=n;return}this.postEvent("web_app_open_tg_link",{path_full:i+r})}async readTextFromClipboard(){const n=this.createRequestId(),{data:s=null}=await _({method:"web_app_read_text_from_clipboard",event:"clipboard_text_received",postEvent:this.postEvent,params:{req_id:n},capture:et(n)});return s}shareURL(n,s){this.openTelegramLink("https://t.me/share/url?"+new URLSearchParams({url:n,text:s||""}).toString())}}const ln=f(({version:e,postEvent:t,createRequestId:n})=>new be(e,n,t));async function lt(e={}){const{is_expanded:t,is_state_stable:n,...s}=await _({...e,method:"web_app_request_viewport",event:"viewport_changed"});return{...s,isExpanded:t,isStateStable:n}}function M(e){return e<0?0:e}class we extends ht{constructor({postEvent:n,stableHeight:s,height:i,width:r,isExpanded:a}){super({height:M(i),isExpanded:a,stableHeight:M(s),width:M(r)});h(this,"postEvent");this.postEvent=n}async sync(n){const{isStateStable:s,...i}=await lt(n);this.set({...i,stableHeight:s?i.height:this.get("stableHeight")})}get height(){return this.get("height")}get stableHeight(){return this.get("stableHeight")}listen(){return m("viewport_changed",n=>{const{height:s,width:i,is_expanded:r,is_state_stable:a}=n,c=M(s);this.set({height:c,isExpanded:r,width:M(i),...a?{stableHeight:c}:{}})})}get isExpanded(){return this.get("isExpanded")}get width(){return this.get("width")}expand(){this.postEvent("web_app_expand"),this.set("isExpanded",!0)}get isStable(){return this.stableHeight===this.height}}const dn=f("viewport",async({state:e,platform:t,postEvent:n,addCleanup:s})=>{let i=!1,r=0,a=0,c=0;if(e)i=e.isExpanded,r=e.height,a=e.width,c=e.stableHeight;else if(["macos","tdesktop","unigram","webk","weba","web"].includes(t))i=!0,r=window.innerHeight,a=window.innerWidth,c=window.innerHeight;else{const l=await lt({timeout:1e3,postEvent:n});i=l.isExpanded,r=l.height,a=l.width,c=l.isStateStable?r:0}const p=new we({postEvent:n,height:r,width:a,stableHeight:c,isExpanded:i});return s(p.listen()),p});function E(e,t){document.documentElement.style.setProperty(e,t)}function _n(e,t,n){n||(n=c=>`--tg-${c}-color`);const s=n("header"),i=n("bg"),r=()=>{const{headerColor:c}=e;if($(c))E(s,c);else{const{bgColor:p,secondaryBgColor:l}=t;c==="bg_color"&&p?E(s,p):c==="secondary_bg_color"&&l&&E(s,l)}E(i,e.bgColor)},a=[t.on("change",r),e.on("change",r)];return r(),()=>a.forEach(c=>c())}function fn(e,t){t||(t=s=>`--tg-theme-${s.replace(/[A-Z]/g,i=>`-${i.toLowerCase()}`)}`);const n=()=>{Object.entries(e.getState()).forEach(([s,i])=>{i&&E(t(s),i)})};return n(),e.on("change",n)}function gn(e,t){t||(t=l=>`--tg-viewport-${l}`);const[n,s,i]=["height","width","stable-height"].map(l=>t(l)),r=()=>E(n,`${e.height}px`),a=()=>E(s,`${e.width}px`),c=()=>E(i,`${e.stableHeight}px`),p=[e.on("change:height",r),e.on("change:width",a),e.on("change:stableHeight",c)];return r(),a(),c(),()=>p.forEach(l=>l())}function bn(e=!0){const t=[m("reload_iframe",()=>{A("iframe_will_reload"),window.location.reload()})],n=()=>t.forEach(s=>s());if(e){const s=document.createElement("style");s.id="telegram-custom-styles",document.head.appendChild(s),t.push(m("set_custom_style",i=>{s.innerHTML=i}),()=>document.head.removeChild(s))}return A("iframe_ready",{reload_supported:!0}),n}function wn(){return typeof window>"u"}async function mn(){if(Bt(window))return!0;try{return await _({method:"web_app_request_theme",event:"theme_changed",timeout:100}),!0}catch{return!1}}function yn(e){const t=typeof e=="string"?G(e):e;Xt(t);function n(i){if(typeof i=="string")try{const{eventType:r}=Dt(i);r==="web_app_request_theme"&&Z("theme_changed",{theme_params:JSON.parse(at(t.themeParams))}),r==="web_app_request_viewport"&&Z("viewport_changed",{width:window.innerWidth,height:window.innerHeight,is_state_stable:!0,is_expanded:!0})}catch{}}if(tt()){const i=window.parent.postMessage.bind(window.parent);window.parent.postMessage=r=>{n(r),i(r)};return}if(Vt(window)){const i=window.external.notify.bind(window.external);window.external.notify=r=>{n(r),i(r)};return}const s=window.TelegramWebviewProxy;window.TelegramWebviewProxy={...s||{},postEvent(...i){n(JSON.stringify({eventType:i[0],eventData:i[1]})),s&&s.postEvent(...i)}}}function me(e){return e instanceof N}function En(e,t){return me(e)&&e.type===t}function dt(e,t){let n,s,i;return typeof e=="string"?n=e:(n=e.pathname===void 0?t:e.pathname,s=e.params,i=e.id),Object.freeze({id:i||(Math.random()*2**14|0).toString(16),pathname:n,params:s})}class ye{constructor(t,n,s=A){h(this,"history");h(this,"ee",new R);h(this,"attached",!1);h(this,"back",()=>this.go(-1));h(this,"on",this.ee.on.bind(this.ee));h(this,"off",this.ee.off.bind(this.ee));if(this._index=n,this.postEvent=s,t.length===0)throw g(At,"History should not be empty.");if(n<0||n>=t.length)throw g(It,"Index should not be zero and higher or equal than history size.");this.history=t.map(i=>dt(i,""))}attach(){this.attached||(this.attached=!0,this.sync(),m("back_button_pressed",this.back))}get current(){return this.history[this.index]}detach(){this.attached=!1,q("back_button_pressed",this.back)}forward(){this.go(1)}go(t,n){const s=this.index+t,i=Math.min(Math.max(0,s),this.history.length-1);(s===i||n)&&this.replaceAndMove(i,this.history[i])}goTo(t,n){this.go(t-this.index,n)}get hasPrev(){return this.index>0}get hasNext(){return this.index!==this.history.length-1}get index(){return this._index}push(t){this.hasNext&&this.history.splice(this.index+1),this.replaceAndMove(this.index+1,dt(t,this.current.pathname))}replace(t){this.replaceAndMove(this.index,dt(t,this.current.pathname))}replaceAndMove(t,n){const s=t-this.index;if(!s&&this.current===n)return;const i=this.current;if(this.index!==t){const r=this._index;this._index=t,this.attached&&r>0!=t>0&&this.sync()}this.history[t]=n,this.ee.emit("change",{navigator:this,from:i,to:this.current,delta:s})}sync(){this.postEvent("web_app_setup_back_button",{is_visible:!!this.index})}}function _t({params:e,...t}){return{...e||{hash:"",search:""},...t}}function V(e,t){return e.startsWith(t)?e:`${t}${e}`}function B(e){return new URL(typeof e=="string"?e:`${e.pathname||""}${V(e.search||"","?")}${V(e.hash||"","#")}`,"http://a")}function L(e){const t=typeof e=="string"?e.startsWith("/"):!!(e.pathname&&e.pathname.startsWith("/")),n=B(e);return`${t?n.pathname:n.pathname.slice(1)}${n.search}${n.hash}`}function ft(e,t,n){let s,i;typeof e=="string"?s=e:(s=L(e),n=e.state,i=e.id);const{pathname:r,search:a,hash:c}=new URL(s,`http://a${V(t,"/")}`);return{id:i,pathname:r,params:{hash:c,search:a,state:n}}}async function O(e){return e===0?!0:Promise.race([new Promise(t=>{const n=F("popstate",()=>{n(),t(!0)});window.history.go(e)}),new Promise(t=>{setTimeout(t,50,!1)})])}async function vn(){if(window.history.length<=1||(window.history.pushState(null,""),await O(1-window.history.length)))return;let t=await O(-1);for(;t;)t=await O(-1)}function gt(e){return B(e).pathname}const Ee=0,bt=1,wt=2;class mt{constructor(t,n,{postEvent:s,hashMode:i="classic",base:r}={}){h(this,"navigator");h(this,"ee",new R);h(this,"hashMode");h(this,"base");h(this,"attached",!1);h(this,"onPopState",({state:t})=>{if(t===null)return this.push(this.parsePath(window.location.href));t===Ee?window.history.forward():t===bt&&this.back(),t===wt&&this.forward()});h(this,"onNavigatorChange",async({to:t,from:n,delta:s})=>{this.attached&&await this.syncHistory(),this.ee.emit("change",{delta:s,from:_t(n),to:_t(t),navigator:this})});h(this,"on",this.ee.on.bind(this.ee));h(this,"off",this.ee.off.bind(this.ee));this.navigator=new ye(t.map(a=>ft(a,"/")),n,s),this.navigator.on("change",a=>{this.onNavigatorChange(a)}),this.hashMode=i,this.base=gt(r||"")}async attach(){this.attached||(this.attached=!0,this.navigator.attach(),window.addEventListener("popstate",this.onPopState),await this.syncHistory())}back(){this.navigator.back()}detach(){this.attached=!1,this.navigator.detach(),window.removeEventListener("popstate",this.onPopState)}forward(){return this.navigator.forward()}get index(){return this.navigator.index}get id(){return this.navigator.current.id}go(t,n){return this.navigator.go(t,n)}goTo(t,n){this.navigator.goTo(t,n)}get hash(){return(this.navigator.current.params||{}).hash||""}get hasPrev(){return this.navigator.hasPrev}get hasNext(){return this.navigator.hasNext}get history(){return this.navigator.history.map(_t)}get path(){return L(this)}get pathname(){return this.navigator.current.pathname}parsePath(t){let n=B(t);return this.hashMode&&(n=B(n.hash.slice(1))),{pathname:n.pathname,search:n.search,hash:n.hash}}push(t,n){const s=ft(t,this.path),{state:i=n}=s.params;this.navigator.push({...s,params:{...s.params,state:i}})}replace(t,n){const s=ft(t,this.path),{state:i=n}=s.params;this.navigator.replace({...s,params:{...s.params,state:i}})}renderPath(t){const n=(this.base.length===1?"":this.base)+V(L(t),"/");return this.hashMode?V(n.slice(1),this.hashMode==="classic"?"#":"#/"):n}async syncHistory(){window.removeEventListener("popstate",this.onPopState);const{state:t}=this,n=this.renderPath(this);await vn(),this.hasPrev&&this.hasNext?(window.history.replaceState(bt,""),window.history.pushState(t,"",n),window.history.pushState(wt,""),await O(-1)):this.hasPrev?(window.history.replaceState(bt,""),window.history.pushState(t,"",n)):this.hasNext?(window.history.replaceState(t,n),window.history.pushState(wt,""),await O(-1)):(window.history.replaceState(Ee,""),window.history.pushState(t,"",n)),window.addEventListener("popstate",this.onPopState)}get search(){return(this.navigator.current.params||{}).search||""}get state(){return(this.navigator.current.params||{}).state}}function ve(e){e||(e={});const{href:t,hash:n}=window.location;let s=L(e.hashMode===null?t:n.includes("?")?n.slice(1):`?${n.slice(1)}`);const i=e.base?gt(e.base):void 0;if(i){if(!s.startsWith(i))throw g(Nt,`Path "${s}" expected to be starting with "${i}"`);s=s.slice(i.length)}return new mt([s],0,e)}function Sn(e){const t=e.match(/#(.+)/);return t?t[1]:null}function Pn(e,t){if(ct()){const n=sessionStorage.getItem(e);if(n)try{const{index:s,history:i}=JSON.parse(n);return new mt(i,s,t)}catch(s){console.error("Unable to restore hash navigator state.",s)}}return ve(t)}function Rn(e,t){const n=Pn(e,t),s=()=>sessionStorage.setItem(e,JSON.stringify({index:n.index,history:n.history}));return n.on("change",s),s(),n}return o.BackButton=Ht,o.BasicNavigator=ye,o.BiometryManager=ee,o.BrowserNavigator=mt,o.ClosingBehavior=se,o.CloudStorage=oe,o.ERR_INVALID_PATH_BASE=Nt,o.ERR_INVOKE_CUSTOM_METHOD_RESPONSE=Rt,o.ERR_METHOD_PARAMETER_UNSUPPORTED=St,o.ERR_METHOD_UNSUPPORTED=vt,o.ERR_NAVIGATION_HISTORY_EMPTY=At,o.ERR_NAVIGATION_INDEX_INVALID=It,o.ERR_NAVIGATION_ITEM_INVALID=Te,o.ERR_PARSE=Q,o.ERR_SSR_INIT=Ce,o.ERR_TIMED_OUT=Tt,o.ERR_UNEXPECTED_TYPE=Ct,o.ERR_UNKNOWN_ENV=Pt,o.EventEmitter=R,o.HapticFeedback=ae,o.InitData=ce,o.Invoice=he,o.MainButton=ue,o.MiniApp=le,o.Popup=de,o.QRScanner=_e,o.SDKError=N,o.SettingsButton=fe,o.ThemeParams=ge,o.Utils=be,o.Viewport=we,o.array=ie,o.bindMiniAppCSSVars=_n,o.bindThemeParamsCSSVars=fn,o.bindViewportCSSVars=gn,o.boolean=y,o.captureSameReq=et,o.classNames=H,o.compareVersions=Mt,o.createBrowserNavigatorFromLocation=ve,o.createPostEvent=Ut,o.createSafeURL=B,o.date=ot,o.getHash=Sn,o.getPathname=gt,o.initBackButton=je,o.initBiometryManager=ze,o.initClosingBehavior=Fe,o.initCloudStorage=Ye,o.initHapticFeedback=Ke,o.initInitData=Xe,o.initInvoice=tn,o.initMainButton=en,o.initMiniApp=rn,o.initNavigator=Rn,o.initPopup=an,o.initQRScanner=cn,o.initSettingsButton=hn,o.initThemeParams=un,o.initUtils=ln,o.initViewport=dn,o.initWeb=bn,o.invokeCustomMethod=I,o.isColorDark=st,o.isIframe=tt,o.isPageReload=ct,o.isRGB=$,o.isRGBShort=kt,o.isSDKError=me,o.isSDKErrorOfType=En,o.isSSR=wn,o.isTMA=mn,o.json=d,o.mergeClassNames=Ve,o.mockTelegramEnv=yn,o.number=S,o.off=q,o.on=m,o.parseInitData=Ze,o.parseLaunchParams=G,o.parseThemeParams=pt,o.postEvent=A,o.request=_,o.requestBiometryInfo=ne,o.requestThemeParams=pn,o.requestViewport=lt,o.retrieveLaunchParams=Zt,o.rgb=X,o.searchParams=x,o.serializeLaunchParams=Kt,o.serializeThemeParams=at,o.setCSSVar=E,o.setDebug=Pe,o.setTargetOrigin=Me,o.string=u,o.subscribe=yt,o.supports=P,o.targetOrigin=Ot,o.toRGB=K,o.unsubscribe=v,o.urlToPath=L,o.withTimeout=nt,Object.defineProperty(o,Symbol.toStringTag,{value:"Module"}),o}({});
|
|
1
|
+
var Cn=Object.defineProperty;var In=(o,b,v)=>b in o?Cn(o,b,{enumerable:!0,configurable:!0,writable:!0,value:v}):o[b]=v;var h=(o,b,v)=>In(o,typeof b!="symbol"?b+"":b,v);this.tmajs=this.tmajs||{};this.tmajs.sdk=function(o){"use strict";function b(e,t){let n;const s=()=>{n!==void 0&&t&&t(n),n=void 0};return[()=>n===void 0?n=e(s):n,s]}function v(e){const t=$(),{count:n}=t;t.unsubscribe(e),n&&!t.count&&De()}function wt(e){return $().subscribe(e),()=>v(e)}class Se{constructor(t,n={}){this.scope=t,this.options=n}print(t,...n){const s=new Date,i=Intl.DateTimeFormat("en-GB",{hour:"2-digit",minute:"2-digit",second:"2-digit",fractionalSecondDigits:3,timeZone:"UTC"}).format(s),{textColor:r,bgColor:a}=this.options,c="font-weight: bold;padding: 0 5px;border-radius:5px";console[t](`%c${i}%c / %c${this.scope}`,`${c};background-color: lightblue;color:black`,"",`${c};${r?`color:${r};`:""}${a?`background-color:${a}`:""}`,...n)}error(...t){this.print("error",...t)}log(...t){this.print("log",...t)}}const j=new Se("SDK",{bgColor:"forestgreen",textColor:"white"});let z=!1;const mt=({name:e,payload:t})=>{j.log("Event received:",t?{name:e,payload:t}:{name:e})};function Pe(e){z!==e&&(z=e,e?wt(mt):v(mt))}function Re(...e){z&&j.log(...e)}class R{constructor(){h(this,"listeners",new Map);h(this,"listenersCount",0);h(this,"subscribeListeners",[])}clear(){this.listeners.clear(),this.subscribeListeners=[]}get count(){return this.listenersCount+this.subscribeListeners.length}emit(t,...n){this.subscribeListeners.forEach(i=>i({event:t,args:n})),(this.listeners.get(t)||[]).forEach(([i,r])=>{i(...n),r&&this.off(t,i)})}on(t,n,s){let i=this.listeners.get(t);return i||this.listeners.set(t,i=[]),i.push([n,s]),this.listenersCount+=1,()=>this.off(t,n)}off(t,n){const s=this.listeners.get(t)||[];for(let i=0;i<s.length;i+=1)if(n===s[i][0]){s.splice(i,1),this.listenersCount-=1;return}}subscribe(t){return this.subscribeListeners.push(t),()=>this.unsubscribe(t)}unsubscribe(t){for(let n=0;n<this.subscribeListeners.length;n+=1)if(this.subscribeListeners[n]===t){this.subscribeListeners.splice(n,1);return}}}function F(e,t,n){return window.addEventListener(e,t,n),()=>window.removeEventListener(e,t,n)}function J(...e){let t=!1;const n=e.flat(1);return[s=>!t&&n.push(s),()=>{t||(t=!0,n.forEach(s=>s()))},t]}class q extends Error{constructor(t,n,s){super(n,{cause:s}),this.type=t,Object.setPrototypeOf(this,q.prototype)}}function f(e,t,n){return new q(e,t,n)}const yt="ERR_METHOD_UNSUPPORTED",Et="ERR_METHOD_PARAMETER_UNSUPPORTED",vt="ERR_UNKNOWN_ENV",St="ERR_INVOKE_CUSTOM_METHOD_RESPONSE",Pt="ERR_TIMED_OUT",Rt="ERR_UNEXPECTED_TYPE",Y="ERR_PARSE",Tt="ERR_NAVIGATION_LIST_EMPTY",Ct="ERR_NAVIGATION_CURSOR_INVALID",Te="ERR_NAVIGATION_ITEM_INVALID",Ce="ERR_SSR_INIT",It="ERR_INVALID_PATH_BASE";function T(){return f(Rt,"Value has unexpected type")}class U{constructor(t,n,s){this.parser=t,this.isOptional=n,this.type=s}parse(t){if(!(this.isOptional&&t===void 0))try{return this.parser(t)}catch(n){throw f(Y,`Unable to parse value${this.type?` as ${this.type}`:""}`,n)}}optional(){return this.isOptional=!0,this}}function C(e,t){return()=>new U(e,!1,t)}const y=C(e=>{if(typeof e=="boolean")return e;const t=String(e);if(t==="1"||t==="true")return!0;if(t==="0"||t==="false")return!1;throw T()},"boolean");function At(e,t){const n={};for(const s in e){const i=e[s];if(!i)continue;let r,a;if(typeof i=="function"||"parse"in i)r=s,a=typeof i=="function"?i:i.parse.bind(i);else{const{type:c}=i;r=i.from||s,a=typeof c=="function"?c:c.parse.bind(c)}try{const c=a(t(r));c!==void 0&&(n[s]=c)}catch(c){throw f(Y,`Unable to parse field "${s}"`,c)}}return n}function Nt(e){let t=e;if(typeof t=="string"&&(t=JSON.parse(t)),typeof t!="object"||t===null||Array.isArray(t))throw T();return t}function w(e,t){return new U(n=>{const s=Nt(n);return At(e,i=>s[i])},!1,t)}const S=C(e=>{if(typeof e=="number")return e;if(typeof e=="string"){const t=Number(e);if(!Number.isNaN(t))return t}throw T()},"number"),p=C(e=>{if(typeof e=="string"||typeof e=="number")return e.toString();throw T()},"string");function qt(e){return w({eventType:p(),eventData:t=>t}).parse(e)}function Ie(){["TelegramGameProxy_receiveEvent","TelegramGameProxy","Telegram"].forEach(e=>{delete window[e]})}function K(e,t){window.dispatchEvent(new MessageEvent("message",{data:JSON.stringify({eventType:e,eventData:t}),source:window.parent}))}function Ae(){[["TelegramGameProxy_receiveEvent"],["TelegramGameProxy","receiveEvent"],["Telegram","WebView","receiveEvent"]].forEach(e=>{let t=window;e.forEach((n,s,i)=>{if(s===i.length-1){t[n]=K;return}n in t||(t[n]={}),t=t[n]})})}const Ne={clipboard_text_received:w({req_id:p(),data:e=>e===null?e:p().optional().parse(e)}),custom_method_invoked:w({req_id:p(),result:e=>e,error:p().optional()}),popup_closed:{parse(e){return w({button_id:t=>t==null?void 0:p().parse(t)}).parse(e??{})}},viewport_changed:w({height:S(),width:e=>e==null?window.innerWidth:S().parse(e),is_state_stable:y(),is_expanded:y()})};function qe(){const e=new R,t=new R;t.subscribe(s=>{e.emit("event",{name:s.event,payload:s.args[0]})}),Ae();const[,n]=J(Ie,F("resize",()=>{t.emit("viewport_changed",{width:window.innerWidth,height:window.innerHeight,is_state_stable:!0,is_expanded:!0})}),F("message",s=>{if(s.source!==window.parent)return;let i;try{i=qt(s.data)}catch{return}const{eventType:r,eventData:a}=i,c=Ne[r];try{const u=c?c.parse(a):a;t.emit(...u?[r,u]:[r])}catch(u){j.error(`An error occurred processing the "${r}" event from the Telegram application.
|
|
2
|
+
Please, file an issue here:
|
|
3
|
+
https://github.com/Telegram-Mini-Apps/tma.js/issues/new/choose`,i,u)}}),()=>e.clear(),()=>t.clear());return[{on:t.on.bind(t),off:t.off.bind(t),subscribe(s){return e.on("event",s)},unsubscribe(s){e.off("event",s)},get count(){return t.count+e.count}},n]}const[ke,De]=b(e=>{const[t,n]=qe(),s=t.off.bind(t);return t.off=(i,r)=>{const{count:a}=t;s(i,r),a&&!t.count&&e()},[t,n]},([,e])=>e());function $(){return ke()[0]}function k(e,t){$().off(e,t)}function m(e,t,n){return $().on(e,t,n)}function D(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function kt(e,t){const n=e.split("."),s=t.split("."),i=Math.max(n.length,s.length);for(let r=0;r<i;r+=1){const a=parseInt(n[r]||"0",10),c=parseInt(s[r]||"0",10);if(a!==c)return a>c?1:-1}return 0}function g(e,t){return kt(e,t)<=0}function P(e,t,n){if(typeof n=="string"){if(e==="web_app_open_link"){if(t==="try_instant_view")return g("6.4",n);if(t==="try_browser")return g("7.6",n)}if(e==="web_app_set_header_color"&&t==="color")return g("6.9",n);if(e==="web_app_close"&&t==="return_back")return g("7.6",n)}switch(e){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 g("6.1",t);case"web_app_open_popup":return g("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 g("6.4",t);case"web_app_switch_inline_query":return g("6.7",t);case"web_app_invoke_custom_method":case"web_app_request_write_access":case"web_app_request_phone":return g("6.9",t);case"web_app_setup_settings_button":return g("6.10",t);case"web_app_biometry_get_info":case"web_app_biometry_open_settings":case"web_app_biometry_request_access":case"web_app_biometry_request_auth":case"web_app_biometry_update_token":return g("7.2",t);default:return["iframe_ready","iframe_will_reload","web_app_close","web_app_data_send","web_app_expand","web_app_open_link","web_app_ready","web_app_request_theme","web_app_request_viewport","web_app_setup_main_button","web_app_setup_closing_behavior"].includes(e)}}function Dt(e){return"external"in e&&D(e.external)&&"notify"in e.external&&typeof e.external.notify=="function"}function Mt(e){return"TelegramWebviewProxy"in e&&D(e.TelegramWebviewProxy)&&"postEvent"in e.TelegramWebviewProxy&&typeof e.TelegramWebviewProxy.postEvent=="function"}function Q(){try{return window.self!==window.top}catch{return!0}}let Vt="https://web.telegram.org";function Me(e){Vt=e}function Bt(){return Vt}function I(e,t,n){let s={},i;if(!t&&!n?s={}:t&&n?(s=n,i=t):t&&("targetOrigin"in t?s=t:i=t),Re("Posting event:",i?{event:e,data:i}:{event:e}),Q())return window.parent.postMessage(JSON.stringify({eventType:e,eventData:i}),s.targetOrigin||Bt());if(Dt(window)){window.external.notify(JSON.stringify({eventType:e,eventData:i}));return}if(Mt(window)){window.TelegramWebviewProxy.postEvent(e,JSON.stringify(i));return}throw f(vt,"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.")}function Lt(e){return(t,n)=>{if(!P(t,e))throw f(yt,`Method "${t}" is unsupported in Mini Apps version ${e}`);if(D(n)&&t==="web_app_set_header_color"&&"color"in n&&!P(t,"color",e))throw f(Et,`Parameter "color" of "${t}" method is unsupported in Mini Apps version ${e}`);return I(t,n)}}function X(e){return({req_id:t})=>t===e}function Ot(e){return f(Pt,`Timeout reached: ${e}ms`)}function Z(e,t){return Promise.race([typeof e=="function"?e():e,new Promise((n,s)=>{setTimeout(()=>{s(Ot(t))},t)})])}async function d(e){let t;const n=new Promise(c=>t=c),{event:s,capture:i,timeout:r}=e,[,a]=J((Array.isArray(s)?s:[s]).map(c=>m(c,u=>{(!i||(Array.isArray(s)?i({event:c,payload:u}):i(u)))&&t(u)})));try{return(e.postEvent||I)(e.method,e.params),await(r?Z(n,r):n)}finally{a()}}async function A(e,t,n,s={}){const{result:i,error:r}=await d({...s,method:"web_app_invoke_custom_method",event:"custom_method_invoked",params:{method:e,params:t,req_id:n},capture:X(n)});if(r)throw f(St,r);return i}function W(...e){return e.map(t=>{if(typeof t=="string")return t;if(D(t))return W(Object.entries(t).map(n=>n[1]&&n[0]));if(Array.isArray(t))return W(...t)}).filter(Boolean).join(" ")}function Ve(...e){return e.reduce((t,n)=>(D(n)&&Object.entries(n).forEach(([s,i])=>{const r=W(t[s],i);r.length&&(t[s]=r)}),t),{})}function H(e){return/^#[\da-f]{6}$/i.test(e)}function Ut(e){return/^#[\da-f]{3}$/i.test(e)}function tt(e){const t=e.replace(/\s/g,"").toLowerCase();if(H(t))return t;if(Ut(t)){let s="#";for(let i=0;i<3;i+=1)s+=t[1+i].repeat(2);return s}const n=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(!n)throw new Error(`Value "${e}" does not satisfy any of known RGB formats.`);return n.slice(1).reduce((s,i)=>{const r=parseInt(i,10).toString(16);return s+(r.length===1?"0":"")+r},"#")}function et(e){const t=tt(e);return Math.sqrt([.299,.587,.114].reduce((n,s,i)=>{const r=parseInt(t.slice(1+i*2,1+(i+1)*2),16);return n+r*r*s},0))<120}class Be{constructor(t){h(this,"ee",new R);h(this,"on",this.ee.on.bind(this.ee));h(this,"off",this.ee.off.bind(this.ee));this.state=t}clone(){return{...this.state}}set(t,n){Object.entries(typeof t=="string"?{[t]:n}:t).reduce((i,[r,a])=>this.state[r]===a||a===void 0?i:(this.state[r]=a,this.ee.emit(`change:${r}`,a),!0),!1)&&this.ee.emit("change",this.state)}get(t){return this.state[t]}}class nt{constructor(t){h(this,"state");h(this,"get");h(this,"set");h(this,"clone");this.state=new Be(t),this.set=this.state.set.bind(this.state),this.get=this.state.get.bind(this.state),this.clone=this.state.clone.bind(this.state)}}function $t(e,t){return n=>P(t[n],e)}class st extends nt{constructor(n,s,i){super(n);h(this,"supports");this.supports=$t(s,i)}}class Wt extends st{constructor(n,s,i){super({isVisible:n},s,{show:"web_app_setup_back_button",hide:"web_app_setup_back_button"});h(this,"on",(n,s)=>n==="click"?m("back_button_pressed",s):this.state.on(n,s));h(this,"off",(n,s)=>n==="click"?k("back_button_pressed",s):this.state.off(n,s));this.postEvent=i}set isVisible(n){this.set("isVisible",n),this.postEvent("web_app_setup_back_button",{is_visible:n})}get isVisible(){return this.get("isVisible")}hide(){this.isVisible=!1}show(){this.isVisible=!0}}const it=C(e=>e instanceof Date?e:new Date(S().parse(e)*1e3),"Date");function G(e,t){return new U(n=>{if(typeof n!="string"&&!(n instanceof URLSearchParams))throw T();const s=typeof n=="string"?new URLSearchParams(n):n;return At(e,i=>{const r=s.get(i);return r===null?void 0:r})},!1,t)}const Le=w({id:S(),type:p(),title:p(),photoUrl:{type:p().optional(),from:"photo_url"},username:p().optional()},"Chat").optional(),Ht=w({addedToAttachmentMenu:{type:y().optional(),from:"added_to_attachment_menu"},allowsWriteToPm:{type:y().optional(),from:"allows_write_to_pm"},firstName:{type:p(),from:"first_name"},id:S(),isBot:{type:y().optional(),from:"is_bot"},isPremium:{type:y().optional(),from:"is_premium"},languageCode:{type:p().optional(),from:"language_code"},lastName:{type:p().optional(),from:"last_name"},photoUrl:{type:p().optional(),from:"photo_url"},username:p().optional()},"User").optional();function Gt(){return G({authDate:{type:it(),from:"auth_date"},canSendAfter:{type:S().optional(),from:"can_send_after"},chat:Le,chatInstance:{type:p().optional(),from:"chat_instance"},chatType:{type:p().optional(),from:"chat_type"},hash:p(),queryId:{type:p().optional(),from:"query_id"},receiver:Ht,startParam:{type:p().optional(),from:"start_param"},user:Ht},"InitData")}const xt=C(e=>tt(p().parse(e)),"rgb");function Oe(e){return e.replace(/_[a-z]/g,t=>t[1].toUpperCase())}function Ue(e){return e.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}const jt=C(e=>{const t=xt().optional();return Object.entries(Nt(e)).reduce((n,[s,i])=>(n[Oe(s)]=t.parse(i),n),{})},"ThemeParams");function x(e){return G({botInline:{type:y().optional(),from:"tgWebAppBotInline"},initData:{type:Gt().optional(),from:"tgWebAppData"},initDataRaw:{type:p().optional(),from:"tgWebAppData"},platform:{type:p(),from:"tgWebAppPlatform"},showSettings:{type:y().optional(),from:"tgWebAppShowSettings"},startParam:{type:p().optional(),from:"tgWebAppStartParam"},themeParams:{type:jt(),from:"tgWebAppThemeParams"},version:{type:p(),from:"tgWebAppVersion"}}).parse(e)}function zt(e){return x(e.replace(/^[^?#]*[?#]/,"").replace(/[?#]/g,"&"))}function $e(){return zt(window.location.href)}function Ft(){return performance.getEntriesByType("navigation")[0]}function We(){const e=Ft();if(!e)throw new Error("Unable to get first navigation entry.");return zt(e.name)}function Jt(e){return`tma.js/${e.replace(/[A-Z]/g,t=>`-${t.toLowerCase()}`)}`}function Yt(e,t){sessionStorage.setItem(Jt(e),JSON.stringify(t))}function Kt(e){const t=sessionStorage.getItem(Jt(e));try{return t?JSON.parse(t):void 0}catch{}}function He(){return x(Kt("launchParams")||"")}function rt(e){return JSON.stringify(Object.fromEntries(Object.entries(e).map(([t,n])=>[Ue(t),n])))}function Qt(e){const{initDataRaw:t,themeParams:n,platform:s,version:i,showSettings:r,startParam:a,botInline:c}=e,u=new URLSearchParams;return u.set("tgWebAppPlatform",s),u.set("tgWebAppThemeParams",rt(n)),u.set("tgWebAppVersion",i),t&&u.set("tgWebAppData",t),a&&u.set("tgWebAppStartParam",a),typeof r=="boolean"&&u.set("tgWebAppShowSettings",r?"1":"0"),typeof c=="boolean"&&u.set("tgWebAppBotInline",c?"1":"0"),u.toString()}function Xt(e){Yt("launchParams",Qt(e))}function Zt(){for(const e of[$e,We,He])try{const t=e();return Xt(t),t}catch{}throw new Error("Unable to retrieve launch parameters from any known source.")}function ot(){const e=Ft();return!!(e&&e.type==="reload")}function Ge(){let e=0;return()=>(e+=1).toString()}const[xe]=b(Ge);function _(e,t){return()=>{const n=Zt(),s={...n,postEvent:Lt(n.version),createRequestId:xe()};if(typeof e=="function")return e(s);const[i,r,a]=J(),c=t({...s,state:ot()?Kt(e):void 0,addCleanup:i}),u=l=>(a||i(l.on("change",Tn=>{Yt(e,Tn)})),l);return[c instanceof Promise?c.then(u):u(c),r]}}const je=_("backButton",({postEvent:e,version:t,state:n={isVisible:!1}})=>new Wt(n.isVisible,t,e));class M extends st{constructor(){super(...arguments);h(this,"on",this.state.on.bind(this.state));h(this,"off",this.state.off.bind(this.state))}}function te(e){const t=e.available?e:{available:!1,device_id:"",token_saved:!1,access_requested:!1,access_granted:!1,type:""};return{available:!0,type:t.type,deviceId:t.device_id,tokenSaved:t.token_saved,accessRequested:t.access_requested,accessGranted:t.access_granted}}class ee extends M{constructor({postEvent:n,version:s,...i}){super(i,s,{auth:"web_app_biometry_request_auth",openSettings:"web_app_biometry_open_settings",requestAccess:"web_app_biometry_request_access",updateToken:"web_app_biometry_update_token"});h(this,"postEvent");h(this,"authPromise");h(this,"accessPromise");this.postEvent=n}get available(){return this.get("available")}get accessGranted(){return this.get("accessGranted")}get accessRequested(){return this.get("accessRequested")}async authenticate({reason:n,...s}){return this.authPromise||(this.authPromise=d({...s,method:"web_app_biometry_request_auth",event:"biometry_auth_requested",postEvent:this.postEvent,params:{reason:(n||"").trim()}}).then(({token:i})=>i).finally(()=>this.authPromise=void 0)),this.authPromise}get deviceId(){return this.get("deviceId")}openSettings(){this.postEvent("web_app_biometry_open_settings")}requestAccess({reason:n,...s}={}){return this.accessPromise||(this.accessPromise=d({...s,postEvent:this.postEvent,method:"web_app_biometry_request_access",event:"biometry_info_received",params:{reason:n||""}}).then(i=>{const r=te(i);return this.set(r),r.accessGranted}).finally(()=>this.accessPromise=void 0)),this.accessPromise}get biometryType(){return this.get("biometryType")}get tokenSaved(){return this.get("tokenSaved")}async updateToken({token:n,...s}={}){return["removed","updated"].includes((await d({...s,postEvent:this.postEvent,method:"web_app_biometry_update_token",event:"biometry_token_updated",params:{token:n||""}})).status)}}async function ne(e){return te(await d({...e||{},method:"web_app_biometry_get_info",event:"biometry_info_received"}))}const ze=_("biometryManager",async({postEvent:e,version:t,state:n})=>new ee({...n||P("web_app_biometry_get_info",t)?n||await ne({timeout:1e3}):{available:!1,accessGranted:!1,accessRequested:!1,tokenSaved:!1,deviceId:""},version:t,postEvent:e}));class at extends nt{constructor(){super(...arguments);h(this,"on",this.state.on.bind(this.state));h(this,"off",this.state.off.bind(this.state))}}class se extends at{constructor(t,n){super({isConfirmationNeeded:t}),this.postEvent=n}set isConfirmationNeeded(t){this.set("isConfirmationNeeded",t),this.postEvent("web_app_setup_closing_behavior",{need_confirmation:t})}get isConfirmationNeeded(){return this.get("isConfirmationNeeded")}disableConfirmation(){this.isConfirmationNeeded=!1}enableConfirmation(){this.isConfirmationNeeded=!0}}const Fe=_("closingBehavior",({postEvent:e,state:t={isConfirmationNeeded:!1}})=>new se(t.isConfirmationNeeded,e));class ct{constructor(t,n){h(this,"supports");this.supports=$t(t,n)}}function Je(e){if(Array.isArray(e))return e;if(typeof e=="string")try{const t=JSON.parse(e);if(Array.isArray(t))return t}catch{}throw T()}class Ye extends U{constructor(n,s,i){super(Je,s,i);h(this,"itemParser");this.itemParser=typeof n=="function"?n:n.parse.bind(n)}parse(n){const s=super.parse(n);return s===void 0?s:s.map(this.itemParser)}of(n){return this.itemParser=typeof n=="function"?n:n.parse.bind(n),this}}function ie(e){return new Ye(t=>t,!1,e)}function re(e,t){return Object.fromEntries(e.map(n=>[n,t]))}class oe extends ct{constructor(t,n,s){super(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"}),this.createRequestId=n,this.postEvent=s}async delete(t,n={}){const s=Array.isArray(t)?t:[t];s.length&&await A("deleteStorageValues",{keys:s},this.createRequestId(),{...n,postEvent:this.postEvent})}async getKeys(t={}){return ie().of(p()).parse(await A("getStorageKeys",{},this.createRequestId(),{...t,postEvent:this.postEvent}))}async get(t,n={}){const s=Array.isArray(t)?t:[t];if(!s.length)return re(s,"");const i=await A("getStorageValues",{keys:s},this.createRequestId(),{...n,postEvent:this.postEvent}),r=w(re(s,p()),"CloudStorageData").parse(i);return Array.isArray(t)?r:r[t]}async set(t,n,s={}){await A("saveStorageValue",{key:t,value:n},this.createRequestId(),{...s,postEvent:this.postEvent})}}const Ke=_(({createRequestId:e,postEvent:t,version:n})=>new oe(n,e,t));class ae extends ct{constructor(t,n){super(t,{impactOccurred:"web_app_trigger_haptic_feedback",notificationOccurred:"web_app_trigger_haptic_feedback",selectionChanged:"web_app_trigger_haptic_feedback"}),this.postEvent=n}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"})}}const Qe=_(({version:e,postEvent:t})=>new ae(e,t));class ce{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?new Date(this.authDate.getTime()+t*1e3):void 0}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}}const Xe=_(({initData:e})=>e?new ce(e):void 0);function Ze(e){return Gt().parse(e)}class he extends M{constructor(t,n,s){super({isOpened:t},n,{open:"web_app_open_invoice"}),this.postEvent=s}set isOpened(t){this.set("isOpened",t)}get isOpened(){return this.get("isOpened")}async open(t,n){if(this.isOpened)throw new Error("Invoice is already opened");let s;if(!n)s=t;else{const{hostname:i,pathname:r}=new URL(t,window.location.href);if(i!=="t.me")throw new Error(`Incorrect hostname: ${i}`);const a=r.match(/^\/(\$|invoice\/)([A-Za-z0-9\-_=]+)$/);if(!a)throw new Error('Link pathname has incorrect format. Expected to receive "/invoice/{slug}" or "/${slug}"');[,,s]=a}this.isOpened=!0;try{return(await d({method:"web_app_open_invoice",event:"invoice_closed",params:{slug:s},postEvent:this.postEvent,capture(r){return s===r.slug}})).status}finally{this.isOpened=!1}}}const tn=_(({version:e,postEvent:t})=>new he(!1,e,t));class ue extends nt{constructor({postEvent:n,...s}){super(s);h(this,"postEvent");h(this,"on",(n,s)=>n==="click"?m("main_button_pressed",s):this.state.on(n,s));h(this,"off",(n,s)=>n==="click"?k("main_button_pressed",s):this.state.off(n,s));this.postEvent=n}get bgColor(){return this.get("bgColor")}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.bgColor,text_color:this.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}set isEnabled(n){this.setParams({isEnabled:n})}get isEnabled(){return this.get("isEnabled")}set isLoaderVisible(n){this.setParams({isLoaderVisible:n})}get isLoaderVisible(){return this.get("isLoaderVisible")}set isVisible(n){this.setParams({isVisible:n})}get isVisible(){return this.get("isVisible")}show(){return this.isVisible=!0,this}showLoader(){return this.isLoaderVisible=!0,this}setText(n){return this.setParams({text:n})}setTextColor(n){return this.setParams({textColor:n})}setBgColor(n){return this.setParams({bgColor:n})}setParams(n){return this.set(n),this.commit(),this}get text(){return this.get("text")}get textColor(){return this.get("textColor")}}const en=_("mainButton",({postEvent:e,themeParams:t,state:n={isVisible:!1,isEnabled:!1,text:"",isLoaderVisible:!1,textColor:t.buttonTextColor||"#ffffff",bgColor:t.buttonColor||"#000000"}})=>new ue({...n,postEvent:e}));function nn(){return G({contact:w({userId:{type:S(),from:"user_id"},phoneNumber:{type:p(),from:"phone_number"},firstName:{type:p(),from:"first_name"},lastName:{type:p().optional(),from:"last_name"}}),authDate:{type:it(),from:"auth_date"},hash:p()},"RequestedContact")}function pe(e,t){return n=>{const[s,i]=t[n];return P(s,i,e)}}function sn(e){return new Promise(t=>{setTimeout(t,e)})}class le extends M{constructor({postEvent:n,createRequestId:s,version:i,botInline:r,...a}){super(a,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"});h(this,"botInline");h(this,"postEvent");h(this,"createRequestId");h(this,"requestPhoneAccessPromise");h(this,"requestWriteAccessPromise");h(this,"supportsParam");this.createRequestId=s,this.postEvent=n,this.botInline=r;const c=this.supports.bind(this);this.supports=u=>c(u)?u!=="switchInlineQuery"||r:!1,this.supportsParam=pe(i,{"setHeaderColor.color":["web_app_set_header_color","color"]})}async getRequestedContact({timeout:n=1e4}={}){return nn().parse(await A("getRequestedContact",{},this.createRequestId(),{postEvent:this.postEvent,timeout:n}))}get bgColor(){return this.get("bgColor")}close(n){this.postEvent("web_app_close",{return_back:n})}get headerColor(){return this.get("headerColor")}get isBotInline(){return this.botInline}get isDark(){return et(this.bgColor)}ready(){this.postEvent("web_app_ready")}async requestContact({timeout:n=5e3}={}){try{return await this.getRequestedContact()}catch{}if(await this.requestPhoneAccess()!=="sent")throw new Error("Access denied.");const i=Date.now()+n;let r=50;return Z(async()=>{for(;Date.now()<i;){try{return await this.getRequestedContact()}catch{}await sn(r),r+=50}throw Ot(n)},n)}async requestPhoneAccess(n={}){return this.requestPhoneAccessPromise||(this.requestPhoneAccessPromise=d({...n,method:"web_app_request_phone",event:"phone_requested",postEvent:this.postEvent}).then(({status:s})=>s).finally(()=>this.requestPhoneAccessPromise=void 0)),this.requestPhoneAccessPromise}async requestWriteAccess(n={}){return this.requestWriteAccessPromise||(this.requestWriteAccessPromise=d({...n,method:"web_app_request_write_access",event:"write_access_requested",postEvent:this.postEvent}).then(({status:s})=>s).finally(()=>this.requestWriteAccessPromise=void 0)),this.requestWriteAccessPromise}sendData(n){const{size:s}=new Blob([n]);if(!s||s>4096)throw new Error(`Passed data has incorrect size: ${s}`);this.postEvent("web_app_data_send",{data:n})}setHeaderColor(n){this.postEvent("web_app_set_header_color",H(n)?{color:n}:{color_key:n}),this.set("headerColor",n)}setBgColor(n){this.postEvent("web_app_set_background_color",{color:n}),this.set("bgColor",n)}switchInlineQuery(n,s=[]){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:n,chat_types:s})}}const rn=_("miniApp",({themeParams:e,botInline:t=!1,state:n={bgColor:e.bgColor||"#ffffff",headerColor:e.headerBgColor||"#000000"},...s})=>new le({...s,...n,botInline:t}));function on(e){const t=e.message.trim(),n=(e.title||"").trim(),s=e.buttons||[];let i;if(n.length>64)throw new Error(`Title has incorrect size: ${n.length}`);if(!t.length||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?i=s.map(r=>{const{id:a=""}=r;if(a.length>64)throw new Error(`Button ID has incorrect size: ${a}`);if(!r.type||r.type==="default"||r.type==="destructive"){const c=r.text.trim();if(!c.length||c.length>64){const u=r.type||"default";throw new Error(`Button text with type "${u}" has incorrect size: ${r.text.length}`)}return{...r,text:c,id:a}}return{...r,id:a}}):i=[{type:"close",id:""}],{title:n,message:t,buttons:i}}class de extends M{constructor(t,n,s){super({isOpened:t},n,{open:"web_app_open_popup"}),this.postEvent=s}set isOpened(t){this.set("isOpened",t)}get isOpened(){return this.get("isOpened")}async open(t){if(this.isOpened)throw new Error("Popup is already opened.");this.isOpened=!0;try{const{button_id:n=null}=await d({event:"popup_closed",method:"web_app_open_popup",postEvent:this.postEvent,params:on(t)});return n}finally{this.isOpened=!1}}}const an=_(({postEvent:e,version:t})=>new de(!1,t,e));class _e extends M{constructor(t,n,s){super({isOpened:t},n,{close:"web_app_close_scan_qr_popup",open:"web_app_open_scan_qr_popup"}),this.postEvent=s}close(){this.postEvent("web_app_close_scan_qr_popup"),this.isOpened=!1}set isOpened(t){this.set("isOpened",t)}get isOpened(){return this.get("isOpened")}async open(t){if(this.isOpened)throw new Error("The scanner is already opened");const{text:n,capture:s}=(typeof t=="string"?{text:t}:t)||{};this.isOpened=!0;try{const r=(await d({method:"web_app_open_scan_qr_popup",event:["qr_text_received","scan_qr_popup_closed"],postEvent:this.postEvent,params:{text:n},capture(a){return a.event==="scan_qr_popup_closed"||!s||s(a.payload)}})||{}).data||null;return r&&this.close(),r}finally{this.isOpened=!1}}}const cn=_(({version:e,postEvent:t})=>new _e(!1,e,t));class fe extends st{constructor(n,s,i){super({isVisible:n},s,{show:"web_app_setup_settings_button",hide:"web_app_setup_settings_button"});h(this,"on",(n,s)=>n==="click"?m("settings_button_pressed",s):this.state.on(n,s));h(this,"off",(n,s)=>n==="click"?k("settings_button_pressed",s):this.state.off(n,s));this.postEvent=i}set isVisible(n){this.set("isVisible",n),this.postEvent("web_app_setup_settings_button",{is_visible:n})}get isVisible(){return this.get("isVisible")}hide(){this.isVisible=!1}show(){this.isVisible=!0}}const hn=_("settingsButton",({version:e,postEvent:t,state:n={isVisible:!1}})=>new fe(n.isVisible,e,t));function ht(e){return jt().parse(e)}class ge extends at{get accentTextColor(){return this.get("accentTextColor")}get bgColor(){return this.get("bgColor")}get buttonColor(){return this.get("buttonColor")}get buttonTextColor(){return this.get("buttonTextColor")}get destructiveTextColor(){return this.get("destructiveTextColor")}getState(){return this.clone()}get headerBgColor(){return this.get("headerBgColor")}get hintColor(){return this.get("hintColor")}get isDark(){return!this.bgColor||et(this.bgColor)}get linkColor(){return this.get("linkColor")}get secondaryBgColor(){return this.get("secondaryBgColor")}get sectionBgColor(){return this.get("sectionBgColor")}get sectionHeaderTextColor(){return this.get("sectionHeaderTextColor")}get sectionSeparatorColor(){return this.get("sectionHeaderTextColor")}listen(){return m("theme_changed",t=>{this.set(ht(t.theme_params))})}get subtitleTextColor(){return this.get("subtitleTextColor")}get textColor(){return this.get("textColor")}}const un=_("themeParams",({themeParams:e,state:t=e,addCleanup:n})=>{const s=new ge(t);return n(s.listen()),s});function pn(e={}){return d({...e,method:"web_app_request_theme",event:"theme_changed"}).then(ht)}function V(e,t){return e.startsWith(t)?e:`${t}${e}`}function N(e){return new URL(typeof e=="string"?e:`${e.pathname||""}${V(e.search||"","?")}${V(e.hash||"","#")}`,"http://a")}class be extends ct{constructor(n,s,i){super(n,{readTextFromClipboard:"web_app_read_text_from_clipboard"});h(this,"supportsParam");this.version=n,this.createRequestId=s,this.postEvent=i,this.supportsParam=pe(n,{"openLink.tryInstantView":["web_app_open_link","try_instant_view"]})}openLink(n,s){const i=N(n).toString();if(!P("web_app_open_link",this.version)){window.open(i,"_blank");return}const r=typeof s=="boolean"?{tryInstantView:s}:s||{};this.postEvent("web_app_open_link",{url:i,try_browser:r.tryBrowser,try_instant_view:r.tryInstantView})}openTelegramLink(n){const{hostname:s,pathname:i,search:r}=new URL(n,"https://t.me");if(s!=="t.me")throw new Error(`URL has not allowed hostname: ${s}. Only "t.me" is allowed`);if(!P("web_app_open_tg_link",this.version)){window.location.href=n;return}this.postEvent("web_app_open_tg_link",{path_full:i+r})}async readTextFromClipboard(){const n=this.createRequestId(),{data:s=null}=await d({method:"web_app_read_text_from_clipboard",event:"clipboard_text_received",postEvent:this.postEvent,params:{req_id:n},capture:X(n)});return s}shareURL(n,s){this.openTelegramLink("https://t.me/share/url?"+new URLSearchParams({url:n,text:s||""}).toString().replace(/\+/g,"%20"))}}const ln=_(({version:e,postEvent:t,createRequestId:n})=>new be(e,n,t));async function ut(e={}){const{is_expanded:t,is_state_stable:n,...s}=await d({...e,method:"web_app_request_viewport",event:"viewport_changed"});return{...s,isExpanded:t,isStateStable:n}}function B(e){return e<0?0:e}class we extends at{constructor({postEvent:n,stableHeight:s,height:i,width:r,isExpanded:a}){super({height:B(i),isExpanded:a,stableHeight:B(s),width:B(r)});h(this,"postEvent");this.postEvent=n}async sync(n){const{isStateStable:s,...i}=await ut(n);this.set({...i,stableHeight:s?i.height:this.get("stableHeight")})}get height(){return this.get("height")}get stableHeight(){return this.get("stableHeight")}listen(){return m("viewport_changed",n=>{const{height:s,width:i,is_expanded:r,is_state_stable:a}=n,c=B(s);this.set({height:c,isExpanded:r,width:B(i),...a?{stableHeight:c}:{}})})}get isExpanded(){return this.get("isExpanded")}get width(){return this.get("width")}expand(){this.postEvent("web_app_expand"),this.set("isExpanded",!0)}get isStable(){return this.stableHeight===this.height}}const dn=_("viewport",async({state:e,platform:t,postEvent:n,addCleanup:s})=>{let i=!1,r=0,a=0,c=0;if(e)i=e.isExpanded,r=e.height,a=e.width,c=e.stableHeight;else if(["macos","tdesktop","unigram","webk","weba","web"].includes(t))i=!0,r=window.innerHeight,a=window.innerWidth,c=window.innerHeight;else{const l=await ut({timeout:1e3,postEvent:n});i=l.isExpanded,r=l.height,a=l.width,c=l.isStateStable?r:0}const u=new we({postEvent:n,height:r,width:a,stableHeight:c,isExpanded:i});return s(u.listen()),u});function E(e,t){document.documentElement.style.setProperty(e,t)}function _n(e,t,n){n||(n=c=>`--tg-${c}-color`);const s=n("header"),i=n("bg"),r=()=>{const{headerColor:c}=e;if(H(c))E(s,c);else{const{bgColor:u,secondaryBgColor:l}=t;c==="bg_color"&&u?E(s,u):c==="secondary_bg_color"&&l&&E(s,l)}E(i,e.bgColor)},a=[t.on("change",r),e.on("change",r)];return r(),()=>a.forEach(c=>c())}function fn(e,t){t||(t=s=>`--tg-theme-${s.replace(/[A-Z]/g,i=>`-${i.toLowerCase()}`)}`);const n=()=>{Object.entries(e.getState()).forEach(([s,i])=>{i&&E(t(s),i)})};return n(),e.on("change",n)}function gn(e,t){t||(t=l=>`--tg-viewport-${l}`);const[n,s,i]=["height","width","stable-height"].map(l=>t(l)),r=()=>E(n,`${e.height}px`),a=()=>E(s,`${e.width}px`),c=()=>E(i,`${e.stableHeight}px`),u=[e.on("change:height",r),e.on("change:width",a),e.on("change:stableHeight",c)];return r(),a(),c(),()=>u.forEach(l=>l())}function bn(e=!0){const t=[m("reload_iframe",()=>{I("iframe_will_reload"),window.location.reload()})],n=()=>t.forEach(s=>s());if(e){const s=document.createElement("style");s.id="telegram-custom-styles",document.head.appendChild(s),t.push(m("set_custom_style",i=>{s.innerHTML=i}),()=>document.head.removeChild(s))}return I("iframe_ready",{reload_supported:!0}),n}function wn(){return typeof window>"u"}async function mn(){if(Mt(window))return!0;try{return await d({method:"web_app_request_theme",event:"theme_changed",timeout:100}),!0}catch{return!1}}function yn(e){const t=typeof e=="string"?x(e):e;Xt(t);function n(i){if(typeof i=="string")try{const{eventType:r}=qt(i);r==="web_app_request_theme"&&K("theme_changed",{theme_params:JSON.parse(rt(t.themeParams))}),r==="web_app_request_viewport"&&K("viewport_changed",{width:window.innerWidth,height:window.innerHeight,is_state_stable:!0,is_expanded:!0})}catch{}}if(Q()){const i=window.parent.postMessage.bind(window.parent);window.parent.postMessage=r=>{n(r),i(r)};return}if(Dt(window)){const i=window.external.notify.bind(window.external);window.external.notify=r=>{n(r),i(r)};return}const s=window.TelegramWebviewProxy;window.TelegramWebviewProxy={...s||{},postEvent(...i){n(JSON.stringify({eventType:i[0],eventData:i[1]})),s&&s.postEvent(...i)}}}function me(e){return e instanceof q}function En(e,t){return me(e)&&e.type===t}function pt(e,t){let n,s,i;return typeof e=="string"?n=e:(n=e.pathname===void 0?t:e.pathname,s=e.params,i=e.id),Object.freeze({id:i||(Math.random()*2**14|0).toString(16),pathname:n,params:s})}class ye{constructor(t,n,s=I){h(this,"history");h(this,"ee",new R);h(this,"attached",!1);h(this,"back",()=>this.go(-1));h(this,"on",this.ee.on.bind(this.ee));h(this,"off",this.ee.off.bind(this.ee));if(this._index=n,this.postEvent=s,t.length===0)throw f(Tt,"History should not be empty.");if(n<0||n>=t.length)throw f(Ct,"Index should not be zero and higher or equal than history size.");this.history=t.map(i=>pt(i,""))}attach(){this.attached||(this.attached=!0,this.sync(),m("back_button_pressed",this.back))}get current(){return this.history[this.index]}detach(){this.attached=!1,k("back_button_pressed",this.back)}forward(){this.go(1)}go(t,n){const s=this.index+t,i=Math.min(Math.max(0,s),this.history.length-1);(s===i||n)&&this.replaceAndMove(i,this.history[i])}goTo(t,n){this.go(t-this.index,n)}get hasPrev(){return this.index>0}get hasNext(){return this.index!==this.history.length-1}get index(){return this._index}push(t){this.hasNext&&this.history.splice(this.index+1),this.replaceAndMove(this.index+1,pt(t,this.current.pathname))}replace(t){this.replaceAndMove(this.index,pt(t,this.current.pathname))}replaceAndMove(t,n){const s=t-this.index;if(!s&&this.current===n)return;const i=this.current;if(this.index!==t){const r=this._index;this._index=t,this.attached&&r>0!=t>0&&this.sync()}this.history[t]=n,this.ee.emit("change",{navigator:this,from:i,to:this.current,delta:s})}sync(){this.postEvent("web_app_setup_back_button",{is_visible:!!this.index})}}function lt({params:e,...t}){return{...e||{hash:"",search:""},...t}}function L(e){const t=typeof e=="string"?e.startsWith("/"):!!(e.pathname&&e.pathname.startsWith("/")),n=N(e);return`${t?n.pathname:n.pathname.slice(1)}${n.search}${n.hash}`}function dt(e,t,n){let s,i;typeof e=="string"?s=e:(s=L(e),n=e.state,i=e.id);const{pathname:r,search:a,hash:c}=new URL(s,`http://a${V(t,"/")}`);return{id:i,pathname:r,params:{hash:c,search:a,state:n}}}async function O(e){return e===0?!0:Promise.race([new Promise(t=>{const n=F("popstate",()=>{n(),t(!0)});window.history.go(e)}),new Promise(t=>{setTimeout(t,50,!1)})])}async function vn(){if(window.history.length<=1||(window.history.pushState(null,""),await O(1-window.history.length)))return;let t=await O(-1);for(;t;)t=await O(-1)}function _t(e){return N(e).pathname}const Ee=0,ft=1,gt=2;class bt{constructor(t,n,{postEvent:s,hashMode:i="classic",base:r}={}){h(this,"navigator");h(this,"ee",new R);h(this,"hashMode");h(this,"base");h(this,"attached",!1);h(this,"onPopState",({state:t})=>{if(t===null)return this.push(this.parsePath(window.location.href));t===Ee?window.history.forward():t===ft&&this.back(),t===gt&&this.forward()});h(this,"onNavigatorChange",async({to:t,from:n,delta:s})=>{this.attached&&await this.syncHistory(),this.ee.emit("change",{delta:s,from:lt(n),to:lt(t),navigator:this})});h(this,"on",this.ee.on.bind(this.ee));h(this,"off",this.ee.off.bind(this.ee));this.navigator=new ye(t.map(a=>dt(a,"/")),n,s),this.navigator.on("change",a=>{this.onNavigatorChange(a)}),this.hashMode=i,this.base=_t(r||"")}async attach(){this.attached||(this.attached=!0,this.navigator.attach(),window.addEventListener("popstate",this.onPopState),await this.syncHistory())}back(){this.navigator.back()}detach(){this.attached=!1,this.navigator.detach(),window.removeEventListener("popstate",this.onPopState)}forward(){return this.navigator.forward()}get index(){return this.navigator.index}get id(){return this.navigator.current.id}go(t,n){return this.navigator.go(t,n)}goTo(t,n){this.navigator.goTo(t,n)}get hash(){return(this.navigator.current.params||{}).hash||""}get hasPrev(){return this.navigator.hasPrev}get hasNext(){return this.navigator.hasNext}get history(){return this.navigator.history.map(lt)}get path(){return L(this)}get pathname(){return this.navigator.current.pathname}parsePath(t){let n=N(t);return this.hashMode&&(n=N(n.hash.slice(1))),{pathname:n.pathname,search:n.search,hash:n.hash}}push(t,n){const s=dt(t,this.path),{state:i=n}=s.params;this.navigator.push({...s,params:{...s.params,state:i}})}replace(t,n){const s=dt(t,this.path),{state:i=n}=s.params;this.navigator.replace({...s,params:{...s.params,state:i}})}renderPath(t){const n=(this.base.length===1?"":this.base)+V(L(t),"/");return this.hashMode?V(n.slice(1),this.hashMode==="classic"?"#":"#/"):n}async syncHistory(){window.removeEventListener("popstate",this.onPopState);const{state:t}=this,n=this.renderPath(this);await vn(),this.hasPrev&&this.hasNext?(window.history.replaceState(ft,""),window.history.pushState(t,"",n),window.history.pushState(gt,""),await O(-1)):this.hasPrev?(window.history.replaceState(ft,""),window.history.pushState(t,"",n)):this.hasNext?(window.history.replaceState(t,n),window.history.pushState(gt,""),await O(-1)):(window.history.replaceState(Ee,""),window.history.pushState(t,"",n)),window.addEventListener("popstate",this.onPopState)}get search(){return(this.navigator.current.params||{}).search||""}get state(){return(this.navigator.current.params||{}).state}}function ve(e){e||(e={});const{href:t,hash:n}=window.location;let s=L(e.hashMode===null?t:n.includes("?")?n.slice(1):`?${n.slice(1)}`);const i=e.base?_t(e.base):void 0;if(i){if(!s.startsWith(i))throw f(It,`Path "${s}" expected to be starting with "${i}"`);s=s.slice(i.length)}return new bt([s],0,e)}function Sn(e){const t=e.match(/#(.+)/);return t?t[1]:null}function Pn(e,t){if(ot()){const n=sessionStorage.getItem(e);if(n)try{const{index:s,history:i}=JSON.parse(n);return new bt(i,s,t)}catch(s){console.error("Unable to restore hash navigator state.",s)}}return ve(t)}function Rn(e,t){const n=Pn(e,t),s=()=>sessionStorage.setItem(e,JSON.stringify({index:n.index,history:n.history}));return n.on("change",s),s(),n}return o.BackButton=Wt,o.BasicNavigator=ye,o.BiometryManager=ee,o.BrowserNavigator=bt,o.ClosingBehavior=se,o.CloudStorage=oe,o.ERR_INVALID_PATH_BASE=It,o.ERR_INVOKE_CUSTOM_METHOD_RESPONSE=St,o.ERR_METHOD_PARAMETER_UNSUPPORTED=Et,o.ERR_METHOD_UNSUPPORTED=yt,o.ERR_NAVIGATION_HISTORY_EMPTY=Tt,o.ERR_NAVIGATION_INDEX_INVALID=Ct,o.ERR_NAVIGATION_ITEM_INVALID=Te,o.ERR_PARSE=Y,o.ERR_SSR_INIT=Ce,o.ERR_TIMED_OUT=Pt,o.ERR_UNEXPECTED_TYPE=Rt,o.ERR_UNKNOWN_ENV=vt,o.EventEmitter=R,o.HapticFeedback=ae,o.InitData=ce,o.Invoice=he,o.MainButton=ue,o.MiniApp=le,o.Popup=de,o.QRScanner=_e,o.SDKError=q,o.SettingsButton=fe,o.ThemeParams=ge,o.Utils=be,o.Viewport=we,o.array=ie,o.bindMiniAppCSSVars=_n,o.bindThemeParamsCSSVars=fn,o.bindViewportCSSVars=gn,o.boolean=y,o.captureSameReq=X,o.classNames=W,o.compareVersions=kt,o.createBrowserNavigatorFromLocation=ve,o.createPostEvent=Lt,o.createSafeURL=N,o.date=it,o.getHash=Sn,o.getPathname=_t,o.initBackButton=je,o.initBiometryManager=ze,o.initClosingBehavior=Fe,o.initCloudStorage=Ke,o.initHapticFeedback=Qe,o.initInitData=Xe,o.initInvoice=tn,o.initMainButton=en,o.initMiniApp=rn,o.initNavigator=Rn,o.initPopup=an,o.initQRScanner=cn,o.initSettingsButton=hn,o.initThemeParams=un,o.initUtils=ln,o.initViewport=dn,o.initWeb=bn,o.invokeCustomMethod=A,o.isColorDark=et,o.isIframe=Q,o.isPageReload=ot,o.isRGB=H,o.isRGBShort=Ut,o.isSDKError=me,o.isSDKErrorOfType=En,o.isSSR=wn,o.isTMA=mn,o.json=w,o.mergeClassNames=Ve,o.mockTelegramEnv=yn,o.number=S,o.off=k,o.on=m,o.parseInitData=Ze,o.parseLaunchParams=x,o.parseThemeParams=ht,o.postEvent=I,o.request=d,o.requestBiometryInfo=ne,o.requestThemeParams=pn,o.requestViewport=ut,o.retrieveLaunchParams=Zt,o.rgb=xt,o.searchParams=G,o.serializeLaunchParams=Qt,o.serializeThemeParams=rt,o.setCSSVar=E,o.setDebug=Pe,o.setTargetOrigin=Me,o.string=p,o.subscribe=wt,o.supports=P,o.targetOrigin=Bt,o.toRGB=tt,o.unsubscribe=v,o.urlToPath=L,o.withTimeout=Z,Object.defineProperty(o,Symbol.toStringTag,{value:"Module"}),o}({});
|
|
2
4
|
//# sourceMappingURL=index.iife.js.map
|