@tma.js/sdk-solid 2.1.0 → 2.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +149 -146
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const m=require("solid-js");var as=Object.defineProperty,cs=(e,t,s)=>t in e?as(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,c=(e,t,s)=>(cs(e,typeof t!="symbol"?t+"":t,s),s);function kt(e,t){let s;const n=()=>{s!==void 0&&t&&t(s),s=void 0};return[()=>s===void 0?s=e(n):s,n]}function it(e){const t=J(),{count:s}=t;t.unsubscribe(e),s&&!t.count&&vs()}function Ot(e){return J().subscribe(e),()=>it(e)}class hs{constructor(t,s={}){this.scope=t,this.options=s}print(t,...s){const n=new Date,r=Intl.DateTimeFormat("en-GB",{hour:"2-digit",minute:"2-digit",second:"2-digit",fractionalSecondDigits:3,timeZone:"UTC"}).format(n),{textColor:i,bgColor:o}=this.options,a="font-weight: bold;padding: 0 5px;border-radius:5px";console[t](`%c${r}%c / %c${this.scope}`,`${a};background-color: lightblue;color:black`,"",`${a};${i?`color:${i};`:""}${o?`background-color:${o}`:""}`,...s)}error(...t){this.print("error",...t)}log(...t){this.print("log",...t)}}const j=new hs("SDK",{bgColor:"forestgreen",textColor:"white"});let st=!1;const Rt=({event:e,args:[t]})=>{j.log("Event received:",t===void 0?{name:e}:{name:e,data:t})};function qt(e){st!==e&&(st=e,e?Ot(Rt):it(Rt))}function ps(...e){st&&j.log(...e)}class V{constructor(){c(this,"listeners",new Map),c(this,"listenersCount",0),c(this,"subscribeListeners",[])}clear(){this.listeners.clear(),this.subscribeListeners=[]}get count(){return this.listenersCount+this.subscribeListeners.length}emit(t,...s){this.subscribeListeners.forEach(n=>n({event:t,args:s})),(this.listeners.get(t)||[]).forEach(([n,r])=>{n(...s),r&&this.off(t,n)})}on(t,s,n){let r=this.listeners.get(t);return r||this.listeners.set(t,r=[]),r.push([s,n]),this.listenersCount+=1,()=>this.off(t,s)}off(t,s){const n=this.listeners.get(t)||[];for(let r=0;r<n.length;r+=1)if(s===n[r][0]){n.splice(r,1),this.listenersCount-=1;return}}subscribe(t){return this.subscribeListeners.push(t),()=>this.unsubscribe(t)}unsubscribe(t){for(let s=0;s<this.subscribeListeners.length;s+=1)if(this.subscribeListeners[s]===t){this.subscribeListeners.splice(s,1);return}}}function nt(e,t,s){return window.addEventListener(e,t,s),()=>window.removeEventListener(e,t,s)}class B extends Error{constructor(t,s,n){super(s,{cause:n}),this.type=t,Object.setPrototypeOf(this,B.prototype)}}function _(e,t,s){return new B(e,t,s)}const Dt="ERR_METHOD_UNSUPPORTED",Nt="ERR_METHOD_PARAMETER_UNSUPPORTED",Vt="ERR_UNKNOWN_ENV",Bt="ERR_INVOKE_CUSTOM_METHOD_RESPONSE",Mt="ERR_TIMED_OUT",$t="ERR_UNEXPECTED_TYPE",ot="ERR_PARSE",Lt="ERR_NAVIGATION_LIST_EMPTY",Ut="ERR_NAVIGATION_CURSOR_INVALID",us="ERR_NAVIGATION_ITEM_INVALID",G="ERR_SSR_INIT",Ht="ERR_SSR_POST_EVENT",Wt="ERR_INVALID_PATH_BASE";function A(){return _($t,"Value has unexpected type")}class K{constructor(t,s,n){this.parser=t,this.isOptional=s,this.type=n}parse(t){if(!(this.isOptional&&t===void 0))try{return this.parser(t)}catch(s){throw _(ot,`Unable to parse value${this.type?` as ${this.type}`:""}`,s)}}optional(){return this.isOptional=!0,this}}function I(e,t){return()=>new K(e,!1,t)}const y=I(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 A()},"boolean");function jt(e,t){const s={};for(const n in e){const r=e[n];if(!r)continue;let i,o;if(typeof r=="function"||"parse"in r)i=n,o=typeof r=="function"?r:r.parse.bind(r);else{const{type:a}=r;i=r.from||n,o=typeof a=="function"?a:a.parse.bind(a)}try{const a=o(t(i));a!==void 0&&(s[n]=a)}catch(a){throw _(ot,`Unable to parse field "${n}"`,a)}}return s}function at(e){let t=e;if(typeof t=="string"&&(t=JSON.parse(t)),typeof t!="object"||t===null||Array.isArray(t))throw A();return t}function d(e,t){return new K(s=>{const n=at(s);return jt(e,r=>n[r])},!1,t)}const P=I(e=>{if(typeof e=="number")return e;if(typeof e=="string"){const t=Number(e);if(!Number.isNaN(t))return t}throw A()},"number");function z(e){return/^#[\da-f]{6}$/i.test(e)}function Gt(e){return/^#[\da-f]{3}$/i.test(e)}function ct(e){const t=e.replace(/\s/g,"").toLowerCase();if(z(t))return t;if(Gt(t)){let n="#";for(let r=0;r<3;r+=1)n+=t[1+r].repeat(2);return n}const s=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(!s)throw new Error(`Value "${e}" does not satisfy any of known RGB formats.`);return s.slice(1).reduce((n,r)=>{const i=parseInt(r,10).toString(16);return n+(i.length===1?"0":"")+i},"#")}const p=I(e=>{if(typeof e=="string"||typeof e=="number")return e.toString();throw A()},"string"),ht=I(e=>ct(p().parse(e)),"rgb");function ds(e){return d({eventType:p(),eventData:t=>t}).parse(e)}function ls(){["TelegramGameProxy_receiveEvent","TelegramGameProxy","Telegram"].forEach(e=>{delete window[e]})}function _s(e,t){window.dispatchEvent(new MessageEvent("message",{data:JSON.stringify({eventType:e,eventData:t}),source:window.parent}))}function gs(){[["TelegramGameProxy_receiveEvent"],["TelegramGameProxy","receiveEvent"],["Telegram","WebView","receiveEvent"]].forEach(e=>{let t=window;e.forEach((s,n,r)=>{if(n===r.length-1){t[s]=_s;return}s in t||(t[s]={}),t=t[s]})})}const fs=d({button_id:e=>e==null?void 0:p().parse(e)}),ws={clipboard_text_received:d({req_id:p(),data:e=>e===null?e:p().optional().parse(e)}),custom_method_invoked:d({req_id:p(),result:e=>e,error:p().optional()}),invoice_closed:d({slug:p(),status:p()}),phone_requested:d({status:p()}),popup_closed:{parse:e=>fs.parse(e??{})},qr_text_received:d({data:p().optional()}),theme_changed:d({theme_params:e=>{const t=ht().optional();return Object.entries(at(e)).reduce((s,[n,r])=>(s[n]=t.parse(r),s),{})}}),viewport_changed:d({height:P(),width:e=>e==null?window.innerWidth:P().parse(e),is_state_stable:y(),is_expanded:y()}),write_access_requested:d({status:p()})};function ms(){const e=new V;gs();let t=[ls,nt("resize",()=>{e.emit("viewport_changed",{width:window.innerWidth,height:window.innerHeight,is_state_stable:!0,is_expanded:!0})}),nt("message",s=>{if(s.source!==window.parent)return;let n;try{n=ds(s.data)}catch{return}const{eventType:r,eventData:i}=n,o=ws[r];try{const a=o?o.parse(i):i;e.emit(...a?[r,a]:[r])}catch(a){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`,n,a)}}),()=>e.clear()];return[e,()=>{t.forEach(s=>s()),t=[]}]}const[bs,vs]=kt(e=>{const[t,s]=ms(),n=t.off.bind(t);return t.off=(r,i)=>{const{count:o}=t;n(r,i),o&&!t.count&&e()},[t,s]},([,e])=>e());function J(){return bs()[0]}function M(e,t){J().off(e,t)}function b(e,t,s){return J().on(e,t,s)}function $(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Kt(e,t){const s=e.split("."),n=t.split("."),r=Math.max(s.length,n.length);for(let i=0;i<r;i+=1){const o=parseInt(s[i]||"0",10),a=parseInt(n[i]||"0",10);if(o!==a)return o>a?1:-1}return 0}function v(e,t){return Kt(e,t)<=0}function S(e,t,s){if(typeof s=="string"){if(e==="web_app_open_link"&&t==="try_instant_view")return v("6.4",s);if(e==="web_app_set_header_color"&&t==="color")return v("6.9",s)}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 v("6.1",t);case"web_app_open_popup":return v("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 v("6.4",t);case"web_app_switch_inline_query":return v("6.7",t);case"web_app_invoke_custom_method":case"web_app_request_write_access":case"web_app_request_phone":return v("6.9",t);case"web_app_setup_settings_button":return v("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 v("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 ys(e){return"external"in e&&$(e.external)&&"notify"in e.external&&typeof e.external.notify=="function"}function Es(e){return"TelegramWebviewProxy"in e&&$(e.TelegramWebviewProxy)&&"postEvent"in e.TelegramWebviewProxy&&typeof e.TelegramWebviewProxy.postEvent=="function"}function pt(){try{return window.self!==window.top}catch{return!0}}let zt="https://web.telegram.org";function Ps(e){zt=e}function Jt(){return zt}function R(e,t,s){let n={},r;t===void 0&&s===void 0?n={}:t!==void 0&&s!==void 0?(n=s,r=t):t!==void 0&&("targetOrigin"in t?n=t:r=t);const{targetOrigin:i=Jt()}=n;if(ps("Posting event:",r?{event:e,data:r}:{event:e}),pt()){window.parent.postMessage(JSON.stringify({eventType:e,eventData:r}),i);return}if(ys(window)){window.external.notify(JSON.stringify({eventType:e,eventData:r}));return}if(Es(window)){window.TelegramWebviewProxy.postEvent(e,JSON.stringify(r));return}throw _(Vt,"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 Qt(e){return(t,s)=>{if(!S(t,e))throw _(Dt,`Method "${t}" is unsupported in Mini Apps version ${e}`);if($(s)){let n;if(t==="web_app_open_link"&&"try_instant_view"in s?n="try_instant_view":t==="web_app_set_header_color"&&"color"in s&&(n="color"),n&&!S(t,n,e))throw _(Nt,`Parameter "${n}" of "${t}" method is unsupported in Mini Apps version ${e}`)}return R(t,s)}}function ut(e){return({req_id:t})=>t===e}function Ft(e){return _(Mt,`Timeout reached: ${e}ms`)}function dt(e,t){return Promise.race([typeof e=="function"?e():e,new Promise((s,n)=>{setTimeout(()=>{n(Ft(t))},t)})])}async function l(e){let t;const s=new Promise(u=>{t=u}),{method:n,event:r,capture:i,postEvent:o=R,timeout:a}=e,h=(Array.isArray(r)?r:[r]).map(u=>b(u,U=>(!i||i(U))&&t(U)));try{return o(n,e.params),await(a?dt(s,a):s)}finally{h.forEach(u=>u())}}async function C(e,t,s,n={}){const{result:r,error:i}=await l({...n,method:"web_app_invoke_custom_method",event:"custom_method_invoked",params:{method:e,params:t,req_id:s},capture:ut(s)});if(i)throw _(Bt,i);return r}function W(...e){return e.map(t=>{if(typeof t=="string")return t;if($(t))return W(Object.entries(t).map(s=>s[1]&&s[0]));if(Array.isArray(t))return W(...t)}).filter(Boolean).join(" ")}function Ss(...e){return e.reduce((t,s)=>($(s)&&Object.entries(s).forEach(([n,r])=>{const i=W(t[n],r);i.length&&(t[n]=i)}),t),{})}function lt(e){const t=ct(e);return Math.sqrt([.299,.587,.114].reduce((s,n,r)=>{const i=parseInt(t.slice(1+r*2,1+(r+1)*2),16);return s+i*i*n},0))<120}class xs{constructor(t){c(this,"ee",new V),c(this,"on",this.ee.on.bind(this.ee)),c(this,"off",this.ee.off.bind(this.ee)),this.state=t}clone(){return{...this.state}}set(t,s){Object.entries(typeof t=="string"?{[t]:s}:t).reduce((n,[r,i])=>this.state[r]===i||i===void 0?n:(this.state[r]=i,this.ee.emit(`change:${r}`,i),!0),!1)&&this.ee.emit("change",this.state)}get(t){return this.state[t]}}class _t{constructor(t){c(this,"state"),c(this,"get"),c(this,"set"),c(this,"clone"),this.state=new xs(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 Yt(e,t){return s=>S(t[s],e)}class gt extends _t{constructor(t,s,n){super(t),c(this,"supports"),this.supports=Yt(s,n)}}class Zt extends gt{constructor(t,s,n){super({isVisible:t},s,{show:"web_app_setup_back_button",hide:"web_app_setup_back_button"}),c(this,"on",(r,i)=>r==="click"?b("back_button_pressed",i):this.state.on(r,i)),c(this,"off",(r,i)=>r==="click"?M("back_button_pressed",i):this.state.off(r,i)),this.postEvent=n}set isVisible(t){this.set("isVisible",t),this.postEvent("web_app_setup_back_button",{is_visible:t})}get isVisible(){return this.get("isVisible")}hide(){this.isVisible=!1}show(){this.isVisible=!0}}function T(){return typeof window>"u"}const ft=I(e=>e instanceof Date?e:new Date(P().parse(e)*1e3),"Date");function Q(e,t){return new K(s=>{if(typeof s!="string"&&!(s instanceof URLSearchParams))throw A();const n=typeof s=="string"?new URLSearchParams(s):s;return jt(e,r=>{const i=n.get(r);return i===null?void 0:i})},!1,t)}const Cs=d({id:P(),type:p(),title:p(),photoUrl:{type:p().optional(),from:"photo_url"},username:p().optional()},"Chat").optional(),Tt=d({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:P(),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 Xt(){return Q({authDate:{type:ft(),from:"auth_date"},canSendAfter:{type:P().optional(),from:"can_send_after"},chat:Cs,chatInstance:{type:p().optional(),from:"chat_instance"},chatType:{type:p().optional(),from:"chat_type"},hash:p(),queryId:{type:p().optional(),from:"query_id"},receiver:Tt,startParam:{type:p().optional(),from:"start_param"},user:Tt},"InitData")}function Rs(e){return e.replace(/_[a-z]/g,t=>t[1].toUpperCase())}function Ts(e){return e.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}const te=I(e=>{const t=ht().optional();return Object.entries(at(e)).reduce((s,[n,r])=>(s[Rs(n)]=t.parse(r),s),{})},"ThemeParams");function wt(e){return Q({botInline:{type:y().optional(),from:"tgWebAppBotInline"},initData:{type:Xt().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:te(),from:"tgWebAppThemeParams"},version:{type:p(),from:"tgWebAppVersion"}}).parse(e)}function ee(e){return wt(e.replace(/^[^?#]*[?#]/,"").replace(/[?#]/g,"&"))}function As(){return ee(window.location.href)}function se(){return performance.getEntriesByType("navigation")[0]}function Is(){const e=se();if(!e)throw new Error("Unable to get first navigation entry.");return ee(e.name)}function ne(e){return`tma.js/${e.replace(/[A-Z]/g,t=>`-${t.toLowerCase()}`)}`}function re(e,t){sessionStorage.setItem(ne(e),JSON.stringify(t))}function ie(e){const t=sessionStorage.getItem(ne(e));try{return t?JSON.parse(t):void 0}catch{}}function ks(){return wt(ie("launchParams")||"")}function oe(e){return JSON.stringify(Object.fromEntries(Object.entries(e).map(([t,s])=>[Ts(t),s])))}function ae(e){const{initDataRaw:t,themeParams:s,platform:n,version:r,showSettings:i,startParam:o,botInline:a}=e,h=new URLSearchParams;return h.set("tgWebAppPlatform",n),h.set("tgWebAppThemeParams",oe(s)),h.set("tgWebAppVersion",r),t&&h.set("tgWebAppData",t),o&&h.set("tgWebAppStartParam",o),typeof i=="boolean"&&h.set("tgWebAppShowSettings",i?"1":"0"),typeof a=="boolean"&&h.set("tgWebAppBotInline",a?"1":"0"),h.toString()}function Os(e){re("launchParams",ae(e))}function ce(){for(const e of[As,Is,ks])try{const t=e();return Os(t),t}catch{}throw new Error("Unable to retrieve launch parameters from any known source.")}function mt(){const e=se();return!!(e&&e.type==="reload")}function qs(){let e=0;return()=>(e+=1).toString()}const[Ds]=kt(qs);function g(e,t){return({ssr:s}={})=>{let n;if(T()){if(!s)throw _(G,"ssr.options must be specified to initialize component on the server side");n=s}else n=ce();const r={...n,postEvent:"version"in n?Qt(n.version):()=>{throw _(Ht,"postEvent function is forbidden to be called on the server side.")},createRequestId:Ds()};if(T()||typeof e=="function")return typeof e=="function"?e(r):t(r);const i=t({...r,state:mt()?ie(e):void 0}),o=a=>(a.on("change",h=>{re(e,h)}),a);return i instanceof Promise?i.then(o):o(i)}}const he=g("backButton",({postEvent:e,version:t,state:s={isVisible:!1}})=>new Zt(s.isVisible,t,e));class L extends gt{constructor(){super(...arguments),c(this,"on",this.state.on.bind(this.state)),c(this,"off",this.state.off.bind(this.state))}}function pe(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 rt extends L{constructor({postEvent:t,version:s,...n}){super(n,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"}),c(this,"postEvent"),c(this,"authPromise"),c(this,"accessPromise"),this.postEvent=t}get available(){return this.get("available")}get accessGranted(){return this.get("accessGranted")}get accessRequested(){return this.get("accessRequested")}async authenticate({reason:t,...s}){return this.authPromise||(this.authPromise=l({...s,method:"web_app_biometry_request_auth",event:"biometry_auth_requested",postEvent:this.postEvent,params:{reason:(t||"").trim()}}).then(({token:n})=>n).finally(()=>this.authPromise=void 0)),this.authPromise}get deviceId(){return this.get("deviceId")}openSettings(){this.postEvent("web_app_biometry_open_settings")}requestAccess({reason:t,...s}={}){return this.accessPromise||(this.accessPromise=l({...s,postEvent:this.postEvent,method:"web_app_biometry_request_access",event:"biometry_info_received",params:{reason:t||""}}).then(n=>{const r=pe(n);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:t,...s}={}){return["removed","updated"].includes((await l({...s,postEvent:this.postEvent,method:"web_app_biometry_update_token",event:"biometry_token_updated",params:{token:t||""}})).status)}}async function ue(e){return pe(await l({...e||{},method:"web_app_biometry_get_info",event:"biometry_info_received"}))}const de=g("biometryManager",async({postEvent:e,version:t,state:s})=>{if(s)return new rt({...s,version:t,postEvent:e});if(T())throw _(G,"BiometryManager cannot be instantiated on the server side without passing the ssr.state object.");return new rt({...await ue({timeout:1e3}),version:t,postEvent:e})});class bt extends _t{constructor(){super(...arguments),c(this,"on",this.state.on.bind(this.state)),c(this,"off",this.state.off.bind(this.state))}}class le extends bt{constructor(t,s){super({isConfirmationNeeded:t}),this.postEvent=s}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 _e=g("closingBehavior",({postEvent:e,state:t={isConfirmationNeeded:!1}})=>new le(t.isConfirmationNeeded,e));class vt{constructor(t,s){c(this,"supports"),this.supports=Yt(t,s)}}function Ns(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 A()}class Vs extends K{constructor(t,s,n){super(Ns,s,n),c(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 ge(e){return new Vs(t=>t,!1,e)}function At(e,t){return Object.fromEntries(e.map(s=>[s,t]))}class fe extends vt{constructor(t,s,n){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=s,this.postEvent=n}async delete(t,s={}){const n=Array.isArray(t)?t:[t];n.length&&await C("deleteStorageValues",{keys:n},this.createRequestId(),{...s,postEvent:this.postEvent})}async getKeys(t={}){return ge().of(p()).parse(await C("getStorageKeys",{},this.createRequestId(),{...t,postEvent:this.postEvent}))}async get(t,s={}){const n=Array.isArray(t)?t:[t];if(!n.length)return At(n,"");const r=await C("getStorageValues",{keys:n},this.createRequestId(),{...s,postEvent:this.postEvent}),i=d(At(n,p()),"CloudStorageData").parse(r);return Array.isArray(t)?i:i[t]}async set(t,s,n={}){await C("saveStorageValue",{key:t,value:s},this.createRequestId(),{...n,postEvent:this.postEvent})}}const we=g(({createRequestId:e,postEvent:t,version:s})=>new fe(s,e,t));class me extends vt{constructor(t,s){super(t,{impactOccurred:"web_app_trigger_haptic_feedback",notificationOccurred:"web_app_trigger_haptic_feedback",selectionChanged:"web_app_trigger_haptic_feedback"}),this.postEvent=s}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 be=g(({version:e,postEvent:t})=>new me(e,t));class ve{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 ye=g(({initData:e})=>e?new ve(e):void 0);function Bs(e){return Xt().parse(e)}class Ee extends L{constructor(t,s,n){super({isOpened:t},s,{open:"web_app_open_invoice"}),this.postEvent=n}set isOpened(t){this.set("isOpened",t)}get isOpened(){return this.get("isOpened")}async open(t,s){if(this.isOpened)throw new Error("Invoice is already opened");let n;if(!s)n=t;else{const{hostname:r,pathname:i}=new URL(t,window.location.href);if(r!=="t.me")throw new Error(`Incorrect hostname: ${r}`);const o=i.match(/^\/(\$|invoice\/)([A-Za-z0-9\-_=]+)$/);if(!o)throw new Error('Link pathname has incorrect format. Expected to receive "/invoice/{slug}" or "/${slug}"');[,,n]=o}this.isOpened=!0;try{return(await l({method:"web_app_open_invoice",event:"invoice_closed",params:{slug:n},postEvent:this.postEvent,capture(r){return n===r.slug}})).status}finally{this.isOpened=!1}}}const Pe=g(({version:e,postEvent:t})=>new Ee(!1,e,t));class Se extends _t{constructor({postEvent:t,...s}){super(s),c(this,"postEvent"),c(this,"on",(n,r)=>n==="click"?b("main_button_pressed",r):this.state.on(n,r)),c(this,"off",(n,r)=>n==="click"?M("main_button_pressed",r):this.state.off(n,r)),this.postEvent=t}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.get("isEnabled")}set isLoaderVisible(t){this.setParams({isLoaderVisible:t})}get isLoaderVisible(){return this.get("isLoaderVisible")}set isVisible(t){this.setParams({isVisible:t})}get isVisible(){return this.get("isVisible")}get backgroundColor(){return this.get("backgroundColor")}get text(){return this.get("text")}get textColor(){return this.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.set(t),this.commit(),this}}const xe=g("mainButton",({postEvent:e,themeParams:t,state:s={isVisible:!1,isEnabled:!1,text:"",isLoaderVisible:!1,textColor:t.buttonTextColor||"#ffffff",backgroundColor:t.buttonColor||"#000000"}})=>new Se({...s,postEvent:e}));function Ms(){return Q({contact:d({userId:{type:P(),from:"user_id"},phoneNumber:{type:p(),from:"phone_number"},firstName:{type:p(),from:"first_name"},lastName:{type:p().optional(),from:"last_name"}}),authDate:{type:ft(),from:"auth_date"},hash:p()},"RequestedContact")}function Ce(e,t){return s=>{const[n,r]=t[s];return S(n,r,e)}}function $s(e){return new Promise(t=>{setTimeout(t,e)})}class Re extends L{constructor({postEvent:t,createRequestId:s,version:n,botInline:r,...i}){super(i,n,{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"}),c(this,"botInline"),c(this,"postEvent"),c(this,"createRequestId"),c(this,"requestPhoneAccessPromise"),c(this,"requestWriteAccessPromise"),c(this,"supportsParam"),this.createRequestId=s,this.postEvent=t,this.botInline=r;const o=this.supports.bind(this);this.supports=a=>o(a)?a!=="switchInlineQuery"||r:!1,this.supportsParam=Ce(n,{"setHeaderColor.color":["web_app_set_header_color","color"]})}async getRequestedContact({timeout:t=1e4}={}){return Ms().parse(await C("getRequestedContact",{},this.createRequestId(),{postEvent:this.postEvent,timeout:t}))}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 lt(this.bgColor)}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 $s(n),n+=50}throw Ft(t)},t)}async requestPhoneAccess(t={}){return this.requestPhoneAccessPromise||(this.requestPhoneAccessPromise=l({...t,method:"web_app_request_phone",event:"phone_requested",postEvent:this.postEvent}).then(({status:s})=>s).finally(()=>this.requestPhoneAccessPromise=void 0)),this.requestPhoneAccessPromise}async requestWriteAccess(t={}){return this.requestWriteAccessPromise||(this.requestWriteAccessPromise=l({...t,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(t){const{size:s}=new Blob([t]);if(!s||s>4096)throw new Error(`Passed data has incorrect size: ${s}`);this.postEvent("web_app_data_send",{data:t})}setHeaderColor(t){this.postEvent("web_app_set_header_color",z(t)?{color:t}:{color_key:t}),this.set("headerColor",t)}setBgColor(t){this.postEvent("web_app_set_background_color",{color:t}),this.set("bgColor",t)}switchInlineQuery(t,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:t,chat_types:s})}}const Te=g("miniApp",({themeParams:e,botInline:t=!1,state:s={bgColor:e.bgColor||"#ffffff",headerColor:e.headerBgColor||"#000000"},...n})=>new Re({...n,...s,botInline:t}));function Ls(e){const t=e.message.trim(),s=(e.title||"").trim(),n=e.buttons||[];let r;if(s.length>64)throw new Error(`Title has incorrect size: ${s.length}`);if(!t.length||t.length>256)throw new Error(`Message has incorrect size: ${t.length}`);if(n.length>3)throw new Error(`Buttons have incorrect size: ${n.length}`);return n.length?r=n.map(i=>{const{id:o=""}=i;if(o.length>64)throw new Error(`Button ID has incorrect size: ${o}`);if(!i.type||i.type==="default"||i.type==="destructive"){const a=i.text.trim();if(!a.length||a.length>64){const h=i.type||"default";throw new Error(`Button text with type "${h}" has incorrect size: ${i.text.length}`)}return{...i,text:a,id:o}}return{...i,id:o}}):r=[{type:"close",id:""}],{title:s,message:t,buttons:r}}class Ae extends L{constructor(t,s,n){super({isOpened:t},s,{open:"web_app_open_popup"}),this.postEvent=n}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:s=null}=await l({event:"popup_closed",method:"web_app_open_popup",postEvent:this.postEvent,params:Ls(t)});return s}finally{this.isOpened=!1}}}const Ie=g(({postEvent:e,version:t})=>new Ae(!1,t,e));class ke extends L{constructor(t,s,n){super({isOpened:t},s,{close:"web_app_close_scan_qr_popup",open:"web_app_open_scan_qr_popup"}),this.postEvent=n}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.");this.isOpened=!0;try{return(await l({method:"web_app_open_scan_qr_popup",event:["qr_text_received","scan_qr_popup_closed"],postEvent:this.postEvent,params:{text:t}})||{}).data||null}finally{this.isOpened=!1}}}const Oe=g(({version:e,postEvent:t})=>new ke(!1,e,t));class qe extends gt{constructor(t,s,n){super({isVisible:t},s,{show:"web_app_setup_settings_button",hide:"web_app_setup_settings_button"}),c(this,"on",(r,i)=>r==="click"?b("settings_button_pressed",i):this.state.on(r,i)),c(this,"off",(r,i)=>r==="click"?M("settings_button_pressed",i):this.state.off(r,i)),this.postEvent=n}set isVisible(t){this.set("isVisible",t),this.postEvent("web_app_setup_settings_button",{is_visible:t})}get isVisible(){return this.get("isVisible")}hide(){this.isVisible=!1}show(){this.isVisible=!0}}const De=g("settingsButton",({version:e,postEvent:t,state:s={isVisible:!1}})=>new qe(s.isVisible,e,t));function yt(e){return te().parse(e)}class Ne extends bt{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||lt(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")}listen(){return b("theme_changed",t=>{this.set(yt(t.theme_params))})}get subtitleTextColor(){return this.get("subtitleTextColor")}get textColor(){return this.get("textColor")}}const Ve=g("themeParams",({themeParams:e,state:t=e})=>{const s=new Ne(t);return T()||s.listen(),s});function Us(e={}){return l({...e,method:"web_app_request_theme",event:"theme_changed"}).then(yt)}class Be extends vt{constructor(t,s,n){super(t,{readTextFromClipboard:"web_app_read_text_from_clipboard"}),c(this,"supportsParam"),this.version=t,this.createRequestId=s,this.postEvent=n,this.supportsParam=Ce(t,{"openLink.tryInstantView":["web_app_open_link","try_instant_view"]})}openLink(t,s){const n=new URL(t,window.location.href).toString();if(!S("web_app_open_link",this.version)){window.open(n,"_blank");return}this.postEvent("web_app_open_link",{url:n,...typeof s=="boolean"?{try_instant_view:s}:{}})}openTelegramLink(t){const{hostname:s,pathname:n,search:r}=new URL(t,window.location.href);if(s!=="t.me")throw new Error(`URL has not allowed hostname: ${s}. Only "t.me" is allowed`);if(!S("web_app_open_tg_link",this.version)){window.location.href=t;return}this.postEvent("web_app_open_tg_link",{path_full:n+r})}async readTextFromClipboard(){const t=this.createRequestId(),{data:s=null}=await l({method:"web_app_read_text_from_clipboard",event:"clipboard_text_received",postEvent:this.postEvent,params:{req_id:t},capture:ut(t)});return s}}const Me=g(({version:e,postEvent:t,createRequestId:s})=>new Be(e,s,t));async function Et(e={}){const{is_expanded:t,is_state_stable:s,...n}=await l({...e,method:"web_app_request_viewport",event:"viewport_changed"});return{...n,isExpanded:t,isStateStable:s}}function k(e){return e<0?0:e}class Pt extends bt{constructor({postEvent:t,stableHeight:s,height:n,width:r,isExpanded:i}){super({height:k(n),isExpanded:i,stableHeight:k(s),width:k(r)}),c(this,"postEvent"),this.postEvent=t}async sync(t){const{isStateStable:s,...n}=await Et(t);this.set({...n,stableHeight:s?n.height:this.get("stableHeight")})}get height(){return this.get("height")}get stableHeight(){return this.get("stableHeight")}listen(){return b("viewport_changed",t=>{const{height:s,width:n,is_expanded:r,is_state_stable:i}=t,o=k(s);this.set({height:o,isExpanded:r,width:k(n),...i?{stableHeight:o}:{}})})}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}}async function Hs(e,t={}){const{height:s,width:n,isExpanded:r,isStateStable:i}=await Et({...t,postEvent:e});return new Pt({postEvent:e,height:s,width:n,isExpanded:r,stableHeight:i?s:0})}function Ws({state:e,platform:t,postEvent:s}){let n=!1,r=0,i=0,o=0;return e?(n=e.isExpanded,r=e.height,i=e.width,o=e.stableHeight):["macos","tdesktop","unigram","webk","weba","web"].includes(t)&&(n=!0,r=window.innerHeight,i=window.innerWidth,o=window.innerHeight),new Pt({postEvent:s,height:r,width:i,stableHeight:o,isExpanded:n})}const $e=g("viewport",async e=>{if(T()&&!e.state)throw _(G,"Viewport cannot be instantiated on the server side without passing the ssr.state object.");let t=Ws(e);return T()||(t.width===0&&await Hs(e.postEvent,{timeout:1e3}).then(s=>t=s).catch(s=>j.error("Unable to sync viewport state",s)),t.listen()),t});function E(e,t){document.documentElement.style.setProperty(e,t)}function js(e,t,s){s||(s=a=>`--tg-${a}-color`);const n=s("header"),r=s("bg"),i=()=>{const{headerColor:a}=e;if(z(a))E(n,a);else{const{bgColor:h,secondaryBgColor:u}=t;a==="bg_color"&&h?E(n,h):a==="secondary_bg_color"&&u&&E(n,u)}E(r,e.bgColor)},o=[t.on("change",i),e.on("change",i)];return i(),()=>o.forEach(a=>a())}function Gs(e,t){t||(t=n=>`--tg-theme-${n.replace(/[A-Z]/g,r=>`-${r.toLowerCase()}`)}`);const s=()=>{Object.entries(e.getState()).forEach(([n,r])=>{r&&E(t(n),r)})};return s(),e.on("change",s)}function Ks(e,t){t||(t=u=>`--tg-viewport-${u}`);const[s,n,r]=["height","width","stable-height"].map(u=>t(u)),i=()=>E(s,`${e.height}px`),o=()=>E(n,`${e.width}px`),a=()=>E(r,`${e.stableHeight}px`),h=[e.on("change:height",i),e.on("change:width",o),e.on("change:stableHeight",a)];return i(),o(),a(),()=>h.forEach(u=>u())}function Le(e=!0){const t=[b("reload_iframe",()=>{R("iframe_will_reload"),window.location.reload()})],s=()=>t.forEach(n=>n());if(e){const n=document.createElement("style");n.id="telegram-custom-styles",document.head.appendChild(n),t.push(b("set_custom_style",r=>{n.innerHTML=r}),()=>document.head.removeChild(n))}return R("iframe_ready",{reload_supported:!0}),s}async function zs(){try{return await l({method:"web_app_request_theme",event:"theme_changed",timeout:100}),!0}catch{return!1}}function Ue(e){return e instanceof B}function Js(e,t){return Ue(e)&&e.type===t}function Y(e,t){let s,n,r;return typeof e=="string"?s=e:(s=e.pathname===void 0?t:e.pathname,n=e.params,r=e.id),Object.freeze({id:r||(Math.random()*2**14|0).toString(16),pathname:s,params:n})}class He{constructor(t,s,n=R){if(c(this,"history"),c(this,"ee",new V),c(this,"attached",!1),c(this,"back",()=>this.go(-1)),c(this,"on",this.ee.on.bind(this.ee)),c(this,"off",this.ee.off.bind(this.ee)),this._index=s,this.postEvent=n,t.length===0)throw _(Lt,"History should not be empty.");if(s<0||s>=t.length)throw _(Ut,"Index should not be zero and higher or equal than history size.");this.history=t.map(r=>Y(r,""))}attach(){this.attached||(this.attached=!0,this.sync(),b("back_button_pressed",this.back))}get current(){return this.history[this.index]}detach(){this.attached=!1,M("back_button_pressed",this.back)}forward(){this.go(1)}go(t,s){const n=this.index+t,r=Math.min(Math.max(0,n),this.history.length-1);(n===r||s)&&this.replaceAndMove(r,this.history[r])}goTo(t,s){this.go(t-this.index,s)}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,Y(t,this.current.pathname))}replace(t){this.replaceAndMove(this.index,Y(t,this.current.pathname))}replaceAndMove(t,s){const n=t-this.index;if(!n&&this.current===s)return;const r=this.current;if(this.index!==t){const i=this._index;this._index=t,this.attached&&i>0!=t>0&&this.sync()}this.history[t]=s,this.ee.emit("change",{navigator:this,from:r,to:this.current,delta:n})}sync(){this.postEvent("web_app_setup_back_button",{is_visible:!!this.index})}}function Z({params:e,...t}){return{...e||{hash:"",search:""},...t}}function q(e,t){return e.startsWith(t)?e:`${t}${e}`}function D(e){return new URL(typeof e=="string"?e:`${e.pathname||""}${q(e.search||"","?")}${q(e.hash||"","#")}`,"http://a")}function N(e){const t=typeof e=="string"?e.startsWith("/"):!!(e.pathname&&e.pathname.startsWith("/")),s=D(e);return`${t?s.pathname:s.pathname.slice(1)}${s.search}${s.hash}`}function X(e,t,s){let n,r;typeof e=="string"?n=e:(n=N(e),s=e.state,r=e.id);const{pathname:i,search:o,hash:a}=new URL(n,`http://a${q(t,"/")}`);return{id:r,pathname:i,params:{hash:a,search:o,state:s}}}async function O(e){return e===0?!0:Promise.race([new Promise(t=>{const s=nt("popstate",()=>{s(),t(!0)});window.history.go(e)}),new Promise(t=>{setTimeout(t,50,!1)})])}async function Qs(){if(window.history.length<=1||(window.history.pushState(null,""),await O(1-window.history.length)))return;let e=await O(-1);for(;e;)e=await O(-1)}function St(e){return D(e).pathname}const It=0,tt=1,et=2;class xt{constructor(t,s,{postEvent:n,hashMode:r,base:i}={}){c(this,"navigator"),c(this,"ee",new V),c(this,"hashMode"),c(this,"base"),c(this,"attached",!1),c(this,"onPopState",({state:o})=>{if(o===null)return this.push(this.parsePath(window.location.href));o===It?window.history.forward():o===tt&&this.back(),o===et&&this.forward()}),c(this,"onNavigatorChange",async({to:o,from:a,delta:h})=>{this.attached&&await this.syncHistory(),this.ee.emit("change",{delta:h,from:Z(a),to:Z(o),navigator:this})}),c(this,"on",this.ee.on.bind(this.ee)),c(this,"off",this.ee.off.bind(this.ee)),this.navigator=new He(t.map(o=>X(o,"/")),s,n),this.navigator.on("change",this.onNavigatorChange),this.hashMode=r,this.base=St(i||"")}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,s){return this.navigator.go(t,s)}goTo(t,s){this.navigator.goTo(t,s)}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(Z)}get path(){return N(this)}get pathname(){return this.navigator.current.pathname}parsePath(t){let s=D(t);return this.hashMode&&(s=D(s.hash.slice(1))),{pathname:s.pathname,search:s.search,hash:s.hash}}push(t,s){const n=X(t,this.path),{state:r=s}=n.params;this.navigator.push({...n,params:{...n.params,state:r}})}replace(t,s){const n=X(t,this.path),{state:r=s}=n.params;this.navigator.replace({...n,params:{...n.params,state:r}})}renderPath(t){const s=(this.base.length===1?"":this.base)+q(N(t),"/");return this.hashMode?q(s.slice(1),this.hashMode==="default"?"#":"#/"):s}async syncHistory(){window.removeEventListener("popstate",this.onPopState);const{state:t}=this,s=this.renderPath(this);await Qs(),this.hasPrev&&this.hasNext?(window.history.replaceState(tt,""),window.history.pushState(t,"",s),window.history.pushState(et,""),await O(-1)):this.hasPrev?(window.history.replaceState(tt,""),window.history.pushState(t,"",s)):this.hasNext?(window.history.replaceState(t,s),window.history.pushState(et,""),await O(-1)):(window.history.replaceState(It,""),window.history.pushState(t,"",s)),window.addEventListener("popstate",this.onPopState)}get search(){return(this.navigator.current.params||{}).search||""}get state(){return(this.navigator.current.params||{}).state}}function We(e){e||(e={});const{href:t,hash:s}=window.location;let n=N(e.hashMode?s.includes("?")?s.slice(1):`?${s.slice(1)}`:t);const r=e.base?St(e.base):void 0;if(r){if(!n.startsWith(r))throw _(Wt,`Path "${n}" expected to be starting with "${r}"`);n=n.slice(r.length)}return new xt([n],0,e)}function Fs(e){const t=e.match(/#(.+)/);return t?t[1]:null}function Ys(e,t){if(mt()){const s=sessionStorage.getItem(e);if(s)try{const{index:n,history:r}=JSON.parse(s);return new xt(r,n,t)}catch(n){console.error("Unable to restore hash navigator state.",n)}}return We(t)}function Zs(e,t){const s=Ys(e,t),n=()=>sessionStorage.setItem(e,JSON.stringify({index:s.index,history:s.history}));return s.on("change",n),n(),s}function f(e){return(t,s,...n)=>r=>m.createComponent(s,m.mergeProps(()=>m.mergeProps({[t]:e(...n)},r)))}const je=m.createContext();function Ge(){const e=m.useContext(je);if(!e)throw new Error("useSDK was used outside of SDKProvider.");return e}function w(e){return(...t)=>Ge()(e,...t)}const Ke=w(he),Xs=f(Ke),ze=w(de),tn=f(ze),Je=w(_e),en=f(Je),Qe=w(we),sn=f(Qe),Fe=w(be),nn=f(Fe),Ye=w(ye),rn=f(Ye),Ze=w(Pe),on=f(Ze),Xe=w(xe),an=f(Xe),ts=w(Te),cn=f(ts),es=w(Ie),hn=f(es),ss=w(Oe),pn=f(ss),ns=w(De),un=f(ns),rs=w(Ve),dn=f(rs),is=w(Me),ln=f(is),os=w($e),_n=f(os),gn=e=>{const t=new Map,s=(n,...r)=>{if(t.has(n))return t.get(n);const[i]=m.createResource(()=>{try{return n(...r)}catch(h){return[h]}}),o=m.createMemo(()=>{if(i.error)return[i.error];if(i.state!=="ready")return;const h=i();if(Array.isArray(h)||!h||!("on"in h))return h;const u=m.from(H=>(H(h),h.on("change",()=>H(h)))),U=Object.getPrototypeOf(h),F={};return new Proxy(h,{get(H,x){if(!(x in F)){const Ct=Reflect.getOwnPropertyDescriptor(U,x);F[x]=Ct&&"get"in Ct?m.createMemo(()=>u()[x]):()=>Reflect.get(H,x)}return F[x]()}})});function a(){const h=o();if(Array.isArray(h))throw h[0];return h}return Object.defineProperty(a,"error",{get(){const h=o();return Array.isArray(h)?h[0]:void 0}}),t.set(n,a),a};return m.createEffect(()=>{qt(e.debug||!1)}),m.createEffect(()=>{pt()&&m.onCleanup(Le(e.acceptCustomStyles))}),m.createComponent(je.Provider,{value:s,get children(){return e.children}})};exports.BackButton=Zt;exports.BasicNavigator=He;exports.BiometryManager=rt;exports.BrowserNavigator=xt;exports.ClosingBehavior=le;exports.CloudStorage=fe;exports.ERR_INVALID_PATH_BASE=Wt;exports.ERR_INVOKE_CUSTOM_METHOD_RESPONSE=Bt;exports.ERR_METHOD_PARAMETER_UNSUPPORTED=Nt;exports.ERR_METHOD_UNSUPPORTED=Dt;exports.ERR_NAVIGATION_HISTORY_EMPTY=Lt;exports.ERR_NAVIGATION_INDEX_INVALID=Ut;exports.ERR_NAVIGATION_ITEM_INVALID=us;exports.ERR_PARSE=ot;exports.ERR_SSR_INIT=G;exports.ERR_SSR_POST_EVENT=Ht;exports.ERR_TIMED_OUT=Mt;exports.ERR_UNEXPECTED_TYPE=$t;exports.ERR_UNKNOWN_ENV=Vt;exports.EventEmitter=V;exports.HapticFeedback=me;exports.InitData=ve;exports.Invoice=Ee;exports.MainButton=Se;exports.MiniApp=Re;exports.Popup=Ae;exports.QRScanner=ke;exports.SDKError=B;exports.SDKProvider=gn;exports.SettingsButton=qe;exports.ThemeParams=Ne;exports.Utils=Be;exports.Viewport=Pt;exports.array=ge;exports.bindMiniAppCSSVars=js;exports.bindThemeParamsCSSVars=Gs;exports.bindViewportCSSVars=Ks;exports.boolean=y;exports.captureSameReq=ut;exports.classNames=W;exports.compareVersions=Kt;exports.createBrowserNavigatorFromLocation=We;exports.createPostEvent=Qt;exports.createSafeURL=D;exports.date=ft;exports.getHash=Fs;exports.getPathname=St;exports.initBackButton=he;exports.initBiometryManager=de;exports.initClosingBehavior=_e;exports.initCloudStorage=we;exports.initHapticFeedback=be;exports.initInitData=ye;exports.initInvoice=Pe;exports.initMainButton=xe;exports.initMiniApp=Te;exports.initNavigator=Zs;exports.initPopup=Ie;exports.initQRScanner=Oe;exports.initSettingsButton=De;exports.initThemeParams=Ve;exports.initUtils=Me;exports.initViewport=$e;exports.initWeb=Le;exports.invokeCustomMethod=C;exports.isColorDark=lt;exports.isIframe=pt;exports.isPageReload=mt;exports.isRGB=z;exports.isRGBShort=Gt;exports.isSDKError=Ue;exports.isSDKErrorOfType=Js;exports.isTMA=zs;exports.json=d;exports.mergeClassNames=Ss;exports.number=P;exports.off=M;exports.on=b;exports.parseInitData=Bs;exports.parseLaunchParams=wt;exports.parseThemeParams=yt;exports.postEvent=R;exports.request=l;exports.requestBiometryInfo=ue;exports.requestThemeParams=Us;exports.requestViewport=Et;exports.retrieveLaunchParams=ce;exports.rgb=ht;exports.searchParams=Q;exports.serializeLaunchParams=ae;exports.serializeThemeParams=oe;exports.setCSSVar=E;exports.setDebug=qt;exports.setTargetOrigin=Ps;exports.string=p;exports.subscribe=Ot;exports.supports=S;exports.targetOrigin=Jt;exports.toRGB=ct;exports.unsubscribe=it;exports.urlToPath=N;exports.useBackButton=Ke;exports.useBiometryManager=ze;exports.useClosingBehavior=Je;exports.useCloudStorage=Qe;exports.useHapticFeedback=Fe;exports.useInitData=Ye;exports.useInvoice=Ze;exports.useMainButton=Xe;exports.useMiniApp=ts;exports.usePopup=es;exports.useQRScanner=ss;exports.useSDK=Ge;exports.useSettingsButton=ns;exports.useThemeParams=rs;exports.useUtils=is;exports.useViewport=os;exports.withBackButton=Xs;exports.withBiometryManager=tn;exports.withClosingBehavior=en;exports.withCloudStorage=sn;exports.withHapticFeedback=nn;exports.withInitData=rn;exports.withInvoice=on;exports.withMainButton=an;exports.withMiniApp=cn;exports.withPopup=hn;exports.withQRScanner=pn;exports.withSettingsButton=un;exports.withThemeParams=dn;exports.withTimeout=dt;exports.withUtils=ln;exports.withViewport=_n;
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const m=require("solid-js");var cs=Object.defineProperty,hs=(e,t,s)=>t in e?cs(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,c=(e,t,s)=>(hs(e,typeof t!="symbol"?t+"":t,s),s);function kt(e,t){let s;const n=()=>{s!==void 0&&t&&t(s),s=void 0};return[()=>s===void 0?s=e(n):s,n]}function it(e){const t=J(),{count:s}=t;t.unsubscribe(e),s&&!t.count&&ys()}function Ot(e){return J().subscribe(e),()=>it(e)}class ps{constructor(t,s={}){this.scope=t,this.options=s}print(t,...s){const n=new Date,r=Intl.DateTimeFormat("en-GB",{hour:"2-digit",minute:"2-digit",second:"2-digit",fractionalSecondDigits:3,timeZone:"UTC"}).format(n),{textColor:i,bgColor:o}=this.options,a="font-weight: bold;padding: 0 5px;border-radius:5px";console[t](`%c${r}%c / %c${this.scope}`,`${a};background-color: lightblue;color:black`,"",`${a};${i?`color:${i};`:""}${o?`background-color:${o}`:""}`,...s)}error(...t){this.print("error",...t)}log(...t){this.print("log",...t)}}const j=new ps("SDK",{bgColor:"forestgreen",textColor:"white"});let st=!1;const Rt=({event:e,args:[t]})=>{j.log("Event received:",t===void 0?{name:e}:{name:e,data:t})};function qt(e){st!==e&&(st=e,e?Ot(Rt):it(Rt))}function us(...e){st&&j.log(...e)}class V{constructor(){c(this,"listeners",new Map),c(this,"listenersCount",0),c(this,"subscribeListeners",[])}clear(){this.listeners.clear(),this.subscribeListeners=[]}get count(){return this.listenersCount+this.subscribeListeners.length}emit(t,...s){this.subscribeListeners.forEach(n=>n({event:t,args:s})),(this.listeners.get(t)||[]).forEach(([n,r])=>{n(...s),r&&this.off(t,n)})}on(t,s,n){let r=this.listeners.get(t);return r||this.listeners.set(t,r=[]),r.push([s,n]),this.listenersCount+=1,()=>this.off(t,s)}off(t,s){const n=this.listeners.get(t)||[];for(let r=0;r<n.length;r+=1)if(s===n[r][0]){n.splice(r,1),this.listenersCount-=1;return}}subscribe(t){return this.subscribeListeners.push(t),()=>this.unsubscribe(t)}unsubscribe(t){for(let s=0;s<this.subscribeListeners.length;s+=1)if(this.subscribeListeners[s]===t){this.subscribeListeners.splice(s,1);return}}}function nt(e,t,s){return window.addEventListener(e,t,s),()=>window.removeEventListener(e,t,s)}class B extends Error{constructor(t,s,n){super(s,{cause:n}),this.type=t,Object.setPrototypeOf(this,B.prototype)}}function _(e,t,s){return new B(e,t,s)}const Dt="ERR_METHOD_UNSUPPORTED",Nt="ERR_METHOD_PARAMETER_UNSUPPORTED",Vt="ERR_UNKNOWN_ENV",Bt="ERR_INVOKE_CUSTOM_METHOD_RESPONSE",Mt="ERR_TIMED_OUT",$t="ERR_UNEXPECTED_TYPE",ot="ERR_PARSE",Lt="ERR_NAVIGATION_LIST_EMPTY",Ut="ERR_NAVIGATION_CURSOR_INVALID",ds="ERR_NAVIGATION_ITEM_INVALID",G="ERR_SSR_INIT",Ht="ERR_SSR_POST_EVENT",Wt="ERR_INVALID_PATH_BASE";function A(){return _($t,"Value has unexpected type")}class K{constructor(t,s,n){this.parser=t,this.isOptional=s,this.type=n}parse(t){if(!(this.isOptional&&t===void 0))try{return this.parser(t)}catch(s){throw _(ot,`Unable to parse value${this.type?` as ${this.type}`:""}`,s)}}optional(){return this.isOptional=!0,this}}function I(e,t){return()=>new K(e,!1,t)}const y=I(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 A()},"boolean");function jt(e,t){const s={};for(const n in e){const r=e[n];if(!r)continue;let i,o;if(typeof r=="function"||"parse"in r)i=n,o=typeof r=="function"?r:r.parse.bind(r);else{const{type:a}=r;i=r.from||n,o=typeof a=="function"?a:a.parse.bind(a)}try{const a=o(t(i));a!==void 0&&(s[n]=a)}catch(a){throw _(ot,`Unable to parse field "${n}"`,a)}}return s}function at(e){let t=e;if(typeof t=="string"&&(t=JSON.parse(t)),typeof t!="object"||t===null||Array.isArray(t))throw A();return t}function d(e,t){return new K(s=>{const n=at(s);return jt(e,r=>n[r])},!1,t)}const P=I(e=>{if(typeof e=="number")return e;if(typeof e=="string"){const t=Number(e);if(!Number.isNaN(t))return t}throw A()},"number");function z(e){return/^#[\da-f]{6}$/i.test(e)}function Gt(e){return/^#[\da-f]{3}$/i.test(e)}function ct(e){const t=e.replace(/\s/g,"").toLowerCase();if(z(t))return t;if(Gt(t)){let n="#";for(let r=0;r<3;r+=1)n+=t[1+r].repeat(2);return n}const s=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(!s)throw new Error(`Value "${e}" does not satisfy any of known RGB formats.`);return s.slice(1).reduce((n,r)=>{const i=parseInt(r,10).toString(16);return n+(i.length===1?"0":"")+i},"#")}const p=I(e=>{if(typeof e=="string"||typeof e=="number")return e.toString();throw A()},"string"),ht=I(e=>ct(p().parse(e)),"rgb");function ls(e){return d({eventType:p(),eventData:t=>t}).parse(e)}function _s(){["TelegramGameProxy_receiveEvent","TelegramGameProxy","Telegram"].forEach(e=>{delete window[e]})}function gs(e,t){window.dispatchEvent(new MessageEvent("message",{data:JSON.stringify({eventType:e,eventData:t}),source:window.parent}))}function fs(){[["TelegramGameProxy_receiveEvent"],["TelegramGameProxy","receiveEvent"],["Telegram","WebView","receiveEvent"]].forEach(e=>{let t=window;e.forEach((s,n,r)=>{if(n===r.length-1){t[s]=gs;return}s in t||(t[s]={}),t=t[s]})})}const ws=d({button_id:e=>e==null?void 0:p().parse(e)}),ms={clipboard_text_received:d({req_id:p(),data:e=>e===null?e:p().optional().parse(e)}),custom_method_invoked:d({req_id:p(),result:e=>e,error:p().optional()}),invoice_closed:d({slug:p(),status:p()}),phone_requested:d({status:p()}),popup_closed:{parse:e=>ws.parse(e??{})},qr_text_received:d({data:p().optional()}),theme_changed:d({theme_params:e=>{const t=ht().optional();return Object.entries(at(e)).reduce((s,[n,r])=>(s[n]=t.parse(r),s),{})}}),viewport_changed:d({height:P(),width:e=>e==null?window.innerWidth:P().parse(e),is_state_stable:y(),is_expanded:y()}),write_access_requested:d({status:p()})};function bs(){const e=new V;fs();let t=[_s,nt("resize",()=>{e.emit("viewport_changed",{width:window.innerWidth,height:window.innerHeight,is_state_stable:!0,is_expanded:!0})}),nt("message",s=>{if(s.source!==window.parent)return;let n;try{n=ls(s.data)}catch{return}const{eventType:r,eventData:i}=n,o=ms[r];try{const a=o?o.parse(i):i;e.emit(...a?[r,a]:[r])}catch(a){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`,n,a)}}),()=>e.clear()];return[e,()=>{t.forEach(s=>s()),t=[]}]}const[vs,ys]=kt(e=>{const[t,s]=bs(),n=t.off.bind(t);return t.off=(r,i)=>{const{count:o}=t;n(r,i),o&&!t.count&&e()},[t,s]},([,e])=>e());function J(){return vs()[0]}function M(e,t){J().off(e,t)}function b(e,t,s){return J().on(e,t,s)}function $(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Kt(e,t){const s=e.split("."),n=t.split("."),r=Math.max(s.length,n.length);for(let i=0;i<r;i+=1){const o=parseInt(s[i]||"0",10),a=parseInt(n[i]||"0",10);if(o!==a)return o>a?1:-1}return 0}function v(e,t){return Kt(e,t)<=0}function S(e,t,s){if(typeof s=="string"){if(e==="web_app_open_link"&&t==="try_instant_view")return v("6.4",s);if(e==="web_app_set_header_color"&&t==="color")return v("6.9",s)}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 v("6.1",t);case"web_app_open_popup":return v("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 v("6.4",t);case"web_app_switch_inline_query":return v("6.7",t);case"web_app_invoke_custom_method":case"web_app_request_write_access":case"web_app_request_phone":return v("6.9",t);case"web_app_setup_settings_button":return v("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 v("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 Es(e){return"external"in e&&$(e.external)&&"notify"in e.external&&typeof e.external.notify=="function"}function zt(e){return"TelegramWebviewProxy"in e&&$(e.TelegramWebviewProxy)&&"postEvent"in e.TelegramWebviewProxy&&typeof e.TelegramWebviewProxy.postEvent=="function"}function pt(){try{return window.self!==window.top}catch{return!0}}let Jt="https://web.telegram.org";function Ps(e){Jt=e}function Qt(){return Jt}function T(e,t,s){let n={},r;t===void 0&&s===void 0?n={}:t!==void 0&&s!==void 0?(n=s,r=t):t!==void 0&&("targetOrigin"in t?n=t:r=t);const{targetOrigin:i=Qt()}=n;if(us("Posting event:",r?{event:e,data:r}:{event:e}),pt()){window.parent.postMessage(JSON.stringify({eventType:e,eventData:r}),i);return}if(Es(window)){window.external.notify(JSON.stringify({eventType:e,eventData:r}));return}if(zt(window)){window.TelegramWebviewProxy.postEvent(e,JSON.stringify(r));return}throw _(Vt,"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 Ft(e){return(t,s)=>{if(!S(t,e))throw _(Dt,`Method "${t}" is unsupported in Mini Apps version ${e}`);if($(s)){let n;if(t==="web_app_open_link"&&"try_instant_view"in s?n="try_instant_view":t==="web_app_set_header_color"&&"color"in s&&(n="color"),n&&!S(t,n,e))throw _(Nt,`Parameter "${n}" of "${t}" method is unsupported in Mini Apps version ${e}`)}return T(t,s)}}function ut(e){return({req_id:t})=>t===e}function Yt(e){return _(Mt,`Timeout reached: ${e}ms`)}function dt(e,t){return Promise.race([typeof e=="function"?e():e,new Promise((s,n)=>{setTimeout(()=>{n(Yt(t))},t)})])}async function l(e){let t;const s=new Promise(u=>{t=u}),{method:n,event:r,capture:i,postEvent:o=T,timeout:a}=e,h=(Array.isArray(r)?r:[r]).map(u=>b(u,U=>(!i||i(U))&&t(U)));try{return o(n,e.params),await(a?dt(s,a):s)}finally{h.forEach(u=>u())}}async function R(e,t,s,n={}){const{result:r,error:i}=await l({...n,method:"web_app_invoke_custom_method",event:"custom_method_invoked",params:{method:e,params:t,req_id:s},capture:ut(s)});if(i)throw _(Bt,i);return r}function W(...e){return e.map(t=>{if(typeof t=="string")return t;if($(t))return W(Object.entries(t).map(s=>s[1]&&s[0]));if(Array.isArray(t))return W(...t)}).filter(Boolean).join(" ")}function Ss(...e){return e.reduce((t,s)=>($(s)&&Object.entries(s).forEach(([n,r])=>{const i=W(t[n],r);i.length&&(t[n]=i)}),t),{})}function lt(e){const t=ct(e);return Math.sqrt([.299,.587,.114].reduce((s,n,r)=>{const i=parseInt(t.slice(1+r*2,1+(r+1)*2),16);return s+i*i*n},0))<120}class xs{constructor(t){c(this,"ee",new V),c(this,"on",this.ee.on.bind(this.ee)),c(this,"off",this.ee.off.bind(this.ee)),this.state=t}clone(){return{...this.state}}set(t,s){Object.entries(typeof t=="string"?{[t]:s}:t).reduce((n,[r,i])=>this.state[r]===i||i===void 0?n:(this.state[r]=i,this.ee.emit(`change:${r}`,i),!0),!1)&&this.ee.emit("change",this.state)}get(t){return this.state[t]}}class _t{constructor(t){c(this,"state"),c(this,"get"),c(this,"set"),c(this,"clone"),this.state=new xs(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 Zt(e,t){return s=>S(t[s],e)}class gt extends _t{constructor(t,s,n){super(t),c(this,"supports"),this.supports=Zt(s,n)}}class Xt extends gt{constructor(t,s,n){super({isVisible:t},s,{show:"web_app_setup_back_button",hide:"web_app_setup_back_button"}),c(this,"on",(r,i)=>r==="click"?b("back_button_pressed",i):this.state.on(r,i)),c(this,"off",(r,i)=>r==="click"?M("back_button_pressed",i):this.state.off(r,i)),this.postEvent=n}set isVisible(t){this.set("isVisible",t),this.postEvent("web_app_setup_back_button",{is_visible:t})}get isVisible(){return this.get("isVisible")}hide(){this.isVisible=!1}show(){this.isVisible=!0}}function x(){return typeof window>"u"}const ft=I(e=>e instanceof Date?e:new Date(P().parse(e)*1e3),"Date");function Q(e,t){return new K(s=>{if(typeof s!="string"&&!(s instanceof URLSearchParams))throw A();const n=typeof s=="string"?new URLSearchParams(s):s;return jt(e,r=>{const i=n.get(r);return i===null?void 0:i})},!1,t)}const Cs=d({id:P(),type:p(),title:p(),photoUrl:{type:p().optional(),from:"photo_url"},username:p().optional()},"Chat").optional(),Tt=d({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:P(),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 te(){return Q({authDate:{type:ft(),from:"auth_date"},canSendAfter:{type:P().optional(),from:"can_send_after"},chat:Cs,chatInstance:{type:p().optional(),from:"chat_instance"},chatType:{type:p().optional(),from:"chat_type"},hash:p(),queryId:{type:p().optional(),from:"query_id"},receiver:Tt,startParam:{type:p().optional(),from:"start_param"},user:Tt},"InitData")}function Rs(e){return e.replace(/_[a-z]/g,t=>t[1].toUpperCase())}function Ts(e){return e.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}const ee=I(e=>{const t=ht().optional();return Object.entries(at(e)).reduce((s,[n,r])=>(s[Rs(n)]=t.parse(r),s),{})},"ThemeParams");function wt(e){return Q({botInline:{type:y().optional(),from:"tgWebAppBotInline"},initData:{type:te().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:ee(),from:"tgWebAppThemeParams"},version:{type:p(),from:"tgWebAppVersion"}}).parse(e)}function se(e){return wt(e.replace(/^[^?#]*[?#]/,"").replace(/[?#]/g,"&"))}function As(){return se(window.location.href)}function ne(){return performance.getEntriesByType("navigation")[0]}function Is(){const e=ne();if(!e)throw new Error("Unable to get first navigation entry.");return se(e.name)}function re(e){return`tma.js/${e.replace(/[A-Z]/g,t=>`-${t.toLowerCase()}`)}`}function ie(e,t){sessionStorage.setItem(re(e),JSON.stringify(t))}function oe(e){const t=sessionStorage.getItem(re(e));try{return t?JSON.parse(t):void 0}catch{}}function ks(){return wt(oe("launchParams")||"")}function ae(e){return JSON.stringify(Object.fromEntries(Object.entries(e).map(([t,s])=>[Ts(t),s])))}function ce(e){const{initDataRaw:t,themeParams:s,platform:n,version:r,showSettings:i,startParam:o,botInline:a}=e,h=new URLSearchParams;return h.set("tgWebAppPlatform",n),h.set("tgWebAppThemeParams",ae(s)),h.set("tgWebAppVersion",r),t&&h.set("tgWebAppData",t),o&&h.set("tgWebAppStartParam",o),typeof i=="boolean"&&h.set("tgWebAppShowSettings",i?"1":"0"),typeof a=="boolean"&&h.set("tgWebAppBotInline",a?"1":"0"),h.toString()}function Os(e){ie("launchParams",ce(e))}function he(){for(const e of[As,Is,ks])try{const t=e();return Os(t),t}catch{}throw new Error("Unable to retrieve launch parameters from any known source.")}function mt(){const e=ne();return!!(e&&e.type==="reload")}function qs(){let e=0;return()=>(e+=1).toString()}const[Ds]=kt(qs);function g(e,t){return({ssr:s}={})=>{let n;if(x()){if(!s)throw _(G,"ssr.options must be specified to initialize component on the server side");n=s}else n=he();const r={...n,postEvent:"version"in n?Ft(n.version):()=>{throw _(Ht,"postEvent function is forbidden to be called on the server side.")},createRequestId:Ds()};if(x()||typeof e=="function")return typeof e=="function"?e(r):t(r);const i=t({...r,state:mt()?oe(e):void 0}),o=a=>(a.on("change",h=>{ie(e,h)}),a);return i instanceof Promise?i.then(o):o(i)}}const pe=g("backButton",({postEvent:e,version:t,state:s={isVisible:!1}})=>new Xt(s.isVisible,t,e));class L extends gt{constructor(){super(...arguments),c(this,"on",this.state.on.bind(this.state)),c(this,"off",this.state.off.bind(this.state))}}function ue(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 rt extends L{constructor({postEvent:t,version:s,...n}){super(n,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"}),c(this,"postEvent"),c(this,"authPromise"),c(this,"accessPromise"),this.postEvent=t}get available(){return this.get("available")}get accessGranted(){return this.get("accessGranted")}get accessRequested(){return this.get("accessRequested")}async authenticate({reason:t,...s}){return this.authPromise||(this.authPromise=l({...s,method:"web_app_biometry_request_auth",event:"biometry_auth_requested",postEvent:this.postEvent,params:{reason:(t||"").trim()}}).then(({token:n})=>n).finally(()=>this.authPromise=void 0)),this.authPromise}get deviceId(){return this.get("deviceId")}openSettings(){this.postEvent("web_app_biometry_open_settings")}requestAccess({reason:t,...s}={}){return this.accessPromise||(this.accessPromise=l({...s,postEvent:this.postEvent,method:"web_app_biometry_request_access",event:"biometry_info_received",params:{reason:t||""}}).then(n=>{const r=ue(n);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:t,...s}={}){return["removed","updated"].includes((await l({...s,postEvent:this.postEvent,method:"web_app_biometry_update_token",event:"biometry_token_updated",params:{token:t||""}})).status)}}async function de(e){return ue(await l({...e||{},method:"web_app_biometry_get_info",event:"biometry_info_received"}))}const le=g("biometryManager",async({postEvent:e,version:t,state:s})=>{if(s)return new rt({...s,version:t,postEvent:e});if(x())throw _(G,"BiometryManager cannot be instantiated on the server side without passing the ssr.state object.");return new rt({...await de({timeout:1e3}),version:t,postEvent:e})});class bt extends _t{constructor(){super(...arguments),c(this,"on",this.state.on.bind(this.state)),c(this,"off",this.state.off.bind(this.state))}}class _e extends bt{constructor(t,s){super({isConfirmationNeeded:t}),this.postEvent=s}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 ge=g("closingBehavior",({postEvent:e,state:t={isConfirmationNeeded:!1}})=>new _e(t.isConfirmationNeeded,e));class vt{constructor(t,s){c(this,"supports"),this.supports=Zt(t,s)}}function Ns(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 A()}class Vs extends K{constructor(t,s,n){super(Ns,s,n),c(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 fe(e){return new Vs(t=>t,!1,e)}function At(e,t){return Object.fromEntries(e.map(s=>[s,t]))}class we extends vt{constructor(t,s,n){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=s,this.postEvent=n}async delete(t,s={}){const n=Array.isArray(t)?t:[t];n.length&&await R("deleteStorageValues",{keys:n},this.createRequestId(),{...s,postEvent:this.postEvent})}async getKeys(t={}){return fe().of(p()).parse(await R("getStorageKeys",{},this.createRequestId(),{...t,postEvent:this.postEvent}))}async get(t,s={}){const n=Array.isArray(t)?t:[t];if(!n.length)return At(n,"");const r=await R("getStorageValues",{keys:n},this.createRequestId(),{...s,postEvent:this.postEvent}),i=d(At(n,p()),"CloudStorageData").parse(r);return Array.isArray(t)?i:i[t]}async set(t,s,n={}){await R("saveStorageValue",{key:t,value:s},this.createRequestId(),{...n,postEvent:this.postEvent})}}const me=g(({createRequestId:e,postEvent:t,version:s})=>new we(s,e,t));class be extends vt{constructor(t,s){super(t,{impactOccurred:"web_app_trigger_haptic_feedback",notificationOccurred:"web_app_trigger_haptic_feedback",selectionChanged:"web_app_trigger_haptic_feedback"}),this.postEvent=s}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 ve=g(({version:e,postEvent:t})=>new be(e,t));class ye{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 Ee=g(({initData:e})=>e?new ye(e):void 0);function Bs(e){return te().parse(e)}class Pe extends L{constructor(t,s,n){super({isOpened:t},s,{open:"web_app_open_invoice"}),this.postEvent=n}set isOpened(t){this.set("isOpened",t)}get isOpened(){return this.get("isOpened")}async open(t,s){if(this.isOpened)throw new Error("Invoice is already opened");let n;if(!s)n=t;else{const{hostname:r,pathname:i}=new URL(t,window.location.href);if(r!=="t.me")throw new Error(`Incorrect hostname: ${r}`);const o=i.match(/^\/(\$|invoice\/)([A-Za-z0-9\-_=]+)$/);if(!o)throw new Error('Link pathname has incorrect format. Expected to receive "/invoice/{slug}" or "/${slug}"');[,,n]=o}this.isOpened=!0;try{return(await l({method:"web_app_open_invoice",event:"invoice_closed",params:{slug:n},postEvent:this.postEvent,capture(r){return n===r.slug}})).status}finally{this.isOpened=!1}}}const Se=g(({version:e,postEvent:t})=>new Pe(!1,e,t));class xe extends _t{constructor({postEvent:t,...s}){super(s),c(this,"postEvent"),c(this,"on",(n,r)=>n==="click"?b("main_button_pressed",r):this.state.on(n,r)),c(this,"off",(n,r)=>n==="click"?M("main_button_pressed",r):this.state.off(n,r)),this.postEvent=t}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.get("isEnabled")}set isLoaderVisible(t){this.setParams({isLoaderVisible:t})}get isLoaderVisible(){return this.get("isLoaderVisible")}set isVisible(t){this.setParams({isVisible:t})}get isVisible(){return this.get("isVisible")}get backgroundColor(){return this.get("backgroundColor")}get text(){return this.get("text")}get textColor(){return this.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.set(t),this.commit(),this}}const Ce=g("mainButton",({postEvent:e,themeParams:t,state:s={isVisible:!1,isEnabled:!1,text:"",isLoaderVisible:!1,textColor:t.buttonTextColor||"#ffffff",backgroundColor:t.buttonColor||"#000000"}})=>new xe({...s,postEvent:e}));function Ms(){return Q({contact:d({userId:{type:P(),from:"user_id"},phoneNumber:{type:p(),from:"phone_number"},firstName:{type:p(),from:"first_name"},lastName:{type:p().optional(),from:"last_name"}}),authDate:{type:ft(),from:"auth_date"},hash:p()},"RequestedContact")}function Re(e,t){return s=>{const[n,r]=t[s];return S(n,r,e)}}function $s(e){return new Promise(t=>{setTimeout(t,e)})}class Te extends L{constructor({postEvent:t,createRequestId:s,version:n,botInline:r,...i}){super(i,n,{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"}),c(this,"botInline"),c(this,"postEvent"),c(this,"createRequestId"),c(this,"requestPhoneAccessPromise"),c(this,"requestWriteAccessPromise"),c(this,"supportsParam"),this.createRequestId=s,this.postEvent=t,this.botInline=r;const o=this.supports.bind(this);this.supports=a=>o(a)?a!=="switchInlineQuery"||r:!1,this.supportsParam=Re(n,{"setHeaderColor.color":["web_app_set_header_color","color"]})}async getRequestedContact({timeout:t=1e4}={}){return Ms().parse(await R("getRequestedContact",{},this.createRequestId(),{postEvent:this.postEvent,timeout:t}))}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 lt(this.bgColor)}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 $s(n),n+=50}throw Yt(t)},t)}async requestPhoneAccess(t={}){return this.requestPhoneAccessPromise||(this.requestPhoneAccessPromise=l({...t,method:"web_app_request_phone",event:"phone_requested",postEvent:this.postEvent}).then(({status:s})=>s).finally(()=>this.requestPhoneAccessPromise=void 0)),this.requestPhoneAccessPromise}async requestWriteAccess(t={}){return this.requestWriteAccessPromise||(this.requestWriteAccessPromise=l({...t,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(t){const{size:s}=new Blob([t]);if(!s||s>4096)throw new Error(`Passed data has incorrect size: ${s}`);this.postEvent("web_app_data_send",{data:t})}setHeaderColor(t){this.postEvent("web_app_set_header_color",z(t)?{color:t}:{color_key:t}),this.set("headerColor",t)}setBgColor(t){this.postEvent("web_app_set_background_color",{color:t}),this.set("bgColor",t)}switchInlineQuery(t,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:t,chat_types:s})}}const Ae=g("miniApp",({themeParams:e,botInline:t=!1,state:s={bgColor:e.bgColor||"#ffffff",headerColor:e.headerBgColor||"#000000"},...n})=>new Te({...n,...s,botInline:t}));function Ls(e){const t=e.message.trim(),s=(e.title||"").trim(),n=e.buttons||[];let r;if(s.length>64)throw new Error(`Title has incorrect size: ${s.length}`);if(!t.length||t.length>256)throw new Error(`Message has incorrect size: ${t.length}`);if(n.length>3)throw new Error(`Buttons have incorrect size: ${n.length}`);return n.length?r=n.map(i=>{const{id:o=""}=i;if(o.length>64)throw new Error(`Button ID has incorrect size: ${o}`);if(!i.type||i.type==="default"||i.type==="destructive"){const a=i.text.trim();if(!a.length||a.length>64){const h=i.type||"default";throw new Error(`Button text with type "${h}" has incorrect size: ${i.text.length}`)}return{...i,text:a,id:o}}return{...i,id:o}}):r=[{type:"close",id:""}],{title:s,message:t,buttons:r}}class Ie extends L{constructor(t,s,n){super({isOpened:t},s,{open:"web_app_open_popup"}),this.postEvent=n}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:s=null}=await l({event:"popup_closed",method:"web_app_open_popup",postEvent:this.postEvent,params:Ls(t)});return s}finally{this.isOpened=!1}}}const ke=g(({postEvent:e,version:t})=>new Ie(!1,t,e));class Oe extends L{constructor(t,s,n){super({isOpened:t},s,{close:"web_app_close_scan_qr_popup",open:"web_app_open_scan_qr_popup"}),this.postEvent=n}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.");this.isOpened=!0;try{return(await l({method:"web_app_open_scan_qr_popup",event:["qr_text_received","scan_qr_popup_closed"],postEvent:this.postEvent,params:{text:t}})||{}).data||null}finally{this.isOpened=!1}}}const qe=g(({version:e,postEvent:t})=>new Oe(!1,e,t));class De extends gt{constructor(t,s,n){super({isVisible:t},s,{show:"web_app_setup_settings_button",hide:"web_app_setup_settings_button"}),c(this,"on",(r,i)=>r==="click"?b("settings_button_pressed",i):this.state.on(r,i)),c(this,"off",(r,i)=>r==="click"?M("settings_button_pressed",i):this.state.off(r,i)),this.postEvent=n}set isVisible(t){this.set("isVisible",t),this.postEvent("web_app_setup_settings_button",{is_visible:t})}get isVisible(){return this.get("isVisible")}hide(){this.isVisible=!1}show(){this.isVisible=!0}}const Ne=g("settingsButton",({version:e,postEvent:t,state:s={isVisible:!1}})=>new De(s.isVisible,e,t));function yt(e){return ee().parse(e)}class Ve extends bt{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||lt(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")}listen(){return b("theme_changed",t=>{this.set(yt(t.theme_params))})}get subtitleTextColor(){return this.get("subtitleTextColor")}get textColor(){return this.get("textColor")}}const Be=g("themeParams",({themeParams:e,state:t=e})=>{const s=new Ve(t);return x()||s.listen(),s});function Us(e={}){return l({...e,method:"web_app_request_theme",event:"theme_changed"}).then(yt)}class Me extends vt{constructor(t,s,n){super(t,{readTextFromClipboard:"web_app_read_text_from_clipboard"}),c(this,"supportsParam"),this.version=t,this.createRequestId=s,this.postEvent=n,this.supportsParam=Re(t,{"openLink.tryInstantView":["web_app_open_link","try_instant_view"]})}openLink(t,s){const n=new URL(t,window.location.href).toString();if(!S("web_app_open_link",this.version)){window.open(n,"_blank");return}this.postEvent("web_app_open_link",{url:n,...typeof s=="boolean"?{try_instant_view:s}:{}})}openTelegramLink(t){const{hostname:s,pathname:n,search:r}=new URL(t,window.location.href);if(s!=="t.me")throw new Error(`URL has not allowed hostname: ${s}. Only "t.me" is allowed`);if(!S("web_app_open_tg_link",this.version)){window.location.href=t;return}this.postEvent("web_app_open_tg_link",{path_full:n+r})}async readTextFromClipboard(){const t=this.createRequestId(),{data:s=null}=await l({method:"web_app_read_text_from_clipboard",event:"clipboard_text_received",postEvent:this.postEvent,params:{req_id:t},capture:ut(t)});return s}}const $e=g(({version:e,postEvent:t,createRequestId:s})=>new Me(e,s,t));async function Et(e={}){const{is_expanded:t,is_state_stable:s,...n}=await l({...e,method:"web_app_request_viewport",event:"viewport_changed"});return{...n,isExpanded:t,isStateStable:s}}function k(e){return e<0?0:e}class Pt extends bt{constructor({postEvent:t,stableHeight:s,height:n,width:r,isExpanded:i}){super({height:k(n),isExpanded:i,stableHeight:k(s),width:k(r)}),c(this,"postEvent"),this.postEvent=t}async sync(t){const{isStateStable:s,...n}=await Et(t);this.set({...n,stableHeight:s?n.height:this.get("stableHeight")})}get height(){return this.get("height")}get stableHeight(){return this.get("stableHeight")}listen(){return b("viewport_changed",t=>{const{height:s,width:n,is_expanded:r,is_state_stable:i}=t,o=k(s);this.set({height:o,isExpanded:r,width:k(n),...i?{stableHeight:o}:{}})})}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}}async function Hs(e,t={}){const{height:s,width:n,isExpanded:r,isStateStable:i}=await Et({...t,postEvent:e});return new Pt({postEvent:e,height:s,width:n,isExpanded:r,stableHeight:i?s:0})}function Ws({state:e,platform:t,postEvent:s}){let n=!1,r=0,i=0,o=0;return e?(n=e.isExpanded,r=e.height,i=e.width,o=e.stableHeight):["macos","tdesktop","unigram","webk","weba","web"].includes(t)&&(n=!0,r=window.innerHeight,i=window.innerWidth,o=window.innerHeight),new Pt({postEvent:s,height:r,width:i,stableHeight:o,isExpanded:n})}const Le=g("viewport",async e=>{if(x()&&!e.state)throw _(G,"Viewport cannot be instantiated on the server side without passing the ssr.state object.");let t=Ws(e);return x()||(t.width===0&&await Hs(e.postEvent,{timeout:1e3}).then(s=>t=s).catch(s=>j.error("Unable to sync viewport state",s)),t.listen()),t});function E(e,t){document.documentElement.style.setProperty(e,t)}function js(e,t,s){s||(s=a=>`--tg-${a}-color`);const n=s("header"),r=s("bg"),i=()=>{const{headerColor:a}=e;if(z(a))E(n,a);else{const{bgColor:h,secondaryBgColor:u}=t;a==="bg_color"&&h?E(n,h):a==="secondary_bg_color"&&u&&E(n,u)}E(r,e.bgColor)},o=[t.on("change",i),e.on("change",i)];return i(),()=>o.forEach(a=>a())}function Gs(e,t){t||(t=n=>`--tg-theme-${n.replace(/[A-Z]/g,r=>`-${r.toLowerCase()}`)}`);const s=()=>{Object.entries(e.getState()).forEach(([n,r])=>{r&&E(t(n),r)})};return s(),e.on("change",s)}function Ks(e,t){t||(t=u=>`--tg-viewport-${u}`);const[s,n,r]=["height","width","stable-height"].map(u=>t(u)),i=()=>E(s,`${e.height}px`),o=()=>E(n,`${e.width}px`),a=()=>E(r,`${e.stableHeight}px`),h=[e.on("change:height",i),e.on("change:width",o),e.on("change:stableHeight",a)];return i(),o(),a(),()=>h.forEach(u=>u())}function Ue(e=!0){const t=[b("reload_iframe",()=>{T("iframe_will_reload"),window.location.reload()})],s=()=>t.forEach(n=>n());if(e){const n=document.createElement("style");n.id="telegram-custom-styles",document.head.appendChild(n),t.push(b("set_custom_style",r=>{n.innerHTML=r}),()=>document.head.removeChild(n))}return T("iframe_ready",{reload_supported:!0}),s}async function zs(){if(zt(window))return!0;try{return await l({method:"web_app_request_theme",event:"theme_changed",timeout:100}),!0}catch{return!1}}function He(e){return e instanceof B}function Js(e,t){return He(e)&&e.type===t}function Y(e,t){let s,n,r;return typeof e=="string"?s=e:(s=e.pathname===void 0?t:e.pathname,n=e.params,r=e.id),Object.freeze({id:r||(Math.random()*2**14|0).toString(16),pathname:s,params:n})}class We{constructor(t,s,n=T){if(c(this,"history"),c(this,"ee",new V),c(this,"attached",!1),c(this,"back",()=>this.go(-1)),c(this,"on",this.ee.on.bind(this.ee)),c(this,"off",this.ee.off.bind(this.ee)),this._index=s,this.postEvent=n,t.length===0)throw _(Lt,"History should not be empty.");if(s<0||s>=t.length)throw _(Ut,"Index should not be zero and higher or equal than history size.");this.history=t.map(r=>Y(r,""))}attach(){this.attached||(this.attached=!0,this.sync(),b("back_button_pressed",this.back))}get current(){return this.history[this.index]}detach(){this.attached=!1,M("back_button_pressed",this.back)}forward(){this.go(1)}go(t,s){const n=this.index+t,r=Math.min(Math.max(0,n),this.history.length-1);(n===r||s)&&this.replaceAndMove(r,this.history[r])}goTo(t,s){this.go(t-this.index,s)}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,Y(t,this.current.pathname))}replace(t){this.replaceAndMove(this.index,Y(t,this.current.pathname))}replaceAndMove(t,s){const n=t-this.index;if(!n&&this.current===s)return;const r=this.current;if(this.index!==t){const i=this._index;this._index=t,this.attached&&i>0!=t>0&&this.sync()}this.history[t]=s,this.ee.emit("change",{navigator:this,from:r,to:this.current,delta:n})}sync(){this.postEvent("web_app_setup_back_button",{is_visible:!!this.index})}}function Z({params:e,...t}){return{...e||{hash:"",search:""},...t}}function q(e,t){return e.startsWith(t)?e:`${t}${e}`}function D(e){return new URL(typeof e=="string"?e:`${e.pathname||""}${q(e.search||"","?")}${q(e.hash||"","#")}`,"http://a")}function N(e){const t=typeof e=="string"?e.startsWith("/"):!!(e.pathname&&e.pathname.startsWith("/")),s=D(e);return`${t?s.pathname:s.pathname.slice(1)}${s.search}${s.hash}`}function X(e,t,s){let n,r;typeof e=="string"?n=e:(n=N(e),s=e.state,r=e.id);const{pathname:i,search:o,hash:a}=new URL(n,`http://a${q(t,"/")}`);return{id:r,pathname:i,params:{hash:a,search:o,state:s}}}async function O(e){return e===0?!0:Promise.race([new Promise(t=>{const s=nt("popstate",()=>{s(),t(!0)});window.history.go(e)}),new Promise(t=>{setTimeout(t,50,!1)})])}async function Qs(){if(window.history.length<=1||(window.history.pushState(null,""),await O(1-window.history.length)))return;let e=await O(-1);for(;e;)e=await O(-1)}function St(e){return D(e).pathname}const It=0,tt=1,et=2;class xt{constructor(t,s,{postEvent:n,hashMode:r,base:i}={}){c(this,"navigator"),c(this,"ee",new V),c(this,"hashMode"),c(this,"base"),c(this,"attached",!1),c(this,"onPopState",({state:o})=>{if(o===null)return this.push(this.parsePath(window.location.href));o===It?window.history.forward():o===tt&&this.back(),o===et&&this.forward()}),c(this,"onNavigatorChange",async({to:o,from:a,delta:h})=>{this.attached&&await this.syncHistory(),this.ee.emit("change",{delta:h,from:Z(a),to:Z(o),navigator:this})}),c(this,"on",this.ee.on.bind(this.ee)),c(this,"off",this.ee.off.bind(this.ee)),this.navigator=new We(t.map(o=>X(o,"/")),s,n),this.navigator.on("change",this.onNavigatorChange),this.hashMode=r,this.base=St(i||"")}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,s){return this.navigator.go(t,s)}goTo(t,s){this.navigator.goTo(t,s)}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(Z)}get path(){return N(this)}get pathname(){return this.navigator.current.pathname}parsePath(t){let s=D(t);return this.hashMode&&(s=D(s.hash.slice(1))),{pathname:s.pathname,search:s.search,hash:s.hash}}push(t,s){const n=X(t,this.path),{state:r=s}=n.params;this.navigator.push({...n,params:{...n.params,state:r}})}replace(t,s){const n=X(t,this.path),{state:r=s}=n.params;this.navigator.replace({...n,params:{...n.params,state:r}})}renderPath(t){const s=(this.base.length===1?"":this.base)+q(N(t),"/");return this.hashMode?q(s.slice(1),this.hashMode==="default"?"#":"#/"):s}async syncHistory(){window.removeEventListener("popstate",this.onPopState);const{state:t}=this,s=this.renderPath(this);await Qs(),this.hasPrev&&this.hasNext?(window.history.replaceState(tt,""),window.history.pushState(t,"",s),window.history.pushState(et,""),await O(-1)):this.hasPrev?(window.history.replaceState(tt,""),window.history.pushState(t,"",s)):this.hasNext?(window.history.replaceState(t,s),window.history.pushState(et,""),await O(-1)):(window.history.replaceState(It,""),window.history.pushState(t,"",s)),window.addEventListener("popstate",this.onPopState)}get search(){return(this.navigator.current.params||{}).search||""}get state(){return(this.navigator.current.params||{}).state}}function je(e){e||(e={});const{href:t,hash:s}=window.location;let n=N(e.hashMode?s.includes("?")?s.slice(1):`?${s.slice(1)}`:t);const r=e.base?St(e.base):void 0;if(r){if(!n.startsWith(r))throw _(Wt,`Path "${n}" expected to be starting with "${r}"`);n=n.slice(r.length)}return new xt([n],0,e)}function Fs(e){const t=e.match(/#(.+)/);return t?t[1]:null}function Ys(e,t){if(mt()){const s=sessionStorage.getItem(e);if(s)try{const{index:n,history:r}=JSON.parse(s);return new xt(r,n,t)}catch(n){console.error("Unable to restore hash navigator state.",n)}}return je(t)}function Zs(e,t){const s=Ys(e,t),n=()=>sessionStorage.setItem(e,JSON.stringify({index:s.index,history:s.history}));return s.on("change",n),n(),s}function f(e){return(t,s,...n)=>r=>m.createComponent(s,m.mergeProps(()=>m.mergeProps({[t]:e(...n)},r)))}const Ge=m.createContext();function Ke(){const e=m.useContext(Ge);if(!e)throw new Error("useSDK was used outside of SDKProvider.");return e}function w(e){return(...t)=>Ke()(e,...t)}const ze=w(pe),Xs=f(ze),Je=w(le),tn=f(Je),Qe=w(ge),en=f(Qe),Fe=w(me),sn=f(Fe),Ye=w(ve),nn=f(Ye),Ze=w(Ee),rn=f(Ze),Xe=w(Se),on=f(Xe),ts=w(Ce),an=f(ts),es=w(Ae),cn=f(es),ss=w(ke),hn=f(ss),ns=w(qe),pn=f(ns),rs=w(Ne),un=f(rs),is=w(Be),dn=f(is),os=w($e),ln=f(os),as=w(Le),_n=f(as),gn=e=>{const t=new Map,s=(n,...r)=>{if(t.has(n))return t.get(n);const[i]=m.createResource(()=>{try{return n(...r)}catch(h){return[h]}}),o=m.createMemo(()=>{if(i.error)return[i.error];if(i.state!=="ready")return;const h=i();if(Array.isArray(h)||!h||!("on"in h))return h;const u=m.from(H=>(H(h),h.on("change",()=>H(h)))),U=Object.getPrototypeOf(h),F={};return new Proxy(h,{get(H,C){if(!(C in F)){const Ct=Reflect.getOwnPropertyDescriptor(U,C);F[C]=Ct&&"get"in Ct?m.createMemo(()=>u()[C]):()=>Reflect.get(H,C)}return F[C]()}})});function a(){const h=o();if(Array.isArray(h))throw h[0];return h}return Object.defineProperty(a,"error",{get(){const h=o();return Array.isArray(h)?h[0]:void 0}}),t.set(n,a),a};return m.createEffect(()=>{qt(e.debug||!1)}),m.createEffect(()=>{pt()&&m.onCleanup(Ue(e.acceptCustomStyles))}),m.createComponent(Ge.Provider,{value:s,get children(){return e.children}})};exports.BackButton=Xt;exports.BasicNavigator=We;exports.BiometryManager=rt;exports.BrowserNavigator=xt;exports.ClosingBehavior=_e;exports.CloudStorage=we;exports.ERR_INVALID_PATH_BASE=Wt;exports.ERR_INVOKE_CUSTOM_METHOD_RESPONSE=Bt;exports.ERR_METHOD_PARAMETER_UNSUPPORTED=Nt;exports.ERR_METHOD_UNSUPPORTED=Dt;exports.ERR_NAVIGATION_HISTORY_EMPTY=Lt;exports.ERR_NAVIGATION_INDEX_INVALID=Ut;exports.ERR_NAVIGATION_ITEM_INVALID=ds;exports.ERR_PARSE=ot;exports.ERR_SSR_INIT=G;exports.ERR_SSR_POST_EVENT=Ht;exports.ERR_TIMED_OUT=Mt;exports.ERR_UNEXPECTED_TYPE=$t;exports.ERR_UNKNOWN_ENV=Vt;exports.EventEmitter=V;exports.HapticFeedback=be;exports.InitData=ye;exports.Invoice=Pe;exports.MainButton=xe;exports.MiniApp=Te;exports.Popup=Ie;exports.QRScanner=Oe;exports.SDKError=B;exports.SDKProvider=gn;exports.SettingsButton=De;exports.ThemeParams=Ve;exports.Utils=Me;exports.Viewport=Pt;exports.array=fe;exports.bindMiniAppCSSVars=js;exports.bindThemeParamsCSSVars=Gs;exports.bindViewportCSSVars=Ks;exports.boolean=y;exports.captureSameReq=ut;exports.classNames=W;exports.compareVersions=Kt;exports.createBrowserNavigatorFromLocation=je;exports.createPostEvent=Ft;exports.createSafeURL=D;exports.date=ft;exports.getHash=Fs;exports.getPathname=St;exports.initBackButton=pe;exports.initBiometryManager=le;exports.initClosingBehavior=ge;exports.initCloudStorage=me;exports.initHapticFeedback=ve;exports.initInitData=Ee;exports.initInvoice=Se;exports.initMainButton=Ce;exports.initMiniApp=Ae;exports.initNavigator=Zs;exports.initPopup=ke;exports.initQRScanner=qe;exports.initSettingsButton=Ne;exports.initThemeParams=Be;exports.initUtils=$e;exports.initViewport=Le;exports.initWeb=Ue;exports.invokeCustomMethod=R;exports.isColorDark=lt;exports.isIframe=pt;exports.isPageReload=mt;exports.isRGB=z;exports.isRGBShort=Gt;exports.isSDKError=He;exports.isSDKErrorOfType=Js;exports.isSSR=x;exports.isTMA=zs;exports.json=d;exports.mergeClassNames=Ss;exports.number=P;exports.off=M;exports.on=b;exports.parseInitData=Bs;exports.parseLaunchParams=wt;exports.parseThemeParams=yt;exports.postEvent=T;exports.request=l;exports.requestBiometryInfo=de;exports.requestThemeParams=Us;exports.requestViewport=Et;exports.retrieveLaunchParams=he;exports.rgb=ht;exports.searchParams=Q;exports.serializeLaunchParams=ce;exports.serializeThemeParams=ae;exports.setCSSVar=E;exports.setDebug=qt;exports.setTargetOrigin=Ps;exports.string=p;exports.subscribe=Ot;exports.supports=S;exports.targetOrigin=Qt;exports.toRGB=ct;exports.unsubscribe=it;exports.urlToPath=N;exports.useBackButton=ze;exports.useBiometryManager=Je;exports.useClosingBehavior=Qe;exports.useCloudStorage=Fe;exports.useHapticFeedback=Ye;exports.useInitData=Ze;exports.useInvoice=Xe;exports.useMainButton=ts;exports.useMiniApp=es;exports.usePopup=ss;exports.useQRScanner=ns;exports.useSDK=Ke;exports.useSettingsButton=rs;exports.useThemeParams=is;exports.useUtils=os;exports.useViewport=as;exports.withBackButton=Xs;exports.withBiometryManager=tn;exports.withClosingBehavior=en;exports.withCloudStorage=sn;exports.withHapticFeedback=nn;exports.withInitData=rn;exports.withInvoice=on;exports.withMainButton=an;exports.withMiniApp=cn;exports.withPopup=hn;exports.withQRScanner=pn;exports.withSettingsButton=un;exports.withThemeParams=dn;exports.withTimeout=dt;exports.withUtils=ln;exports.withViewport=_n;
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|