@wowlabtech/mini-app-adapter 0.2.85 → 0.2.86

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 CHANGED
@@ -1,10 +1,10 @@
1
- "use strict";var pt=Object.create;var U=Object.defineProperty;var dt=Object.getOwnPropertyDescriptor;var lt=Object.getOwnPropertyNames;var ct=Object.getPrototypeOf,ut=Object.prototype.hasOwnProperty;var ft=(o,r,e)=>r in o?U(o,r,{enumerable:!0,configurable:!0,writable:!0,value:e}):o[r]=e;var mt=(o,r)=>{for(var e in r)U(o,e,{get:r[e],enumerable:!0})},Ee=(o,r,e,t)=>{if(r&&typeof r=="object"||typeof r=="function")for(let n of lt(r))!ut.call(o,n)&&n!==e&&U(o,n,{get:()=>r[n],enumerable:!(t=dt(r,n))||t.enumerable});return o};var le=(o,r,e)=>(e=o!=null?pt(ct(o)):{},Ee(r||!o||!o.__esModule?U(e,"default",{value:o,enumerable:!0}):e,o)),ht=o=>Ee(U({},"__esModule",{value:!0}),o);var f=(o,r,e)=>ft(o,typeof r!="symbol"?r+"":r,e);var xt={};mt(xt,{AdapterProvider:()=>Ye,BaseMiniAppAdapter:()=>A,MaxMiniAppAdapter:()=>_,ShellMiniAppAdapter:()=>R,TelegramMiniAppAdapter:()=>F,VKMiniAppAdapter:()=>I,WebMiniAppAdapter:()=>W,configureVkPixel:()=>nt,createAdapter:()=>je,createShellAPI:()=>$,detectPlatform:()=>Y,getActiveAdapter:()=>H,getPlatform:()=>oe,isShell:()=>we,isShellAndroid:()=>Oe,isShellIOS:()=>He,readShellPlatform:()=>G,requestShellPushPermission:()=>ne,shell:()=>Ne,storeShellToken:()=>De,trackConversionEvent:()=>rt,trackPixelEvent:()=>it,useAdapterTheme:()=>Ze,useMiniAppAdapter:()=>O,useSafeArea:()=>tt});module.exports=ht(xt);var Z=class{constructor(){f(this,"disposers",new Set)}add(r){if(!r)return()=>{};let e=typeof r=="function"?r:typeof r.dispose=="function"?r.dispose.bind(r):void 0;if(!e)return()=>{};let t=!1,n=()=>{if(!t){t=!0;try{e()}catch(i){console.warn("[tvm-app-adapter] disposable failed:",i)}finally{this.disposers.delete(n)}}};return this.disposers.add(n),n}disposeAll(){for(let r of Array.from(this.disposers))try{r()}catch(e){console.warn("[tvm-app-adapter] disposeAll failed:",e)}this.disposers.clear()}};var Te=typeof window<"u"&&typeof document<"u";function vt(o,r){if(r&&r.trim().length>0)return r;try{let t=new URL(o).pathname.split("/").filter(Boolean).pop();if(t)return t}catch{}return"download"}function Le(o,r,{targetBlank:e}){if(!Te)return;let t=document.createElement("a");t.href=o,t.download=r,t.rel="noopener noreferrer",e&&(t.target="_blank"),document.body.appendChild(t),t.click(),document.body.removeChild(t)}async function ee(o,r,e){if(!o)return;let t=vt(o,r),n=e?.preferBlob??!1;if(!Te){typeof window<"u"&&window.open(o,"_blank","noopener,noreferrer");return}if(n&&typeof fetch=="function")try{let i=await fetch(o,{credentials:"include"});if(!i.ok)throw new Error(`Failed to download file: ${i.status}`);let p=await i.blob(),d=URL.createObjectURL(p);Le(d,t,{targetBlank:!1}),setTimeout(()=>URL.revokeObjectURL(d),3e4);return}catch(i){console.warn("[tvm-app-adapter] blob download failed, falling back to direct link:",i)}Le(o,t,{targetBlank:!0})}var ue=["top","right","bottom","left"],Fe={top:0,right:0,bottom:0,left:0};function ce(o){return{...o}}function Q(o,r){if(r)for(let e of ue){let t=r[e];typeof t=="number"&&Number.isFinite(t)&&(o[e]+=t)}}function _e(o,r){if(r)for(let e of ue){let t=r[e];typeof t=="number"&&Number.isFinite(t)&&(o[e]=Math.max(o[e],t))}}function yt(o,r){return!o||!r?!1:ue.every(e=>o[e]===r[e])}function j(o={}){let r=ce(Fe);return Q(r,o.environment),o.viewport&&(Q(r,o.viewport.safeArea),Q(r,o.viewport.contentSafeArea)),Q(r,o.additions),_e(r,o.css),_e(r,o.minimum),r}function te(){if(typeof window>"u"||typeof document>"u")return;let o=getComputedStyle(document.documentElement),r=p=>{let d=parseFloat(o.getPropertyValue(p));return Number.isFinite(d)?d:0},e=r("--safe-area-inset-top"),t=r("--safe-area-inset-right"),n=r("--safe-area-inset-bottom"),i=r("--safe-area-inset-left");if(e||t||n||i)return{top:e,right:t,bottom:n,left:i}}function Re(o){if(!o)return;let r={...Fe};return Q(r,o),r}function Ie(o){let r=o.windowObj??(typeof window<"u"?window:void 0);if(!r)return;let e=Re(o.getSafeArea());e&&(o.onChange(e),e=ce(e));let t=()=>{let i=Re(o.getSafeArea());i&&(!e||!yt(e,i))&&(o.onChange(i),e=ce(i))};t();let n=o.events??["resize","orientationchange"];for(let i of n)r.addEventListener(i,t);return()=>{for(let i of n)r.removeEventListener(i,t)}}var gt=["shell_ios","shell_android"];var me=new Set,he=new Set,ve=new Set,ye=new Set,ge=null,S=null,wt={platformFlag:"nativePlatform",pushTokenCallback:"nativePushToken",qrResultCallback:"nativeQRResult",deepLinkCallback:"nativeDeepLink",appActiveCallback:"nativeAppActive",appBackgroundCallback:"nativeAppBackground"},We={...wt},fe={};function bt(o){ge=o;for(let r of me)try{r(o)}catch(e){console.warn("[tvm-app-adapter] push token listener failed:",e)}}function we(o){return gt.includes(o)}function He(o){return o==="shell_ios"}function Oe(o){return o==="shell_android"}function G(){let o=be();if(!o)return;let r=o[We.platformFlag];if(r==="shell_ios"||r==="shell_android")return r}function $(o){kt();let r=typeof o=="function"?o:()=>o;return{async openNativeQR(){let e=r();return we(e)?Pt():St()},onPushToken(e){return me.add(e),ge&&queueMicrotask(()=>{try{e(ge)}catch(t){console.warn("[tvm-app-adapter] push token listener failed:",t)}}),()=>me.delete(e)},onDeepLink(e){return he.add(e),()=>he.delete(e)},onAppActive(e){return ve.add(e),()=>ve.delete(e)},onAppBackground(e){return ye.add(e),()=>ye.delete(e)}}}var Ne=$(()=>G()??"web");function De(o){return Ae({type:"storeToken",payload:o})}function ne(){return Ae({type:"requestPushPermission"})}function be(){return typeof window>"u"?null:window}function At(){let o=be();if(!o)return null;let r=o.NativeBridge;return!r||typeof r.postMessage!="function"?null:r}function Ae(o){let r=At();if(!r)return!1;try{return r.postMessage(o),!0}catch(e){return console.warn("[tvm-app-adapter] NativeBridge.postMessage failed:",e),!1}}function kt(){let o=be();if(!o){fe={};return}let r=o,e=(t,n)=>{let i=We[t],p=fe[t];p&&p!==i&&delete r[p],fe[t]=i,r[i]=n};e("pushTokenCallback",t=>{typeof t=="string"&&(console.log("[tvm-app-adapter] nativePushToken",t),bt(t))}),e("deepLinkCallback",t=>{if(typeof t=="string")for(let n of he)try{n(t)}catch(i){console.warn("[tvm-app-adapter] deep link listener failed:",i)}}),e("appActiveCallback",()=>{for(let t of ve)try{t()}catch(n){console.warn("[tvm-app-adapter] app active listener failed:",n)}}),e("appBackgroundCallback",()=>{for(let t of ye)try{t()}catch(n){console.warn("[tvm-app-adapter] app background listener failed:",n)}}),e("qrResultCallback",t=>{typeof t=="string"&&S&&(clearTimeout(S.timeoutId),S.resolve(t),S=null)})}function Pt(){return new Promise((o,r)=>{if(S&&(S.reject(new Error("QR request superseded by a new call.")),clearTimeout(S.timeoutId),S=null),!Ae({type:"openNativeQR"})){r(new Error("Native bridge is unavailable."));return}let e=setTimeout(()=>{S&&(S.reject(new Error("Native QR request timed out.")),S=null)},6e4);S={resolve:o,reject:r,timeoutId:e}})}async function St(){if(typeof document>"u")throw new Error("QR scanning requires a browser environment.");let[{Html5Qrcode:o}]=await Promise.all([import("html5-qrcode")]);return new Promise((r,e)=>{let t=`native-shell-qr-${Date.now()}`,n=document.createElement("div");n.style.position="fixed",n.style.inset="0",n.style.background="rgba(0, 0, 0, 0.9)",n.style.display="flex",n.style.flexDirection="column",n.style.alignItems="center",n.style.justifyContent="center",n.style.zIndex="2147483647",n.style.backdropFilter="blur(2px)";let i=document.createElement("div");i.id=t,i.style.width="280px",i.style.height="280px",i.style.borderRadius="16px",i.style.overflow="hidden",i.style.position="relative";let p=document.createElement("button");p.type="button",p.textContent="\u2715",p.style.position="absolute",p.style.top="16px",p.style.right="16px",p.style.background="transparent",p.style.border="none",p.style.color="#fff",p.style.fontSize="28px",p.style.cursor="pointer",n.appendChild(p),n.appendChild(i),document.body.appendChild(n);let d=document.body.style.overflow;document.body.style.overflow="hidden";let l=!1,a=new o(t),u=async(y,h)=>{if(!l){l=!0;try{await a.stop();let k=a.clear;typeof k=="function"&&await Promise.resolve(k.call(a))}catch{}n.remove(),document.body.style.overflow=d,typeof y=="string"?r(y):e(h||new Error("QR scanning was cancelled."))}};p.addEventListener("click",()=>{u(void 0,new Error("QR scanning was cancelled by the user."))}),a.start({facingMode:"environment"},{fps:10,qrbox:{width:240,height:240}},y=>{u(y)},()=>{}).catch(y=>{let h=y instanceof Error?y:new Error("Unable to start HTML5 QR scanner.");u(void 0,h)})})}var A=class{constructor(r,e){f(this,"ready",!1);f(this,"environment");f(this,"listeners",new Set);f(this,"disposables",new Z);f(this,"shell");if(this.shell=$(r),this.environment={platform:r,...e},typeof window<"u"){let t=()=>this.notifyEnvironmentChanged();if(window.addEventListener("resize",t),this.registerDisposable(()=>window.removeEventListener("resize",t)),r!=="web"){let n=this.applyScrollGuards();n&&this.registerDisposable(n)}}}supports(r){switch(r){case"openExternalLink":return!0;default:return!1}}get platform(){return this.environment.platform}async init(r){this.ready=!0}isReady(){return this.ready}getEnvironment(){return{...this.environment}}destroy(){try{this.onDestroy()}finally{this.disposables.disposeAll(),this.listeners.clear(),this.ready=!1}}subscribe(r){return this.listeners.add(r),()=>{this.listeners.delete(r)}}async setColors(r){if(r.background&&(document.body.style.backgroundColor=r.background),r.header){let e=document.querySelector('meta[name="theme-color"]');e&&e.setAttribute("content",r.header)}}onBackButton(r){let e=()=>r();return window.addEventListener("popstate",e),()=>window.removeEventListener("popstate",e)}onPushToken(r){return this.shell.onPushToken(r)}onDeepLink(r){return this.shell.onDeepLink(r)}async openExternalLink(r){window.open(r,"_blank","noopener,noreferrer")}async openInternalLink(r){window.open(r,"_self","noopener,noreferrer")}async closeApp(){window.history.length>1?window.history.back():window.close()}setBackButtonVisibility(r){}onAppearanceChange(r){return r(this.environment.appearance),()=>{}}getInitData(){}getLaunchParams(){return{customLaunchParams:this.readCustomUrlParams()}}decodeStartParam(r){}requestFullscreen(){}onViewportChange(r){if(typeof window>"u")return()=>{};let e=()=>window.visualViewport?.height??window.innerHeight,t=()=>{let i=e();r({height:i,stableHeight:i})};t();let n=()=>t();return window.visualViewport?.addEventListener("resize",n),window.visualViewport?.addEventListener("scroll",n),window.addEventListener("resize",n),()=>{window.visualViewport?.removeEventListener("resize",n),window.visualViewport?.removeEventListener("scroll",n),window.removeEventListener("resize",n)}}getViewportInsets(){}shareMessage(r){return Promise.resolve()}shareUrl(r,e){}async downloadFile(r,e){await ee(r,e)}shareStory(r,e){return Promise.resolve()}trackConversionEvent(r,e){}trackPixelEvent(r,e){}copyTextToClipboard(r){return navigator.clipboard.writeText(r).catch(()=>{let e=document.createElement("textarea");e.value=r,e.style.position="fixed",document.body.appendChild(e),e.focus(),e.select();try{document.execCommand("copy")}catch{}document.body.removeChild(e)})}computeSafeArea(){let r=this.getViewportInsets?.(),e=te();return j({environment:this.environment.safeArea,viewport:r,css:e})}bindCssVariables(r){}vibrateImpact(r){navigator.vibrate?.(10)}vibrateNotification(r){navigator.vibrate?.([10,30,10])}vibrateSelection(){navigator.vibrate?.(5)}onViewHide(r){return()=>{}}onViewRestore(r){return()=>{}}async showPopup(r){let e=[r.title,r.message].filter(Boolean).join(`
1
+ "use strict";var at=Object.create;var z=Object.defineProperty;var st=Object.getOwnPropertyDescriptor;var pt=Object.getOwnPropertyNames;var dt=Object.getPrototypeOf,lt=Object.prototype.hasOwnProperty;var ct=(i,n,e)=>n in i?z(i,n,{enumerable:!0,configurable:!0,writable:!0,value:e}):i[n]=e;var ut=(i,n)=>{for(var e in n)z(i,e,{get:n[e],enumerable:!0})},Ve=(i,n,e,t)=>{if(n&&typeof n=="object"||typeof n=="function")for(let r of pt(n))!lt.call(i,r)&&r!==e&&z(i,r,{get:()=>n[r],enumerable:!(t=st(n,r))||t.enumerable});return i};var se=(i,n,e)=>(e=i!=null?at(dt(i)):{},Ve(n||!i||!i.__esModule?z(e,"default",{value:i,enumerable:!0}):e,i)),ft=i=>Ve(z({},"__esModule",{value:!0}),i);var h=(i,n,e)=>ct(i,typeof n!="symbol"?n+"":n,e);var Ct={};ut(Ct,{AdapterProvider:()=>Ge,BaseMiniAppAdapter:()=>S,ShellMiniAppAdapter:()=>_,TelegramMiniAppAdapter:()=>W,VKMiniAppAdapter:()=>I,WebMiniAppAdapter:()=>F,configureVkPixel:()=>Xe,createAdapter:()=>ze,createShellAPI:()=>j,detectPlatform:()=>$,getActiveAdapter:()=>O,getPlatform:()=>rt,isShell:()=>ve,isShellAndroid:()=>Ie,isShellIOS:()=>We,readShellPlatform:()=>G,requestShellPushPermission:()=>te,shell:()=>Fe,storeShellToken:()=>Oe,trackConversionEvent:()=>et,trackPixelEvent:()=>tt,useAdapterTheme:()=>Ye,useMiniAppAdapter:()=>H,useSafeArea:()=>Ze});module.exports=ft(Ct);var Z=class{constructor(){h(this,"disposers",new Set)}add(n){if(!n)return()=>{};let e=typeof n=="function"?n:typeof n.dispose=="function"?n.dispose.bind(n):void 0;if(!e)return()=>{};let t=!1,r=()=>{if(!t){t=!0;try{e()}catch(o){console.warn("[tvm-app-adapter] disposable failed:",o)}finally{this.disposers.delete(r)}}};return this.disposers.add(r),r}disposeAll(){for(let n of Array.from(this.disposers))try{n()}catch(e){console.warn("[tvm-app-adapter] disposeAll failed:",e)}this.disposers.clear()}};var Ee=typeof window<"u"&&typeof document<"u";function mt(i,n){if(n&&n.trim().length>0)return n;try{let t=new URL(i).pathname.split("/").filter(Boolean).pop();if(t)return t}catch{}return"download"}function xe(i,n,{targetBlank:e}){if(!Ee)return;let t=document.createElement("a");t.href=i,t.download=n,t.rel="noopener noreferrer",e&&(t.target="_blank"),document.body.appendChild(t),t.click(),document.body.removeChild(t)}async function X(i,n,e){if(!i)return;let t=mt(i,n),r=e?.preferBlob??!1;if(!Ee){typeof window<"u"&&window.open(i,"_blank","noopener,noreferrer");return}if(r&&typeof fetch=="function")try{let o=await fetch(i,{credentials:"include"});if(!o.ok)throw new Error(`Failed to download file: ${o.status}`);let p=await o.blob(),d=URL.createObjectURL(p);xe(d,t,{targetBlank:!1}),setTimeout(()=>URL.revokeObjectURL(d),3e4);return}catch(o){console.warn("[tvm-app-adapter] blob download failed, falling back to direct link:",o)}xe(i,t,{targetBlank:!0})}var de=["top","right","bottom","left"],Be={top:0,right:0,bottom:0,left:0};function pe(i){return{...i}}function Q(i,n){if(n)for(let e of de){let t=n[e];typeof t=="number"&&Number.isFinite(t)&&(i[e]+=t)}}function Le(i,n){if(n)for(let e of de){let t=n[e];typeof t=="number"&&Number.isFinite(t)&&(i[e]=Math.max(i[e],t))}}function ht(i,n){return!i||!n?!1:de.every(e=>i[e]===n[e])}function U(i={}){let n=pe(Be);return Q(n,i.environment),i.viewport&&(Q(n,i.viewport.safeArea),Q(n,i.viewport.contentSafeArea)),Q(n,i.additions),Le(n,i.css),Le(n,i.minimum),n}function ee(){if(typeof window>"u"||typeof document>"u")return;let i=getComputedStyle(document.documentElement),n=p=>{let d=parseFloat(i.getPropertyValue(p));return Number.isFinite(d)?d:0},e=n("--safe-area-inset-top"),t=n("--safe-area-inset-right"),r=n("--safe-area-inset-bottom"),o=n("--safe-area-inset-left");if(e||t||r||o)return{top:e,right:t,bottom:r,left:o}}function Te(i){if(!i)return;let n={...Be};return Q(n,i),n}function Re(i){let n=i.windowObj??(typeof window<"u"?window:void 0);if(!n)return;let e=Te(i.getSafeArea());e&&(i.onChange(e),e=pe(e));let t=()=>{let o=Te(i.getSafeArea());o&&(!e||!ht(e,o))&&(i.onChange(o),e=pe(o))};t();let r=i.events??["resize","orientationchange"];for(let o of r)n.addEventListener(o,t);return()=>{for(let o of r)n.removeEventListener(o,t)}}var vt=["shell_ios","shell_android"];var ce=new Set,ue=new Set,fe=new Set,me=new Set,he=null,k=null,yt={platformFlag:"nativePlatform",pushTokenCallback:"nativePushToken",qrResultCallback:"nativeQRResult",deepLinkCallback:"nativeDeepLink",appActiveCallback:"nativeAppActive",appBackgroundCallback:"nativeAppBackground"},_e={...yt},le={};function gt(i){he=i;for(let n of ce)try{n(i)}catch(e){console.warn("[tvm-app-adapter] push token listener failed:",e)}}function ve(i){return vt.includes(i)}function We(i){return i==="shell_ios"}function Ie(i){return i==="shell_android"}function G(){let i=ye();if(!i)return;let n=i[_e.platformFlag];if(n==="shell_ios"||n==="shell_android")return n}function j(i){bt();let n=typeof i=="function"?i:()=>i;return{async openNativeQR(){let e=n();return ve(e)?At():kt()},onPushToken(e){return ce.add(e),he&&queueMicrotask(()=>{try{e(he)}catch(t){console.warn("[tvm-app-adapter] push token listener failed:",t)}}),()=>ce.delete(e)},onDeepLink(e){return ue.add(e),()=>ue.delete(e)},onAppActive(e){return fe.add(e),()=>fe.delete(e)},onAppBackground(e){return me.add(e),()=>me.delete(e)}}}var Fe=j(()=>G()??"web");function Oe(i){return ge({type:"storeToken",payload:i})}function te(){return ge({type:"requestPushPermission"})}function ye(){return typeof window>"u"?null:window}function wt(){let i=ye();if(!i)return null;let n=i.NativeBridge;return!n||typeof n.postMessage!="function"?null:n}function ge(i){let n=wt();if(!n)return!1;try{return n.postMessage(i),!0}catch(e){return console.warn("[tvm-app-adapter] NativeBridge.postMessage failed:",e),!1}}function bt(){let i=ye();if(!i){le={};return}let n=i,e=(t,r)=>{let o=_e[t],p=le[t];p&&p!==o&&delete n[p],le[t]=o,n[o]=r};e("pushTokenCallback",t=>{typeof t=="string"&&(console.log("[tvm-app-adapter] nativePushToken",t),gt(t))}),e("deepLinkCallback",t=>{if(typeof t=="string")for(let r of ue)try{r(t)}catch(o){console.warn("[tvm-app-adapter] deep link listener failed:",o)}}),e("appActiveCallback",()=>{for(let t of fe)try{t()}catch(r){console.warn("[tvm-app-adapter] app active listener failed:",r)}}),e("appBackgroundCallback",()=>{for(let t of me)try{t()}catch(r){console.warn("[tvm-app-adapter] app background listener failed:",r)}}),e("qrResultCallback",t=>{typeof t=="string"&&k&&(clearTimeout(k.timeoutId),k.resolve(t),k=null)})}function At(){return new Promise((i,n)=>{if(k&&(k.reject(new Error("QR request superseded by a new call.")),clearTimeout(k.timeoutId),k=null),!ge({type:"openNativeQR"})){n(new Error("Native bridge is unavailable."));return}let e=setTimeout(()=>{k&&(k.reject(new Error("Native QR request timed out.")),k=null)},6e4);k={resolve:i,reject:n,timeoutId:e}})}async function kt(){if(typeof document>"u")throw new Error("QR scanning requires a browser environment.");let[{Html5Qrcode:i}]=await Promise.all([import("html5-qrcode")]);return new Promise((n,e)=>{let t=`native-shell-qr-${Date.now()}`,r=document.createElement("div");r.style.position="fixed",r.style.inset="0",r.style.background="rgba(0, 0, 0, 0.9)",r.style.display="flex",r.style.flexDirection="column",r.style.alignItems="center",r.style.justifyContent="center",r.style.zIndex="2147483647",r.style.backdropFilter="blur(2px)";let o=document.createElement("div");o.id=t,o.style.width="280px",o.style.height="280px",o.style.borderRadius="16px",o.style.overflow="hidden",o.style.position="relative";let p=document.createElement("button");p.type="button",p.textContent="\u2715",p.style.position="absolute",p.style.top="16px",p.style.right="16px",p.style.background="transparent",p.style.border="none",p.style.color="#fff",p.style.fontSize="28px",p.style.cursor="pointer",r.appendChild(p),r.appendChild(o),document.body.appendChild(r);let d=document.body.style.overflow;document.body.style.overflow="hidden";let l=!1,s=new i(t),u=async(v,m)=>{if(!l){l=!0;try{await s.stop();let A=s.clear;typeof A=="function"&&await Promise.resolve(A.call(s))}catch{}r.remove(),document.body.style.overflow=d,typeof v=="string"?n(v):e(m||new Error("QR scanning was cancelled."))}};p.addEventListener("click",()=>{u(void 0,new Error("QR scanning was cancelled by the user."))}),s.start({facingMode:"environment"},{fps:10,qrbox:{width:240,height:240}},v=>{u(v)},()=>{}).catch(v=>{let m=v instanceof Error?v:new Error("Unable to start HTML5 QR scanner.");u(void 0,m)})})}var S=class{constructor(n,e){h(this,"ready",!1);h(this,"environment");h(this,"listeners",new Set);h(this,"disposables",new Z);h(this,"shell");if(this.shell=j(n),this.environment={platform:n,...e},typeof window<"u"){let t=()=>this.notifyEnvironmentChanged();if(window.addEventListener("resize",t),this.registerDisposable(()=>window.removeEventListener("resize",t)),n!=="web"){let r=this.applyScrollGuards();r&&this.registerDisposable(r)}}}async supports(n){switch(n){case"openExternalLink":return!0;default:return!1}}get platform(){return this.environment.platform}async init(n){this.ready=!0}isReady(){return this.ready}getEnvironment(){return{...this.environment}}destroy(){try{this.onDestroy()}finally{this.disposables.disposeAll(),this.listeners.clear(),this.ready=!1}}subscribe(n){return this.listeners.add(n),()=>{this.listeners.delete(n)}}async setColors(n){if(n.background&&(document.body.style.backgroundColor=n.background),n.header){let e=document.querySelector('meta[name="theme-color"]');e&&e.setAttribute("content",n.header)}}onBackButton(n){let e=()=>n();return window.addEventListener("popstate",e),()=>window.removeEventListener("popstate",e)}onPushToken(n){return this.shell.onPushToken(n)}onDeepLink(n){return this.shell.onDeepLink(n)}async openExternalLink(n){window.open(n,"_blank","noopener,noreferrer")}async openInternalLink(n){window.open(n,"_self","noopener,noreferrer")}async closeApp(){}setBackButtonVisibility(n){}onAppearanceChange(n){return n(this.environment.appearance),()=>{}}getInitData(){}getLaunchParams(){return{customLaunchParams:this.readCustomUrlParams()}}decodeStartParam(n){}requestFullscreen(){}onViewportChange(n){if(typeof window>"u")return()=>{};let e=()=>window.visualViewport?.height??window.innerHeight,t=()=>{let o=e();n({height:o,stableHeight:o})};t();let r=()=>t();return window.visualViewport?.addEventListener("resize",r),window.visualViewport?.addEventListener("scroll",r),window.addEventListener("resize",r),()=>{window.visualViewport?.removeEventListener("resize",r),window.visualViewport?.removeEventListener("scroll",r),window.removeEventListener("resize",r)}}getViewportInsets(){}shareMessage(n){return Promise.resolve()}shareUrl(n,e){}async downloadFile(n,e){await X(n,e)}shareStory(n,e){return Promise.resolve()}trackConversionEvent(n,e){}trackPixelEvent(n,e){}copyTextToClipboard(n){return navigator.clipboard.writeText(n).catch(()=>{let e=document.createElement("textarea");e.value=n,e.style.position="fixed",document.body.appendChild(e),e.focus(),e.select();try{document.execCommand("copy")}catch{}document.body.removeChild(e)})}computeSafeArea(){let n=this.getViewportInsets?.(),e=ee();return U({environment:this.environment.safeArea,viewport:n,css:e})}bindCssVariables(n){}vibrateImpact(n){navigator.vibrate?.(10)}vibrateNotification(n){navigator.vibrate?.([10,30,10])}vibrateSelection(){navigator.vibrate?.(5)}onViewHide(n){return()=>{}}onViewRestore(n){return()=>{}}async showPopup(n){let e=[n.title,n.message].filter(Boolean).join(`
2
2
 
3
- `);return window.alert(e),r.buttons?.[0]?.id??"ok"}async scanQRCode(r){return null}async requestPhone(){return null}async requestNotificationsPermission(){if(typeof Notification>"u"||typeof Notification.requestPermission!="function")return!1;try{return await Notification.requestPermission()==="granted"}catch(r){return console.warn("[tvm-app-adapter] requestNotificationsPermission fallback failed:",r),!1}}async addToHomeScreen(){return!1}async checkHomeScreenStatus(){return"unknown"}async denyNotifications(){return console.warn("[tvm-app-adapter] denyNotifications fallback is not supported in this environment."),!1}enableVerticalSwipes(){}disableVerticalSwipes(){}notifyEnvironmentChanged(){for(let r of this.listeners)try{r()}catch(e){console.warn("[tvm-app-adapter] environment listener failed:",e)}}onDestroy(){}registerDisposable(r){return this.disposables.add(r)}readCustomUrlParams(r){if(typeof window>"u")return{};let e={},t=i=>{let p=new Set;for(let[d]of i.entries())p.add(d);for(let d of p){if(r?.(d))continue;let l=i.getAll(d);l.length&&(e[d]=l.length===1?l[0]:l)}};t(new URLSearchParams(window.location.search));let n=window.location.hash.startsWith("#")?window.location.hash.slice(1):window.location.hash;return n&&n.includes("=")&&t(new URLSearchParams(n)),e}applyScrollGuards(){if(typeof document>"u")return;let r=document.documentElement,e=document.body;if(!r||!e)return;let t=r.style.overscrollBehaviorY,n=e.style.overscrollBehaviorY,i=e.style.touchAction;return r.style.overscrollBehaviorY="none",e.style.overscrollBehaviorY="none",e.style.touchAction="manipulation",()=>{r.style.overscrollBehaviorY=t,e.style.overscrollBehaviorY=n,e.style.touchAction=i}}};function P(){return window.WebApp}var _=class extends A{constructor(){super("max");f(this,"backHandlers",new Map);f(this,"initData");f(this,"initDataUnsafe")}async init(e){if(this.ready)return;let t=P();t?.ready?.(),this.initData=t?.initData,this.initDataUnsafe=t?.initDataUnsafe;let n={platform:"max",sdkVersion:t?.version,appVersion:t?.version,languageCode:t?.initDataUnsafe?.user?.language_code,isWebView:!0};this.environment=n,this.ready=!0}supports(e){let t=P();switch(e){case"haptics":return!!t?.HapticFeedback?.impactOccurred;case"qrScanner":return typeof t?.openCodeReader=="function";case"closeApp":return typeof t?.close=="function";case"backButton":return!!t?.BackButton?.onClick;case"backButtonVisibility":return!!(t?.BackButton?.show&&t.BackButton.hide);case"openInternalLink":return typeof t?.openMaxLink=="function";case"downloadFile":return typeof t?.downloadFile=="function";case"requestPhone":return t?typeof t.requestPhoneNumber=="function"||typeof window<"u":!1;case"popup":return!1;default:return!1}}getInitData(){return this.initData}getLaunchParams(){return{launchParams:this.initDataUnsafe,customLaunchParams:this.readCustomUrlParams()}}onBackButton(e){let t=P();if(!t?.BackButton?.onClick)return super.onBackButton(e);let n=()=>e(),i=t.BackButton.onClick(n);t.BackButton.show?.();let p=this.registerDisposable(()=>{typeof i=="function"?i():t.BackButton?.offClick?.(n),this.backHandlers.delete(e),this.backHandlers.size||t.BackButton?.hide?.()});return this.backHandlers.set(e,p),p}setBackButtonVisibility(e){let t=P();t?.BackButton&&(e?t.BackButton.show?.():t.BackButton.hide?.())}async openExternalLink(e){let t=P();if(t?.openExternalLink){t.openExternalLink(e);return}await super.openExternalLink(e)}async openInternalLink(e){let t=P();if(t?.openMaxLink){t.openMaxLink(e);return}await super.openInternalLink(e)}async closeApp(){let e=P();if(e?.close){e.close();return}await super.closeApp()}vibrateImpact(e){let t=P();if(!t?.HapticFeedback?.impactOccurred){super.vibrateImpact(e);return}t.HapticFeedback.impactOccurred(e).catch(n=>{console.warn("[mini-app-template] MAX impact haptic failed:",n)})}vibrateNotification(e){let t=P();if(!t?.HapticFeedback?.notificationOccurred){super.vibrateNotification(e);return}t.HapticFeedback.notificationOccurred(e).catch(n=>{console.warn("[mini-app-template] MAX notification haptic failed:",n)})}vibrateSelection(){let e=P();if(!e?.HapticFeedback?.selectionChanged){super.vibrateSelection();return}e.HapticFeedback.selectionChanged().catch(t=>{console.warn("[mini-app-template] MAX selection haptic failed:",t)})}async scanQRCode(e){let t=P();if(!t?.openCodeReader)return super.scanQRCode(e);try{return(await t.openCodeReader(e?.closeOnCapture!==!1))?.value??null}catch(n){return console.warn("[mini-app-template] MAX QR scanner failed:",n),null}}async requestPhone(){let e=P();if(e?.requestPhoneNumber)try{let t=await e.requestPhoneNumber();return this.extractPhone(t)}catch(t){return console.warn("[mini-app-template] MAX requestPhone failed:",t),null}return this.requestPhoneViaEvent()}async showPopup(e){return super.showPopup(e)}async downloadFile(e,t){let n=P();if(n?.downloadFile)try{await n.downloadFile(e,t);return}catch(i){console.warn("[mini-app-template] MAX downloadFile failed:",i)}await super.downloadFile(e,t)}async requestPhoneViaEvent(){if(typeof window>"u")return null;let e,t={providePromise:n=>{e=n}};if(window.dispatchEvent(new CustomEvent("WebAppRequestPhone",{detail:t})),!e)return console.warn("[mini-app-template] MAX requestPhone not handled: native promise missing"),null;try{let n=await e;return this.extractPhone(n)}catch(n){return console.warn("[mini-app-template] MAX requestPhone promise rejected:",n),null}}extractPhone(e){if(typeof e=="string")return e||null;if(!e||typeof e!="object")return null;let t=e.phone??e.phone_number??e.phoneNumber;if(typeof t=="string"&&t)return t;let n=e.contact;if(n&&typeof n=="object"){let i=n.phone??n.phone_number??n.phoneNumber;if(typeof i=="string"&&i)return i}return null}onDestroy(){this.backHandlers.clear(),super.onDestroy()}};var R=class extends A{constructor(r){super(r,{isWebView:!0,hasNativeQR:!0,hasPush:!0,hasWidgets:!0})}supports(r){switch(r){case"qrScanner":return!0;case"notifications":return!0;default:return super.supports(r)}}async scanQRCode(){try{return await this.shell.openNativeQR()??null}catch(r){return console.warn("[tvm-app-adapter] shell.openNativeQR failed:",r),null}}async requestNotificationsPermission(){return ne()}};var s=require("@tma.js/sdk-react"),c=require("@tma.js/sdk");function V(o){if(typeof o!="function")return!1;let r=o;if(typeof r.isAvailable=="function")try{return r.isAvailable()}catch(e){return console.warn("[tvm-app-adapter] feature availability check failed:",e),!1}return!0}function M(o,...r){if(!V(o))return{ok:!1};try{return{ok:!0,value:o(...r)}}catch(e){return console.warn("[tvm-app-adapter] feature call failed:",e),{ok:!1}}}async function re(o){let{sdkViewport:r,fallbackMount:e}=o;if(r?.isSupported?.()){if(typeof r.isMounted=="function"&&r.isMounted())return;typeof r.mount=="function"&&await r.mount();return}typeof e=="function"&&await e()}async function qe(o){if(await re(o),typeof o.bindCssVars=="function")try{o.bindCssVars(o.mapper)}catch(r){if(r instanceof Error&&/css variables are already bound/i.test(r.message))return;throw r}}var F=class extends A{constructor(){super("telegram");f(this,"backHandlers",new Map);f(this,"cssVariablesBound",!1);f(this,"appearanceListeners",new Set);f(this,"appearanceWatcherDispose");f(this,"viewHideListeners",new Set);f(this,"viewRestoreListeners",new Set);f(this,"activeWatcherDispose")}async init(e){if(this.ready)return;let t=!!e?.debug,n=!!e?.eruda,i=!!e?.mockForMacOS;if((0,s.setDebug)(t),(0,s.init)(),s.miniApp.isSupported()||console.warn("[tvm-app-adapter] miniApp feature is not supported; falling back to limited mode."),n&&typeof window<"u"&&window.eruda&&(window.eruda.init(),window.eruda.position({x:window.innerWidth-150,y:window.innerHeight-150})),i){let a=!1;(0,s.mockTelegramEnv)({onEvent(u,y){if(u.name==="web_app_request_theme"){let h={};return a?h=s.themeParams.state():(a=!0,h||(h=(0,s.retrieveLaunchParams)().tgWebAppThemeParams)),(0,s.emitEvent)("theme_changed",{theme_params:h})}if(u.name==="web_app_request_safe_area")return(0,s.emitEvent)("safe_area_changed",{left:0,top:0,right:0,bottom:0});y()}})}s.initData.restore(),s.miniApp.ready();let p=(0,s.retrieveLaunchParams)(),d;try{d=s.miniApp.isDark()?"dark":"light"}catch{d=void 0}let l={platform:"telegram",sdkVersion:p.tgWebAppVersion,languageCode:s.initData.user()?.language_code,appearance:d,isWebView:!0};this.environment=l,this.notifyAppearance(l.appearance),s.backButton.mount.ifAvailable(),s.miniApp.mount.isAvailable()&&(s.themeParams.mount(),s.miniApp.mount(),this.bindCssVariables()),await this.prepareViewport(),this.setupAppearanceWatcher(),this.setupActiveWatcher(),this.ready=!0}async setColors(e){let t={};if(e.header)if(s.miniApp.setHeaderColor.isAvailable()){let n=s.miniApp.setHeaderColor.supports?.("rgb")?e.header:"bg_color",{ok:i}=M(s.miniApp.setHeaderColor,n);i||(t.header=e.header)}else t.header=e.header;if(e.background)if(s.miniApp.setBgColor.isAvailable()){let{ok:n}=M(s.miniApp.setBgColor,e.background);n||(t.background=e.background)}else t.background=e.background;if(e.footer)if(s.miniApp.setBgColor.isAvailable()){let{ok:n}=M(s.miniApp.setBottomBarColorFp,e.footer);n||(t.footer=e.footer)}else t.footer=e.footer;(t.header||t.background)&&await super.setColors(t)}copyTextToClipboard(e){return(0,c.copyTextToClipboard)(e)}onBackButton(e){if(!s.backButton.isSupported())return super.onBackButton(e);let t=s.backButton.onClick(()=>e()),n=this.registerDisposable(()=>{typeof t=="function"&&t(),this.backHandlers.delete(e),this.backHandlers.size||s.backButton.hide()});return this.backHandlers.set(e,n),n}async openExternalLink(e){try{(0,s.openLink)(e,{tryInstantView:!0});return}catch{}await super.openExternalLink(e)}async openInternalLink(e){(0,s.postEvent)("web_app_open_tg_link",{path_full:e})}enableDebug(e){try{e?c.closingBehavior.enableConfirmation():c.closingBehavior.disableConfirmation()}catch{}}supports(e){switch(e){case"haptics":return V(s.hapticFeedback.selectionChanged);case"popup":return V(s.popup.show);case"qrScanner":return V(s.qrScanner.open);case"closeApp":return V(s.miniApp.close);case"backButton":return s.backButton.isSupported();case"backButtonVisibility":return s.backButton.hide.isSupported();case"bindCssVariables":return!0;case"openExternalLink":return V(s.openLink);case"openInternalLink":return!0;case"requestFullscreen":return!!(typeof c.viewport.requestFullscreen=="function"||s.viewport.requestFullscreen?.isAvailable?.());case"verticalSwipes":return!!(c.swipeBehavior.enableVertical.isAvailable()||c.swipeBehavior.disableVertical.isAvailable());case"viewVisibility":return!0;case"shareUrl":return typeof c.shareURL=="function";case"shareStory":return typeof c.shareStory=="function";case"copyTextToClipboard":return typeof c.copyTextToClipboard=="function";case"downloadFile":return typeof c.downloadFile=="function";case"addToHomeScreen":return typeof c.addToHomeScreen?.isAvailable=="function"?c.addToHomeScreen.isAvailable():typeof c.addToHomeScreen=="function";case"checkHomeScreenStatus":return typeof c.checkHomeScreenStatus=="function";case"requestPhone":return!!(V(c.requestPhoneAccess)||V(c.requestContact));default:return!1}}bindCssVariables(e){if(!this.cssVariablesBound)try{s.themeParams.bindCssVars(e),this.cssVariablesBound=!0}catch(t){if(t instanceof Error&&/css variables are already bound/i.test(t.message)){this.cssVariablesBound=!0;return}throw t}}vibrateImpact(e){this.supports("haptics")&&s.hapticFeedback.impactOccurred(e)}vibrateNotification(e){this.supports("haptics")&&s.hapticFeedback.notificationOccurred(e)}vibrateSelection(){this.supports("haptics")&&s.hapticFeedback.selectionChanged()}async showPopup(e){let t=M(s.popup.show,{title:e.title,message:e.message,buttons:e.buttons?.map(i=>({id:i.id,text:i.text??i.id,type:i.type??"default"}))});return t.ok?await t.value??null:super.showPopup(e)}async scanQRCode(e){let t=null,n=e?.closeOnCapture??!0,i=M(s.qrScanner.open,{onCaptured:p=>{t=p,n&&M(s.qrScanner.close)}});return i.ok?(await i.value,t):super.scanQRCode(e)}async closeApp(){M(s.miniApp.close).ok||await super.closeApp()}getInitData(){try{return s.initData.raw()}catch{return}}getLaunchParams(){let e=this.readCustomUrlParams(n=>n.toLowerCase().startsWith("tgwebapp")),t={};try{let n=(0,s.retrieveLaunchParams)(),i=n.tgWebAppStartParam;return typeof i=="string"&&i&&(t=this.normalizeDecodedStartParam(i)),{launchParams:n,customLaunchParams:{...e,...t}}}catch{return{customLaunchParams:{...e,...t}}}}decodeStartParam(e){try{return(0,c.decodeStartParam)(e)}catch{return}}requestFullscreen(){this.requestFullscreenInternal()}getViewportInsets(){try{let e=s.viewport.safeAreaInsets(),t=s.viewport.contentSafeAreaInsets();return{safeArea:e,contentSafeArea:t}}catch{return}}onViewportChange(e){let t=[],n=()=>typeof window<"u"?window.visualViewport?.height??window.innerHeight:0,i=l=>{let a=l?.height??this.safeHeightFromSdk(),u=l?.stableHeight??this.stableHeightFromSdk(),y=Number.isFinite(a)?a:n(),h=Number.isFinite(u)&&u>0?u:y;e({height:y,stableHeight:h})};(async()=>{try{await re(this.getViewportMountOptions())}catch(l){console.warn("[tvm-app-adapter] ensureViewportMounted failed:",l)}})().finally(()=>i());let{sdkViewport:d}=this.getViewportMountOptions();if(typeof d.on=="function")try{let l=d.on("change",a=>i(a));typeof l=="function"&&t.push(l)}catch(l){console.warn("[tvm-app-adapter] viewport.on(change) subscription failed:",l)}try{typeof d.height?.sub=="function"&&t.push(d.height.sub(()=>i())),typeof d.stableHeight?.sub=="function"&&t.push(d.stableHeight.sub(()=>i()))}catch(l){console.warn("[tvm-app-adapter] viewport signal subscriptions failed:",l)}if(typeof window<"u"){let l=()=>i();window.visualViewport?.addEventListener("resize",l),window.addEventListener("resize",l),t.push(()=>{window.visualViewport?.removeEventListener("resize",l),window.removeEventListener("resize",l)})}return()=>{t.forEach(l=>{try{l()}catch{}})}}onAppearanceChange(e){return this.appearanceListeners.add(e),e(this.environment.appearance),()=>{this.appearanceListeners.delete(e)}}setBackButtonVisibility(e){s.backButton.isSupported()&&(e?s.backButton.show():s.backButton.hide())}enableVerticalSwipes(){try{let e=c.swipeBehavior;typeof e.isSupported=="function"&&e.isSupported()?(typeof e.isMounted=="function"&&!e.isMounted()&&e.mount?.(),e.enableVertical?.()):c.swipeBehavior.enableVertical.isAvailable()&&c.swipeBehavior.enableVertical()}catch(e){console.warn("[tvm-app-adapter] enableVerticalSwipes failed:",e)}}disableVerticalSwipes(){try{let e=c.swipeBehavior;typeof e.isSupported=="function"&&e.isSupported()?(typeof e.isMounted=="function"&&!e.isMounted()&&e.mount?.(),e.disableVertical?.()):c.swipeBehavior.disableVertical.isAvailable()&&c.swipeBehavior.disableVertical()}catch(e){console.warn("[tvm-app-adapter] disableVerticalSwipes failed:",e)}}onViewHide(e){return this.viewHideListeners.add(e),()=>{this.viewHideListeners.delete(e)}}onViewRestore(e){return this.viewRestoreListeners.add(e),()=>{this.viewRestoreListeners.delete(e)}}shareUrl(e,t){return(0,c.shareURL)(e,t)}async downloadFile(e,t){let n=M(c.downloadFile,e,t);if(n.ok)try{await n.value;return}catch(i){console.warn("[tvm-app-adapter] Telegram downloadFile failed:",i)}await super.downloadFile(e,t)}async shareStory(e,t){let n=t?.telegram?.text??t?.text,i=t?.telegram?.widgetLink??(t?.link?{url:t.link.url,...t.link.name?{name:t.link.name}:{}}:void 0);(0,c.shareStory)(e,{...n?{text:n}:{},...i?{widgetLink:i}:{}})}async addToHomeScreen(){return(typeof c.addToHomeScreen?.isAvailable=="function"?c.addToHomeScreen.isAvailable():!0)?new Promise(t=>{let n=()=>{(0,c.off)("home_screen_added",i),(0,c.off)("home_screen_failed",p)},i=()=>{n(),t(!0)},p=()=>{n(),t(!1)};(0,c.on)("home_screen_added",i),(0,c.on)("home_screen_failed",p);try{(0,c.addToHomeScreen)()}catch(d){n(),console.warn("[tvm-app-adapter] Telegram addToHomeScreen failed:",d),t(!1)}}):super.addToHomeScreen()}async checkHomeScreenStatus(){try{let e=await(0,c.checkHomeScreenStatus)();return typeof e=="string"?e:typeof e=="boolean"?e?"added":"not_added":"unknown"}catch(e){return console.warn("[tvm-app-adapter] Telegram checkHomeScreenStatus failed:",e),"unknown"}}async requestPhone(){let e=M(c.requestContact);if(!e.ok)return super.requestPhone();if(c.requestPhoneAccess){let t=M(c.requestPhoneAccess);if(t.ok)try{await t.value}catch(n){console.warn("[tvm-app-adapter] Telegram requestPhone access failed:",n)}}try{let t=await e.value;if(!t||typeof t!="object")return null;let n=t.contact,i=n?.phoneNumber??n?.phone_number??n?.phone??t.phoneNumber??t.phone_number??t.phone;return typeof i=="string"&&i?i:null}catch(t){return console.warn("[tvm-app-adapter] Telegram requestPhone failed:",t),null}}setupAppearanceWatcher(){if(this.appearanceWatcherDispose?.(),typeof s.themeParams.isDark?.sub=="function"){let e=s.themeParams.isDark.sub(()=>{let t=s.themeParams.isDark()?"dark":"light";this.environment.appearance=t,this.notifyAppearance(t)});this.appearanceWatcherDispose=this.registerDisposable(e)}}notifyAppearance(e){for(let t of this.appearanceListeners)t(e)}setupActiveWatcher(){this.activeWatcherDispose?.();let e=s.miniApp.isActive,t=()=>{try{s.miniApp.isActive()?this.notifyViewRestore():this.notifyViewHide()}catch(n){console.warn("[tvm-app-adapter] miniApp.isActive() failed:",n)}};if(typeof e?.sub=="function"){let n=e.sub(()=>t());this.activeWatcherDispose=this.registerDisposable(n),t();return}try{t()}catch{}}async prepareViewport(){try{await qe({...this.getViewportMountOptions(),bindCssVars:typeof s.viewport.bindCssVars=="function"?s.viewport.bindCssVars:void 0})}catch(e){console.warn("[tvm-app-adapter] prepareViewport failed:",e)}}async requestFullscreenInternal(){try{let e=this.getViewportMountOptions();await re(e);let{sdkViewport:t}=e;(typeof t.isSupported=="function"?t.isSupported():!1)&&typeof t.requestFullscreen=="function"?await t.requestFullscreen():s.viewport.requestFullscreen&&s.viewport.requestFullscreen.isAvailable?.()?await s.viewport.requestFullscreen():(0,s.postEvent)("web_app_request_fullscreen"),this.disableVerticalSwipes()}catch(e){console.warn("[tvm-app-adapter] Telegram requestFullscreen failed:",e)}}getViewportMountOptions(){return{sdkViewport:c.viewport,fallbackMount:async()=>{s.viewport.mount?.isAvailable?.()&&await s.viewport.mount()}}}safeHeightFromSdk(){try{if(typeof c.viewport.height=="function")return c.viewport.height()}catch{return}}stableHeightFromSdk(){try{if(typeof c.viewport.stableHeight=="function")return c.viewport.stableHeight()}catch{return}}notifyViewHide(){for(let e of this.viewHideListeners)try{e()}catch(t){console.warn("[tvm-app-adapter] onViewHide listener failed:",t)}}normalizeDecodedStartParam(e){let t;try{t=(0,c.decodeStartParam)(e)}catch{t=e}if(t&&typeof t=="object"&&!Array.isArray(t))return{...t};if(typeof t=="string"&&t){let n=this.parseQueryString(t);return Object.keys(n).length?n:{startParam:t}}return{}}parseQueryString(e){let t=e.startsWith("?")?e.slice(1):e,n=new URLSearchParams(t),i={},p=new Set;for(let[d]of n.entries())p.add(d);for(let d of p){let l=n.getAll(d);l.length&&(i[d]=l.length===1?l[0]:l)}return i}notifyViewRestore(){for(let e of this.viewRestoreListeners)try{e()}catch(t){console.warn("[tvm-app-adapter] onViewRestore listener failed:",t)}}onDestroy(){this.appearanceWatcherDispose?.(),this.appearanceWatcherDispose=void 0,this.activeWatcherDispose?.(),this.activeWatcherDispose=void 0,this.appearanceListeners.clear(),this.viewHideListeners.clear(),this.viewRestoreListeners.clear(),this.backHandlers.clear(),super.onDestroy()}};var m=le(require("@vkontakte/vk-bridge"),1);var ke=null;function ie(o){if(typeof o!="string"){ke=null;return}ke=o.trim()||null}function Pe(){return ke}async function Ke(o,r){if(typeof r!="function")return!1;try{return await r(o)}catch(e){return console.warn("[tvm-app-adapter] bridge.supportsAsync failed:",e),!1}}var Mt=/^[a-z0-9][a-z0-9_.:-]{0,63}$/i,ze="VK_ANALYTICS_EVENT",I=class extends A{constructor(){super("vk");f(this,"configSafeArea");f(this,"stopViewportTracking");f(this,"supportsAsync",typeof m.default.supportsAsync=="function"?m.default.supportsAsync.bind(m.default):void 0);f(this,"pixelCodeWarningShown",!1);f(this,"unsubscribe");f(this,"launchParams");f(this,"queryParams");f(this,"viewHideListeners",new Set);f(this,"viewRestoreListeners",new Set)}computeSafeArea(){let e=this.computeBaseSafeArea(),t=this.resolveOverlayInsets();return t?j({environment:e,minimum:t}):e}async init(e){if(this.ready)return;let t=a=>this.handleBridgeEvent(a);m.default.subscribe(t),this.unsubscribe=this.registerDisposable(()=>m.default.unsubscribe(t));let n;try{n=await m.default.send("VKWebAppGetConfig")}catch(a){console.warn("[tvm-app-adapter] VKWebAppGetConfig failed:",a)}try{let a=await m.default.send("VKWebAppInit");a&&"result"in a&&a.result===!1&&console.warn("[tvm-app-adapter] VKWebAppInit returned result=false.")}catch(a){throw console.error("[tvm-app-adapter] VKWebAppInit failed:",a),this.unsubscribe?.(),this.unsubscribe=void 0,a}let i;try{i=await m.default.send("VKWebAppGetLaunchParams")}catch(a){throw console.error("[tvm-app-adapter] VKWebAppGetLaunchParams failed:",a),this.unsubscribe?.(),this.unsubscribe=void 0,a}let p=typeof window<"u"?window.location.search:"",d=(0,m.parseURLSearchParamsForGetLaunchParams)(p);this.launchParams=i,this.queryParams=d,this.environment=this.composeEnvironment(i,d,n),this.configSafeArea=this.environment.safeArea;let l=this.computeSafeArea();this.environment.safeArea=l,this.applyAppearance(this.environment.appearance,n?.scheme),this.notifyEnvironmentChanged(),this.ready=!0,this.startViewportTracking()}async vibrateImpact(e){await this.supportsBridgeMethod("VKWebAppTapticImpactOccurred")&&m.default.send("VKWebAppTapticImpactOccurred",{style:e})}async vibrateNotification(e){await this.supportsBridgeMethod("VKWebAppTapticNotificationOccurred")&&m.default.send("VKWebAppTapticNotificationOccurred",{type:e})}async vibrateSelection(){await this.supportsBridgeMethod("VKWebAppTapticSelectionChanged")&&m.default.send("VKWebAppTapticSelectionChanged")}async setColors(e){let{header:t,background:n}=e;if((t||n)&&await this.supportsBridgeMethod("VKWebAppSetViewSettings")){let p=t?this.resolveStatusBarStyle(t):this.environment.appearance?.includes("dark")?"light":"dark";await m.default.send("VKWebAppSetViewSettings",{status_bar_style:p,...t?{action_bar_color:t}:{},...n?{navigation_bar_color:n}:{}})}await super.setColors(e)}getEnvironment(){return{...this.environment,isWebView:m.default.isWebView()}}getLaunchParams(){return this.launchParams?{launchParams:this.launchParams,customLaunchParams:this.readCustomUrlParams(e=>{let t=e.toLowerCase();return t.startsWith("vk_")||t==="sign"})}:{customLaunchParams:this.readCustomUrlParams(e=>{let t=e.toLowerCase();return t.startsWith("vk_")||t==="sign"})}}async openExternalLink(e){let t=document.createElement("a");t.href=e,t.target="_blank",t.rel="noopener noreferrer",t.style.display="none",document.body.appendChild(t),t.click(),t.remove()}async supports(e){switch(e){case"haptics":{let[t,n,i]=await Promise.all([this.supportsBridgeMethod("VKWebAppTapticImpactOccurred"),this.supportsBridgeMethod("VKWebAppTapticNotificationOccurred"),this.supportsBridgeMethod("VKWebAppTapticSelectionChanged")]);return t||n||i}case"qrScanner":return this.supportsBridgeMethod("VKWebAppOpenCodeReader");case"requestPhone":{let[t,n]=await Promise.all([this.supportsBridgeMethod("VKWebAppGetPhoneNumber"),this.supportsBridgeMethod("VKWebAppGetPersonalCard")]);return t||n}case"notifications":return this.supportsBridgeMethod("VKWebAppAllowNotifications");case"shareUrl":return this.supportsBridgeMethod("VKWebAppShare");case"shareStory":return this.supportsBridgeMethod("VKWebAppShowStoryBox");case"downloadFile":return this.supportsBridgeMethod("VKWebAppDownloadFile");case"addToHomeScreen":return this.supportsBridgeMethod("VKWebAppAddToHomeScreen");case"denyNotifications":return this.supportsBridgeMethod("VKWebAppDenyNotifications");case"openExternalLink":return!0;case"viewVisibility":return!0;default:return await super.supports(e)}}async requestPhone(){let[e,t]=await Promise.all([this.supportsBridgeMethod("VKWebAppGetPhoneNumber"),this.supportsBridgeMethod("VKWebAppGetPersonalCard")]);if(!e&&!t)return super.requestPhone();try{if(e){let d=(await m.default.send("VKWebAppGetPhoneNumber")).phone_number;return typeof d=="string"&&d?d:null}let i=(await m.default.send("VKWebAppGetPersonalCard",{type:["phone"]})).phone;return typeof i=="string"&&i?i:null}catch(n){return console.warn("[tvm-app-adapter] VK requestPhone failed:",n),null}}async requestNotificationsPermission(){if(!await this.supportsBridgeMethod("VKWebAppAllowNotifications"))return super.requestNotificationsPermission();try{let t=await m.default.send("VKWebAppAllowNotifications");return t&&typeof t=="object"&&"result"in t?!!t.result:!0}catch(t){return console.warn("[tvm-app-adapter] VK allow notifications failed:",t),!1}}async addToHomeScreen(){if(!await this.supportsBridgeMethod("VKWebAppAddToHomeScreen"))return console.warn("[tvm-app-adapter] VK addToHomeScreen not supported"),super.addToHomeScreen();try{let t=await m.default.send("VKWebAppAddToHomeScreen");return t&&typeof t=="object"&&"result"in t?!!t.result:!0}catch(t){return console.warn("[tvm-app-adapter] VK addToHomeScreen failed:",t),!1}}async denyNotifications(){if(!await this.supportsBridgeMethod("VKWebAppDenyNotifications"))return super.denyNotifications();try{let t=await m.default.send("VKWebAppDenyNotifications");return t&&typeof t=="object"&&"result"in t?!!t.result:!0}catch(t){return console.warn("[tvm-app-adapter] VK deny notifications failed:",t),!1}}async scanQRCode(e){if(!await this.supportsBridgeMethod("VKWebAppOpenCodeReader"))return super.scanQRCode(e);let n=null;try{let i=await m.default.send("VKWebAppOpenCodeReader");i.code_data&&(n=i.code_data)}catch(i){console.log(i)}return n}onViewHide(e){return this.viewHideListeners.add(e),()=>{this.viewHideListeners.delete(e)}}onViewRestore(e){return this.viewRestoreListeners.add(e),()=>{this.viewRestoreListeners.delete(e)}}async shareStory(e,t){let n=t,i=n?.vk,p=n?.link?{type:"url",text:"open",url:n.link.url}:void 0,d=n?.text?[{sticker_type:"native",sticker:{action_type:"text",action:{text:n.text,style:"classic",background_style:"none"},transform:{gravity:"center_bottom",translation_y:-.2}}}]:void 0,l={background_type:i?.backgroundType??"image",url:e,locked:i?.locked??!0,...i?.attachment??p?{attachment:i?.attachment??p}:{},...i?.stickers??d?{stickers:i?.stickers??d}:{}};await m.default.send("VKWebAppShowStoryBox",l)}shareUrl(e,t){this.shareUrlInternal(e,t)}async shareUrlInternal(e,t){if(!await this.supportsBridgeMethod("VKWebAppShare")){super.shareUrl(e,t??"");return}try{await m.default.send("VKWebAppShare",{link:e,...t?{text:t}:{}})}catch(i){console.warn("[tvm-app-adapter] VK shareUrl failed:",i),super.shareUrl(e,t??"")}}async downloadFile(e,t){if(!await this.supportsBridgeMethod("VKWebAppDownloadFile")){await super.downloadFile(e,t);return}try{if((await m.default.send("VKWebAppDownloadFile",{url:e,filename:t}))?.result===!1)throw new Error("VKWebAppDownloadFile returned result=false")}catch(i){console.warn("[tvm-app-adapter] VK downloadFile failed:",i),await super.downloadFile(e,t)}}trackConversionEvent(e,t){let n=this.normalizeAnalyticsEventName(e);if(!n)return;let i={method:"VKWebAppConversionHit",params:{event:n,params:this.normalizeAnalyticsPayload(t)}};this.dispatchAnalytics(i)}trackPixelEvent(e,t){let n=Pe();if(!n){this.pixelCodeWarningShown||(console.warn("[VKAnalytics] VK pixel code is not configured. Call configureVkPixel() before tracking."),this.pixelCodeWarningShown=!0);return}let i=this.normalizeAnalyticsEventName(e);if(!i)return;let p={method:"VKWebAppRetargetingPixel",params:{pixel_code:n,type:i,data:this.normalizeAnalyticsPayload(t)}};this.pixelCodeWarningShown=!1,this.dispatchAnalytics(p)}dispatchAnalytics(e){if(typeof m.default.isWebView=="function")try{if(!m.default.isWebView()){this.emitAnalyticsFallback(e);return}}catch(t){console.warn("[VKAnalytics] bridge.isWebView check failed:",t),this.emitAnalyticsFallback(e);return}this.safeBridgeSend(e.method,e.params)}emitAnalyticsFallback(e){if(typeof window>"u")return;let t={...e,timestamp:Date.now()};if(typeof window.dispatchEvent=="function"&&typeof window.CustomEvent=="function"){window.dispatchEvent(new CustomEvent(ze,{detail:t}));return}try{window.postMessage({type:ze,detail:t},"*")}catch(n){console.warn("[VKAnalytics] fallback dispatch failed",n)}}normalizeAnalyticsEventName(e){if(typeof e!="string")return null;let t=e.trim();return!t||!Mt.test(t)?(console.warn(`[VKAnalytics] Invalid event name: "${e}"`),null):t}normalizeAnalyticsPayload(e){return this.isPlainObject(e)?{...e}:{}}isPlainObject(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}async safeBridgeSend(e,t){try{if(!await this.supportsBridgeMethod(e))return;await m.default.send(e,t)}catch(n){console.warn(`[VKAnalytics] ${e} failed`,n)}}composeEnvironment(e,t,n){let i=t.vk_language??e.vk_language,p=t.vk_platform??e.vk_platform,d=t.vk_app_id??e.vk_app_id,l=typeof window<"u"&&typeof window.matchMedia=="function"?window.matchMedia("(prefers-color-scheme: dark)").matches:!1,a=this.normalizeAppearance(n?.appearance,n?.scheme)??(l?"dark":"light"),u=this.extractSafeAreaFromConfig(n);return{platform:"vk",sdkVersion:p?String(p):void 0,appVersion:typeof d=="number"?`vk-app-${d}`:void 0,languageCode:i?String(i):void 0,appearance:a,isWebView:m.default.isWebView(),safeArea:u}}handleBridgeEvent(e){let{type:t,data:n}=e.detail??{};if(t==="VKWebAppViewHide"){this.notifyVisibilityListeners(this.viewHideListeners);return}if(t==="VKWebAppViewRestore"){this.notifyVisibilityListeners(this.viewRestoreListeners);return}if(t==="VKWebAppUpdateConfig"&&n){let i=n;this.updateEnvironmentFromConfig(i)}}updateEnvironmentFromConfig(e){if(!this.environment)return;let t=this.normalizeAppearance(e.appearance,e.scheme),n=!1;t&&t!==this.environment.appearance&&(this.environment.appearance=t,n=!0);let i=this.environment.safeArea,p=this.extractSafeAreaFromConfig(e);p?(this.configSafeArea=p,this.environment.safeArea=p):(this.configSafeArea=void 0,this.environment.safeArea=void 0);let d=this.computeSafeArea()??{top:0,right:0,bottom:0,left:0},l=i;!l||l.top!==d.top||l.right!==d.right||l.bottom!==d.bottom||l.left!==d.left?(this.environment.safeArea=d,n=!0):this.environment.safeArea=i,this.applyAppearance(this.environment.appearance,e.scheme),n&&this.notifyEnvironmentChanged()}applyAppearance(e,t){if(!(typeof document>"u")&&(e&&(document.documentElement.dataset.vkAppearance=e,document.documentElement.classList.toggle("dark",e==="dark")),t&&(document.documentElement.dataset.vkScheme=t,!e))){let n=this.normalizeAppearance(void 0,t);document.documentElement.classList.toggle("dark",n==="dark")}}resolveStatusBarStyle(e){let t=e.replace("#",""),n=t.length===3?t.split("").map(a=>a+a).join(""):t.slice(0,6),i=parseInt(n.slice(0,2),16)/255,p=parseInt(n.slice(2,4),16)/255,d=parseInt(n.slice(4,6),16)/255;return .2126*i+.7152*p+.0722*d>.6?"dark":"light"}normalizeAppearance(e,t){let n=e?.toLowerCase();if(n==="dark"||n==="light")return n;let i=t?.toLowerCase();if(i)return i.includes("dark")||i.includes("space_gray")?"dark":"light"}extractSafeAreaFromConfig(e){let t=e&&"insets"in e?e.insets:void 0;if(!t)return;let{top:n=0,right:i=0,bottom:p=0,left:d=0}=t,l=[n,i,p,d].map(v=>typeof v=="number"?v:Number(v)||0);if(!l.some(v=>v!==0))return;let[u,y,h,k]=l;return{top:u,right:y,bottom:h,left:k}}notifyVisibilityListeners(e){for(let t of e)try{t()}catch(n){console.warn("[tvm-app-adapter] VK visibility listener failed:",n)}}computeBaseSafeArea(){return j({environment:this.configSafeArea,viewport:this.getViewportInsets?.(),css:te()})}startViewportTracking(){this.stopViewportTracking?.();let e=Ie({getSafeArea:()=>this.computeSafeArea(),onChange:t=>{this.environment.safeArea=t,this.notifyEnvironmentChanged()}});e&&(this.stopViewportTracking=this.registerDisposable(e))}resolveOverlayInsets(){if(typeof window>"u"||!m.default.isWebView()||!this.isLikelyMobilePlatform())return;let e=window.innerWidth||document.documentElement?.clientWidth||0;if(!e||e>880)return;let i=!!window.matchMedia?.("(orientation: landscape)")?.matches;return{top:i?48:56,right:i?72:88}}isLikelyMobilePlatform(){let e=(this.resolveLaunchParam("vk_platform")??"").toLowerCase(),t=(this.resolveLaunchParam("vk_viewer_device")??"").toLowerCase();if(this.resolveLaunchParam("vk_is_layer")==="1")return!1;let i=/(iphone|ipad|ios|android|mobile)/i,p=/(desktop|web|tablet)/i,d=i.test(e)||i.test(t),l=p.test(e)||p.test(t);return d?!l:!1}resolveLaunchParam(e){let t=this.queryParams?.[e];if(typeof t=="string"&&t)return t;let n=this.launchParams?this.launchParams[e]:void 0;if(typeof n=="string"&&n)return n;if(typeof n=="number")return String(n);if(typeof n=="boolean")return n?"1":"0"}supportsBridgeMethod(e){return Ke(e,this.supportsAsync)}onDestroy(){this.unsubscribe?.(),this.unsubscribe=void 0,this.stopViewportTracking?.(),this.stopViewportTracking=void 0,this.viewHideListeners.clear(),this.viewRestoreListeners.clear(),super.onDestroy()}};var Ue=le(require("jsqr"),1);var W=class extends A{constructor(){super("web",{sdkVersion:navigator.userAgent,languageCode:navigator.language,isWebView:!1});f(this,"deferredPrompt",null);typeof window<"u"&&window.addEventListener("beforeinstallprompt",e=>{e.preventDefault(),this.deferredPrompt=e})}supports(e){switch(e){case"copyTextToClipboard":return typeof navigator<"u"&&!!navigator.clipboard?.writeText;case"downloadFile":return typeof document<"u";case"shareUrl":return typeof navigator<"u"&&(!!navigator.share||!!navigator.clipboard?.writeText);case"addToHomeScreen":return/android/i.test(navigator.userAgent)&&!!this.deferredPrompt;case"checkHomeScreenStatus":return!0;default:return super.supports(e)}}async downloadFile(e,t){try{await ee(e,t,{preferBlob:!0})}catch(n){console.warn("[mini-app-template] Web downloadFile fallback:",n),await super.downloadFile(e,t)}}scanQRCode(e){return new Promise(async t=>{if(typeof document>"u"){t(null);return}let n=document.body.style.overflow,i=document.body.style.position,p=document.body.style.touchAction,d=document.body.style.width,l=document.documentElement.style.overflow;document.body.style.overflow="hidden",document.body.style.position="fixed",document.body.style.width="100%",document.body.style.touchAction="none",document.documentElement.style.overflow="hidden";let a=document.createElement("div");a.id="qr-overlay",a.style.position="fixed",a.style.top="0",a.style.left="0",a.style.right="0",a.style.bottom="0",a.style.zIndex="999999999",a.style.background="rgba(0,0,0,0.92)",a.style.width="100%",a.style.height="100%",a.style.display="flex",a.style.flexDirection="column",a.style.alignItems="center",a.style.justifyContent="center",a.style.gap="20px",a.style.padding="24px",a.style.boxSizing="border-box",a.style.overflow="hidden",a.style.backdropFilter="blur(3px)",document.body.appendChild(a);let u=document.createElement("button");u.innerText="\u2715",u.style.position="absolute",u.style.top="22px",u.style.right="22px",u.style.fontSize="32px",u.style.color="white",u.style.background="transparent",u.style.border="none",u.style.cursor="pointer",u.style.zIndex="9999999999",a.appendChild(u);let y=Math.min(Math.floor(Math.min(window.innerWidth,window.innerHeight)*.72),320),h=document.createElement("div");h.style.width=`${y}px`,h.style.height=`${y}px`,h.style.position="relative",h.style.flex="0 0 auto",h.style.borderRadius="18px",h.style.overflow="hidden",a.appendChild(h);let k=document.createElement("div");k.style.position="absolute",k.style.inset="0",k.style.zIndex="1",k.style.background="#000",h.appendChild(k);let v=document.createElement("video");v.setAttribute("playsinline","true"),v.autoplay=!0,v.muted=!0,v.style.width="100%",v.style.height="100%",v.style.objectFit="cover",v.style.position="absolute",v.style.inset="0",k.appendChild(v);let g=document.createElement("div");g.style.position="absolute",g.style.top="0",g.style.left="0",g.style.right="0",g.style.bottom="0",g.style.border="3px solid rgba(255,255,255,0.9)",g.style.borderRadius="18px",g.style.pointerEvents="none",g.style.zIndex="3",h.appendChild(g);let w=document.createElement("div");w.style.position="absolute",w.style.left="0",w.style.right="0",w.style.height="2px",w.style.background="rgba(255,255,255,0.85)",w.style.borderRadius="2px",w.style.animation="qr-line 2s infinite",w.style.zIndex="4",h.appendChild(w);let ae=document.createElement("style");ae.innerHTML=`
3
+ `);return window.alert(e),n.buttons?.[0]?.id??"ok"}async scanQRCode(n){return null}async requestPhone(){return null}async requestNotificationsPermission(){if(typeof Notification>"u"||typeof Notification.requestPermission!="function")return!1;try{return await Notification.requestPermission()==="granted"}catch(n){return console.warn("[tvm-app-adapter] requestNotificationsPermission fallback failed:",n),!1}}async addToHomeScreen(){return!1}async checkHomeScreenStatus(){return"unknown"}async denyNotifications(){return console.warn("[tvm-app-adapter] denyNotifications fallback is not supported in this environment."),!1}enableVerticalSwipes(){}disableVerticalSwipes(){}notifyEnvironmentChanged(){for(let n of this.listeners)try{n()}catch(e){console.warn("[tvm-app-adapter] environment listener failed:",e)}}onDestroy(){}registerDisposable(n){return this.disposables.add(n)}readCustomUrlParams(n){if(typeof window>"u")return{};let e={},t=o=>{let p=new Set;for(let[d]of o.entries())p.add(d);for(let d of p){if(n?.(d))continue;let l=o.getAll(d);l.length&&(e[d]=l.length===1?l[0]:l)}};t(new URLSearchParams(window.location.search));let r=window.location.hash.startsWith("#")?window.location.hash.slice(1):window.location.hash;return r&&r.includes("=")&&t(new URLSearchParams(r)),e}applyScrollGuards(){if(typeof document>"u")return;let n=document.documentElement,e=document.body;if(!n||!e)return;let t=n.style.overscrollBehaviorY,r=e.style.overscrollBehaviorY,o=e.style.touchAction;return n.style.overscrollBehaviorY="none",e.style.overscrollBehaviorY="none",e.style.touchAction="manipulation",()=>{n.style.overscrollBehaviorY=t,e.style.overscrollBehaviorY=r,e.style.touchAction=o}}};var _=class extends S{constructor(n){super(n,{isWebView:!0,hasNativeQR:!0,hasPush:!0,hasWidgets:!0})}async supports(n){switch(n){case"qrScanner":return!0;case"notifications":return!0;default:return super.supports(n)}}async scanQRCode(){try{return await this.shell.openNativeQR()??null}catch(n){return console.warn("[tvm-app-adapter] shell.openNativeQR failed:",n),null}}async requestNotificationsPermission(){return te()}};var a=require("@tma.js/sdk-react"),c=require("@tma.js/sdk");function V(i){if(typeof i!="function")return!1;let n=i;if(typeof n.isAvailable=="function")try{return n.isAvailable()}catch(e){return console.warn("[tvm-app-adapter] feature availability check failed:",e),!1}return!0}function x(i,...n){if(!V(i))return{ok:!1};try{return{ok:!0,value:i(...n)}}catch(e){return console.warn("[tvm-app-adapter] feature call failed:",e),{ok:!1}}}async function ne(i){let{sdkViewport:n,fallbackMount:e}=i;if(n?.isSupported?.()){if(typeof n.isMounted=="function"&&n.isMounted())return;typeof n.mount=="function"&&await n.mount();return}typeof e=="function"&&await e()}async function He(i){if(await ne(i),typeof i.bindCssVars=="function")try{i.bindCssVars(i.mapper)}catch(n){if(n instanceof Error&&/css variables are already bound/i.test(n.message))return;throw n}}var W=class extends S{constructor(){super("telegram");h(this,"backHandlers",new Map);h(this,"cssVariablesBound",!1);h(this,"appearanceListeners",new Set);h(this,"appearanceWatcherDispose");h(this,"viewHideListeners",new Set);h(this,"viewRestoreListeners",new Set);h(this,"activeWatcherDispose")}async init(e){if(this.ready)return;let t=!!e?.debug,r=!!e?.eruda,o=!!e?.mockForMacOS;if((0,a.setDebug)(t),(0,a.init)(),a.miniApp.isSupported()||console.warn("[tvm-app-adapter] miniApp feature is not supported; falling back to limited mode."),r&&typeof window<"u"&&window.eruda&&(window.eruda.init(),window.eruda.position({x:window.innerWidth-150,y:window.innerHeight-150})),o){let s=!1;(0,a.mockTelegramEnv)({onEvent(u,v){if(u.name==="web_app_request_theme"){let m={};return s?m=a.themeParams.state():(s=!0,m||(m=(0,a.retrieveLaunchParams)().tgWebAppThemeParams)),(0,a.emitEvent)("theme_changed",{theme_params:m})}if(u.name==="web_app_request_safe_area")return(0,a.emitEvent)("safe_area_changed",{left:0,top:0,right:0,bottom:0});v()}})}a.initData.restore(),a.miniApp.ready();let p=(0,a.retrieveLaunchParams)(),d;try{d=a.miniApp.isDark()?"dark":"light"}catch{d=void 0}let l={platform:"telegram",sdkVersion:p.tgWebAppVersion,languageCode:a.initData.user()?.language_code,appearance:d,isWebView:!0};this.environment=l,this.notifyAppearance(l.appearance),a.backButton.mount.ifAvailable(),a.miniApp.mount.isAvailable()&&(a.themeParams.mount(),a.miniApp.mount(),this.bindCssVariables()),await this.prepareViewport(),this.setupAppearanceWatcher(),this.setupActiveWatcher(),this.registerDisposable(this.onViewportChange(()=>this.notifyEnvironmentChanged())),this.ready=!0}async setColors(e){let t={};if(e.header)if(a.miniApp.setHeaderColor.isAvailable()){let r=a.miniApp.setHeaderColor.supports?.("rgb")?e.header:"bg_color",{ok:o}=x(a.miniApp.setHeaderColor,r);o||(t.header=e.header)}else t.header=e.header;if(e.background)if(a.miniApp.setBgColor.isAvailable()){let{ok:r}=x(a.miniApp.setBgColor,e.background);r||(t.background=e.background)}else t.background=e.background;if(e.footer)if(a.miniApp.setBgColor.isAvailable()){let{ok:r}=x(a.miniApp.setBottomBarColorFp,e.footer);r||(t.footer=e.footer)}else t.footer=e.footer;(t.header||t.background)&&await super.setColors(t)}copyTextToClipboard(e){return(0,c.copyTextToClipboard)(e)}onBackButton(e){if(!a.backButton.isSupported())return super.onBackButton(e);let t=a.backButton.onClick(()=>e()),r=this.registerDisposable(()=>{typeof t=="function"&&t(),this.backHandlers.delete(e),this.backHandlers.size||a.backButton.hide()});return this.backHandlers.set(e,r),r}async openExternalLink(e){try{(0,a.openLink)(e,{tryInstantView:!0});return}catch{}await super.openExternalLink(e)}async openInternalLink(e){try{(0,a.postEvent)("web_app_open_tg_link",{path_full:e});return}catch(t){console.warn("[tvm-app-adapter] Telegram openInternalLink failed:",t)}await super.openInternalLink(e)}enableDebug(e){try{e?c.closingBehavior.enableConfirmation():c.closingBehavior.disableConfirmation()}catch{}}hapticsAvailable(){return V(a.hapticFeedback.selectionChanged)}async supports(e){switch(e){case"haptics":return this.hapticsAvailable();case"popup":return V(a.popup.show);case"qrScanner":return V(a.qrScanner.open);case"closeApp":return V(a.miniApp.close);case"backButton":return a.backButton.isSupported();case"backButtonVisibility":return a.backButton.hide.isSupported();case"bindCssVariables":return!0;case"openExternalLink":return V(a.openLink);case"openInternalLink":return!0;case"requestFullscreen":return!!(typeof c.viewport.requestFullscreen=="function"||a.viewport.requestFullscreen?.isAvailable?.());case"verticalSwipes":return!!(c.swipeBehavior.enableVertical.isAvailable()||c.swipeBehavior.disableVertical.isAvailable());case"viewVisibility":return!0;case"shareUrl":return typeof c.shareURL=="function";case"shareStory":return typeof c.shareStory=="function";case"copyTextToClipboard":return typeof c.copyTextToClipboard=="function";case"downloadFile":return typeof c.downloadFile=="function";case"addToHomeScreen":return typeof c.addToHomeScreen?.isAvailable=="function"?c.addToHomeScreen.isAvailable():typeof c.addToHomeScreen=="function";case"checkHomeScreenStatus":return typeof c.checkHomeScreenStatus=="function";case"requestPhone":return V(c.requestContact);default:return!1}}bindCssVariables(e){if(!this.cssVariablesBound)try{a.themeParams.bindCssVars(e),this.cssVariablesBound=!0}catch(t){if(t instanceof Error&&/css variables are already bound/i.test(t.message)){this.cssVariablesBound=!0;return}throw t}}vibrateImpact(e){this.hapticsAvailable()&&a.hapticFeedback.impactOccurred(e)}vibrateNotification(e){this.hapticsAvailable()&&a.hapticFeedback.notificationOccurred(e)}vibrateSelection(){this.hapticsAvailable()&&a.hapticFeedback.selectionChanged()}async showPopup(e){let t=x(a.popup.show,{title:e.title,message:e.message,buttons:e.buttons?.map(o=>({id:o.id,text:o.text??o.id,type:o.type??"default"}))});return t.ok?await t.value??null:super.showPopup(e)}async scanQRCode(e){let t=null,r=e?.closeOnCapture??!0,o=x(a.qrScanner.open,{onCaptured:p=>{t=p,r&&x(a.qrScanner.close)}});return o.ok?(await o.value,t):super.scanQRCode(e)}async closeApp(){x(a.miniApp.close).ok||await super.closeApp()}getInitData(){try{return a.initData.raw()}catch{return}}getLaunchParams(){let e=this.readCustomUrlParams(r=>r.toLowerCase().startsWith("tgwebapp")),t={};try{let r=(0,a.retrieveLaunchParams)(),o=r.tgWebAppStartParam;return typeof o=="string"&&o&&(t=this.normalizeDecodedStartParam(o)),{launchParams:r,customLaunchParams:{...e,...t}}}catch{return{customLaunchParams:{...e,...t}}}}decodeStartParam(e){try{return(0,c.decodeStartParam)(e)}catch{return}}requestFullscreen(){this.requestFullscreenInternal()}getViewportInsets(){try{let e=a.viewport.safeAreaInsets(),t=a.viewport.contentSafeAreaInsets();return{safeArea:e,contentSafeArea:t}}catch{return}}onViewportChange(e){let t=[],r=()=>typeof window<"u"?window.visualViewport?.height??window.innerHeight:0,o=l=>{let s=l?.height??this.safeHeightFromSdk(),u=l?.stableHeight??this.stableHeightFromSdk(),v=Number.isFinite(s)?s:r(),m=Number.isFinite(u)&&u>0?u:v;e({height:v,stableHeight:m})};(async()=>{try{await ne(this.getViewportMountOptions())}catch(l){console.warn("[tvm-app-adapter] ensureViewportMounted failed:",l)}})().finally(()=>o());let{sdkViewport:d}=this.getViewportMountOptions();if(typeof d.on=="function")try{let l=d.on("change",s=>o(s));typeof l=="function"&&t.push(l)}catch(l){console.warn("[tvm-app-adapter] viewport.on(change) subscription failed:",l)}try{typeof d.height?.sub=="function"&&t.push(d.height.sub(()=>o())),typeof d.stableHeight?.sub=="function"&&t.push(d.stableHeight.sub(()=>o()))}catch(l){console.warn("[tvm-app-adapter] viewport signal subscriptions failed:",l)}if(typeof window<"u"){let l=()=>o();window.visualViewport?.addEventListener("resize",l),window.addEventListener("resize",l),t.push(()=>{window.visualViewport?.removeEventListener("resize",l),window.removeEventListener("resize",l)})}return()=>{t.forEach(l=>{try{l()}catch{}})}}onAppearanceChange(e){return this.appearanceListeners.add(e),e(this.environment.appearance),()=>{this.appearanceListeners.delete(e)}}setBackButtonVisibility(e){a.backButton.isSupported()&&(e?a.backButton.show():a.backButton.hide())}enableVerticalSwipes(){try{let e=c.swipeBehavior;typeof e.isSupported=="function"&&e.isSupported()?(typeof e.isMounted=="function"&&!e.isMounted()&&e.mount?.(),e.enableVertical?.()):c.swipeBehavior.enableVertical.isAvailable()&&c.swipeBehavior.enableVertical()}catch(e){console.warn("[tvm-app-adapter] enableVerticalSwipes failed:",e)}}disableVerticalSwipes(){try{let e=c.swipeBehavior;typeof e.isSupported=="function"&&e.isSupported()?(typeof e.isMounted=="function"&&!e.isMounted()&&e.mount?.(),e.disableVertical?.()):c.swipeBehavior.disableVertical.isAvailable()&&c.swipeBehavior.disableVertical()}catch(e){console.warn("[tvm-app-adapter] disableVerticalSwipes failed:",e)}}onViewHide(e){return this.viewHideListeners.add(e),()=>{this.viewHideListeners.delete(e)}}onViewRestore(e){return this.viewRestoreListeners.add(e),()=>{this.viewRestoreListeners.delete(e)}}shareUrl(e,t){return(0,c.shareURL)(e,t)}async downloadFile(e,t){let r=x(c.downloadFile,e,t);if(r.ok)try{await r.value;return}catch(o){console.warn("[tvm-app-adapter] Telegram downloadFile failed:",o)}await super.downloadFile(e,t)}async shareStory(e,t){let r=t?.telegram?.text??t?.text,o=t?.telegram?.widgetLink??(t?.link?{url:t.link.url,...t.link.name?{name:t.link.name}:{}}:void 0);(0,c.shareStory)(e,{...r?{text:r}:{},...o?{widgetLink:o}:{}})}async addToHomeScreen(){return(typeof c.addToHomeScreen?.isAvailable=="function"?c.addToHomeScreen.isAvailable():!0)?new Promise(t=>{let r=()=>{(0,c.off)("home_screen_added",o),(0,c.off)("home_screen_failed",p)},o=()=>{r(),t(!0)},p=()=>{r(),t(!1)};(0,c.on)("home_screen_added",o),(0,c.on)("home_screen_failed",p);try{(0,c.addToHomeScreen)()}catch(d){r(),console.warn("[tvm-app-adapter] Telegram addToHomeScreen failed:",d),t(!1)}}):super.addToHomeScreen()}async checkHomeScreenStatus(){try{let e=await(0,c.checkHomeScreenStatus)();return typeof e=="string"?e:typeof e=="boolean"?e?"added":"not_added":"unknown"}catch(e){return console.warn("[tvm-app-adapter] Telegram checkHomeScreenStatus failed:",e),"unknown"}}async requestPhone(){if(!V(c.requestContact))return super.requestPhone();try{let e=await(0,c.requestContact)();if(!e||typeof e!="object")return null;let t=e.contact,r=t?.phoneNumber??t?.phone_number??t?.phone??e.phoneNumber??e.phone_number??e.phone;return typeof r=="string"&&r?r:null}catch(e){return console.warn("[tvm-app-adapter] Telegram requestPhone failed:",e),null}}setupAppearanceWatcher(){if(this.appearanceWatcherDispose?.(),typeof a.themeParams.isDark?.sub=="function"){let e=a.themeParams.isDark.sub(()=>{let t=a.themeParams.isDark()?"dark":"light";this.environment.appearance=t,this.notifyAppearance(t)});this.appearanceWatcherDispose=this.registerDisposable(e)}}notifyAppearance(e){for(let t of this.appearanceListeners)t(e)}setupActiveWatcher(){this.activeWatcherDispose?.();let e=a.miniApp.isActive,t=()=>{try{a.miniApp.isActive()?this.notifyViewRestore():this.notifyViewHide()}catch(r){console.warn("[tvm-app-adapter] miniApp.isActive() failed:",r)}};if(typeof e?.sub=="function"){let r=e.sub(()=>t());this.activeWatcherDispose=this.registerDisposable(r),t();return}try{t()}catch{}}async prepareViewport(){try{await He({...this.getViewportMountOptions(),bindCssVars:typeof a.viewport.bindCssVars=="function"?a.viewport.bindCssVars:void 0})}catch(e){console.warn("[tvm-app-adapter] prepareViewport failed:",e)}}async requestFullscreenInternal(){try{let e=this.getViewportMountOptions();await ne(e);let{sdkViewport:t}=e;(typeof t.isSupported=="function"?t.isSupported():!1)&&typeof t.requestFullscreen=="function"?await t.requestFullscreen():a.viewport.requestFullscreen&&a.viewport.requestFullscreen.isAvailable?.()?await a.viewport.requestFullscreen():(0,a.postEvent)("web_app_request_fullscreen"),this.disableVerticalSwipes()}catch(e){console.warn("[tvm-app-adapter] Telegram requestFullscreen failed:",e)}}getViewportMountOptions(){return{sdkViewport:c.viewport,fallbackMount:async()=>{a.viewport.mount?.isAvailable?.()&&await a.viewport.mount()}}}safeHeightFromSdk(){try{if(typeof c.viewport.height=="function")return c.viewport.height()}catch{return}}stableHeightFromSdk(){try{if(typeof c.viewport.stableHeight=="function")return c.viewport.stableHeight()}catch{return}}notifyViewHide(){for(let e of this.viewHideListeners)try{e()}catch(t){console.warn("[tvm-app-adapter] onViewHide listener failed:",t)}}normalizeDecodedStartParam(e){let t;try{t=(0,c.decodeStartParam)(e)}catch{t=e}if(t&&typeof t=="object"&&!Array.isArray(t))return{...t};if(typeof t=="string"&&t){let r=this.parseQueryString(t);return Object.keys(r).length?r:{startParam:t}}return{}}parseQueryString(e){let t=e.startsWith("?")?e.slice(1):e,r=new URLSearchParams(t),o={},p=new Set;for(let[d]of r.entries())p.add(d);for(let d of p){let l=r.getAll(d);l.length&&(o[d]=l.length===1?l[0]:l)}return o}notifyViewRestore(){for(let e of this.viewRestoreListeners)try{e()}catch(t){console.warn("[tvm-app-adapter] onViewRestore listener failed:",t)}}onDestroy(){this.appearanceWatcherDispose?.(),this.appearanceWatcherDispose=void 0,this.activeWatcherDispose?.(),this.activeWatcherDispose=void 0,this.appearanceListeners.clear(),this.viewHideListeners.clear(),this.viewRestoreListeners.clear(),this.backHandlers.clear(),super.onDestroy()}};var f=se(require("@vkontakte/vk-bridge"),1);var we=null;function re(i){if(typeof i!="string"){we=null;return}we=i.trim()||null}function be(){return we}async function Ne(i,n){if(typeof n!="function")return!1;try{return await n(i)}catch(e){return console.warn("[tvm-app-adapter] bridge.supportsAsync failed:",e),!1}}var St=/^[a-z0-9][a-z0-9_.:-]{0,63}$/i,De="VK_ANALYTICS_EVENT",I=class extends S{constructor(){super("vk");h(this,"configSafeArea");h(this,"stopViewportTracking");h(this,"supportsAsync",typeof f.default.supportsAsync=="function"?f.default.supportsAsync.bind(f.default):void 0);h(this,"pixelCodeWarningShown",!1);h(this,"unsubscribe");h(this,"launchParams");h(this,"queryParams");h(this,"viewHideListeners",new Set);h(this,"viewRestoreListeners",new Set)}computeSafeArea(){let e=this.computeBaseSafeArea(),t=this.resolveOverlayInsets();return t?U({environment:e,minimum:t}):e}async init(e){if(this.ready)return;let t=s=>this.handleBridgeEvent(s);f.default.subscribe(t),this.unsubscribe=this.registerDisposable(()=>f.default.unsubscribe(t));let r;try{r=await f.default.send("VKWebAppGetConfig")}catch(s){console.warn("[tvm-app-adapter] VKWebAppGetConfig failed:",s)}try{let s=await f.default.send("VKWebAppInit");s&&"result"in s&&s.result===!1&&console.warn("[tvm-app-adapter] VKWebAppInit returned result=false.")}catch(s){console.warn("[tvm-app-adapter] VKWebAppInit failed:",s)}let o;try{o=await f.default.send("VKWebAppGetLaunchParams")}catch(s){console.warn("[tvm-app-adapter] VKWebAppGetLaunchParams failed; falling back to URL params:",s)}let p=typeof window<"u"?window.location.search:"",d=(0,f.parseURLSearchParamsForGetLaunchParams)(p);this.launchParams=o,this.queryParams=d,this.environment=this.composeEnvironment(o,d,r),this.configSafeArea=this.environment.safeArea;let l=this.computeSafeArea();this.environment.safeArea=l,this.applyAppearance(this.environment.appearance,r?.scheme),this.notifyEnvironmentChanged(),this.ready=!0,this.startViewportTracking()}async vibrateImpact(e){await this.supportsBridgeMethod("VKWebAppTapticImpactOccurred")&&f.default.send("VKWebAppTapticImpactOccurred",{style:e})}async vibrateNotification(e){await this.supportsBridgeMethod("VKWebAppTapticNotificationOccurred")&&f.default.send("VKWebAppTapticNotificationOccurred",{type:e})}async vibrateSelection(){await this.supportsBridgeMethod("VKWebAppTapticSelectionChanged")&&f.default.send("VKWebAppTapticSelectionChanged")}async setColors(e){let{header:t,background:r}=e;if((t||r)&&await this.supportsBridgeMethod("VKWebAppSetViewSettings")){let p=t?this.resolveStatusBarStyle(t):this.environment.appearance?.includes("dark")?"light":"dark";await f.default.send("VKWebAppSetViewSettings",{status_bar_style:p,...t?{action_bar_color:t}:{},...r?{navigation_bar_color:r}:{}})}await super.setColors(e)}getEnvironment(){return{...this.environment,isWebView:f.default.isWebView()}}getLaunchParams(){return this.launchParams?{launchParams:this.launchParams,customLaunchParams:this.readCustomUrlParams(e=>{let t=e.toLowerCase();return t.startsWith("vk_")||t==="sign"})}:{customLaunchParams:this.readCustomUrlParams(e=>{let t=e.toLowerCase();return t.startsWith("vk_")||t==="sign"})}}async openExternalLink(e){let t=document.createElement("a");t.href=e,t.target="_blank",t.rel="noopener noreferrer",t.style.display="none",document.body.appendChild(t),t.click(),t.remove()}async closeApp(){if(!await this.supportsBridgeMethod("VKWebAppClose")){await super.closeApp();return}try{await f.default.send("VKWebAppClose",{status:"success"})}catch(t){console.warn("[tvm-app-adapter] VK closeApp failed:",t),await super.closeApp()}}async supports(e){switch(e){case"haptics":{let[t,r,o]=await Promise.all([this.supportsBridgeMethod("VKWebAppTapticImpactOccurred"),this.supportsBridgeMethod("VKWebAppTapticNotificationOccurred"),this.supportsBridgeMethod("VKWebAppTapticSelectionChanged")]);return t||r||o}case"qrScanner":return this.supportsBridgeMethod("VKWebAppOpenCodeReader");case"requestPhone":{let[t,r]=await Promise.all([this.supportsBridgeMethod("VKWebAppGetPhoneNumber"),this.supportsBridgeMethod("VKWebAppGetPersonalCard")]);return t||r}case"notifications":return this.supportsBridgeMethod("VKWebAppAllowNotifications");case"shareUrl":return this.supportsBridgeMethod("VKWebAppShare");case"shareStory":return this.supportsBridgeMethod("VKWebAppShowStoryBox");case"downloadFile":return this.supportsBridgeMethod("VKWebAppDownloadFile");case"addToHomeScreen":return this.supportsBridgeMethod("VKWebAppAddToHomeScreen");case"denyNotifications":return this.supportsBridgeMethod("VKWebAppDenyNotifications");case"closeApp":return this.supportsBridgeMethod("VKWebAppClose");case"openExternalLink":return!0;case"viewVisibility":return!0;default:return await super.supports(e)}}async requestPhone(){let[e,t]=await Promise.all([this.supportsBridgeMethod("VKWebAppGetPhoneNumber"),this.supportsBridgeMethod("VKWebAppGetPersonalCard")]);if(!e&&!t)return super.requestPhone();try{if(e){let d=(await f.default.send("VKWebAppGetPhoneNumber")).phone_number;return typeof d=="string"&&d?d:null}let o=(await f.default.send("VKWebAppGetPersonalCard",{type:["phone"]})).phone;return typeof o=="string"&&o?o:null}catch(r){return console.warn("[tvm-app-adapter] VK requestPhone failed:",r),null}}async requestNotificationsPermission(){if(!await this.supportsBridgeMethod("VKWebAppAllowNotifications"))return super.requestNotificationsPermission();try{let t=await f.default.send("VKWebAppAllowNotifications");return t&&typeof t=="object"&&"result"in t?!!t.result:!0}catch(t){return console.warn("[tvm-app-adapter] VK allow notifications failed:",t),!1}}async addToHomeScreen(){if(!await this.supportsBridgeMethod("VKWebAppAddToHomeScreen"))return console.warn("[tvm-app-adapter] VK addToHomeScreen not supported"),super.addToHomeScreen();try{let t=await f.default.send("VKWebAppAddToHomeScreen");return t&&typeof t=="object"&&"result"in t?!!t.result:!0}catch(t){return console.warn("[tvm-app-adapter] VK addToHomeScreen failed:",t),!1}}async denyNotifications(){if(!await this.supportsBridgeMethod("VKWebAppDenyNotifications"))return super.denyNotifications();try{let t=await f.default.send("VKWebAppDenyNotifications");return t&&typeof t=="object"&&"result"in t?!!t.result:!0}catch(t){return console.warn("[tvm-app-adapter] VK deny notifications failed:",t),!1}}async scanQRCode(e){if(!await this.supportsBridgeMethod("VKWebAppOpenCodeReader"))return super.scanQRCode(e);try{let r=await f.default.send("VKWebAppOpenCodeReader");return r.code_data?r.code_data:null}catch(r){return console.warn("[tvm-app-adapter] VK scanQRCode failed:",r),super.scanQRCode(e)}}onViewHide(e){return this.viewHideListeners.add(e),()=>{this.viewHideListeners.delete(e)}}onViewRestore(e){return this.viewRestoreListeners.add(e),()=>{this.viewRestoreListeners.delete(e)}}async shareStory(e,t){let r=t,o=r?.vk,p=r?.link?{type:"url",text:"open",url:r.link.url}:void 0,d=r?.text?[{sticker_type:"native",sticker:{action_type:"text",action:{text:r.text,style:"classic",background_style:"none"},transform:{gravity:"center_bottom",translation_y:-.2}}}]:void 0,l={background_type:o?.backgroundType??"image",url:e,locked:o?.locked??!0,...o?.attachment??p?{attachment:o?.attachment??p}:{},...o?.stickers??d?{stickers:o?.stickers??d}:{}};await f.default.send("VKWebAppShowStoryBox",l)}shareUrl(e,t){this.shareUrlInternal(e,t)}async shareUrlInternal(e,t){if(!await this.supportsBridgeMethod("VKWebAppShare")){super.shareUrl(e,t??"");return}try{await f.default.send("VKWebAppShare",{link:e,...t?{text:t}:{}})}catch(o){console.warn("[tvm-app-adapter] VK shareUrl failed:",o),super.shareUrl(e,t??"")}}async downloadFile(e,t){if(!await this.supportsBridgeMethod("VKWebAppDownloadFile")){await super.downloadFile(e,t);return}try{if((await f.default.send("VKWebAppDownloadFile",{url:e,filename:t}))?.result===!1)throw new Error("VKWebAppDownloadFile returned result=false")}catch(o){console.warn("[tvm-app-adapter] VK downloadFile failed:",o),await super.downloadFile(e,t)}}trackConversionEvent(e,t){let r=this.normalizeAnalyticsEventName(e);if(!r)return;let o={method:"VKWebAppConversionHit",params:{event:r,params:this.normalizeAnalyticsPayload(t)}};this.dispatchAnalytics(o)}trackPixelEvent(e,t){let r=be();if(!r){this.pixelCodeWarningShown||(console.warn("[VKAnalytics] VK pixel code is not configured. Call configureVkPixel() before tracking."),this.pixelCodeWarningShown=!0);return}let o=this.normalizeAnalyticsEventName(e);if(!o)return;let p={method:"VKWebAppRetargetingPixel",params:{pixel_code:r,type:o,data:this.normalizeAnalyticsPayload(t)}};this.pixelCodeWarningShown=!1,this.dispatchAnalytics(p)}dispatchAnalytics(e){if(typeof f.default.isWebView=="function")try{if(!f.default.isWebView()){this.emitAnalyticsFallback(e);return}}catch(t){console.warn("[VKAnalytics] bridge.isWebView check failed:",t),this.emitAnalyticsFallback(e);return}this.safeBridgeSend(e.method,e.params)}emitAnalyticsFallback(e){if(typeof window>"u")return;let t={...e,timestamp:Date.now()};if(typeof window.dispatchEvent=="function"&&typeof window.CustomEvent=="function"){window.dispatchEvent(new CustomEvent(De,{detail:t}));return}try{window.postMessage({type:De,detail:t},"*")}catch(r){console.warn("[VKAnalytics] fallback dispatch failed",r)}}normalizeAnalyticsEventName(e){if(typeof e!="string")return null;let t=e.trim();return!t||!St.test(t)?(console.warn(`[VKAnalytics] Invalid event name: "${e}"`),null):t}normalizeAnalyticsPayload(e){return this.isPlainObject(e)?{...e}:{}}isPlainObject(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}async safeBridgeSend(e,t){try{if(!await this.supportsBridgeMethod(e))return;await f.default.send(e,t)}catch(r){console.warn(`[VKAnalytics] ${e} failed`,r)}}composeEnvironment(e,t,r){let o=t.vk_language??e?.vk_language,p=t.vk_platform??e?.vk_platform,d=t.vk_app_id??e?.vk_app_id,l=typeof window<"u"&&typeof window.matchMedia=="function"?window.matchMedia("(prefers-color-scheme: dark)").matches:!1,s=this.normalizeAppearance(r?.appearance,r?.scheme)??(l?"dark":"light"),u=this.extractSafeAreaFromConfig(r);return{platform:"vk",sdkVersion:p?String(p):void 0,appVersion:typeof d=="number"?`vk-app-${d}`:void 0,languageCode:o?String(o):void 0,appearance:s,isWebView:f.default.isWebView(),safeArea:u}}handleBridgeEvent(e){let{type:t,data:r}=e.detail??{};if(t==="VKWebAppViewHide"){this.notifyVisibilityListeners(this.viewHideListeners);return}if(t==="VKWebAppViewRestore"){this.notifyVisibilityListeners(this.viewRestoreListeners);return}if(t==="VKWebAppUpdateConfig"&&r){let o=r;this.updateEnvironmentFromConfig(o)}}updateEnvironmentFromConfig(e){if(!this.environment)return;let t=this.normalizeAppearance(e.appearance,e.scheme),r=!1;t&&t!==this.environment.appearance&&(this.environment.appearance=t,r=!0);let o=this.environment.safeArea,p=this.extractSafeAreaFromConfig(e);p?(this.configSafeArea=p,this.environment.safeArea=p):(this.configSafeArea=void 0,this.environment.safeArea=void 0);let d=this.computeSafeArea()??{top:0,right:0,bottom:0,left:0},l=o;!l||l.top!==d.top||l.right!==d.right||l.bottom!==d.bottom||l.left!==d.left?(this.environment.safeArea=d,r=!0):this.environment.safeArea=o,this.applyAppearance(this.environment.appearance,e.scheme),r&&this.notifyEnvironmentChanged()}applyAppearance(e,t){if(!(typeof document>"u")&&(e&&(document.documentElement.dataset.vkAppearance=e,document.documentElement.classList.toggle("dark",e==="dark")),t&&(document.documentElement.dataset.vkScheme=t,!e))){let r=this.normalizeAppearance(void 0,t);document.documentElement.classList.toggle("dark",r==="dark")}}resolveStatusBarStyle(e){let t=e.replace("#",""),r=t.length===3?t.split("").map(s=>s+s).join(""):t.slice(0,6),o=parseInt(r.slice(0,2),16)/255,p=parseInt(r.slice(2,4),16)/255,d=parseInt(r.slice(4,6),16)/255;return .2126*o+.7152*p+.0722*d>.6?"dark":"light"}normalizeAppearance(e,t){let r=e?.toLowerCase();if(r==="dark"||r==="light")return r;let o=t?.toLowerCase();if(o)return o.includes("dark")||o.includes("space_gray")?"dark":"light"}extractSafeAreaFromConfig(e){let t=e&&"insets"in e?e.insets:void 0;if(!t)return;let{top:r=0,right:o=0,bottom:p=0,left:d=0}=t,l=[r,o,p,d].map(g=>typeof g=="number"?g:Number(g)||0);if(!l.some(g=>g!==0))return;let[u,v,m,A]=l;return{top:u,right:v,bottom:m,left:A}}notifyVisibilityListeners(e){for(let t of e)try{t()}catch(r){console.warn("[tvm-app-adapter] VK visibility listener failed:",r)}}computeBaseSafeArea(){return U({environment:this.configSafeArea,viewport:this.getViewportInsets?.(),css:ee()})}startViewportTracking(){this.stopViewportTracking?.();let e=Re({getSafeArea:()=>this.computeSafeArea(),onChange:t=>{this.environment.safeArea=t,this.notifyEnvironmentChanged()}});e&&(this.stopViewportTracking=this.registerDisposable(e))}resolveOverlayInsets(){if(typeof window>"u"||!f.default.isWebView()||!this.isLikelyMobilePlatform())return;let e=window.innerWidth||document.documentElement?.clientWidth||0;if(!e||e>880)return;let o=!!window.matchMedia?.("(orientation: landscape)")?.matches;return{top:o?48:56,right:o?72:88}}isLikelyMobilePlatform(){let e=(this.resolveLaunchParam("vk_platform")??"").toLowerCase(),t=(this.resolveLaunchParam("vk_viewer_device")??"").toLowerCase();if(this.resolveLaunchParam("vk_is_layer")==="1")return!1;let o=/(iphone|ipad|ios|android|mobile)/i,p=/(desktop|web|tablet)/i,d=o.test(e)||o.test(t),l=p.test(e)||p.test(t);return d?!l:!1}resolveLaunchParam(e){let t=this.queryParams?.[e];if(typeof t=="string"&&t)return t;let r=this.launchParams?this.launchParams[e]:void 0;if(typeof r=="string"&&r)return r;if(typeof r=="number")return String(r);if(typeof r=="boolean")return r?"1":"0"}supportsBridgeMethod(e){return Ne(e,this.supportsAsync)}onDestroy(){this.unsubscribe?.(),this.unsubscribe=void 0,this.stopViewportTracking?.(),this.stopViewportTracking=void 0,this.viewHideListeners.clear(),this.viewRestoreListeners.clear(),super.onDestroy()}};var Ke=se(require("jsqr"),1);var F=class extends S{constructor(){super("web",{sdkVersion:navigator.userAgent,languageCode:navigator.language,isWebView:!1});h(this,"deferredPrompt",null);typeof window<"u"&&window.addEventListener("beforeinstallprompt",e=>{e.preventDefault(),this.deferredPrompt=e})}async supports(e){switch(e){case"copyTextToClipboard":return typeof navigator<"u"&&!!navigator.clipboard?.writeText;case"downloadFile":return typeof document<"u";case"shareUrl":return typeof navigator<"u"&&(!!navigator.share||!!navigator.clipboard?.writeText);case"addToHomeScreen":return/android/i.test(navigator.userAgent)&&!!this.deferredPrompt;case"checkHomeScreenStatus":return!0;default:return super.supports(e)}}async downloadFile(e,t){try{await X(e,t,{preferBlob:!0})}catch(r){console.warn("[mini-app-template] Web downloadFile fallback:",r),await super.downloadFile(e,t)}}scanQRCode(e){return new Promise(async t=>{if(typeof document>"u"){t(null);return}let r=document.body.style.overflow,o=document.body.style.position,p=document.body.style.touchAction,d=document.body.style.width,l=document.documentElement.style.overflow;document.body.style.overflow="hidden",document.body.style.position="fixed",document.body.style.width="100%",document.body.style.touchAction="none",document.documentElement.style.overflow="hidden";let s=document.createElement("div");s.id="qr-overlay",s.style.position="fixed",s.style.top="0",s.style.left="0",s.style.right="0",s.style.bottom="0",s.style.zIndex="999999999",s.style.background="rgba(0,0,0,0.92)",s.style.width="100%",s.style.height="100%",s.style.display="flex",s.style.flexDirection="column",s.style.alignItems="center",s.style.justifyContent="center",s.style.gap="20px",s.style.padding="24px",s.style.boxSizing="border-box",s.style.overflow="hidden",s.style.backdropFilter="blur(3px)",document.body.appendChild(s);let u=document.createElement("button");u.innerText="\u2715",u.style.position="absolute",u.style.top="22px",u.style.right="22px",u.style.fontSize="32px",u.style.color="white",u.style.background="transparent",u.style.border="none",u.style.cursor="pointer",u.style.zIndex="9999999999",s.appendChild(u);let v=Math.min(Math.floor(Math.min(window.innerWidth,window.innerHeight)*.72),320),m=document.createElement("div");m.style.width=`${v}px`,m.style.height=`${v}px`,m.style.position="relative",m.style.flex="0 0 auto",m.style.borderRadius="18px",m.style.overflow="hidden",s.appendChild(m);let A=document.createElement("div");A.style.position="absolute",A.style.inset="0",A.style.zIndex="1",A.style.background="#000",m.appendChild(A);let g=document.createElement("video");g.setAttribute("playsinline","true"),g.autoplay=!0,g.muted=!0,g.style.width="100%",g.style.height="100%",g.style.objectFit="cover",g.style.position="absolute",g.style.inset="0",A.appendChild(g);let w=document.createElement("div");w.style.position="absolute",w.style.top="0",w.style.left="0",w.style.right="0",w.style.bottom="0",w.style.border="3px solid rgba(255,255,255,0.9)",w.style.borderRadius="18px",w.style.pointerEvents="none",w.style.zIndex="3",m.appendChild(w);let y=document.createElement("div");y.style.position="absolute",y.style.left="0",y.style.right="0",y.style.height="2px",y.style.background="rgba(255,255,255,0.85)",y.style.borderRadius="2px",y.style.animation="qr-line 2s infinite",y.style.zIndex="4",m.appendChild(y);let M=document.createElement("style");M.innerHTML=`
4
4
  @keyframes qr-line {
5
5
  0% { top: 0; }
6
6
  50% { top: calc(100% - 2px); }
7
7
  100% { top: 0; }
8
8
  }
9
- `,document.head.appendChild(ae);let D=document.createElement("div");D.innerText="\u041D\u0430\u0432\u0435\u0434\u0438\u0442\u0435 \u043A\u0430\u043C\u0435\u0440\u0443 \u043D\u0430 QR-\u043A\u043E\u0434",D.style.color="white",D.style.fontSize="17px",D.style.opacity="0.9",a.appendChild(D);let b=document.createElement("button");b.innerText="\u0417\u0430\u043A\u0440\u044B\u0442\u044C",b.style.minWidth=`${Math.min(y,220)}px`,b.style.height="48px",b.style.padding="0 20px",b.style.border="1px solid rgba(255,255,255,0.24)",b.style.borderRadius="14px",b.style.background="rgba(255,255,255,0.12)",b.style.color="white",b.style.fontSize="16px",b.style.fontWeight="600",b.style.cursor="pointer",b.style.backdropFilter="blur(8px)",a.appendChild(b);let se=document.createElement("canvas"),pe=se.getContext("2d",{willReadFrequently:!0}),B=null,q=null,Me=0,de=!1,Ce=async E=>{de||(de=!0,q!==null&&(cancelAnimationFrame(q),q=null),B&&(B.getTracks().forEach(K=>K.stop()),B=null),v.srcObject=null,a.remove(),ae.remove(),document.body.style.overflow=n,document.body.style.position=i,document.body.style.width=d,document.body.style.touchAction=p,document.documentElement.style.overflow=l,t(E))},at=this.registerDisposable(()=>{Ce(null)}),J=E=>{Ce(E),at()};u.onclick=()=>J(null),b.onclick=()=>J(null);try{let E=[{video:{facingMode:{ideal:"environment"},width:{ideal:1920},height:{ideal:1080},aspectRatio:{ideal:1.7777777778}},audio:!1},{video:{facingMode:"environment",width:{ideal:1280},height:{ideal:720}},audio:!1},{video:!0,audio:!1}],K=null;for(let T of E)try{B=await navigator.mediaDevices.getUserMedia(T);break}catch(L){K=L}if(!B)throw K instanceof Error?K:new Error("Unable to access camera");let[Ve]=B.getVideoTracks();if(Ve)try{let T=[{focusMode:"continuous"},{exposureMode:"continuous"},{whiteBalanceMode:"continuous"}];await Ve.applyConstraints({advanced:T})}catch{}v.srcObject=B,await v.play();let xe=T=>{if(!de){if(T-Me>=80&&pe&&v.readyState>=HTMLMediaElement.HAVE_CURRENT_DATA){let L=v.videoWidth,z=v.videoHeight;if(L>0&&z>0){se.width=L,se.height=z,pe.drawImage(v,0,0,L,z);let st=pe.getImageData(0,0,L,z),Be=(0,Ue.default)(st.data,L,z,{inversionAttempts:"attemptBoth"});if(Be?.data){J(Be.data);return}Me=T}}q=requestAnimationFrame(xe)}};q=requestAnimationFrame(xe)}catch(E){console.error("QR Start error",E),J(null)}})}shareUrl(e,t){if(navigator.share)try{navigator.share({title:t,text:t,url:e});return}catch(i){console.warn("Share cancelled or failed:",i)}let n=t?`${t}
10
- ${e}`:e;this.copyTextToClipboard(n).catch(i=>{console.warn("Share fallback (clipboard) failed:",i)})}async addToHomeScreen(){if(!/android/i.test(navigator.userAgent)||!this.deferredPrompt)return super.addToHomeScreen();try{this.deferredPrompt.prompt();let t=await this.deferredPrompt.userChoice;return this.deferredPrompt=null,t?.outcome==="accepted"}catch(t){return console.warn("[tvm-app-adapter] Web addToHomeScreen failed:",t),this.deferredPrompt=null,!1}}async checkHomeScreenStatus(){try{return typeof window<"u"&&window.matchMedia?.("(display-mode: standalone)").matches||typeof navigator<"u"&&navigator.standalone===!0?"added":"unknown"}catch{return"unknown"}}};var Qe="mini-app-adapter:confirmed-platform",Ct=1800*1e3;function Y(){if(typeof window>"u")return"web";let o=new URLSearchParams(window.location.search),r=(()=>{let g=window.location.hash.startsWith("#")?window.location.hash.slice(1):window.location.hash;return new URLSearchParams(g)})(),e=g=>o.get(g)??r.get(g),t=(...g)=>g.some(w=>e(w)),n=()=>{try{let g=window.sessionStorage.getItem(Qe);if(!g)return null;let w=JSON.parse(g);return!w?.platform||typeof w.ts!="number"||Date.now()-w.ts>Ct?null:w.platform}catch{return null}},i=g=>{if(g!=="web")try{window.sessionStorage.setItem(Qe,JSON.stringify({platform:g,ts:Date.now()}))}catch{}},p=G();if(p)return i(p),p;let d=navigator.userAgent.toLowerCase();if(typeof window.NativeBridge?.postMessage=="function")return d.includes("android")?(i("shell_android"),"shell_android"):(i("shell_ios"),"shell_ios");let a=window,u=!!window.Telegram?.WebApp||typeof a.TelegramWebviewProxy<"u"||typeof a.TelegramGameProxy<"u",y=t("tgWebAppPlatform","tgWebAppVersion","tgWebAppData","tgWebAppLanguage");if(u||y||d.includes("telegram"))return i("telegram"),"telegram";if(window.WebApp||window.MaxMiniApp)return i("max"),"max";let h=t("vk_app_id","vk_platform","vk_user_id","vk_language","sign"),k=d.includes("vkclient")||d.includes("vk-android")||d.includes("vkontakte");if(h||k)return i("vk"),"vk";let v=n();return v&&v!=="web"?v:"web"}function je(o){let r=Vt(o),e=r.platform??Y();switch(e==="vk"&&ie(r.vk?.pixelCode??null),e){case"shell_ios":case"shell_android":return new R(e);case"telegram":return new F;case"vk":return new I;case"max":return new _;default:return new W}}function Vt(o){return o?typeof o=="string"?{platform:o}:o:{}}var x=require("react");var Ge=null;function Se(o){Ge=o}function H(){return Ge}var Xe=require("react/jsx-runtime"),$e=(0,x.createContext)(null);function Ye({adapter:o,children:r}){let e=(0,x.useMemo)(()=>new Proxy(o,{get(t,n,i){let p=Reflect.get(t,n,i);return typeof p=="function"?p.bind(t):p}}),[o]);return(0,x.useEffect)(()=>(Se(e),()=>{if(Se(null),typeof e.destroy=="function")try{e.destroy()}catch(t){console.warn("[tvm-app-adapter] adapter destroy failed:",t)}}),[e]),(0,Xe.jsx)($e.Provider,{value:e,children:r})}function O(){let o=(0,x.useContext)($e);if(!o)throw new Error("useMiniAppAdapter must be used inside <AdapterProvider/>.");return o}var C=require("react");var Je="loyalka-theme-preference";function Ze(){let o=O(),[r,e]=(0,C.useState)(()=>{let{appearance:a}=o.getEnvironment();return o.onAppearanceChange&&a?a==="dark":typeof window<"u"&&window.matchMedia?window.matchMedia("(prefers-color-scheme: dark)").matches:!1}),[t,n]=(0,C.useState)(()=>{try{let a=localStorage.getItem(Je);if(a==="light"||a==="dark"||a==="system")return a}catch{}return"system"});(0,C.useEffect)(()=>{if(o.onAppearanceChange)return o.onAppearanceChange(a=>{a&&e(a==="dark")});if(typeof window<"u"&&window.matchMedia){let a=window.matchMedia("(prefers-color-scheme: dark)"),u=y=>e(y.matches);return a.addEventListener("change",u),()=>a.removeEventListener("change",u)}},[o]);let i=(0,C.useMemo)(()=>!!(t==="dark"||t==="system"&&r),[t,r]),p=i?"dark":"light";(0,C.useEffect)(()=>{let a=document.documentElement;i?a.classList.add("dark"):a.classList.remove("dark")},[i]);let d=(0,C.useCallback)(a=>{n(a);try{localStorage.setItem(Je,a)}catch{}},[]),l=(0,C.useCallback)(()=>{document.documentElement.classList.add("theme-transition"),setTimeout(()=>{setTimeout(()=>{document.documentElement.classList.remove("theme-transition")},400)},50);let a=document.documentElement,u=getComputedStyle(a),y=u.getPropertyValue("--primary").trim(),h=u.getPropertyValue("--background").trim();o.setColors({header:y,background:h,footer:h}),d(t==="dark"?"light":"dark")},[o,t,d]);return{isDark:i,appearance:p,preference:t,setPreference:d,toggle:l}}var N=require("react");var et={top:0,right:0,bottom:0,left:0};function tt(){let o=O(),r=(0,N.useCallback)(()=>o.computeSafeArea()??et,[o]),[e,t]=(0,N.useState)(r);return(0,N.useEffect)(()=>{t(r());let n=o.subscribe?.(()=>{t(r())});return()=>n?.()},[o,r]),e??et}var X=null;function oe(){let o=H();if(o)return o.platform!=="web"&&(X=o.platform),o.platform;if(X&&X!=="web")return X;let r=Y();return r!=="web"&&(X=r),r}function nt(o){ie(o)}function rt(o,r){ot()?.trackConversionEvent(o,r)}function it(o,r){ot()?.trackPixelEvent(o,r)}function ot(){let o=H();return o?o.platform==="vk"?o:null:(oe()!=="vk",null)}0&&(module.exports={AdapterProvider,BaseMiniAppAdapter,MaxMiniAppAdapter,ShellMiniAppAdapter,TelegramMiniAppAdapter,VKMiniAppAdapter,WebMiniAppAdapter,configureVkPixel,createAdapter,createShellAPI,detectPlatform,getActiveAdapter,getPlatform,isShell,isShellAndroid,isShellIOS,readShellPlatform,requestShellPushPermission,shell,storeShellToken,trackConversionEvent,trackPixelEvent,useAdapterTheme,useMiniAppAdapter,useSafeArea});
9
+ `,document.head.appendChild(M);let P=document.createElement("div");P.innerText="\u041D\u0430\u0432\u0435\u0434\u0438\u0442\u0435 \u043A\u0430\u043C\u0435\u0440\u0443 \u043D\u0430 QR-\u043A\u043E\u0434",P.style.color="white",P.style.fontSize="17px",P.style.opacity="0.9",s.appendChild(P);let b=document.createElement("button");b.innerText="\u0417\u0430\u043A\u0440\u044B\u0442\u044C",b.style.minWidth=`${Math.min(v,220)}px`,b.style.height="48px",b.style.padding="0 20px",b.style.border="1px solid rgba(255,255,255,0.24)",b.style.borderRadius="14px",b.style.background="rgba(255,255,255,0.12)",b.style.color="white",b.style.fontSize="16px",b.style.fontWeight="600",b.style.cursor="pointer",b.style.backdropFilter="blur(8px)",s.appendChild(b);let ie=document.createElement("canvas"),oe=ie.getContext("2d",{willReadFrequently:!0}),L=null,D=null,ke=0,ae=!1,Se=async T=>{ae||(ae=!0,D!==null&&(cancelAnimationFrame(D),D=null),L&&(L.getTracks().forEach(K=>K.stop()),L=null),g.srcObject=null,s.remove(),M.remove(),document.body.style.overflow=r,document.body.style.position=o,document.body.style.width=d,document.body.style.touchAction=p,document.documentElement.style.overflow=l,t(T))},it=this.registerDisposable(()=>{Se(null)}),J=T=>{Se(T),it()};u.onclick=()=>J(null),b.onclick=()=>J(null);try{let T=[{video:{facingMode:{ideal:"environment"},width:{ideal:1920},height:{ideal:1080},aspectRatio:{ideal:1.7777777778}},audio:!1},{video:{facingMode:"environment",width:{ideal:1280},height:{ideal:720}},audio:!1},{video:!0,audio:!1}],K=null;for(let R of T)try{L=await navigator.mediaDevices.getUserMedia(R);break}catch(B){K=B}if(!L)throw K instanceof Error?K:new Error("Unable to access camera");let[Pe]=L.getVideoTracks();if(Pe)try{let R=[{focusMode:"continuous"},{exposureMode:"continuous"},{whiteBalanceMode:"continuous"}];await Pe.applyConstraints({advanced:R})}catch{}g.srcObject=L,await g.play();let Ce=R=>{if(!ae){if(R-ke>=80&&oe&&g.readyState>=HTMLMediaElement.HAVE_CURRENT_DATA){let B=g.videoWidth,q=g.videoHeight;if(B>0&&q>0){ie.width=B,ie.height=q,oe.drawImage(g,0,0,B,q);let ot=oe.getImageData(0,0,B,q),Me=(0,Ke.default)(ot.data,B,q,{inversionAttempts:"attemptBoth"});if(Me?.data){J(Me.data);return}ke=R}}D=requestAnimationFrame(Ce)}};D=requestAnimationFrame(Ce)}catch(T){console.error("QR Start error",T),J(null)}})}shareUrl(e,t){if(navigator.share)try{navigator.share({title:t,text:t,url:e});return}catch(o){console.warn("Share cancelled or failed:",o)}let r=t?`${t}
10
+ ${e}`:e;this.copyTextToClipboard(r).catch(o=>{console.warn("Share fallback (clipboard) failed:",o)})}async addToHomeScreen(){if(!/android/i.test(navigator.userAgent)||!this.deferredPrompt)return super.addToHomeScreen();try{this.deferredPrompt.prompt();let t=await this.deferredPrompt.userChoice;return this.deferredPrompt=null,t?.outcome==="accepted"}catch(t){return console.warn("[tvm-app-adapter] Web addToHomeScreen failed:",t),this.deferredPrompt=null,!1}}async checkHomeScreenStatus(){try{return typeof window<"u"&&window.matchMedia?.("(display-mode: standalone)").matches||typeof navigator<"u"&&navigator.standalone===!0?"added":"unknown"}catch{return"unknown"}}};var qe="mini-app-adapter:confirmed-platform";function $(){if(typeof window>"u")return"web";let i=new URLSearchParams(window.location.search),n=(()=>{let y=window.location.hash.startsWith("#")?window.location.hash.slice(1):window.location.hash;return new URLSearchParams(y)})(),e=y=>i.get(y)??n.get(y),t=(...y)=>y.some(M=>e(M)),r=()=>{let y=[];try{window.localStorage&&y.push(window.localStorage)}catch{}try{window.sessionStorage&&y.push(window.sessionStorage)}catch{}return y},o=()=>{for(let y of r())try{let M=y.getItem(qe);if(!M)continue;let P=JSON.parse(M);if(P?.platform&&P.platform!=="web")return P.platform}catch{}return null},p=y=>{if(y==="web")return;let M=JSON.stringify({platform:y,ts:Date.now()});for(let P of r())try{P.setItem(qe,M)}catch{}},d=G();if(d)return p(d),d;let l=navigator.userAgent.toLowerCase();if(typeof window.NativeBridge?.postMessage=="function")return l.includes("android")?(p("shell_android"),"shell_android"):(p("shell_ios"),"shell_ios");let u=window,v=!!window.Telegram?.WebApp||typeof u.TelegramWebviewProxy<"u"||typeof u.TelegramGameProxy<"u",m=t("tgWebAppPlatform","tgWebAppVersion","tgWebAppData","tgWebAppLanguage");if(v||m||l.includes("telegram"))return p("telegram"),"telegram";let A=t("vk_app_id","vk_platform","vk_user_id","vk_language","sign"),g=l.includes("vkclient")||l.includes("vk-android")||l.includes("vkontakte");if(A||g)return p("vk"),"vk";let w=o();return w&&w!=="web"?w:"web"}function ze(i){let n=Pt(i),e=n.platform??$();switch(e==="vk"&&re(n.vk?.pixelCode??null),e){case"shell_ios":case"shell_android":return new _(e);case"telegram":return new W;case"vk":return new I;default:return new F}}function Pt(i){return i?typeof i=="string"?{platform:i}:i:{}}var E=require("react");var Qe=null;function Ae(i){Qe=i}function O(){return Qe}var je=require("react/jsx-runtime"),Ue=(0,E.createContext)(null);function Ge({adapter:i,children:n}){let e=(0,E.useMemo)(()=>{let t=new Map;return new Proxy(i,{get(r,o,p){let d=Reflect.get(r,o,p);if(typeof d!="function")return d;let l=t.get(o);return l||(l=d.bind(r),t.set(o,l)),l}})},[i]);return(0,E.useEffect)(()=>(Ae(e),()=>{Ae(null)}),[e]),(0,je.jsx)(Ue.Provider,{value:e,children:n})}function H(){let i=(0,E.useContext)(Ue);if(!i)throw new Error("useMiniAppAdapter must be used inside <AdapterProvider/>.");return i}var C=require("react");var $e="mini-app-adapter:theme-preference";function Ye(){let i=H(),[n,e]=(0,C.useState)(()=>{let{appearance:s}=i.getEnvironment();return i.onAppearanceChange&&s?s==="dark":typeof window<"u"&&window.matchMedia?window.matchMedia("(prefers-color-scheme: dark)").matches:!1}),[t,r]=(0,C.useState)(()=>{try{let s=localStorage.getItem($e);if(s==="light"||s==="dark"||s==="system")return s}catch{}return"system"});(0,C.useEffect)(()=>{if(i.onAppearanceChange)return i.onAppearanceChange(s=>{s&&e(s==="dark")});if(typeof window<"u"&&window.matchMedia){let s=window.matchMedia("(prefers-color-scheme: dark)"),u=v=>e(v.matches);return s.addEventListener("change",u),()=>s.removeEventListener("change",u)}},[i]);let o=(0,C.useMemo)(()=>!!(t==="dark"||t==="system"&&n),[t,n]),p=o?"dark":"light";(0,C.useEffect)(()=>{let s=document.documentElement;o?s.classList.add("dark"):s.classList.remove("dark");let u=getComputedStyle(s),v=u.getPropertyValue("--primary").trim(),m=u.getPropertyValue("--background").trim();(v||m)&&i.setColors({...v?{header:v}:{},...m?{background:m,footer:m}:{}})},[o,i]);let d=(0,C.useCallback)(s=>{r(s);try{localStorage.setItem($e,s)}catch{}},[]),l=(0,C.useCallback)(()=>{document.documentElement.classList.add("theme-transition"),setTimeout(()=>{setTimeout(()=>{document.documentElement.classList.remove("theme-transition")},400)},50),d(t==="dark"?"light":"dark")},[t,d]);return{isDark:o,appearance:p,preference:t,setPreference:d,toggle:l}}var N=require("react");var Je={top:0,right:0,bottom:0,left:0};function Ze(){let i=H(),n=(0,N.useCallback)(()=>i.computeSafeArea()??Je,[i]),[e,t]=(0,N.useState)(n);return(0,N.useEffect)(()=>{t(n());let r=i.subscribe?.(()=>{t(n())});return()=>r?.()},[i,n]),e??Je}function Xe(i){re(i)}function et(i,n){nt()?.trackConversionEvent(i,n)}function tt(i,n){nt()?.trackPixelEvent(i,n)}function nt(){let i=O();return i&&i.platform==="vk"?i:null}var Y=null;function rt(){let i=O();if(i)return i.platform!=="web"&&(Y=i.platform),i.platform;if(Y&&Y!=="web")return Y;let n=$();return n!=="web"&&(Y=n),n}0&&(module.exports={AdapterProvider,BaseMiniAppAdapter,ShellMiniAppAdapter,TelegramMiniAppAdapter,VKMiniAppAdapter,WebMiniAppAdapter,configureVkPixel,createAdapter,createShellAPI,detectPlatform,getActiveAdapter,getPlatform,isShell,isShellAndroid,isShellIOS,readShellPlatform,requestShellPushPermission,shell,storeShellToken,trackConversionEvent,trackPixelEvent,useAdapterTheme,useMiniAppAdapter,useSafeArea});
package/dist/index.d.cts CHANGED
@@ -139,8 +139,10 @@ interface MiniAppAdapter {
139
139
  readonly shell: ShellAPI;
140
140
  /**
141
141
  * Quick capability check before calling platform specific APIs.
142
+ * Always asynchronous so callers can rely on a single contract across platforms
143
+ * (VK resolves capabilities via the async bridge). Always `await` the result.
142
144
  */
143
- supports(capability: MiniAppCapability): boolean | Promise<boolean>;
145
+ supports(capability: MiniAppCapability): Promise<boolean>;
144
146
  /**
145
147
  * Initializes platform SDK. Safe to call multiple times.
146
148
  */
@@ -229,9 +231,9 @@ interface MiniAppAdapter {
229
231
  /**
230
232
  * Strong/weak haptic feedback helpers.
231
233
  */
232
- vibrateImpact(style: ImpactHapticFeedbackStyle): void;
233
- vibrateNotification(type: NotificationHapticFeedbackType): void;
234
- vibrateSelection(): void;
234
+ vibrateImpact(style: ImpactHapticFeedbackStyle): void | Promise<void>;
235
+ vibrateNotification(type: NotificationHapticFeedbackType): void | Promise<void>;
236
+ vibrateSelection(): void | Promise<void>;
235
237
  /**
236
238
  * Notifies when the host view goes to background/foreground (VK only).
237
239
  */
@@ -294,7 +296,7 @@ interface MiniAppAdapter {
294
296
  /**
295
297
  * Shares a URL using platform-specific capabilities.
296
298
  */
297
- shareUrl?(url: string, text: string): void;
299
+ shareUrl?(url: string, text?: string): void;
298
300
  /**
299
301
  * Copies text to the clipboard if supported by the platform.
300
302
  */
@@ -328,7 +330,7 @@ declare abstract class BaseMiniAppAdapter implements MiniAppAdapter {
328
330
  private readonly disposables;
329
331
  readonly shell: ShellAPI;
330
332
  protected constructor(platform: MiniAppPlatform, environment?: Partial<MiniAppEnvironmentInfo>);
331
- supports(capability: MiniAppCapability): boolean | Promise<boolean>;
333
+ supports(capability: MiniAppCapability): Promise<boolean>;
332
334
  get platform(): MiniAppPlatform;
333
335
  init(_options?: MiniAppInitOptions): Promise<void>;
334
336
  isReady(): boolean;
@@ -357,7 +359,7 @@ declare abstract class BaseMiniAppAdapter implements MiniAppAdapter {
357
359
  }) => void): () => void;
358
360
  getViewportInsets(): MiniAppViewportInsets | undefined;
359
361
  shareMessage(_message: string): Promise<void>;
360
- shareUrl(_url: string, _text: string): void;
362
+ shareUrl(_url: string, _text?: string): void;
361
363
  downloadFile(url: string, filename: string): Promise<void>;
362
364
  shareStory(_mediaUrl: string, _options?: MiniAppShareStoryOptions): Promise<void>;
363
365
  trackConversionEvent(_event: string, _payload?: Record<string, unknown>): void;
@@ -386,35 +388,9 @@ declare abstract class BaseMiniAppAdapter implements MiniAppAdapter {
386
388
  private applyScrollGuards;
387
389
  }
388
390
 
389
- declare class MaxMiniAppAdapter extends BaseMiniAppAdapter {
390
- private readonly backHandlers;
391
- private initData?;
392
- private initDataUnsafe?;
393
- constructor();
394
- init(_options?: MiniAppInitOptions): Promise<void>;
395
- supports(capability: MiniAppCapability): boolean;
396
- getInitData(): string | undefined;
397
- getLaunchParams(): MiniAppLaunchParams | undefined;
398
- onBackButton(callback: () => void): () => void;
399
- setBackButtonVisibility(visible: boolean): void;
400
- openExternalLink(url: string): Promise<void>;
401
- openInternalLink(url: string): Promise<void>;
402
- closeApp(): Promise<void>;
403
- vibrateImpact(style: ImpactHapticFeedbackStyle): void;
404
- vibrateNotification(type: NotificationHapticFeedbackType): void;
405
- vibrateSelection(): void;
406
- scanQRCode(options?: MiniAppQrScanOptions): Promise<string | null>;
407
- requestPhone(): Promise<string | null>;
408
- showPopup(options: MiniAppPopupOptions): Promise<string | null>;
409
- downloadFile(url: string, filename: string): Promise<void>;
410
- private requestPhoneViaEvent;
411
- private extractPhone;
412
- protected onDestroy(): void;
413
- }
414
-
415
391
  declare class ShellMiniAppAdapter extends BaseMiniAppAdapter {
416
392
  constructor(platform: 'shell_ios' | 'shell_android');
417
- supports(capability: MiniAppCapability): boolean | Promise<boolean>;
393
+ supports(capability: MiniAppCapability): Promise<boolean>;
418
394
  scanQRCode(): Promise<string | null>;
419
395
  requestNotificationsPermission(): Promise<boolean>;
420
396
  }
@@ -439,7 +415,8 @@ declare class TelegramMiniAppAdapter extends BaseMiniAppAdapter {
439
415
  openExternalLink(url: string): Promise<void>;
440
416
  openInternalLink(url: string): Promise<void>;
441
417
  enableDebug(state: boolean): void;
442
- supports(capability: MiniAppCapability): boolean;
418
+ private hapticsAvailable;
419
+ supports(capability: MiniAppCapability): Promise<boolean>;
443
420
  bindCssVariables(mapper?: (key: string) => string): void;
444
421
  vibrateImpact(style: ImpactHapticFeedbackStyle): void;
445
422
  vibrateNotification(type: NotificationHapticFeedbackType): void;
@@ -506,6 +483,7 @@ declare class VKMiniAppAdapter extends BaseMiniAppAdapter {
506
483
  getEnvironment(): MiniAppEnvironmentInfo;
507
484
  getLaunchParams(): MiniAppLaunchParams | undefined;
508
485
  openExternalLink(url: string): Promise<void>;
486
+ closeApp(): Promise<void>;
509
487
  supports(capability: MiniAppCapability): Promise<boolean>;
510
488
  requestPhone(): Promise<string | null>;
511
489
  requestNotificationsPermission(): Promise<boolean>;
@@ -546,10 +524,10 @@ declare class VKMiniAppAdapter extends BaseMiniAppAdapter {
546
524
  declare class WebMiniAppAdapter extends BaseMiniAppAdapter {
547
525
  private deferredPrompt;
548
526
  constructor();
549
- supports(capability: MiniAppCapability): boolean | Promise<boolean>;
527
+ supports(capability: MiniAppCapability): Promise<boolean>;
550
528
  downloadFile(url: string, filename: string): Promise<void>;
551
529
  scanQRCode(_options?: MiniAppQrScanOptions): Promise<string | null>;
552
- shareUrl(url: string, text: string): void;
530
+ shareUrl(url: string, text?: string): void;
553
531
  addToHomeScreen(): Promise<boolean>;
554
532
  checkHomeScreenStatus(): Promise<'added' | 'not_added' | 'unknown' | string>;
555
533
  }
@@ -596,4 +574,4 @@ declare function trackPixelEvent(event: string, payload?: Record<string, unknown
596
574
 
597
575
  declare function getPlatform(): MiniAppPlatform;
598
576
 
599
- export { AdapterProvider, BaseMiniAppAdapter, type CreateAdapterOptions, MaxMiniAppAdapter, type MiniAppAdapter, type MiniAppCapability, type MiniAppEnvironmentInfo, type MiniAppInitOptions, type MiniAppLaunchParams, type MiniAppPlatform, type MiniAppPopupOptions, type MiniAppQrScanOptions, type MiniAppShareStoryOptions, type MiniAppViewportState, ShellMiniAppAdapter, TelegramMiniAppAdapter, VKMiniAppAdapter, WebMiniAppAdapter, configureVkPixel, createAdapter, createShellAPI, detectPlatform, getActiveAdapter, getPlatform, isShell, isShellAndroid, isShellIOS, readShellPlatform, requestShellPushPermission, shell, storeShellToken, trackConversionEvent, trackPixelEvent, useAdapterTheme, useMiniAppAdapter, useSafeArea };
577
+ export { AdapterProvider, BaseMiniAppAdapter, type CreateAdapterOptions, type MiniAppAdapter, type MiniAppCapability, type MiniAppEnvironmentInfo, type MiniAppInitOptions, type MiniAppLaunchParams, type MiniAppPlatform, type MiniAppPopupOptions, type MiniAppQrScanOptions, type MiniAppShareStoryOptions, type MiniAppViewportState, ShellMiniAppAdapter, TelegramMiniAppAdapter, VKMiniAppAdapter, WebMiniAppAdapter, configureVkPixel, createAdapter, createShellAPI, detectPlatform, getActiveAdapter, getPlatform, isShell, isShellAndroid, isShellIOS, readShellPlatform, requestShellPushPermission, shell, storeShellToken, trackConversionEvent, trackPixelEvent, useAdapterTheme, useMiniAppAdapter, useSafeArea };
package/dist/index.d.ts CHANGED
@@ -139,8 +139,10 @@ interface MiniAppAdapter {
139
139
  readonly shell: ShellAPI;
140
140
  /**
141
141
  * Quick capability check before calling platform specific APIs.
142
+ * Always asynchronous so callers can rely on a single contract across platforms
143
+ * (VK resolves capabilities via the async bridge). Always `await` the result.
142
144
  */
143
- supports(capability: MiniAppCapability): boolean | Promise<boolean>;
145
+ supports(capability: MiniAppCapability): Promise<boolean>;
144
146
  /**
145
147
  * Initializes platform SDK. Safe to call multiple times.
146
148
  */
@@ -229,9 +231,9 @@ interface MiniAppAdapter {
229
231
  /**
230
232
  * Strong/weak haptic feedback helpers.
231
233
  */
232
- vibrateImpact(style: ImpactHapticFeedbackStyle): void;
233
- vibrateNotification(type: NotificationHapticFeedbackType): void;
234
- vibrateSelection(): void;
234
+ vibrateImpact(style: ImpactHapticFeedbackStyle): void | Promise<void>;
235
+ vibrateNotification(type: NotificationHapticFeedbackType): void | Promise<void>;
236
+ vibrateSelection(): void | Promise<void>;
235
237
  /**
236
238
  * Notifies when the host view goes to background/foreground (VK only).
237
239
  */
@@ -294,7 +296,7 @@ interface MiniAppAdapter {
294
296
  /**
295
297
  * Shares a URL using platform-specific capabilities.
296
298
  */
297
- shareUrl?(url: string, text: string): void;
299
+ shareUrl?(url: string, text?: string): void;
298
300
  /**
299
301
  * Copies text to the clipboard if supported by the platform.
300
302
  */
@@ -328,7 +330,7 @@ declare abstract class BaseMiniAppAdapter implements MiniAppAdapter {
328
330
  private readonly disposables;
329
331
  readonly shell: ShellAPI;
330
332
  protected constructor(platform: MiniAppPlatform, environment?: Partial<MiniAppEnvironmentInfo>);
331
- supports(capability: MiniAppCapability): boolean | Promise<boolean>;
333
+ supports(capability: MiniAppCapability): Promise<boolean>;
332
334
  get platform(): MiniAppPlatform;
333
335
  init(_options?: MiniAppInitOptions): Promise<void>;
334
336
  isReady(): boolean;
@@ -357,7 +359,7 @@ declare abstract class BaseMiniAppAdapter implements MiniAppAdapter {
357
359
  }) => void): () => void;
358
360
  getViewportInsets(): MiniAppViewportInsets | undefined;
359
361
  shareMessage(_message: string): Promise<void>;
360
- shareUrl(_url: string, _text: string): void;
362
+ shareUrl(_url: string, _text?: string): void;
361
363
  downloadFile(url: string, filename: string): Promise<void>;
362
364
  shareStory(_mediaUrl: string, _options?: MiniAppShareStoryOptions): Promise<void>;
363
365
  trackConversionEvent(_event: string, _payload?: Record<string, unknown>): void;
@@ -386,35 +388,9 @@ declare abstract class BaseMiniAppAdapter implements MiniAppAdapter {
386
388
  private applyScrollGuards;
387
389
  }
388
390
 
389
- declare class MaxMiniAppAdapter extends BaseMiniAppAdapter {
390
- private readonly backHandlers;
391
- private initData?;
392
- private initDataUnsafe?;
393
- constructor();
394
- init(_options?: MiniAppInitOptions): Promise<void>;
395
- supports(capability: MiniAppCapability): boolean;
396
- getInitData(): string | undefined;
397
- getLaunchParams(): MiniAppLaunchParams | undefined;
398
- onBackButton(callback: () => void): () => void;
399
- setBackButtonVisibility(visible: boolean): void;
400
- openExternalLink(url: string): Promise<void>;
401
- openInternalLink(url: string): Promise<void>;
402
- closeApp(): Promise<void>;
403
- vibrateImpact(style: ImpactHapticFeedbackStyle): void;
404
- vibrateNotification(type: NotificationHapticFeedbackType): void;
405
- vibrateSelection(): void;
406
- scanQRCode(options?: MiniAppQrScanOptions): Promise<string | null>;
407
- requestPhone(): Promise<string | null>;
408
- showPopup(options: MiniAppPopupOptions): Promise<string | null>;
409
- downloadFile(url: string, filename: string): Promise<void>;
410
- private requestPhoneViaEvent;
411
- private extractPhone;
412
- protected onDestroy(): void;
413
- }
414
-
415
391
  declare class ShellMiniAppAdapter extends BaseMiniAppAdapter {
416
392
  constructor(platform: 'shell_ios' | 'shell_android');
417
- supports(capability: MiniAppCapability): boolean | Promise<boolean>;
393
+ supports(capability: MiniAppCapability): Promise<boolean>;
418
394
  scanQRCode(): Promise<string | null>;
419
395
  requestNotificationsPermission(): Promise<boolean>;
420
396
  }
@@ -439,7 +415,8 @@ declare class TelegramMiniAppAdapter extends BaseMiniAppAdapter {
439
415
  openExternalLink(url: string): Promise<void>;
440
416
  openInternalLink(url: string): Promise<void>;
441
417
  enableDebug(state: boolean): void;
442
- supports(capability: MiniAppCapability): boolean;
418
+ private hapticsAvailable;
419
+ supports(capability: MiniAppCapability): Promise<boolean>;
443
420
  bindCssVariables(mapper?: (key: string) => string): void;
444
421
  vibrateImpact(style: ImpactHapticFeedbackStyle): void;
445
422
  vibrateNotification(type: NotificationHapticFeedbackType): void;
@@ -506,6 +483,7 @@ declare class VKMiniAppAdapter extends BaseMiniAppAdapter {
506
483
  getEnvironment(): MiniAppEnvironmentInfo;
507
484
  getLaunchParams(): MiniAppLaunchParams | undefined;
508
485
  openExternalLink(url: string): Promise<void>;
486
+ closeApp(): Promise<void>;
509
487
  supports(capability: MiniAppCapability): Promise<boolean>;
510
488
  requestPhone(): Promise<string | null>;
511
489
  requestNotificationsPermission(): Promise<boolean>;
@@ -546,10 +524,10 @@ declare class VKMiniAppAdapter extends BaseMiniAppAdapter {
546
524
  declare class WebMiniAppAdapter extends BaseMiniAppAdapter {
547
525
  private deferredPrompt;
548
526
  constructor();
549
- supports(capability: MiniAppCapability): boolean | Promise<boolean>;
527
+ supports(capability: MiniAppCapability): Promise<boolean>;
550
528
  downloadFile(url: string, filename: string): Promise<void>;
551
529
  scanQRCode(_options?: MiniAppQrScanOptions): Promise<string | null>;
552
- shareUrl(url: string, text: string): void;
530
+ shareUrl(url: string, text?: string): void;
553
531
  addToHomeScreen(): Promise<boolean>;
554
532
  checkHomeScreenStatus(): Promise<'added' | 'not_added' | 'unknown' | string>;
555
533
  }
@@ -596,4 +574,4 @@ declare function trackPixelEvent(event: string, payload?: Record<string, unknown
596
574
 
597
575
  declare function getPlatform(): MiniAppPlatform;
598
576
 
599
- export { AdapterProvider, BaseMiniAppAdapter, type CreateAdapterOptions, MaxMiniAppAdapter, type MiniAppAdapter, type MiniAppCapability, type MiniAppEnvironmentInfo, type MiniAppInitOptions, type MiniAppLaunchParams, type MiniAppPlatform, type MiniAppPopupOptions, type MiniAppQrScanOptions, type MiniAppShareStoryOptions, type MiniAppViewportState, ShellMiniAppAdapter, TelegramMiniAppAdapter, VKMiniAppAdapter, WebMiniAppAdapter, configureVkPixel, createAdapter, createShellAPI, detectPlatform, getActiveAdapter, getPlatform, isShell, isShellAndroid, isShellIOS, readShellPlatform, requestShellPushPermission, shell, storeShellToken, trackConversionEvent, trackPixelEvent, useAdapterTheme, useMiniAppAdapter, useSafeArea };
577
+ export { AdapterProvider, BaseMiniAppAdapter, type CreateAdapterOptions, type MiniAppAdapter, type MiniAppCapability, type MiniAppEnvironmentInfo, type MiniAppInitOptions, type MiniAppLaunchParams, type MiniAppPlatform, type MiniAppPopupOptions, type MiniAppQrScanOptions, type MiniAppShareStoryOptions, type MiniAppViewportState, ShellMiniAppAdapter, TelegramMiniAppAdapter, VKMiniAppAdapter, WebMiniAppAdapter, configureVkPixel, createAdapter, createShellAPI, detectPlatform, getActiveAdapter, getPlatform, isShell, isShellAndroid, isShellIOS, readShellPlatform, requestShellPushPermission, shell, storeShellToken, trackConversionEvent, trackPixelEvent, useAdapterTheme, useMiniAppAdapter, useSafeArea };
package/dist/index.js CHANGED
@@ -1,10 +1,10 @@
1
- var vt=Object.defineProperty;var yt=(o,r,e)=>r in o?vt(o,r,{enumerable:!0,configurable:!0,writable:!0,value:e}):o[r]=e;var c=(o,r,e)=>yt(o,typeof r!="symbol"?r+"":r,e);var X=class{constructor(){c(this,"disposers",new Set)}add(r){if(!r)return()=>{};let e=typeof r=="function"?r:typeof r.dispose=="function"?r.dispose.bind(r):void 0;if(!e)return()=>{};let t=!1,n=()=>{if(!t){t=!0;try{e()}catch(i){console.warn("[tvm-app-adapter] disposable failed:",i)}finally{this.disposers.delete(n)}}};return this.disposers.add(n),n}disposeAll(){for(let r of Array.from(this.disposers))try{r()}catch(e){console.warn("[tvm-app-adapter] disposeAll failed:",e)}this.disposers.clear()}};var Fe=typeof window<"u"&&typeof document<"u";function gt(o,r){if(r&&r.trim().length>0)return r;try{let t=new URL(o).pathname.split("/").filter(Boolean).pop();if(t)return t}catch{}return"download"}function Re(o,r,{targetBlank:e}){if(!Fe)return;let t=document.createElement("a");t.href=o,t.download=r,t.rel="noopener noreferrer",e&&(t.target="_blank"),document.body.appendChild(t),t.click(),document.body.removeChild(t)}async function J(o,r,e){if(!o)return;let t=gt(o,r),n=e?.preferBlob??!1;if(!Fe){typeof window<"u"&&window.open(o,"_blank","noopener,noreferrer");return}if(n&&typeof fetch=="function")try{let i=await fetch(o,{credentials:"include"});if(!i.ok)throw new Error(`Failed to download file: ${i.status}`);let s=await i.blob(),p=URL.createObjectURL(s);Re(p,t,{targetBlank:!1}),setTimeout(()=>URL.revokeObjectURL(p),3e4);return}catch(i){console.warn("[tvm-app-adapter] blob download failed, falling back to direct link:",i)}Re(o,t,{targetBlank:!0})}var ce=["top","right","bottom","left"],He={top:0,right:0,bottom:0,left:0};function le(o){return{...o}}function N(o,r){if(r)for(let e of ce){let t=r[e];typeof t=="number"&&Number.isFinite(t)&&(o[e]+=t)}}function Ie(o,r){if(r)for(let e of ce){let t=r[e];typeof t=="number"&&Number.isFinite(t)&&(o[e]=Math.max(o[e],t))}}function wt(o,r){return!o||!r?!1:ce.every(e=>o[e]===r[e])}function D(o={}){let r=le(He);return N(r,o.environment),o.viewport&&(N(r,o.viewport.safeArea),N(r,o.viewport.contentSafeArea)),N(r,o.additions),Ie(r,o.css),Ie(r,o.minimum),r}function Z(){if(typeof window>"u"||typeof document>"u")return;let o=getComputedStyle(document.documentElement),r=s=>{let p=parseFloat(o.getPropertyValue(s));return Number.isFinite(p)?p:0},e=r("--safe-area-inset-top"),t=r("--safe-area-inset-right"),n=r("--safe-area-inset-bottom"),i=r("--safe-area-inset-left");if(e||t||n||i)return{top:e,right:t,bottom:n,left:i}}function We(o){if(!o)return;let r={...He};return N(r,o),r}function Oe(o){let r=o.windowObj??(typeof window<"u"?window:void 0);if(!r)return;let e=We(o.getSafeArea());e&&(o.onChange(e),e=le(e));let t=()=>{let i=We(o.getSafeArea());i&&(!e||!wt(e,i))&&(o.onChange(i),e=le(i))};t();let n=o.events??["resize","orientationchange"];for(let i of n)r.addEventListener(i,t);return()=>{for(let i of n)r.removeEventListener(i,t)}}var bt=["shell_ios","shell_android"];var fe=new Set,me=new Set,he=new Set,ve=new Set,ye=null,P=null,At={platformFlag:"nativePlatform",pushTokenCallback:"nativePushToken",qrResultCallback:"nativeQRResult",deepLinkCallback:"nativeDeepLink",appActiveCallback:"nativeAppActive",appBackgroundCallback:"nativeAppBackground"},Ne={...At},ue={};function kt(o){ye=o;for(let r of fe)try{r(o)}catch(e){console.warn("[tvm-app-adapter] push token listener failed:",e)}}function De(o){return bt.includes(o)}function Pt(o){return o==="shell_ios"}function St(o){return o==="shell_android"}function ee(){let o=we();if(!o)return;let r=o[Ne.platformFlag];if(r==="shell_ios"||r==="shell_android")return r}function te(o){xt();let r=typeof o=="function"?o:()=>o;return{async openNativeQR(){let e=r();return De(e)?Bt():Et()},onPushToken(e){return fe.add(e),ye&&queueMicrotask(()=>{try{e(ye)}catch(t){console.warn("[tvm-app-adapter] push token listener failed:",t)}}),()=>fe.delete(e)},onDeepLink(e){return me.add(e),()=>me.delete(e)},onAppActive(e){return he.add(e),()=>he.delete(e)},onAppBackground(e){return ve.add(e),()=>ve.delete(e)}}}var Mt=te(()=>ee()??"web");function Ct(o){return be({type:"storeToken",payload:o})}function ge(){return be({type:"requestPushPermission"})}function we(){return typeof window>"u"?null:window}function Vt(){let o=we();if(!o)return null;let r=o.NativeBridge;return!r||typeof r.postMessage!="function"?null:r}function be(o){let r=Vt();if(!r)return!1;try{return r.postMessage(o),!0}catch(e){return console.warn("[tvm-app-adapter] NativeBridge.postMessage failed:",e),!1}}function xt(){let o=we();if(!o){ue={};return}let r=o,e=(t,n)=>{let i=Ne[t],s=ue[t];s&&s!==i&&delete r[s],ue[t]=i,r[i]=n};e("pushTokenCallback",t=>{typeof t=="string"&&(console.log("[tvm-app-adapter] nativePushToken",t),kt(t))}),e("deepLinkCallback",t=>{if(typeof t=="string")for(let n of me)try{n(t)}catch(i){console.warn("[tvm-app-adapter] deep link listener failed:",i)}}),e("appActiveCallback",()=>{for(let t of he)try{t()}catch(n){console.warn("[tvm-app-adapter] app active listener failed:",n)}}),e("appBackgroundCallback",()=>{for(let t of ve)try{t()}catch(n){console.warn("[tvm-app-adapter] app background listener failed:",n)}}),e("qrResultCallback",t=>{typeof t=="string"&&P&&(clearTimeout(P.timeoutId),P.resolve(t),P=null)})}function Bt(){return new Promise((o,r)=>{if(P&&(P.reject(new Error("QR request superseded by a new call.")),clearTimeout(P.timeoutId),P=null),!be({type:"openNativeQR"})){r(new Error("Native bridge is unavailable."));return}let e=setTimeout(()=>{P&&(P.reject(new Error("Native QR request timed out.")),P=null)},6e4);P={resolve:o,reject:r,timeoutId:e}})}async function Et(){if(typeof document>"u")throw new Error("QR scanning requires a browser environment.");let[{Html5Qrcode:o}]=await Promise.all([import("html5-qrcode")]);return new Promise((r,e)=>{let t=`native-shell-qr-${Date.now()}`,n=document.createElement("div");n.style.position="fixed",n.style.inset="0",n.style.background="rgba(0, 0, 0, 0.9)",n.style.display="flex",n.style.flexDirection="column",n.style.alignItems="center",n.style.justifyContent="center",n.style.zIndex="2147483647",n.style.backdropFilter="blur(2px)";let i=document.createElement("div");i.id=t,i.style.width="280px",i.style.height="280px",i.style.borderRadius="16px",i.style.overflow="hidden",i.style.position="relative";let s=document.createElement("button");s.type="button",s.textContent="\u2715",s.style.position="absolute",s.style.top="16px",s.style.right="16px",s.style.background="transparent",s.style.border="none",s.style.color="#fff",s.style.fontSize="28px",s.style.cursor="pointer",n.appendChild(s),n.appendChild(i),document.body.appendChild(n);let p=document.body.style.overflow;document.body.style.overflow="hidden";let d=!1,a=new o(t),l=async(h,u)=>{if(!d){d=!0;try{await a.stop();let b=a.clear;typeof b=="function"&&await Promise.resolve(b.call(a))}catch{}n.remove(),document.body.style.overflow=p,typeof h=="string"?r(h):e(u||new Error("QR scanning was cancelled."))}};s.addEventListener("click",()=>{l(void 0,new Error("QR scanning was cancelled by the user."))}),a.start({facingMode:"environment"},{fps:10,qrbox:{width:240,height:240}},h=>{l(h)},()=>{}).catch(h=>{let u=h instanceof Error?h:new Error("Unable to start HTML5 QR scanner.");l(void 0,u)})})}var A=class{constructor(r,e){c(this,"ready",!1);c(this,"environment");c(this,"listeners",new Set);c(this,"disposables",new X);c(this,"shell");if(this.shell=te(r),this.environment={platform:r,...e},typeof window<"u"){let t=()=>this.notifyEnvironmentChanged();if(window.addEventListener("resize",t),this.registerDisposable(()=>window.removeEventListener("resize",t)),r!=="web"){let n=this.applyScrollGuards();n&&this.registerDisposable(n)}}}supports(r){switch(r){case"openExternalLink":return!0;default:return!1}}get platform(){return this.environment.platform}async init(r){this.ready=!0}isReady(){return this.ready}getEnvironment(){return{...this.environment}}destroy(){try{this.onDestroy()}finally{this.disposables.disposeAll(),this.listeners.clear(),this.ready=!1}}subscribe(r){return this.listeners.add(r),()=>{this.listeners.delete(r)}}async setColors(r){if(r.background&&(document.body.style.backgroundColor=r.background),r.header){let e=document.querySelector('meta[name="theme-color"]');e&&e.setAttribute("content",r.header)}}onBackButton(r){let e=()=>r();return window.addEventListener("popstate",e),()=>window.removeEventListener("popstate",e)}onPushToken(r){return this.shell.onPushToken(r)}onDeepLink(r){return this.shell.onDeepLink(r)}async openExternalLink(r){window.open(r,"_blank","noopener,noreferrer")}async openInternalLink(r){window.open(r,"_self","noopener,noreferrer")}async closeApp(){window.history.length>1?window.history.back():window.close()}setBackButtonVisibility(r){}onAppearanceChange(r){return r(this.environment.appearance),()=>{}}getInitData(){}getLaunchParams(){return{customLaunchParams:this.readCustomUrlParams()}}decodeStartParam(r){}requestFullscreen(){}onViewportChange(r){if(typeof window>"u")return()=>{};let e=()=>window.visualViewport?.height??window.innerHeight,t=()=>{let i=e();r({height:i,stableHeight:i})};t();let n=()=>t();return window.visualViewport?.addEventListener("resize",n),window.visualViewport?.addEventListener("scroll",n),window.addEventListener("resize",n),()=>{window.visualViewport?.removeEventListener("resize",n),window.visualViewport?.removeEventListener("scroll",n),window.removeEventListener("resize",n)}}getViewportInsets(){}shareMessage(r){return Promise.resolve()}shareUrl(r,e){}async downloadFile(r,e){await J(r,e)}shareStory(r,e){return Promise.resolve()}trackConversionEvent(r,e){}trackPixelEvent(r,e){}copyTextToClipboard(r){return navigator.clipboard.writeText(r).catch(()=>{let e=document.createElement("textarea");e.value=r,e.style.position="fixed",document.body.appendChild(e),e.focus(),e.select();try{document.execCommand("copy")}catch{}document.body.removeChild(e)})}computeSafeArea(){let r=this.getViewportInsets?.(),e=Z();return D({environment:this.environment.safeArea,viewport:r,css:e})}bindCssVariables(r){}vibrateImpact(r){navigator.vibrate?.(10)}vibrateNotification(r){navigator.vibrate?.([10,30,10])}vibrateSelection(){navigator.vibrate?.(5)}onViewHide(r){return()=>{}}onViewRestore(r){return()=>{}}async showPopup(r){let e=[r.title,r.message].filter(Boolean).join(`
1
+ var ut=Object.defineProperty;var ft=(i,n,e)=>n in i?ut(i,n,{enumerable:!0,configurable:!0,writable:!0,value:e}):i[n]=e;var u=(i,n,e)=>ft(i,typeof n!="symbol"?n+"":n,e);var Y=class{constructor(){u(this,"disposers",new Set)}add(n){if(!n)return()=>{};let e=typeof n=="function"?n:typeof n.dispose=="function"?n.dispose.bind(n):void 0;if(!e)return()=>{};let t=!1,r=()=>{if(!t){t=!0;try{e()}catch(o){console.warn("[tvm-app-adapter] disposable failed:",o)}finally{this.disposers.delete(r)}}};return this.disposers.add(r),r}disposeAll(){for(let n of Array.from(this.disposers))try{n()}catch(e){console.warn("[tvm-app-adapter] disposeAll failed:",e)}this.disposers.clear()}};var Be=typeof window<"u"&&typeof document<"u";function mt(i,n){if(n&&n.trim().length>0)return n;try{let t=new URL(i).pathname.split("/").filter(Boolean).pop();if(t)return t}catch{}return"download"}function Te(i,n,{targetBlank:e}){if(!Be)return;let t=document.createElement("a");t.href=i,t.download=n,t.rel="noopener noreferrer",e&&(t.target="_blank"),document.body.appendChild(t),t.click(),document.body.removeChild(t)}async function J(i,n,e){if(!i)return;let t=mt(i,n),r=e?.preferBlob??!1;if(!Be){typeof window<"u"&&window.open(i,"_blank","noopener,noreferrer");return}if(r&&typeof fetch=="function")try{let o=await fetch(i,{credentials:"include"});if(!o.ok)throw new Error(`Failed to download file: ${o.status}`);let s=await o.blob(),p=URL.createObjectURL(s);Te(p,t,{targetBlank:!1}),setTimeout(()=>URL.revokeObjectURL(p),3e4);return}catch(o){console.warn("[tvm-app-adapter] blob download failed, falling back to direct link:",o)}Te(i,t,{targetBlank:!0})}var de=["top","right","bottom","left"],We={top:0,right:0,bottom:0,left:0};function pe(i){return{...i}}function N(i,n){if(n)for(let e of de){let t=n[e];typeof t=="number"&&Number.isFinite(t)&&(i[e]+=t)}}function Re(i,n){if(n)for(let e of de){let t=n[e];typeof t=="number"&&Number.isFinite(t)&&(i[e]=Math.max(i[e],t))}}function ht(i,n){return!i||!n?!1:de.every(e=>i[e]===n[e])}function D(i={}){let n=pe(We);return N(n,i.environment),i.viewport&&(N(n,i.viewport.safeArea),N(n,i.viewport.contentSafeArea)),N(n,i.additions),Re(n,i.css),Re(n,i.minimum),n}function Z(){if(typeof window>"u"||typeof document>"u")return;let i=getComputedStyle(document.documentElement),n=s=>{let p=parseFloat(i.getPropertyValue(s));return Number.isFinite(p)?p:0},e=n("--safe-area-inset-top"),t=n("--safe-area-inset-right"),r=n("--safe-area-inset-bottom"),o=n("--safe-area-inset-left");if(e||t||r||o)return{top:e,right:t,bottom:r,left:o}}function _e(i){if(!i)return;let n={...We};return N(n,i),n}function Ie(i){let n=i.windowObj??(typeof window<"u"?window:void 0);if(!n)return;let e=_e(i.getSafeArea());e&&(i.onChange(e),e=pe(e));let t=()=>{let o=_e(i.getSafeArea());o&&(!e||!ht(e,o))&&(i.onChange(o),e=pe(o))};t();let r=i.events??["resize","orientationchange"];for(let o of r)n.addEventListener(o,t);return()=>{for(let o of r)n.removeEventListener(o,t)}}var vt=["shell_ios","shell_android"];var ce=new Set,ue=new Set,fe=new Set,me=new Set,he=null,A=null,yt={platformFlag:"nativePlatform",pushTokenCallback:"nativePushToken",qrResultCallback:"nativeQRResult",deepLinkCallback:"nativeDeepLink",appActiveCallback:"nativeAppActive",appBackgroundCallback:"nativeAppBackground"},Fe={...yt},le={};function gt(i){he=i;for(let n of ce)try{n(i)}catch(e){console.warn("[tvm-app-adapter] push token listener failed:",e)}}function Oe(i){return vt.includes(i)}function wt(i){return i==="shell_ios"}function bt(i){return i==="shell_android"}function X(){let i=ye();if(!i)return;let n=i[Fe.platformFlag];if(n==="shell_ios"||n==="shell_android")return n}function ee(i){Pt();let n=typeof i=="function"?i:()=>i;return{async openNativeQR(){let e=n();return Oe(e)?Ct():Mt()},onPushToken(e){return ce.add(e),he&&queueMicrotask(()=>{try{e(he)}catch(t){console.warn("[tvm-app-adapter] push token listener failed:",t)}}),()=>ce.delete(e)},onDeepLink(e){return ue.add(e),()=>ue.delete(e)},onAppActive(e){return fe.add(e),()=>fe.delete(e)},onAppBackground(e){return me.add(e),()=>me.delete(e)}}}var At=ee(()=>X()??"web");function kt(i){return ge({type:"storeToken",payload:i})}function ve(){return ge({type:"requestPushPermission"})}function ye(){return typeof window>"u"?null:window}function St(){let i=ye();if(!i)return null;let n=i.NativeBridge;return!n||typeof n.postMessage!="function"?null:n}function ge(i){let n=St();if(!n)return!1;try{return n.postMessage(i),!0}catch(e){return console.warn("[tvm-app-adapter] NativeBridge.postMessage failed:",e),!1}}function Pt(){let i=ye();if(!i){le={};return}let n=i,e=(t,r)=>{let o=Fe[t],s=le[t];s&&s!==o&&delete n[s],le[t]=o,n[o]=r};e("pushTokenCallback",t=>{typeof t=="string"&&(console.log("[tvm-app-adapter] nativePushToken",t),gt(t))}),e("deepLinkCallback",t=>{if(typeof t=="string")for(let r of ue)try{r(t)}catch(o){console.warn("[tvm-app-adapter] deep link listener failed:",o)}}),e("appActiveCallback",()=>{for(let t of fe)try{t()}catch(r){console.warn("[tvm-app-adapter] app active listener failed:",r)}}),e("appBackgroundCallback",()=>{for(let t of me)try{t()}catch(r){console.warn("[tvm-app-adapter] app background listener failed:",r)}}),e("qrResultCallback",t=>{typeof t=="string"&&A&&(clearTimeout(A.timeoutId),A.resolve(t),A=null)})}function Ct(){return new Promise((i,n)=>{if(A&&(A.reject(new Error("QR request superseded by a new call.")),clearTimeout(A.timeoutId),A=null),!ge({type:"openNativeQR"})){n(new Error("Native bridge is unavailable."));return}let e=setTimeout(()=>{A&&(A.reject(new Error("Native QR request timed out.")),A=null)},6e4);A={resolve:i,reject:n,timeoutId:e}})}async function Mt(){if(typeof document>"u")throw new Error("QR scanning requires a browser environment.");let[{Html5Qrcode:i}]=await Promise.all([import("html5-qrcode")]);return new Promise((n,e)=>{let t=`native-shell-qr-${Date.now()}`,r=document.createElement("div");r.style.position="fixed",r.style.inset="0",r.style.background="rgba(0, 0, 0, 0.9)",r.style.display="flex",r.style.flexDirection="column",r.style.alignItems="center",r.style.justifyContent="center",r.style.zIndex="2147483647",r.style.backdropFilter="blur(2px)";let o=document.createElement("div");o.id=t,o.style.width="280px",o.style.height="280px",o.style.borderRadius="16px",o.style.overflow="hidden",o.style.position="relative";let s=document.createElement("button");s.type="button",s.textContent="\u2715",s.style.position="absolute",s.style.top="16px",s.style.right="16px",s.style.background="transparent",s.style.border="none",s.style.color="#fff",s.style.fontSize="28px",s.style.cursor="pointer",r.appendChild(s),r.appendChild(o),document.body.appendChild(r);let p=document.body.style.overflow;document.body.style.overflow="hidden";let d=!1,a=new i(t),l=async(m,c)=>{if(!d){d=!0;try{await a.stop();let b=a.clear;typeof b=="function"&&await Promise.resolve(b.call(a))}catch{}r.remove(),document.body.style.overflow=p,typeof m=="string"?n(m):e(c||new Error("QR scanning was cancelled."))}};s.addEventListener("click",()=>{l(void 0,new Error("QR scanning was cancelled by the user."))}),a.start({facingMode:"environment"},{fps:10,qrbox:{width:240,height:240}},m=>{l(m)},()=>{}).catch(m=>{let c=m instanceof Error?m:new Error("Unable to start HTML5 QR scanner.");l(void 0,c)})})}var S=class{constructor(n,e){u(this,"ready",!1);u(this,"environment");u(this,"listeners",new Set);u(this,"disposables",new Y);u(this,"shell");if(this.shell=ee(n),this.environment={platform:n,...e},typeof window<"u"){let t=()=>this.notifyEnvironmentChanged();if(window.addEventListener("resize",t),this.registerDisposable(()=>window.removeEventListener("resize",t)),n!=="web"){let r=this.applyScrollGuards();r&&this.registerDisposable(r)}}}async supports(n){switch(n){case"openExternalLink":return!0;default:return!1}}get platform(){return this.environment.platform}async init(n){this.ready=!0}isReady(){return this.ready}getEnvironment(){return{...this.environment}}destroy(){try{this.onDestroy()}finally{this.disposables.disposeAll(),this.listeners.clear(),this.ready=!1}}subscribe(n){return this.listeners.add(n),()=>{this.listeners.delete(n)}}async setColors(n){if(n.background&&(document.body.style.backgroundColor=n.background),n.header){let e=document.querySelector('meta[name="theme-color"]');e&&e.setAttribute("content",n.header)}}onBackButton(n){let e=()=>n();return window.addEventListener("popstate",e),()=>window.removeEventListener("popstate",e)}onPushToken(n){return this.shell.onPushToken(n)}onDeepLink(n){return this.shell.onDeepLink(n)}async openExternalLink(n){window.open(n,"_blank","noopener,noreferrer")}async openInternalLink(n){window.open(n,"_self","noopener,noreferrer")}async closeApp(){}setBackButtonVisibility(n){}onAppearanceChange(n){return n(this.environment.appearance),()=>{}}getInitData(){}getLaunchParams(){return{customLaunchParams:this.readCustomUrlParams()}}decodeStartParam(n){}requestFullscreen(){}onViewportChange(n){if(typeof window>"u")return()=>{};let e=()=>window.visualViewport?.height??window.innerHeight,t=()=>{let o=e();n({height:o,stableHeight:o})};t();let r=()=>t();return window.visualViewport?.addEventListener("resize",r),window.visualViewport?.addEventListener("scroll",r),window.addEventListener("resize",r),()=>{window.visualViewport?.removeEventListener("resize",r),window.visualViewport?.removeEventListener("scroll",r),window.removeEventListener("resize",r)}}getViewportInsets(){}shareMessage(n){return Promise.resolve()}shareUrl(n,e){}async downloadFile(n,e){await J(n,e)}shareStory(n,e){return Promise.resolve()}trackConversionEvent(n,e){}trackPixelEvent(n,e){}copyTextToClipboard(n){return navigator.clipboard.writeText(n).catch(()=>{let e=document.createElement("textarea");e.value=n,e.style.position="fixed",document.body.appendChild(e),e.focus(),e.select();try{document.execCommand("copy")}catch{}document.body.removeChild(e)})}computeSafeArea(){let n=this.getViewportInsets?.(),e=Z();return D({environment:this.environment.safeArea,viewport:n,css:e})}bindCssVariables(n){}vibrateImpact(n){navigator.vibrate?.(10)}vibrateNotification(n){navigator.vibrate?.([10,30,10])}vibrateSelection(){navigator.vibrate?.(5)}onViewHide(n){return()=>{}}onViewRestore(n){return()=>{}}async showPopup(n){let e=[n.title,n.message].filter(Boolean).join(`
2
2
 
3
- `);return window.alert(e),r.buttons?.[0]?.id??"ok"}async scanQRCode(r){return null}async requestPhone(){return null}async requestNotificationsPermission(){if(typeof Notification>"u"||typeof Notification.requestPermission!="function")return!1;try{return await Notification.requestPermission()==="granted"}catch(r){return console.warn("[tvm-app-adapter] requestNotificationsPermission fallback failed:",r),!1}}async addToHomeScreen(){return!1}async checkHomeScreenStatus(){return"unknown"}async denyNotifications(){return console.warn("[tvm-app-adapter] denyNotifications fallback is not supported in this environment."),!1}enableVerticalSwipes(){}disableVerticalSwipes(){}notifyEnvironmentChanged(){for(let r of this.listeners)try{r()}catch(e){console.warn("[tvm-app-adapter] environment listener failed:",e)}}onDestroy(){}registerDisposable(r){return this.disposables.add(r)}readCustomUrlParams(r){if(typeof window>"u")return{};let e={},t=i=>{let s=new Set;for(let[p]of i.entries())s.add(p);for(let p of s){if(r?.(p))continue;let d=i.getAll(p);d.length&&(e[p]=d.length===1?d[0]:d)}};t(new URLSearchParams(window.location.search));let n=window.location.hash.startsWith("#")?window.location.hash.slice(1):window.location.hash;return n&&n.includes("=")&&t(new URLSearchParams(n)),e}applyScrollGuards(){if(typeof document>"u")return;let r=document.documentElement,e=document.body;if(!r||!e)return;let t=r.style.overscrollBehaviorY,n=e.style.overscrollBehaviorY,i=e.style.touchAction;return r.style.overscrollBehaviorY="none",e.style.overscrollBehaviorY="none",e.style.touchAction="manipulation",()=>{r.style.overscrollBehaviorY=t,e.style.overscrollBehaviorY=n,e.style.touchAction=i}}};function k(){return window.WebApp}var q=class extends A{constructor(){super("max");c(this,"backHandlers",new Map);c(this,"initData");c(this,"initDataUnsafe")}async init(e){if(this.ready)return;let t=k();t?.ready?.(),this.initData=t?.initData,this.initDataUnsafe=t?.initDataUnsafe;let n={platform:"max",sdkVersion:t?.version,appVersion:t?.version,languageCode:t?.initDataUnsafe?.user?.language_code,isWebView:!0};this.environment=n,this.ready=!0}supports(e){let t=k();switch(e){case"haptics":return!!t?.HapticFeedback?.impactOccurred;case"qrScanner":return typeof t?.openCodeReader=="function";case"closeApp":return typeof t?.close=="function";case"backButton":return!!t?.BackButton?.onClick;case"backButtonVisibility":return!!(t?.BackButton?.show&&t.BackButton.hide);case"openInternalLink":return typeof t?.openMaxLink=="function";case"downloadFile":return typeof t?.downloadFile=="function";case"requestPhone":return t?typeof t.requestPhoneNumber=="function"||typeof window<"u":!1;case"popup":return!1;default:return!1}}getInitData(){return this.initData}getLaunchParams(){return{launchParams:this.initDataUnsafe,customLaunchParams:this.readCustomUrlParams()}}onBackButton(e){let t=k();if(!t?.BackButton?.onClick)return super.onBackButton(e);let n=()=>e(),i=t.BackButton.onClick(n);t.BackButton.show?.();let s=this.registerDisposable(()=>{typeof i=="function"?i():t.BackButton?.offClick?.(n),this.backHandlers.delete(e),this.backHandlers.size||t.BackButton?.hide?.()});return this.backHandlers.set(e,s),s}setBackButtonVisibility(e){let t=k();t?.BackButton&&(e?t.BackButton.show?.():t.BackButton.hide?.())}async openExternalLink(e){let t=k();if(t?.openExternalLink){t.openExternalLink(e);return}await super.openExternalLink(e)}async openInternalLink(e){let t=k();if(t?.openMaxLink){t.openMaxLink(e);return}await super.openInternalLink(e)}async closeApp(){let e=k();if(e?.close){e.close();return}await super.closeApp()}vibrateImpact(e){let t=k();if(!t?.HapticFeedback?.impactOccurred){super.vibrateImpact(e);return}t.HapticFeedback.impactOccurred(e).catch(n=>{console.warn("[mini-app-template] MAX impact haptic failed:",n)})}vibrateNotification(e){let t=k();if(!t?.HapticFeedback?.notificationOccurred){super.vibrateNotification(e);return}t.HapticFeedback.notificationOccurred(e).catch(n=>{console.warn("[mini-app-template] MAX notification haptic failed:",n)})}vibrateSelection(){let e=k();if(!e?.HapticFeedback?.selectionChanged){super.vibrateSelection();return}e.HapticFeedback.selectionChanged().catch(t=>{console.warn("[mini-app-template] MAX selection haptic failed:",t)})}async scanQRCode(e){let t=k();if(!t?.openCodeReader)return super.scanQRCode(e);try{return(await t.openCodeReader(e?.closeOnCapture!==!1))?.value??null}catch(n){return console.warn("[mini-app-template] MAX QR scanner failed:",n),null}}async requestPhone(){let e=k();if(e?.requestPhoneNumber)try{let t=await e.requestPhoneNumber();return this.extractPhone(t)}catch(t){return console.warn("[mini-app-template] MAX requestPhone failed:",t),null}return this.requestPhoneViaEvent()}async showPopup(e){return super.showPopup(e)}async downloadFile(e,t){let n=k();if(n?.downloadFile)try{await n.downloadFile(e,t);return}catch(i){console.warn("[mini-app-template] MAX downloadFile failed:",i)}await super.downloadFile(e,t)}async requestPhoneViaEvent(){if(typeof window>"u")return null;let e,t={providePromise:n=>{e=n}};if(window.dispatchEvent(new CustomEvent("WebAppRequestPhone",{detail:t})),!e)return console.warn("[mini-app-template] MAX requestPhone not handled: native promise missing"),null;try{let n=await e;return this.extractPhone(n)}catch(n){return console.warn("[mini-app-template] MAX requestPhone promise rejected:",n),null}}extractPhone(e){if(typeof e=="string")return e||null;if(!e||typeof e!="object")return null;let t=e.phone??e.phone_number??e.phoneNumber;if(typeof t=="string"&&t)return t;let n=e.contact;if(n&&typeof n=="object"){let i=n.phone??n.phone_number??n.phoneNumber;if(typeof i=="string"&&i)return i}return null}onDestroy(){this.backHandlers.clear(),super.onDestroy()}};var K=class extends A{constructor(r){super(r,{isWebView:!0,hasNativeQR:!0,hasPush:!0,hasWidgets:!0})}supports(r){switch(r){case"qrScanner":return!0;case"notifications":return!0;default:return super.supports(r)}}async scanQRCode(){try{return await this.shell.openNativeQR()??null}catch(r){return console.warn("[tvm-app-adapter] shell.openNativeQR failed:",r),null}}async requestNotificationsPermission(){return ge()}};import{backButton as V,emitEvent as Ke,hapticFeedback as re,init as Lt,initData as Ae,mockTelegramEnv as Tt,miniApp as g,openLink as ze,popup as Ue,qrScanner as ke,postEvent as Qe,retrieveLaunchParams as Pe,setDebug as _t,themeParams as _,viewport as M}from"@tma.js/sdk-react";import{decodeStartParam as je,closingBehavior as Ge,requestContact as $e,requestPhoneAccess as Se,swipeBehavior as x,viewport as R,shareURL as Ye,copyTextToClipboard as Xe,downloadFile as Je,shareStory as Ze,addToHomeScreen as F,checkHomeScreenStatus as et,on as tt,off as nt}from"@tma.js/sdk";function C(o){if(typeof o!="function")return!1;let r=o;if(typeof r.isAvailable=="function")try{return r.isAvailable()}catch(e){return console.warn("[tvm-app-adapter] feature availability check failed:",e),!1}return!0}function S(o,...r){if(!C(o))return{ok:!1};try{return{ok:!0,value:o(...r)}}catch(e){return console.warn("[tvm-app-adapter] feature call failed:",e),{ok:!1}}}async function ne(o){let{sdkViewport:r,fallbackMount:e}=o;if(r?.isSupported?.()){if(typeof r.isMounted=="function"&&r.isMounted())return;typeof r.mount=="function"&&await r.mount();return}typeof e=="function"&&await e()}async function qe(o){if(await ne(o),typeof o.bindCssVars=="function")try{o.bindCssVars(o.mapper)}catch(r){if(r instanceof Error&&/css variables are already bound/i.test(r.message))return;throw r}}var z=class extends A{constructor(){super("telegram");c(this,"backHandlers",new Map);c(this,"cssVariablesBound",!1);c(this,"appearanceListeners",new Set);c(this,"appearanceWatcherDispose");c(this,"viewHideListeners",new Set);c(this,"viewRestoreListeners",new Set);c(this,"activeWatcherDispose")}async init(e){if(this.ready)return;let t=!!e?.debug,n=!!e?.eruda,i=!!e?.mockForMacOS;if(_t(t),Lt(),g.isSupported()||console.warn("[tvm-app-adapter] miniApp feature is not supported; falling back to limited mode."),n&&typeof window<"u"&&window.eruda&&(window.eruda.init(),window.eruda.position({x:window.innerWidth-150,y:window.innerHeight-150})),i){let a=!1;Tt({onEvent(l,h){if(l.name==="web_app_request_theme"){let u={};return a?u=_.state():(a=!0,u||(u=Pe().tgWebAppThemeParams)),Ke("theme_changed",{theme_params:u})}if(l.name==="web_app_request_safe_area")return Ke("safe_area_changed",{left:0,top:0,right:0,bottom:0});h()}})}Ae.restore(),g.ready();let s=Pe(),p;try{p=g.isDark()?"dark":"light"}catch{p=void 0}let d={platform:"telegram",sdkVersion:s.tgWebAppVersion,languageCode:Ae.user()?.language_code,appearance:p,isWebView:!0};this.environment=d,this.notifyAppearance(d.appearance),V.mount.ifAvailable(),g.mount.isAvailable()&&(_.mount(),g.mount(),this.bindCssVariables()),await this.prepareViewport(),this.setupAppearanceWatcher(),this.setupActiveWatcher(),this.ready=!0}async setColors(e){let t={};if(e.header)if(g.setHeaderColor.isAvailable()){let n=g.setHeaderColor.supports?.("rgb")?e.header:"bg_color",{ok:i}=S(g.setHeaderColor,n);i||(t.header=e.header)}else t.header=e.header;if(e.background)if(g.setBgColor.isAvailable()){let{ok:n}=S(g.setBgColor,e.background);n||(t.background=e.background)}else t.background=e.background;if(e.footer)if(g.setBgColor.isAvailable()){let{ok:n}=S(g.setBottomBarColorFp,e.footer);n||(t.footer=e.footer)}else t.footer=e.footer;(t.header||t.background)&&await super.setColors(t)}copyTextToClipboard(e){return Xe(e)}onBackButton(e){if(!V.isSupported())return super.onBackButton(e);let t=V.onClick(()=>e()),n=this.registerDisposable(()=>{typeof t=="function"&&t(),this.backHandlers.delete(e),this.backHandlers.size||V.hide()});return this.backHandlers.set(e,n),n}async openExternalLink(e){try{ze(e,{tryInstantView:!0});return}catch{}await super.openExternalLink(e)}async openInternalLink(e){Qe("web_app_open_tg_link",{path_full:e})}enableDebug(e){try{e?Ge.enableConfirmation():Ge.disableConfirmation()}catch{}}supports(e){switch(e){case"haptics":return C(re.selectionChanged);case"popup":return C(Ue.show);case"qrScanner":return C(ke.open);case"closeApp":return C(g.close);case"backButton":return V.isSupported();case"backButtonVisibility":return V.hide.isSupported();case"bindCssVariables":return!0;case"openExternalLink":return C(ze);case"openInternalLink":return!0;case"requestFullscreen":return!!(typeof R.requestFullscreen=="function"||M.requestFullscreen?.isAvailable?.());case"verticalSwipes":return!!(x.enableVertical.isAvailable()||x.disableVertical.isAvailable());case"viewVisibility":return!0;case"shareUrl":return typeof Ye=="function";case"shareStory":return typeof Ze=="function";case"copyTextToClipboard":return typeof Xe=="function";case"downloadFile":return typeof Je=="function";case"addToHomeScreen":return typeof F?.isAvailable=="function"?F.isAvailable():typeof F=="function";case"checkHomeScreenStatus":return typeof et=="function";case"requestPhone":return!!(C(Se)||C($e));default:return!1}}bindCssVariables(e){if(!this.cssVariablesBound)try{_.bindCssVars(e),this.cssVariablesBound=!0}catch(t){if(t instanceof Error&&/css variables are already bound/i.test(t.message)){this.cssVariablesBound=!0;return}throw t}}vibrateImpact(e){this.supports("haptics")&&re.impactOccurred(e)}vibrateNotification(e){this.supports("haptics")&&re.notificationOccurred(e)}vibrateSelection(){this.supports("haptics")&&re.selectionChanged()}async showPopup(e){let t=S(Ue.show,{title:e.title,message:e.message,buttons:e.buttons?.map(i=>({id:i.id,text:i.text??i.id,type:i.type??"default"}))});return t.ok?await t.value??null:super.showPopup(e)}async scanQRCode(e){let t=null,n=e?.closeOnCapture??!0,i=S(ke.open,{onCaptured:s=>{t=s,n&&S(ke.close)}});return i.ok?(await i.value,t):super.scanQRCode(e)}async closeApp(){S(g.close).ok||await super.closeApp()}getInitData(){try{return Ae.raw()}catch{return}}getLaunchParams(){let e=this.readCustomUrlParams(n=>n.toLowerCase().startsWith("tgwebapp")),t={};try{let n=Pe(),i=n.tgWebAppStartParam;return typeof i=="string"&&i&&(t=this.normalizeDecodedStartParam(i)),{launchParams:n,customLaunchParams:{...e,...t}}}catch{return{customLaunchParams:{...e,...t}}}}decodeStartParam(e){try{return je(e)}catch{return}}requestFullscreen(){this.requestFullscreenInternal()}getViewportInsets(){try{let e=M.safeAreaInsets(),t=M.contentSafeAreaInsets();return{safeArea:e,contentSafeArea:t}}catch{return}}onViewportChange(e){let t=[],n=()=>typeof window<"u"?window.visualViewport?.height??window.innerHeight:0,i=d=>{let a=d?.height??this.safeHeightFromSdk(),l=d?.stableHeight??this.stableHeightFromSdk(),h=Number.isFinite(a)?a:n(),u=Number.isFinite(l)&&l>0?l:h;e({height:h,stableHeight:u})};(async()=>{try{await ne(this.getViewportMountOptions())}catch(d){console.warn("[tvm-app-adapter] ensureViewportMounted failed:",d)}})().finally(()=>i());let{sdkViewport:p}=this.getViewportMountOptions();if(typeof p.on=="function")try{let d=p.on("change",a=>i(a));typeof d=="function"&&t.push(d)}catch(d){console.warn("[tvm-app-adapter] viewport.on(change) subscription failed:",d)}try{typeof p.height?.sub=="function"&&t.push(p.height.sub(()=>i())),typeof p.stableHeight?.sub=="function"&&t.push(p.stableHeight.sub(()=>i()))}catch(d){console.warn("[tvm-app-adapter] viewport signal subscriptions failed:",d)}if(typeof window<"u"){let d=()=>i();window.visualViewport?.addEventListener("resize",d),window.addEventListener("resize",d),t.push(()=>{window.visualViewport?.removeEventListener("resize",d),window.removeEventListener("resize",d)})}return()=>{t.forEach(d=>{try{d()}catch{}})}}onAppearanceChange(e){return this.appearanceListeners.add(e),e(this.environment.appearance),()=>{this.appearanceListeners.delete(e)}}setBackButtonVisibility(e){V.isSupported()&&(e?V.show():V.hide())}enableVerticalSwipes(){try{let e=x;typeof e.isSupported=="function"&&e.isSupported()?(typeof e.isMounted=="function"&&!e.isMounted()&&e.mount?.(),e.enableVertical?.()):x.enableVertical.isAvailable()&&x.enableVertical()}catch(e){console.warn("[tvm-app-adapter] enableVerticalSwipes failed:",e)}}disableVerticalSwipes(){try{let e=x;typeof e.isSupported=="function"&&e.isSupported()?(typeof e.isMounted=="function"&&!e.isMounted()&&e.mount?.(),e.disableVertical?.()):x.disableVertical.isAvailable()&&x.disableVertical()}catch(e){console.warn("[tvm-app-adapter] disableVerticalSwipes failed:",e)}}onViewHide(e){return this.viewHideListeners.add(e),()=>{this.viewHideListeners.delete(e)}}onViewRestore(e){return this.viewRestoreListeners.add(e),()=>{this.viewRestoreListeners.delete(e)}}shareUrl(e,t){return Ye(e,t)}async downloadFile(e,t){let n=S(Je,e,t);if(n.ok)try{await n.value;return}catch(i){console.warn("[tvm-app-adapter] Telegram downloadFile failed:",i)}await super.downloadFile(e,t)}async shareStory(e,t){let n=t?.telegram?.text??t?.text,i=t?.telegram?.widgetLink??(t?.link?{url:t.link.url,...t.link.name?{name:t.link.name}:{}}:void 0);Ze(e,{...n?{text:n}:{},...i?{widgetLink:i}:{}})}async addToHomeScreen(){return(typeof F?.isAvailable=="function"?F.isAvailable():!0)?new Promise(t=>{let n=()=>{nt("home_screen_added",i),nt("home_screen_failed",s)},i=()=>{n(),t(!0)},s=()=>{n(),t(!1)};tt("home_screen_added",i),tt("home_screen_failed",s);try{F()}catch(p){n(),console.warn("[tvm-app-adapter] Telegram addToHomeScreen failed:",p),t(!1)}}):super.addToHomeScreen()}async checkHomeScreenStatus(){try{let e=await et();return typeof e=="string"?e:typeof e=="boolean"?e?"added":"not_added":"unknown"}catch(e){return console.warn("[tvm-app-adapter] Telegram checkHomeScreenStatus failed:",e),"unknown"}}async requestPhone(){let e=S($e);if(!e.ok)return super.requestPhone();if(Se){let t=S(Se);if(t.ok)try{await t.value}catch(n){console.warn("[tvm-app-adapter] Telegram requestPhone access failed:",n)}}try{let t=await e.value;if(!t||typeof t!="object")return null;let n=t.contact,i=n?.phoneNumber??n?.phone_number??n?.phone??t.phoneNumber??t.phone_number??t.phone;return typeof i=="string"&&i?i:null}catch(t){return console.warn("[tvm-app-adapter] Telegram requestPhone failed:",t),null}}setupAppearanceWatcher(){if(this.appearanceWatcherDispose?.(),typeof _.isDark?.sub=="function"){let e=_.isDark.sub(()=>{let t=_.isDark()?"dark":"light";this.environment.appearance=t,this.notifyAppearance(t)});this.appearanceWatcherDispose=this.registerDisposable(e)}}notifyAppearance(e){for(let t of this.appearanceListeners)t(e)}setupActiveWatcher(){this.activeWatcherDispose?.();let e=g.isActive,t=()=>{try{g.isActive()?this.notifyViewRestore():this.notifyViewHide()}catch(n){console.warn("[tvm-app-adapter] miniApp.isActive() failed:",n)}};if(typeof e?.sub=="function"){let n=e.sub(()=>t());this.activeWatcherDispose=this.registerDisposable(n),t();return}try{t()}catch{}}async prepareViewport(){try{await qe({...this.getViewportMountOptions(),bindCssVars:typeof M.bindCssVars=="function"?M.bindCssVars:void 0})}catch(e){console.warn("[tvm-app-adapter] prepareViewport failed:",e)}}async requestFullscreenInternal(){try{let e=this.getViewportMountOptions();await ne(e);let{sdkViewport:t}=e;(typeof t.isSupported=="function"?t.isSupported():!1)&&typeof t.requestFullscreen=="function"?await t.requestFullscreen():M.requestFullscreen&&M.requestFullscreen.isAvailable?.()?await M.requestFullscreen():Qe("web_app_request_fullscreen"),this.disableVerticalSwipes()}catch(e){console.warn("[tvm-app-adapter] Telegram requestFullscreen failed:",e)}}getViewportMountOptions(){return{sdkViewport:R,fallbackMount:async()=>{M.mount?.isAvailable?.()&&await M.mount()}}}safeHeightFromSdk(){try{if(typeof R.height=="function")return R.height()}catch{return}}stableHeightFromSdk(){try{if(typeof R.stableHeight=="function")return R.stableHeight()}catch{return}}notifyViewHide(){for(let e of this.viewHideListeners)try{e()}catch(t){console.warn("[tvm-app-adapter] onViewHide listener failed:",t)}}normalizeDecodedStartParam(e){let t;try{t=je(e)}catch{t=e}if(t&&typeof t=="object"&&!Array.isArray(t))return{...t};if(typeof t=="string"&&t){let n=this.parseQueryString(t);return Object.keys(n).length?n:{startParam:t}}return{}}parseQueryString(e){let t=e.startsWith("?")?e.slice(1):e,n=new URLSearchParams(t),i={},s=new Set;for(let[p]of n.entries())s.add(p);for(let p of s){let d=n.getAll(p);d.length&&(i[p]=d.length===1?d[0]:d)}return i}notifyViewRestore(){for(let e of this.viewRestoreListeners)try{e()}catch(t){console.warn("[tvm-app-adapter] onViewRestore listener failed:",t)}}onDestroy(){this.appearanceWatcherDispose?.(),this.appearanceWatcherDispose=void 0,this.activeWatcherDispose?.(),this.activeWatcherDispose=void 0,this.appearanceListeners.clear(),this.viewHideListeners.clear(),this.viewRestoreListeners.clear(),this.backHandlers.clear(),super.onDestroy()}};import f,{parseURLSearchParamsForGetLaunchParams as Rt}from"@vkontakte/vk-bridge";var Me=null;function ie(o){if(typeof o!="string"){Me=null;return}Me=o.trim()||null}function Ce(){return Me}async function rt(o,r){if(typeof r!="function")return!1;try{return await r(o)}catch(e){return console.warn("[tvm-app-adapter] bridge.supportsAsync failed:",e),!1}}var Ft=/^[a-z0-9][a-z0-9_.:-]{0,63}$/i,it="VK_ANALYTICS_EVENT",U=class extends A{constructor(){super("vk");c(this,"configSafeArea");c(this,"stopViewportTracking");c(this,"supportsAsync",typeof f.supportsAsync=="function"?f.supportsAsync.bind(f):void 0);c(this,"pixelCodeWarningShown",!1);c(this,"unsubscribe");c(this,"launchParams");c(this,"queryParams");c(this,"viewHideListeners",new Set);c(this,"viewRestoreListeners",new Set)}computeSafeArea(){let e=this.computeBaseSafeArea(),t=this.resolveOverlayInsets();return t?D({environment:e,minimum:t}):e}async init(e){if(this.ready)return;let t=a=>this.handleBridgeEvent(a);f.subscribe(t),this.unsubscribe=this.registerDisposable(()=>f.unsubscribe(t));let n;try{n=await f.send("VKWebAppGetConfig")}catch(a){console.warn("[tvm-app-adapter] VKWebAppGetConfig failed:",a)}try{let a=await f.send("VKWebAppInit");a&&"result"in a&&a.result===!1&&console.warn("[tvm-app-adapter] VKWebAppInit returned result=false.")}catch(a){throw console.error("[tvm-app-adapter] VKWebAppInit failed:",a),this.unsubscribe?.(),this.unsubscribe=void 0,a}let i;try{i=await f.send("VKWebAppGetLaunchParams")}catch(a){throw console.error("[tvm-app-adapter] VKWebAppGetLaunchParams failed:",a),this.unsubscribe?.(),this.unsubscribe=void 0,a}let s=typeof window<"u"?window.location.search:"",p=Rt(s);this.launchParams=i,this.queryParams=p,this.environment=this.composeEnvironment(i,p,n),this.configSafeArea=this.environment.safeArea;let d=this.computeSafeArea();this.environment.safeArea=d,this.applyAppearance(this.environment.appearance,n?.scheme),this.notifyEnvironmentChanged(),this.ready=!0,this.startViewportTracking()}async vibrateImpact(e){await this.supportsBridgeMethod("VKWebAppTapticImpactOccurred")&&f.send("VKWebAppTapticImpactOccurred",{style:e})}async vibrateNotification(e){await this.supportsBridgeMethod("VKWebAppTapticNotificationOccurred")&&f.send("VKWebAppTapticNotificationOccurred",{type:e})}async vibrateSelection(){await this.supportsBridgeMethod("VKWebAppTapticSelectionChanged")&&f.send("VKWebAppTapticSelectionChanged")}async setColors(e){let{header:t,background:n}=e;if((t||n)&&await this.supportsBridgeMethod("VKWebAppSetViewSettings")){let s=t?this.resolveStatusBarStyle(t):this.environment.appearance?.includes("dark")?"light":"dark";await f.send("VKWebAppSetViewSettings",{status_bar_style:s,...t?{action_bar_color:t}:{},...n?{navigation_bar_color:n}:{}})}await super.setColors(e)}getEnvironment(){return{...this.environment,isWebView:f.isWebView()}}getLaunchParams(){return this.launchParams?{launchParams:this.launchParams,customLaunchParams:this.readCustomUrlParams(e=>{let t=e.toLowerCase();return t.startsWith("vk_")||t==="sign"})}:{customLaunchParams:this.readCustomUrlParams(e=>{let t=e.toLowerCase();return t.startsWith("vk_")||t==="sign"})}}async openExternalLink(e){let t=document.createElement("a");t.href=e,t.target="_blank",t.rel="noopener noreferrer",t.style.display="none",document.body.appendChild(t),t.click(),t.remove()}async supports(e){switch(e){case"haptics":{let[t,n,i]=await Promise.all([this.supportsBridgeMethod("VKWebAppTapticImpactOccurred"),this.supportsBridgeMethod("VKWebAppTapticNotificationOccurred"),this.supportsBridgeMethod("VKWebAppTapticSelectionChanged")]);return t||n||i}case"qrScanner":return this.supportsBridgeMethod("VKWebAppOpenCodeReader");case"requestPhone":{let[t,n]=await Promise.all([this.supportsBridgeMethod("VKWebAppGetPhoneNumber"),this.supportsBridgeMethod("VKWebAppGetPersonalCard")]);return t||n}case"notifications":return this.supportsBridgeMethod("VKWebAppAllowNotifications");case"shareUrl":return this.supportsBridgeMethod("VKWebAppShare");case"shareStory":return this.supportsBridgeMethod("VKWebAppShowStoryBox");case"downloadFile":return this.supportsBridgeMethod("VKWebAppDownloadFile");case"addToHomeScreen":return this.supportsBridgeMethod("VKWebAppAddToHomeScreen");case"denyNotifications":return this.supportsBridgeMethod("VKWebAppDenyNotifications");case"openExternalLink":return!0;case"viewVisibility":return!0;default:return await super.supports(e)}}async requestPhone(){let[e,t]=await Promise.all([this.supportsBridgeMethod("VKWebAppGetPhoneNumber"),this.supportsBridgeMethod("VKWebAppGetPersonalCard")]);if(!e&&!t)return super.requestPhone();try{if(e){let p=(await f.send("VKWebAppGetPhoneNumber")).phone_number;return typeof p=="string"&&p?p:null}let i=(await f.send("VKWebAppGetPersonalCard",{type:["phone"]})).phone;return typeof i=="string"&&i?i:null}catch(n){return console.warn("[tvm-app-adapter] VK requestPhone failed:",n),null}}async requestNotificationsPermission(){if(!await this.supportsBridgeMethod("VKWebAppAllowNotifications"))return super.requestNotificationsPermission();try{let t=await f.send("VKWebAppAllowNotifications");return t&&typeof t=="object"&&"result"in t?!!t.result:!0}catch(t){return console.warn("[tvm-app-adapter] VK allow notifications failed:",t),!1}}async addToHomeScreen(){if(!await this.supportsBridgeMethod("VKWebAppAddToHomeScreen"))return console.warn("[tvm-app-adapter] VK addToHomeScreen not supported"),super.addToHomeScreen();try{let t=await f.send("VKWebAppAddToHomeScreen");return t&&typeof t=="object"&&"result"in t?!!t.result:!0}catch(t){return console.warn("[tvm-app-adapter] VK addToHomeScreen failed:",t),!1}}async denyNotifications(){if(!await this.supportsBridgeMethod("VKWebAppDenyNotifications"))return super.denyNotifications();try{let t=await f.send("VKWebAppDenyNotifications");return t&&typeof t=="object"&&"result"in t?!!t.result:!0}catch(t){return console.warn("[tvm-app-adapter] VK deny notifications failed:",t),!1}}async scanQRCode(e){if(!await this.supportsBridgeMethod("VKWebAppOpenCodeReader"))return super.scanQRCode(e);let n=null;try{let i=await f.send("VKWebAppOpenCodeReader");i.code_data&&(n=i.code_data)}catch(i){console.log(i)}return n}onViewHide(e){return this.viewHideListeners.add(e),()=>{this.viewHideListeners.delete(e)}}onViewRestore(e){return this.viewRestoreListeners.add(e),()=>{this.viewRestoreListeners.delete(e)}}async shareStory(e,t){let n=t,i=n?.vk,s=n?.link?{type:"url",text:"open",url:n.link.url}:void 0,p=n?.text?[{sticker_type:"native",sticker:{action_type:"text",action:{text:n.text,style:"classic",background_style:"none"},transform:{gravity:"center_bottom",translation_y:-.2}}}]:void 0,d={background_type:i?.backgroundType??"image",url:e,locked:i?.locked??!0,...i?.attachment??s?{attachment:i?.attachment??s}:{},...i?.stickers??p?{stickers:i?.stickers??p}:{}};await f.send("VKWebAppShowStoryBox",d)}shareUrl(e,t){this.shareUrlInternal(e,t)}async shareUrlInternal(e,t){if(!await this.supportsBridgeMethod("VKWebAppShare")){super.shareUrl(e,t??"");return}try{await f.send("VKWebAppShare",{link:e,...t?{text:t}:{}})}catch(i){console.warn("[tvm-app-adapter] VK shareUrl failed:",i),super.shareUrl(e,t??"")}}async downloadFile(e,t){if(!await this.supportsBridgeMethod("VKWebAppDownloadFile")){await super.downloadFile(e,t);return}try{if((await f.send("VKWebAppDownloadFile",{url:e,filename:t}))?.result===!1)throw new Error("VKWebAppDownloadFile returned result=false")}catch(i){console.warn("[tvm-app-adapter] VK downloadFile failed:",i),await super.downloadFile(e,t)}}trackConversionEvent(e,t){let n=this.normalizeAnalyticsEventName(e);if(!n)return;let i={method:"VKWebAppConversionHit",params:{event:n,params:this.normalizeAnalyticsPayload(t)}};this.dispatchAnalytics(i)}trackPixelEvent(e,t){let n=Ce();if(!n){this.pixelCodeWarningShown||(console.warn("[VKAnalytics] VK pixel code is not configured. Call configureVkPixel() before tracking."),this.pixelCodeWarningShown=!0);return}let i=this.normalizeAnalyticsEventName(e);if(!i)return;let s={method:"VKWebAppRetargetingPixel",params:{pixel_code:n,type:i,data:this.normalizeAnalyticsPayload(t)}};this.pixelCodeWarningShown=!1,this.dispatchAnalytics(s)}dispatchAnalytics(e){if(typeof f.isWebView=="function")try{if(!f.isWebView()){this.emitAnalyticsFallback(e);return}}catch(t){console.warn("[VKAnalytics] bridge.isWebView check failed:",t),this.emitAnalyticsFallback(e);return}this.safeBridgeSend(e.method,e.params)}emitAnalyticsFallback(e){if(typeof window>"u")return;let t={...e,timestamp:Date.now()};if(typeof window.dispatchEvent=="function"&&typeof window.CustomEvent=="function"){window.dispatchEvent(new CustomEvent(it,{detail:t}));return}try{window.postMessage({type:it,detail:t},"*")}catch(n){console.warn("[VKAnalytics] fallback dispatch failed",n)}}normalizeAnalyticsEventName(e){if(typeof e!="string")return null;let t=e.trim();return!t||!Ft.test(t)?(console.warn(`[VKAnalytics] Invalid event name: "${e}"`),null):t}normalizeAnalyticsPayload(e){return this.isPlainObject(e)?{...e}:{}}isPlainObject(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}async safeBridgeSend(e,t){try{if(!await this.supportsBridgeMethod(e))return;await f.send(e,t)}catch(n){console.warn(`[VKAnalytics] ${e} failed`,n)}}composeEnvironment(e,t,n){let i=t.vk_language??e.vk_language,s=t.vk_platform??e.vk_platform,p=t.vk_app_id??e.vk_app_id,d=typeof window<"u"&&typeof window.matchMedia=="function"?window.matchMedia("(prefers-color-scheme: dark)").matches:!1,a=this.normalizeAppearance(n?.appearance,n?.scheme)??(d?"dark":"light"),l=this.extractSafeAreaFromConfig(n);return{platform:"vk",sdkVersion:s?String(s):void 0,appVersion:typeof p=="number"?`vk-app-${p}`:void 0,languageCode:i?String(i):void 0,appearance:a,isWebView:f.isWebView(),safeArea:l}}handleBridgeEvent(e){let{type:t,data:n}=e.detail??{};if(t==="VKWebAppViewHide"){this.notifyVisibilityListeners(this.viewHideListeners);return}if(t==="VKWebAppViewRestore"){this.notifyVisibilityListeners(this.viewRestoreListeners);return}if(t==="VKWebAppUpdateConfig"&&n){let i=n;this.updateEnvironmentFromConfig(i)}}updateEnvironmentFromConfig(e){if(!this.environment)return;let t=this.normalizeAppearance(e.appearance,e.scheme),n=!1;t&&t!==this.environment.appearance&&(this.environment.appearance=t,n=!0);let i=this.environment.safeArea,s=this.extractSafeAreaFromConfig(e);s?(this.configSafeArea=s,this.environment.safeArea=s):(this.configSafeArea=void 0,this.environment.safeArea=void 0);let p=this.computeSafeArea()??{top:0,right:0,bottom:0,left:0},d=i;!d||d.top!==p.top||d.right!==p.right||d.bottom!==p.bottom||d.left!==p.left?(this.environment.safeArea=p,n=!0):this.environment.safeArea=i,this.applyAppearance(this.environment.appearance,e.scheme),n&&this.notifyEnvironmentChanged()}applyAppearance(e,t){if(!(typeof document>"u")&&(e&&(document.documentElement.dataset.vkAppearance=e,document.documentElement.classList.toggle("dark",e==="dark")),t&&(document.documentElement.dataset.vkScheme=t,!e))){let n=this.normalizeAppearance(void 0,t);document.documentElement.classList.toggle("dark",n==="dark")}}resolveStatusBarStyle(e){let t=e.replace("#",""),n=t.length===3?t.split("").map(a=>a+a).join(""):t.slice(0,6),i=parseInt(n.slice(0,2),16)/255,s=parseInt(n.slice(2,4),16)/255,p=parseInt(n.slice(4,6),16)/255;return .2126*i+.7152*s+.0722*p>.6?"dark":"light"}normalizeAppearance(e,t){let n=e?.toLowerCase();if(n==="dark"||n==="light")return n;let i=t?.toLowerCase();if(i)return i.includes("dark")||i.includes("space_gray")?"dark":"light"}extractSafeAreaFromConfig(e){let t=e&&"insets"in e?e.insets:void 0;if(!t)return;let{top:n=0,right:i=0,bottom:s=0,left:p=0}=t,d=[n,i,s,p].map(m=>typeof m=="number"?m:Number(m)||0);if(!d.some(m=>m!==0))return;let[l,h,u,b]=d;return{top:l,right:h,bottom:u,left:b}}notifyVisibilityListeners(e){for(let t of e)try{t()}catch(n){console.warn("[tvm-app-adapter] VK visibility listener failed:",n)}}computeBaseSafeArea(){return D({environment:this.configSafeArea,viewport:this.getViewportInsets?.(),css:Z()})}startViewportTracking(){this.stopViewportTracking?.();let e=Oe({getSafeArea:()=>this.computeSafeArea(),onChange:t=>{this.environment.safeArea=t,this.notifyEnvironmentChanged()}});e&&(this.stopViewportTracking=this.registerDisposable(e))}resolveOverlayInsets(){if(typeof window>"u"||!f.isWebView()||!this.isLikelyMobilePlatform())return;let e=window.innerWidth||document.documentElement?.clientWidth||0;if(!e||e>880)return;let i=!!window.matchMedia?.("(orientation: landscape)")?.matches;return{top:i?48:56,right:i?72:88}}isLikelyMobilePlatform(){let e=(this.resolveLaunchParam("vk_platform")??"").toLowerCase(),t=(this.resolveLaunchParam("vk_viewer_device")??"").toLowerCase();if(this.resolveLaunchParam("vk_is_layer")==="1")return!1;let i=/(iphone|ipad|ios|android|mobile)/i,s=/(desktop|web|tablet)/i,p=i.test(e)||i.test(t),d=s.test(e)||s.test(t);return p?!d:!1}resolveLaunchParam(e){let t=this.queryParams?.[e];if(typeof t=="string"&&t)return t;let n=this.launchParams?this.launchParams[e]:void 0;if(typeof n=="string"&&n)return n;if(typeof n=="number")return String(n);if(typeof n=="boolean")return n?"1":"0"}supportsBridgeMethod(e){return rt(e,this.supportsAsync)}onDestroy(){this.unsubscribe?.(),this.unsubscribe=void 0,this.stopViewportTracking?.(),this.stopViewportTracking=void 0,this.viewHideListeners.clear(),this.viewRestoreListeners.clear(),super.onDestroy()}};import It from"jsqr";var Q=class extends A{constructor(){super("web",{sdkVersion:navigator.userAgent,languageCode:navigator.language,isWebView:!1});c(this,"deferredPrompt",null);typeof window<"u"&&window.addEventListener("beforeinstallprompt",e=>{e.preventDefault(),this.deferredPrompt=e})}supports(e){switch(e){case"copyTextToClipboard":return typeof navigator<"u"&&!!navigator.clipboard?.writeText;case"downloadFile":return typeof document<"u";case"shareUrl":return typeof navigator<"u"&&(!!navigator.share||!!navigator.clipboard?.writeText);case"addToHomeScreen":return/android/i.test(navigator.userAgent)&&!!this.deferredPrompt;case"checkHomeScreenStatus":return!0;default:return super.supports(e)}}async downloadFile(e,t){try{await J(e,t,{preferBlob:!0})}catch(n){console.warn("[mini-app-template] Web downloadFile fallback:",n),await super.downloadFile(e,t)}}scanQRCode(e){return new Promise(async t=>{if(typeof document>"u"){t(null);return}let n=document.body.style.overflow,i=document.body.style.position,s=document.body.style.touchAction,p=document.body.style.width,d=document.documentElement.style.overflow;document.body.style.overflow="hidden",document.body.style.position="fixed",document.body.style.width="100%",document.body.style.touchAction="none",document.documentElement.style.overflow="hidden";let a=document.createElement("div");a.id="qr-overlay",a.style.position="fixed",a.style.top="0",a.style.left="0",a.style.right="0",a.style.bottom="0",a.style.zIndex="999999999",a.style.background="rgba(0,0,0,0.92)",a.style.width="100%",a.style.height="100%",a.style.display="flex",a.style.flexDirection="column",a.style.alignItems="center",a.style.justifyContent="center",a.style.gap="20px",a.style.padding="24px",a.style.boxSizing="border-box",a.style.overflow="hidden",a.style.backdropFilter="blur(3px)",document.body.appendChild(a);let l=document.createElement("button");l.innerText="\u2715",l.style.position="absolute",l.style.top="22px",l.style.right="22px",l.style.fontSize="32px",l.style.color="white",l.style.background="transparent",l.style.border="none",l.style.cursor="pointer",l.style.zIndex="9999999999",a.appendChild(l);let h=Math.min(Math.floor(Math.min(window.innerWidth,window.innerHeight)*.72),320),u=document.createElement("div");u.style.width=`${h}px`,u.style.height=`${h}px`,u.style.position="relative",u.style.flex="0 0 auto",u.style.borderRadius="18px",u.style.overflow="hidden",a.appendChild(u);let b=document.createElement("div");b.style.position="absolute",b.style.inset="0",b.style.zIndex="1",b.style.background="#000",u.appendChild(b);let m=document.createElement("video");m.setAttribute("playsinline","true"),m.autoplay=!0,m.muted=!0,m.style.width="100%",m.style.height="100%",m.style.objectFit="cover",m.style.position="absolute",m.style.inset="0",b.appendChild(m);let v=document.createElement("div");v.style.position="absolute",v.style.top="0",v.style.left="0",v.style.right="0",v.style.bottom="0",v.style.border="3px solid rgba(255,255,255,0.9)",v.style.borderRadius="18px",v.style.pointerEvents="none",v.style.zIndex="3",u.appendChild(v);let y=document.createElement("div");y.style.position="absolute",y.style.left="0",y.style.right="0",y.style.height="2px",y.style.background="rgba(255,255,255,0.85)",y.style.borderRadius="2px",y.style.animation="qr-line 2s infinite",y.style.zIndex="4",u.appendChild(y);let ae=document.createElement("style");ae.innerHTML=`
3
+ `);return window.alert(e),n.buttons?.[0]?.id??"ok"}async scanQRCode(n){return null}async requestPhone(){return null}async requestNotificationsPermission(){if(typeof Notification>"u"||typeof Notification.requestPermission!="function")return!1;try{return await Notification.requestPermission()==="granted"}catch(n){return console.warn("[tvm-app-adapter] requestNotificationsPermission fallback failed:",n),!1}}async addToHomeScreen(){return!1}async checkHomeScreenStatus(){return"unknown"}async denyNotifications(){return console.warn("[tvm-app-adapter] denyNotifications fallback is not supported in this environment."),!1}enableVerticalSwipes(){}disableVerticalSwipes(){}notifyEnvironmentChanged(){for(let n of this.listeners)try{n()}catch(e){console.warn("[tvm-app-adapter] environment listener failed:",e)}}onDestroy(){}registerDisposable(n){return this.disposables.add(n)}readCustomUrlParams(n){if(typeof window>"u")return{};let e={},t=o=>{let s=new Set;for(let[p]of o.entries())s.add(p);for(let p of s){if(n?.(p))continue;let d=o.getAll(p);d.length&&(e[p]=d.length===1?d[0]:d)}};t(new URLSearchParams(window.location.search));let r=window.location.hash.startsWith("#")?window.location.hash.slice(1):window.location.hash;return r&&r.includes("=")&&t(new URLSearchParams(r)),e}applyScrollGuards(){if(typeof document>"u")return;let n=document.documentElement,e=document.body;if(!n||!e)return;let t=n.style.overscrollBehaviorY,r=e.style.overscrollBehaviorY,o=e.style.touchAction;return n.style.overscrollBehaviorY="none",e.style.overscrollBehaviorY="none",e.style.touchAction="manipulation",()=>{n.style.overscrollBehaviorY=t,e.style.overscrollBehaviorY=r,e.style.touchAction=o}}};var K=class extends S{constructor(n){super(n,{isWebView:!0,hasNativeQR:!0,hasPush:!0,hasWidgets:!0})}async supports(n){switch(n){case"qrScanner":return!0;case"notifications":return!0;default:return super.supports(n)}}async scanQRCode(){try{return await this.shell.openNativeQR()??null}catch(n){return console.warn("[tvm-app-adapter] shell.openNativeQR failed:",n),null}}async requestNotificationsPermission(){return ve()}};import{backButton as x,emitEvent as Ne,hapticFeedback as ne,init as Vt,initData as we,mockTelegramEnv as xt,miniApp as y,openLink as De,popup as Ke,qrScanner as be,postEvent as qe,retrieveLaunchParams as Ae,setDebug as Et,themeParams as _,viewport as C}from"@tma.js/sdk-react";import{decodeStartParam as ze,closingBehavior as Qe,requestContact as ke,swipeBehavior as E,viewport as W,shareURL as Ue,copyTextToClipboard as Ge,downloadFile as je,shareStory as $e,addToHomeScreen as I,checkHomeScreenStatus as Ye,on as Je,off as Ze}from"@tma.js/sdk";function M(i){if(typeof i!="function")return!1;let n=i;if(typeof n.isAvailable=="function")try{return n.isAvailable()}catch(e){return console.warn("[tvm-app-adapter] feature availability check failed:",e),!1}return!0}function V(i,...n){if(!M(i))return{ok:!1};try{return{ok:!0,value:i(...n)}}catch(e){return console.warn("[tvm-app-adapter] feature call failed:",e),{ok:!1}}}async function te(i){let{sdkViewport:n,fallbackMount:e}=i;if(n?.isSupported?.()){if(typeof n.isMounted=="function"&&n.isMounted())return;typeof n.mount=="function"&&await n.mount();return}typeof e=="function"&&await e()}async function He(i){if(await te(i),typeof i.bindCssVars=="function")try{i.bindCssVars(i.mapper)}catch(n){if(n instanceof Error&&/css variables are already bound/i.test(n.message))return;throw n}}var q=class extends S{constructor(){super("telegram");u(this,"backHandlers",new Map);u(this,"cssVariablesBound",!1);u(this,"appearanceListeners",new Set);u(this,"appearanceWatcherDispose");u(this,"viewHideListeners",new Set);u(this,"viewRestoreListeners",new Set);u(this,"activeWatcherDispose")}async init(e){if(this.ready)return;let t=!!e?.debug,r=!!e?.eruda,o=!!e?.mockForMacOS;if(Et(t),Vt(),y.isSupported()||console.warn("[tvm-app-adapter] miniApp feature is not supported; falling back to limited mode."),r&&typeof window<"u"&&window.eruda&&(window.eruda.init(),window.eruda.position({x:window.innerWidth-150,y:window.innerHeight-150})),o){let a=!1;xt({onEvent(l,m){if(l.name==="web_app_request_theme"){let c={};return a?c=_.state():(a=!0,c||(c=Ae().tgWebAppThemeParams)),Ne("theme_changed",{theme_params:c})}if(l.name==="web_app_request_safe_area")return Ne("safe_area_changed",{left:0,top:0,right:0,bottom:0});m()}})}we.restore(),y.ready();let s=Ae(),p;try{p=y.isDark()?"dark":"light"}catch{p=void 0}let d={platform:"telegram",sdkVersion:s.tgWebAppVersion,languageCode:we.user()?.language_code,appearance:p,isWebView:!0};this.environment=d,this.notifyAppearance(d.appearance),x.mount.ifAvailable(),y.mount.isAvailable()&&(_.mount(),y.mount(),this.bindCssVariables()),await this.prepareViewport(),this.setupAppearanceWatcher(),this.setupActiveWatcher(),this.registerDisposable(this.onViewportChange(()=>this.notifyEnvironmentChanged())),this.ready=!0}async setColors(e){let t={};if(e.header)if(y.setHeaderColor.isAvailable()){let r=y.setHeaderColor.supports?.("rgb")?e.header:"bg_color",{ok:o}=V(y.setHeaderColor,r);o||(t.header=e.header)}else t.header=e.header;if(e.background)if(y.setBgColor.isAvailable()){let{ok:r}=V(y.setBgColor,e.background);r||(t.background=e.background)}else t.background=e.background;if(e.footer)if(y.setBgColor.isAvailable()){let{ok:r}=V(y.setBottomBarColorFp,e.footer);r||(t.footer=e.footer)}else t.footer=e.footer;(t.header||t.background)&&await super.setColors(t)}copyTextToClipboard(e){return Ge(e)}onBackButton(e){if(!x.isSupported())return super.onBackButton(e);let t=x.onClick(()=>e()),r=this.registerDisposable(()=>{typeof t=="function"&&t(),this.backHandlers.delete(e),this.backHandlers.size||x.hide()});return this.backHandlers.set(e,r),r}async openExternalLink(e){try{De(e,{tryInstantView:!0});return}catch{}await super.openExternalLink(e)}async openInternalLink(e){try{qe("web_app_open_tg_link",{path_full:e});return}catch(t){console.warn("[tvm-app-adapter] Telegram openInternalLink failed:",t)}await super.openInternalLink(e)}enableDebug(e){try{e?Qe.enableConfirmation():Qe.disableConfirmation()}catch{}}hapticsAvailable(){return M(ne.selectionChanged)}async supports(e){switch(e){case"haptics":return this.hapticsAvailable();case"popup":return M(Ke.show);case"qrScanner":return M(be.open);case"closeApp":return M(y.close);case"backButton":return x.isSupported();case"backButtonVisibility":return x.hide.isSupported();case"bindCssVariables":return!0;case"openExternalLink":return M(De);case"openInternalLink":return!0;case"requestFullscreen":return!!(typeof W.requestFullscreen=="function"||C.requestFullscreen?.isAvailable?.());case"verticalSwipes":return!!(E.enableVertical.isAvailable()||E.disableVertical.isAvailable());case"viewVisibility":return!0;case"shareUrl":return typeof Ue=="function";case"shareStory":return typeof $e=="function";case"copyTextToClipboard":return typeof Ge=="function";case"downloadFile":return typeof je=="function";case"addToHomeScreen":return typeof I?.isAvailable=="function"?I.isAvailable():typeof I=="function";case"checkHomeScreenStatus":return typeof Ye=="function";case"requestPhone":return M(ke);default:return!1}}bindCssVariables(e){if(!this.cssVariablesBound)try{_.bindCssVars(e),this.cssVariablesBound=!0}catch(t){if(t instanceof Error&&/css variables are already bound/i.test(t.message)){this.cssVariablesBound=!0;return}throw t}}vibrateImpact(e){this.hapticsAvailable()&&ne.impactOccurred(e)}vibrateNotification(e){this.hapticsAvailable()&&ne.notificationOccurred(e)}vibrateSelection(){this.hapticsAvailable()&&ne.selectionChanged()}async showPopup(e){let t=V(Ke.show,{title:e.title,message:e.message,buttons:e.buttons?.map(o=>({id:o.id,text:o.text??o.id,type:o.type??"default"}))});return t.ok?await t.value??null:super.showPopup(e)}async scanQRCode(e){let t=null,r=e?.closeOnCapture??!0,o=V(be.open,{onCaptured:s=>{t=s,r&&V(be.close)}});return o.ok?(await o.value,t):super.scanQRCode(e)}async closeApp(){V(y.close).ok||await super.closeApp()}getInitData(){try{return we.raw()}catch{return}}getLaunchParams(){let e=this.readCustomUrlParams(r=>r.toLowerCase().startsWith("tgwebapp")),t={};try{let r=Ae(),o=r.tgWebAppStartParam;return typeof o=="string"&&o&&(t=this.normalizeDecodedStartParam(o)),{launchParams:r,customLaunchParams:{...e,...t}}}catch{return{customLaunchParams:{...e,...t}}}}decodeStartParam(e){try{return ze(e)}catch{return}}requestFullscreen(){this.requestFullscreenInternal()}getViewportInsets(){try{let e=C.safeAreaInsets(),t=C.contentSafeAreaInsets();return{safeArea:e,contentSafeArea:t}}catch{return}}onViewportChange(e){let t=[],r=()=>typeof window<"u"?window.visualViewport?.height??window.innerHeight:0,o=d=>{let a=d?.height??this.safeHeightFromSdk(),l=d?.stableHeight??this.stableHeightFromSdk(),m=Number.isFinite(a)?a:r(),c=Number.isFinite(l)&&l>0?l:m;e({height:m,stableHeight:c})};(async()=>{try{await te(this.getViewportMountOptions())}catch(d){console.warn("[tvm-app-adapter] ensureViewportMounted failed:",d)}})().finally(()=>o());let{sdkViewport:p}=this.getViewportMountOptions();if(typeof p.on=="function")try{let d=p.on("change",a=>o(a));typeof d=="function"&&t.push(d)}catch(d){console.warn("[tvm-app-adapter] viewport.on(change) subscription failed:",d)}try{typeof p.height?.sub=="function"&&t.push(p.height.sub(()=>o())),typeof p.stableHeight?.sub=="function"&&t.push(p.stableHeight.sub(()=>o()))}catch(d){console.warn("[tvm-app-adapter] viewport signal subscriptions failed:",d)}if(typeof window<"u"){let d=()=>o();window.visualViewport?.addEventListener("resize",d),window.addEventListener("resize",d),t.push(()=>{window.visualViewport?.removeEventListener("resize",d),window.removeEventListener("resize",d)})}return()=>{t.forEach(d=>{try{d()}catch{}})}}onAppearanceChange(e){return this.appearanceListeners.add(e),e(this.environment.appearance),()=>{this.appearanceListeners.delete(e)}}setBackButtonVisibility(e){x.isSupported()&&(e?x.show():x.hide())}enableVerticalSwipes(){try{let e=E;typeof e.isSupported=="function"&&e.isSupported()?(typeof e.isMounted=="function"&&!e.isMounted()&&e.mount?.(),e.enableVertical?.()):E.enableVertical.isAvailable()&&E.enableVertical()}catch(e){console.warn("[tvm-app-adapter] enableVerticalSwipes failed:",e)}}disableVerticalSwipes(){try{let e=E;typeof e.isSupported=="function"&&e.isSupported()?(typeof e.isMounted=="function"&&!e.isMounted()&&e.mount?.(),e.disableVertical?.()):E.disableVertical.isAvailable()&&E.disableVertical()}catch(e){console.warn("[tvm-app-adapter] disableVerticalSwipes failed:",e)}}onViewHide(e){return this.viewHideListeners.add(e),()=>{this.viewHideListeners.delete(e)}}onViewRestore(e){return this.viewRestoreListeners.add(e),()=>{this.viewRestoreListeners.delete(e)}}shareUrl(e,t){return Ue(e,t)}async downloadFile(e,t){let r=V(je,e,t);if(r.ok)try{await r.value;return}catch(o){console.warn("[tvm-app-adapter] Telegram downloadFile failed:",o)}await super.downloadFile(e,t)}async shareStory(e,t){let r=t?.telegram?.text??t?.text,o=t?.telegram?.widgetLink??(t?.link?{url:t.link.url,...t.link.name?{name:t.link.name}:{}}:void 0);$e(e,{...r?{text:r}:{},...o?{widgetLink:o}:{}})}async addToHomeScreen(){return(typeof I?.isAvailable=="function"?I.isAvailable():!0)?new Promise(t=>{let r=()=>{Ze("home_screen_added",o),Ze("home_screen_failed",s)},o=()=>{r(),t(!0)},s=()=>{r(),t(!1)};Je("home_screen_added",o),Je("home_screen_failed",s);try{I()}catch(p){r(),console.warn("[tvm-app-adapter] Telegram addToHomeScreen failed:",p),t(!1)}}):super.addToHomeScreen()}async checkHomeScreenStatus(){try{let e=await Ye();return typeof e=="string"?e:typeof e=="boolean"?e?"added":"not_added":"unknown"}catch(e){return console.warn("[tvm-app-adapter] Telegram checkHomeScreenStatus failed:",e),"unknown"}}async requestPhone(){if(!M(ke))return super.requestPhone();try{let e=await ke();if(!e||typeof e!="object")return null;let t=e.contact,r=t?.phoneNumber??t?.phone_number??t?.phone??e.phoneNumber??e.phone_number??e.phone;return typeof r=="string"&&r?r:null}catch(e){return console.warn("[tvm-app-adapter] Telegram requestPhone failed:",e),null}}setupAppearanceWatcher(){if(this.appearanceWatcherDispose?.(),typeof _.isDark?.sub=="function"){let e=_.isDark.sub(()=>{let t=_.isDark()?"dark":"light";this.environment.appearance=t,this.notifyAppearance(t)});this.appearanceWatcherDispose=this.registerDisposable(e)}}notifyAppearance(e){for(let t of this.appearanceListeners)t(e)}setupActiveWatcher(){this.activeWatcherDispose?.();let e=y.isActive,t=()=>{try{y.isActive()?this.notifyViewRestore():this.notifyViewHide()}catch(r){console.warn("[tvm-app-adapter] miniApp.isActive() failed:",r)}};if(typeof e?.sub=="function"){let r=e.sub(()=>t());this.activeWatcherDispose=this.registerDisposable(r),t();return}try{t()}catch{}}async prepareViewport(){try{await He({...this.getViewportMountOptions(),bindCssVars:typeof C.bindCssVars=="function"?C.bindCssVars:void 0})}catch(e){console.warn("[tvm-app-adapter] prepareViewport failed:",e)}}async requestFullscreenInternal(){try{let e=this.getViewportMountOptions();await te(e);let{sdkViewport:t}=e;(typeof t.isSupported=="function"?t.isSupported():!1)&&typeof t.requestFullscreen=="function"?await t.requestFullscreen():C.requestFullscreen&&C.requestFullscreen.isAvailable?.()?await C.requestFullscreen():qe("web_app_request_fullscreen"),this.disableVerticalSwipes()}catch(e){console.warn("[tvm-app-adapter] Telegram requestFullscreen failed:",e)}}getViewportMountOptions(){return{sdkViewport:W,fallbackMount:async()=>{C.mount?.isAvailable?.()&&await C.mount()}}}safeHeightFromSdk(){try{if(typeof W.height=="function")return W.height()}catch{return}}stableHeightFromSdk(){try{if(typeof W.stableHeight=="function")return W.stableHeight()}catch{return}}notifyViewHide(){for(let e of this.viewHideListeners)try{e()}catch(t){console.warn("[tvm-app-adapter] onViewHide listener failed:",t)}}normalizeDecodedStartParam(e){let t;try{t=ze(e)}catch{t=e}if(t&&typeof t=="object"&&!Array.isArray(t))return{...t};if(typeof t=="string"&&t){let r=this.parseQueryString(t);return Object.keys(r).length?r:{startParam:t}}return{}}parseQueryString(e){let t=e.startsWith("?")?e.slice(1):e,r=new URLSearchParams(t),o={},s=new Set;for(let[p]of r.entries())s.add(p);for(let p of s){let d=r.getAll(p);d.length&&(o[p]=d.length===1?d[0]:d)}return o}notifyViewRestore(){for(let e of this.viewRestoreListeners)try{e()}catch(t){console.warn("[tvm-app-adapter] onViewRestore listener failed:",t)}}onDestroy(){this.appearanceWatcherDispose?.(),this.appearanceWatcherDispose=void 0,this.activeWatcherDispose?.(),this.activeWatcherDispose=void 0,this.appearanceListeners.clear(),this.viewHideListeners.clear(),this.viewRestoreListeners.clear(),this.backHandlers.clear(),super.onDestroy()}};import f,{parseURLSearchParamsForGetLaunchParams as Lt}from"@vkontakte/vk-bridge";var Se=null;function re(i){if(typeof i!="string"){Se=null;return}Se=i.trim()||null}function Pe(){return Se}async function Xe(i,n){if(typeof n!="function")return!1;try{return await n(i)}catch(e){return console.warn("[tvm-app-adapter] bridge.supportsAsync failed:",e),!1}}var Tt=/^[a-z0-9][a-z0-9_.:-]{0,63}$/i,et="VK_ANALYTICS_EVENT",z=class extends S{constructor(){super("vk");u(this,"configSafeArea");u(this,"stopViewportTracking");u(this,"supportsAsync",typeof f.supportsAsync=="function"?f.supportsAsync.bind(f):void 0);u(this,"pixelCodeWarningShown",!1);u(this,"unsubscribe");u(this,"launchParams");u(this,"queryParams");u(this,"viewHideListeners",new Set);u(this,"viewRestoreListeners",new Set)}computeSafeArea(){let e=this.computeBaseSafeArea(),t=this.resolveOverlayInsets();return t?D({environment:e,minimum:t}):e}async init(e){if(this.ready)return;let t=a=>this.handleBridgeEvent(a);f.subscribe(t),this.unsubscribe=this.registerDisposable(()=>f.unsubscribe(t));let r;try{r=await f.send("VKWebAppGetConfig")}catch(a){console.warn("[tvm-app-adapter] VKWebAppGetConfig failed:",a)}try{let a=await f.send("VKWebAppInit");a&&"result"in a&&a.result===!1&&console.warn("[tvm-app-adapter] VKWebAppInit returned result=false.")}catch(a){console.warn("[tvm-app-adapter] VKWebAppInit failed:",a)}let o;try{o=await f.send("VKWebAppGetLaunchParams")}catch(a){console.warn("[tvm-app-adapter] VKWebAppGetLaunchParams failed; falling back to URL params:",a)}let s=typeof window<"u"?window.location.search:"",p=Lt(s);this.launchParams=o,this.queryParams=p,this.environment=this.composeEnvironment(o,p,r),this.configSafeArea=this.environment.safeArea;let d=this.computeSafeArea();this.environment.safeArea=d,this.applyAppearance(this.environment.appearance,r?.scheme),this.notifyEnvironmentChanged(),this.ready=!0,this.startViewportTracking()}async vibrateImpact(e){await this.supportsBridgeMethod("VKWebAppTapticImpactOccurred")&&f.send("VKWebAppTapticImpactOccurred",{style:e})}async vibrateNotification(e){await this.supportsBridgeMethod("VKWebAppTapticNotificationOccurred")&&f.send("VKWebAppTapticNotificationOccurred",{type:e})}async vibrateSelection(){await this.supportsBridgeMethod("VKWebAppTapticSelectionChanged")&&f.send("VKWebAppTapticSelectionChanged")}async setColors(e){let{header:t,background:r}=e;if((t||r)&&await this.supportsBridgeMethod("VKWebAppSetViewSettings")){let s=t?this.resolveStatusBarStyle(t):this.environment.appearance?.includes("dark")?"light":"dark";await f.send("VKWebAppSetViewSettings",{status_bar_style:s,...t?{action_bar_color:t}:{},...r?{navigation_bar_color:r}:{}})}await super.setColors(e)}getEnvironment(){return{...this.environment,isWebView:f.isWebView()}}getLaunchParams(){return this.launchParams?{launchParams:this.launchParams,customLaunchParams:this.readCustomUrlParams(e=>{let t=e.toLowerCase();return t.startsWith("vk_")||t==="sign"})}:{customLaunchParams:this.readCustomUrlParams(e=>{let t=e.toLowerCase();return t.startsWith("vk_")||t==="sign"})}}async openExternalLink(e){let t=document.createElement("a");t.href=e,t.target="_blank",t.rel="noopener noreferrer",t.style.display="none",document.body.appendChild(t),t.click(),t.remove()}async closeApp(){if(!await this.supportsBridgeMethod("VKWebAppClose")){await super.closeApp();return}try{await f.send("VKWebAppClose",{status:"success"})}catch(t){console.warn("[tvm-app-adapter] VK closeApp failed:",t),await super.closeApp()}}async supports(e){switch(e){case"haptics":{let[t,r,o]=await Promise.all([this.supportsBridgeMethod("VKWebAppTapticImpactOccurred"),this.supportsBridgeMethod("VKWebAppTapticNotificationOccurred"),this.supportsBridgeMethod("VKWebAppTapticSelectionChanged")]);return t||r||o}case"qrScanner":return this.supportsBridgeMethod("VKWebAppOpenCodeReader");case"requestPhone":{let[t,r]=await Promise.all([this.supportsBridgeMethod("VKWebAppGetPhoneNumber"),this.supportsBridgeMethod("VKWebAppGetPersonalCard")]);return t||r}case"notifications":return this.supportsBridgeMethod("VKWebAppAllowNotifications");case"shareUrl":return this.supportsBridgeMethod("VKWebAppShare");case"shareStory":return this.supportsBridgeMethod("VKWebAppShowStoryBox");case"downloadFile":return this.supportsBridgeMethod("VKWebAppDownloadFile");case"addToHomeScreen":return this.supportsBridgeMethod("VKWebAppAddToHomeScreen");case"denyNotifications":return this.supportsBridgeMethod("VKWebAppDenyNotifications");case"closeApp":return this.supportsBridgeMethod("VKWebAppClose");case"openExternalLink":return!0;case"viewVisibility":return!0;default:return await super.supports(e)}}async requestPhone(){let[e,t]=await Promise.all([this.supportsBridgeMethod("VKWebAppGetPhoneNumber"),this.supportsBridgeMethod("VKWebAppGetPersonalCard")]);if(!e&&!t)return super.requestPhone();try{if(e){let p=(await f.send("VKWebAppGetPhoneNumber")).phone_number;return typeof p=="string"&&p?p:null}let o=(await f.send("VKWebAppGetPersonalCard",{type:["phone"]})).phone;return typeof o=="string"&&o?o:null}catch(r){return console.warn("[tvm-app-adapter] VK requestPhone failed:",r),null}}async requestNotificationsPermission(){if(!await this.supportsBridgeMethod("VKWebAppAllowNotifications"))return super.requestNotificationsPermission();try{let t=await f.send("VKWebAppAllowNotifications");return t&&typeof t=="object"&&"result"in t?!!t.result:!0}catch(t){return console.warn("[tvm-app-adapter] VK allow notifications failed:",t),!1}}async addToHomeScreen(){if(!await this.supportsBridgeMethod("VKWebAppAddToHomeScreen"))return console.warn("[tvm-app-adapter] VK addToHomeScreen not supported"),super.addToHomeScreen();try{let t=await f.send("VKWebAppAddToHomeScreen");return t&&typeof t=="object"&&"result"in t?!!t.result:!0}catch(t){return console.warn("[tvm-app-adapter] VK addToHomeScreen failed:",t),!1}}async denyNotifications(){if(!await this.supportsBridgeMethod("VKWebAppDenyNotifications"))return super.denyNotifications();try{let t=await f.send("VKWebAppDenyNotifications");return t&&typeof t=="object"&&"result"in t?!!t.result:!0}catch(t){return console.warn("[tvm-app-adapter] VK deny notifications failed:",t),!1}}async scanQRCode(e){if(!await this.supportsBridgeMethod("VKWebAppOpenCodeReader"))return super.scanQRCode(e);try{let r=await f.send("VKWebAppOpenCodeReader");return r.code_data?r.code_data:null}catch(r){return console.warn("[tvm-app-adapter] VK scanQRCode failed:",r),super.scanQRCode(e)}}onViewHide(e){return this.viewHideListeners.add(e),()=>{this.viewHideListeners.delete(e)}}onViewRestore(e){return this.viewRestoreListeners.add(e),()=>{this.viewRestoreListeners.delete(e)}}async shareStory(e,t){let r=t,o=r?.vk,s=r?.link?{type:"url",text:"open",url:r.link.url}:void 0,p=r?.text?[{sticker_type:"native",sticker:{action_type:"text",action:{text:r.text,style:"classic",background_style:"none"},transform:{gravity:"center_bottom",translation_y:-.2}}}]:void 0,d={background_type:o?.backgroundType??"image",url:e,locked:o?.locked??!0,...o?.attachment??s?{attachment:o?.attachment??s}:{},...o?.stickers??p?{stickers:o?.stickers??p}:{}};await f.send("VKWebAppShowStoryBox",d)}shareUrl(e,t){this.shareUrlInternal(e,t)}async shareUrlInternal(e,t){if(!await this.supportsBridgeMethod("VKWebAppShare")){super.shareUrl(e,t??"");return}try{await f.send("VKWebAppShare",{link:e,...t?{text:t}:{}})}catch(o){console.warn("[tvm-app-adapter] VK shareUrl failed:",o),super.shareUrl(e,t??"")}}async downloadFile(e,t){if(!await this.supportsBridgeMethod("VKWebAppDownloadFile")){await super.downloadFile(e,t);return}try{if((await f.send("VKWebAppDownloadFile",{url:e,filename:t}))?.result===!1)throw new Error("VKWebAppDownloadFile returned result=false")}catch(o){console.warn("[tvm-app-adapter] VK downloadFile failed:",o),await super.downloadFile(e,t)}}trackConversionEvent(e,t){let r=this.normalizeAnalyticsEventName(e);if(!r)return;let o={method:"VKWebAppConversionHit",params:{event:r,params:this.normalizeAnalyticsPayload(t)}};this.dispatchAnalytics(o)}trackPixelEvent(e,t){let r=Pe();if(!r){this.pixelCodeWarningShown||(console.warn("[VKAnalytics] VK pixel code is not configured. Call configureVkPixel() before tracking."),this.pixelCodeWarningShown=!0);return}let o=this.normalizeAnalyticsEventName(e);if(!o)return;let s={method:"VKWebAppRetargetingPixel",params:{pixel_code:r,type:o,data:this.normalizeAnalyticsPayload(t)}};this.pixelCodeWarningShown=!1,this.dispatchAnalytics(s)}dispatchAnalytics(e){if(typeof f.isWebView=="function")try{if(!f.isWebView()){this.emitAnalyticsFallback(e);return}}catch(t){console.warn("[VKAnalytics] bridge.isWebView check failed:",t),this.emitAnalyticsFallback(e);return}this.safeBridgeSend(e.method,e.params)}emitAnalyticsFallback(e){if(typeof window>"u")return;let t={...e,timestamp:Date.now()};if(typeof window.dispatchEvent=="function"&&typeof window.CustomEvent=="function"){window.dispatchEvent(new CustomEvent(et,{detail:t}));return}try{window.postMessage({type:et,detail:t},"*")}catch(r){console.warn("[VKAnalytics] fallback dispatch failed",r)}}normalizeAnalyticsEventName(e){if(typeof e!="string")return null;let t=e.trim();return!t||!Tt.test(t)?(console.warn(`[VKAnalytics] Invalid event name: "${e}"`),null):t}normalizeAnalyticsPayload(e){return this.isPlainObject(e)?{...e}:{}}isPlainObject(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}async safeBridgeSend(e,t){try{if(!await this.supportsBridgeMethod(e))return;await f.send(e,t)}catch(r){console.warn(`[VKAnalytics] ${e} failed`,r)}}composeEnvironment(e,t,r){let o=t.vk_language??e?.vk_language,s=t.vk_platform??e?.vk_platform,p=t.vk_app_id??e?.vk_app_id,d=typeof window<"u"&&typeof window.matchMedia=="function"?window.matchMedia("(prefers-color-scheme: dark)").matches:!1,a=this.normalizeAppearance(r?.appearance,r?.scheme)??(d?"dark":"light"),l=this.extractSafeAreaFromConfig(r);return{platform:"vk",sdkVersion:s?String(s):void 0,appVersion:typeof p=="number"?`vk-app-${p}`:void 0,languageCode:o?String(o):void 0,appearance:a,isWebView:f.isWebView(),safeArea:l}}handleBridgeEvent(e){let{type:t,data:r}=e.detail??{};if(t==="VKWebAppViewHide"){this.notifyVisibilityListeners(this.viewHideListeners);return}if(t==="VKWebAppViewRestore"){this.notifyVisibilityListeners(this.viewRestoreListeners);return}if(t==="VKWebAppUpdateConfig"&&r){let o=r;this.updateEnvironmentFromConfig(o)}}updateEnvironmentFromConfig(e){if(!this.environment)return;let t=this.normalizeAppearance(e.appearance,e.scheme),r=!1;t&&t!==this.environment.appearance&&(this.environment.appearance=t,r=!0);let o=this.environment.safeArea,s=this.extractSafeAreaFromConfig(e);s?(this.configSafeArea=s,this.environment.safeArea=s):(this.configSafeArea=void 0,this.environment.safeArea=void 0);let p=this.computeSafeArea()??{top:0,right:0,bottom:0,left:0},d=o;!d||d.top!==p.top||d.right!==p.right||d.bottom!==p.bottom||d.left!==p.left?(this.environment.safeArea=p,r=!0):this.environment.safeArea=o,this.applyAppearance(this.environment.appearance,e.scheme),r&&this.notifyEnvironmentChanged()}applyAppearance(e,t){if(!(typeof document>"u")&&(e&&(document.documentElement.dataset.vkAppearance=e,document.documentElement.classList.toggle("dark",e==="dark")),t&&(document.documentElement.dataset.vkScheme=t,!e))){let r=this.normalizeAppearance(void 0,t);document.documentElement.classList.toggle("dark",r==="dark")}}resolveStatusBarStyle(e){let t=e.replace("#",""),r=t.length===3?t.split("").map(a=>a+a).join(""):t.slice(0,6),o=parseInt(r.slice(0,2),16)/255,s=parseInt(r.slice(2,4),16)/255,p=parseInt(r.slice(4,6),16)/255;return .2126*o+.7152*s+.0722*p>.6?"dark":"light"}normalizeAppearance(e,t){let r=e?.toLowerCase();if(r==="dark"||r==="light")return r;let o=t?.toLowerCase();if(o)return o.includes("dark")||o.includes("space_gray")?"dark":"light"}extractSafeAreaFromConfig(e){let t=e&&"insets"in e?e.insets:void 0;if(!t)return;let{top:r=0,right:o=0,bottom:s=0,left:p=0}=t,d=[r,o,s,p].map(v=>typeof v=="number"?v:Number(v)||0);if(!d.some(v=>v!==0))return;let[l,m,c,b]=d;return{top:l,right:m,bottom:c,left:b}}notifyVisibilityListeners(e){for(let t of e)try{t()}catch(r){console.warn("[tvm-app-adapter] VK visibility listener failed:",r)}}computeBaseSafeArea(){return D({environment:this.configSafeArea,viewport:this.getViewportInsets?.(),css:Z()})}startViewportTracking(){this.stopViewportTracking?.();let e=Ie({getSafeArea:()=>this.computeSafeArea(),onChange:t=>{this.environment.safeArea=t,this.notifyEnvironmentChanged()}});e&&(this.stopViewportTracking=this.registerDisposable(e))}resolveOverlayInsets(){if(typeof window>"u"||!f.isWebView()||!this.isLikelyMobilePlatform())return;let e=window.innerWidth||document.documentElement?.clientWidth||0;if(!e||e>880)return;let o=!!window.matchMedia?.("(orientation: landscape)")?.matches;return{top:o?48:56,right:o?72:88}}isLikelyMobilePlatform(){let e=(this.resolveLaunchParam("vk_platform")??"").toLowerCase(),t=(this.resolveLaunchParam("vk_viewer_device")??"").toLowerCase();if(this.resolveLaunchParam("vk_is_layer")==="1")return!1;let o=/(iphone|ipad|ios|android|mobile)/i,s=/(desktop|web|tablet)/i,p=o.test(e)||o.test(t),d=s.test(e)||s.test(t);return p?!d:!1}resolveLaunchParam(e){let t=this.queryParams?.[e];if(typeof t=="string"&&t)return t;let r=this.launchParams?this.launchParams[e]:void 0;if(typeof r=="string"&&r)return r;if(typeof r=="number")return String(r);if(typeof r=="boolean")return r?"1":"0"}supportsBridgeMethod(e){return Xe(e,this.supportsAsync)}onDestroy(){this.unsubscribe?.(),this.unsubscribe=void 0,this.stopViewportTracking?.(),this.stopViewportTracking=void 0,this.viewHideListeners.clear(),this.viewRestoreListeners.clear(),super.onDestroy()}};import Bt from"jsqr";var Q=class extends S{constructor(){super("web",{sdkVersion:navigator.userAgent,languageCode:navigator.language,isWebView:!1});u(this,"deferredPrompt",null);typeof window<"u"&&window.addEventListener("beforeinstallprompt",e=>{e.preventDefault(),this.deferredPrompt=e})}async supports(e){switch(e){case"copyTextToClipboard":return typeof navigator<"u"&&!!navigator.clipboard?.writeText;case"downloadFile":return typeof document<"u";case"shareUrl":return typeof navigator<"u"&&(!!navigator.share||!!navigator.clipboard?.writeText);case"addToHomeScreen":return/android/i.test(navigator.userAgent)&&!!this.deferredPrompt;case"checkHomeScreenStatus":return!0;default:return super.supports(e)}}async downloadFile(e,t){try{await J(e,t,{preferBlob:!0})}catch(r){console.warn("[mini-app-template] Web downloadFile fallback:",r),await super.downloadFile(e,t)}}scanQRCode(e){return new Promise(async t=>{if(typeof document>"u"){t(null);return}let r=document.body.style.overflow,o=document.body.style.position,s=document.body.style.touchAction,p=document.body.style.width,d=document.documentElement.style.overflow;document.body.style.overflow="hidden",document.body.style.position="fixed",document.body.style.width="100%",document.body.style.touchAction="none",document.documentElement.style.overflow="hidden";let a=document.createElement("div");a.id="qr-overlay",a.style.position="fixed",a.style.top="0",a.style.left="0",a.style.right="0",a.style.bottom="0",a.style.zIndex="999999999",a.style.background="rgba(0,0,0,0.92)",a.style.width="100%",a.style.height="100%",a.style.display="flex",a.style.flexDirection="column",a.style.alignItems="center",a.style.justifyContent="center",a.style.gap="20px",a.style.padding="24px",a.style.boxSizing="border-box",a.style.overflow="hidden",a.style.backdropFilter="blur(3px)",document.body.appendChild(a);let l=document.createElement("button");l.innerText="\u2715",l.style.position="absolute",l.style.top="22px",l.style.right="22px",l.style.fontSize="32px",l.style.color="white",l.style.background="transparent",l.style.border="none",l.style.cursor="pointer",l.style.zIndex="9999999999",a.appendChild(l);let m=Math.min(Math.floor(Math.min(window.innerWidth,window.innerHeight)*.72),320),c=document.createElement("div");c.style.width=`${m}px`,c.style.height=`${m}px`,c.style.position="relative",c.style.flex="0 0 auto",c.style.borderRadius="18px",c.style.overflow="hidden",a.appendChild(c);let b=document.createElement("div");b.style.position="absolute",b.style.inset="0",b.style.zIndex="1",b.style.background="#000",c.appendChild(b);let v=document.createElement("video");v.setAttribute("playsinline","true"),v.autoplay=!0,v.muted=!0,v.style.width="100%",v.style.height="100%",v.style.objectFit="cover",v.style.position="absolute",v.style.inset="0",b.appendChild(v);let g=document.createElement("div");g.style.position="absolute",g.style.top="0",g.style.left="0",g.style.right="0",g.style.bottom="0",g.style.border="3px solid rgba(255,255,255,0.9)",g.style.borderRadius="18px",g.style.pointerEvents="none",g.style.zIndex="3",c.appendChild(g);let h=document.createElement("div");h.style.position="absolute",h.style.left="0",h.style.right="0",h.style.height="2px",h.style.background="rgba(255,255,255,0.85)",h.style.borderRadius="2px",h.style.animation="qr-line 2s infinite",h.style.zIndex="4",c.appendChild(h);let P=document.createElement("style");P.innerHTML=`
4
4
  @keyframes qr-line {
5
5
  0% { top: 0; }
6
6
  50% { top: calc(100% - 2px); }
7
7
  100% { top: 0; }
8
8
  }
9
- `,document.head.appendChild(ae);let I=document.createElement("div");I.innerText="\u041D\u0430\u0432\u0435\u0434\u0438\u0442\u0435 \u043A\u0430\u043C\u0435\u0440\u0443 \u043D\u0430 QR-\u043A\u043E\u0434",I.style.color="white",I.style.fontSize="17px",I.style.opacity="0.9",a.appendChild(I);let w=document.createElement("button");w.innerText="\u0417\u0430\u043A\u0440\u044B\u0442\u044C",w.style.minWidth=`${Math.min(h,220)}px`,w.style.height="48px",w.style.padding="0 20px",w.style.border="1px solid rgba(255,255,255,0.24)",w.style.borderRadius="14px",w.style.background="rgba(255,255,255,0.12)",w.style.color="white",w.style.fontSize="16px",w.style.fontWeight="600",w.style.cursor="pointer",w.style.backdropFilter="blur(8px)",a.appendChild(w);let se=document.createElement("canvas"),pe=se.getContext("2d",{willReadFrequently:!0}),B=null,W=null,Be=0,de=!1,Ee=async E=>{de||(de=!0,W!==null&&(cancelAnimationFrame(W),W=null),B&&(B.getTracks().forEach(H=>H.stop()),B=null),m.srcObject=null,a.remove(),ae.remove(),document.body.style.overflow=n,document.body.style.position=i,document.body.style.width=p,document.body.style.touchAction=s,document.documentElement.style.overflow=d,t(E))},mt=this.registerDisposable(()=>{Ee(null)}),Y=E=>{Ee(E),mt()};l.onclick=()=>Y(null),w.onclick=()=>Y(null);try{let E=[{video:{facingMode:{ideal:"environment"},width:{ideal:1920},height:{ideal:1080},aspectRatio:{ideal:1.7777777778}},audio:!1},{video:{facingMode:"environment",width:{ideal:1280},height:{ideal:720}},audio:!1},{video:!0,audio:!1}],H=null;for(let T of E)try{B=await navigator.mediaDevices.getUserMedia(T);break}catch(L){H=L}if(!B)throw H instanceof Error?H:new Error("Unable to access camera");let[Le]=B.getVideoTracks();if(Le)try{let T=[{focusMode:"continuous"},{exposureMode:"continuous"},{whiteBalanceMode:"continuous"}];await Le.applyConstraints({advanced:T})}catch{}m.srcObject=B,await m.play();let Te=T=>{if(!de){if(T-Be>=80&&pe&&m.readyState>=HTMLMediaElement.HAVE_CURRENT_DATA){let L=m.videoWidth,O=m.videoHeight;if(L>0&&O>0){se.width=L,se.height=O,pe.drawImage(m,0,0,L,O);let ht=pe.getImageData(0,0,L,O),_e=It(ht.data,L,O,{inversionAttempts:"attemptBoth"});if(_e?.data){Y(_e.data);return}Be=T}}W=requestAnimationFrame(Te)}};W=requestAnimationFrame(Te)}catch(E){console.error("QR Start error",E),Y(null)}})}shareUrl(e,t){if(navigator.share)try{navigator.share({title:t,text:t,url:e});return}catch(i){console.warn("Share cancelled or failed:",i)}let n=t?`${t}
10
- ${e}`:e;this.copyTextToClipboard(n).catch(i=>{console.warn("Share fallback (clipboard) failed:",i)})}async addToHomeScreen(){if(!/android/i.test(navigator.userAgent)||!this.deferredPrompt)return super.addToHomeScreen();try{this.deferredPrompt.prompt();let t=await this.deferredPrompt.userChoice;return this.deferredPrompt=null,t?.outcome==="accepted"}catch(t){return console.warn("[tvm-app-adapter] Web addToHomeScreen failed:",t),this.deferredPrompt=null,!1}}async checkHomeScreenStatus(){try{return typeof window<"u"&&window.matchMedia?.("(display-mode: standalone)").matches||typeof navigator<"u"&&navigator.standalone===!0?"added":"unknown"}catch{return"unknown"}}};var ot="mini-app-adapter:confirmed-platform",Wt=1800*1e3;function oe(){if(typeof window>"u")return"web";let o=new URLSearchParams(window.location.search),r=(()=>{let v=window.location.hash.startsWith("#")?window.location.hash.slice(1):window.location.hash;return new URLSearchParams(v)})(),e=v=>o.get(v)??r.get(v),t=(...v)=>v.some(y=>e(y)),n=()=>{try{let v=window.sessionStorage.getItem(ot);if(!v)return null;let y=JSON.parse(v);return!y?.platform||typeof y.ts!="number"||Date.now()-y.ts>Wt?null:y.platform}catch{return null}},i=v=>{if(v!=="web")try{window.sessionStorage.setItem(ot,JSON.stringify({platform:v,ts:Date.now()}))}catch{}},s=ee();if(s)return i(s),s;let p=navigator.userAgent.toLowerCase();if(typeof window.NativeBridge?.postMessage=="function")return p.includes("android")?(i("shell_android"),"shell_android"):(i("shell_ios"),"shell_ios");let a=window,l=!!window.Telegram?.WebApp||typeof a.TelegramWebviewProxy<"u"||typeof a.TelegramGameProxy<"u",h=t("tgWebAppPlatform","tgWebAppVersion","tgWebAppData","tgWebAppLanguage");if(l||h||p.includes("telegram"))return i("telegram"),"telegram";if(window.WebApp||window.MaxMiniApp)return i("max"),"max";let u=t("vk_app_id","vk_platform","vk_user_id","vk_language","sign"),b=p.includes("vkclient")||p.includes("vk-android")||p.includes("vkontakte");if(u||b)return i("vk"),"vk";let m=n();return m&&m!=="web"?m:"web"}function Ht(o){let r=Ot(o),e=r.platform??oe();switch(e==="vk"&&ie(r.vk?.pixelCode??null),e){case"shell_ios":case"shell_android":return new K(e);case"telegram":return new z;case"vk":return new U;case"max":return new q;default:return new Q}}function Ot(o){return o?typeof o=="string"?{platform:o}:o:{}}import{createContext as Nt,useContext as Dt,useEffect as qt,useMemo as Kt}from"react";var at=null;function Ve(o){at=o}function j(){return at}import{jsx as Ut}from"react/jsx-runtime";var st=Nt(null);function zt({adapter:o,children:r}){let e=Kt(()=>new Proxy(o,{get(t,n,i){let s=Reflect.get(t,n,i);return typeof s=="function"?s.bind(t):s}}),[o]);return qt(()=>(Ve(e),()=>{if(Ve(null),typeof e.destroy=="function")try{e.destroy()}catch(t){console.warn("[tvm-app-adapter] adapter destroy failed:",t)}}),[e]),Ut(st.Provider,{value:e,children:r})}function G(){let o=Dt(st);if(!o)throw new Error("useMiniAppAdapter must be used inside <AdapterProvider/>.");return o}import{useCallback as pt,useEffect as dt,useMemo as Qt,useState as lt}from"react";var ct="loyalka-theme-preference";function jt(){let o=G(),[r,e]=lt(()=>{let{appearance:a}=o.getEnvironment();return o.onAppearanceChange&&a?a==="dark":typeof window<"u"&&window.matchMedia?window.matchMedia("(prefers-color-scheme: dark)").matches:!1}),[t,n]=lt(()=>{try{let a=localStorage.getItem(ct);if(a==="light"||a==="dark"||a==="system")return a}catch{}return"system"});dt(()=>{if(o.onAppearanceChange)return o.onAppearanceChange(a=>{a&&e(a==="dark")});if(typeof window<"u"&&window.matchMedia){let a=window.matchMedia("(prefers-color-scheme: dark)"),l=h=>e(h.matches);return a.addEventListener("change",l),()=>a.removeEventListener("change",l)}},[o]);let i=Qt(()=>!!(t==="dark"||t==="system"&&r),[t,r]),s=i?"dark":"light";dt(()=>{let a=document.documentElement;i?a.classList.add("dark"):a.classList.remove("dark")},[i]);let p=pt(a=>{n(a);try{localStorage.setItem(ct,a)}catch{}},[]),d=pt(()=>{document.documentElement.classList.add("theme-transition"),setTimeout(()=>{setTimeout(()=>{document.documentElement.classList.remove("theme-transition")},400)},50);let a=document.documentElement,l=getComputedStyle(a),h=l.getPropertyValue("--primary").trim(),u=l.getPropertyValue("--background").trim();o.setColors({header:h,background:u,footer:u}),p(t==="dark"?"light":"dark")},[o,t,p]);return{isDark:i,appearance:s,preference:t,setPreference:p,toggle:d}}import{useCallback as Gt,useEffect as $t,useState as Yt}from"react";var ut={top:0,right:0,bottom:0,left:0};function Xt(){let o=G(),r=Gt(()=>o.computeSafeArea()??ut,[o]),[e,t]=Yt(r);return $t(()=>{t(r());let n=o.subscribe?.(()=>{t(r())});return()=>n?.()},[o,r]),e??ut}var $=null;function xe(){let o=j();if(o)return o.platform!=="web"&&($=o.platform),o.platform;if($&&$!=="web")return $;let r=oe();return r!=="web"&&($=r),r}function Jt(o){ie(o)}function Zt(o,r){ft()?.trackConversionEvent(o,r)}function en(o,r){ft()?.trackPixelEvent(o,r)}function ft(){let o=j();return o?o.platform==="vk"?o:null:(xe()!=="vk",null)}export{zt as AdapterProvider,A as BaseMiniAppAdapter,q as MaxMiniAppAdapter,K as ShellMiniAppAdapter,z as TelegramMiniAppAdapter,U as VKMiniAppAdapter,Q as WebMiniAppAdapter,Jt as configureVkPixel,Ht as createAdapter,te as createShellAPI,oe as detectPlatform,j as getActiveAdapter,xe as getPlatform,De as isShell,St as isShellAndroid,Pt as isShellIOS,ee as readShellPlatform,ge as requestShellPushPermission,Mt as shell,Ct as storeShellToken,Zt as trackConversionEvent,en as trackPixelEvent,jt as useAdapterTheme,G as useMiniAppAdapter,Xt as useSafeArea};
9
+ `,document.head.appendChild(P);let k=document.createElement("div");k.innerText="\u041D\u0430\u0432\u0435\u0434\u0438\u0442\u0435 \u043A\u0430\u043C\u0435\u0440\u0443 \u043D\u0430 QR-\u043A\u043E\u0434",k.style.color="white",k.style.fontSize="17px",k.style.opacity="0.9",a.appendChild(k);let w=document.createElement("button");w.innerText="\u0417\u0430\u043A\u0440\u044B\u0442\u044C",w.style.minWidth=`${Math.min(m,220)}px`,w.style.height="48px",w.style.padding="0 20px",w.style.border="1px solid rgba(255,255,255,0.24)",w.style.borderRadius="14px",w.style.background="rgba(255,255,255,0.12)",w.style.color="white",w.style.fontSize="16px",w.style.fontWeight="600",w.style.cursor="pointer",w.style.backdropFilter="blur(8px)",a.appendChild(w);let oe=document.createElement("canvas"),ae=oe.getContext("2d",{willReadFrequently:!0}),L=null,F=null,Me=0,se=!1,Ve=async T=>{se||(se=!0,F!==null&&(cancelAnimationFrame(F),F=null),L&&(L.getTracks().forEach(O=>O.stop()),L=null),v.srcObject=null,a.remove(),P.remove(),document.body.style.overflow=r,document.body.style.position=o,document.body.style.width=p,document.body.style.touchAction=s,document.documentElement.style.overflow=d,t(T))},lt=this.registerDisposable(()=>{Ve(null)}),$=T=>{Ve(T),lt()};l.onclick=()=>$(null),w.onclick=()=>$(null);try{let T=[{video:{facingMode:{ideal:"environment"},width:{ideal:1920},height:{ideal:1080},aspectRatio:{ideal:1.7777777778}},audio:!1},{video:{facingMode:"environment",width:{ideal:1280},height:{ideal:720}},audio:!1},{video:!0,audio:!1}],O=null;for(let R of T)try{L=await navigator.mediaDevices.getUserMedia(R);break}catch(B){O=B}if(!L)throw O instanceof Error?O:new Error("Unable to access camera");let[xe]=L.getVideoTracks();if(xe)try{let R=[{focusMode:"continuous"},{exposureMode:"continuous"},{whiteBalanceMode:"continuous"}];await xe.applyConstraints({advanced:R})}catch{}v.srcObject=L,await v.play();let Ee=R=>{if(!se){if(R-Me>=80&&ae&&v.readyState>=HTMLMediaElement.HAVE_CURRENT_DATA){let B=v.videoWidth,H=v.videoHeight;if(B>0&&H>0){oe.width=B,oe.height=H,ae.drawImage(v,0,0,B,H);let ct=ae.getImageData(0,0,B,H),Le=Bt(ct.data,B,H,{inversionAttempts:"attemptBoth"});if(Le?.data){$(Le.data);return}Me=R}}F=requestAnimationFrame(Ee)}};F=requestAnimationFrame(Ee)}catch(T){console.error("QR Start error",T),$(null)}})}shareUrl(e,t){if(navigator.share)try{navigator.share({title:t,text:t,url:e});return}catch(o){console.warn("Share cancelled or failed:",o)}let r=t?`${t}
10
+ ${e}`:e;this.copyTextToClipboard(r).catch(o=>{console.warn("Share fallback (clipboard) failed:",o)})}async addToHomeScreen(){if(!/android/i.test(navigator.userAgent)||!this.deferredPrompt)return super.addToHomeScreen();try{this.deferredPrompt.prompt();let t=await this.deferredPrompt.userChoice;return this.deferredPrompt=null,t?.outcome==="accepted"}catch(t){return console.warn("[tvm-app-adapter] Web addToHomeScreen failed:",t),this.deferredPrompt=null,!1}}async checkHomeScreenStatus(){try{return typeof window<"u"&&window.matchMedia?.("(display-mode: standalone)").matches||typeof navigator<"u"&&navigator.standalone===!0?"added":"unknown"}catch{return"unknown"}}};var tt="mini-app-adapter:confirmed-platform";function ie(){if(typeof window>"u")return"web";let i=new URLSearchParams(window.location.search),n=(()=>{let h=window.location.hash.startsWith("#")?window.location.hash.slice(1):window.location.hash;return new URLSearchParams(h)})(),e=h=>i.get(h)??n.get(h),t=(...h)=>h.some(P=>e(P)),r=()=>{let h=[];try{window.localStorage&&h.push(window.localStorage)}catch{}try{window.sessionStorage&&h.push(window.sessionStorage)}catch{}return h},o=()=>{for(let h of r())try{let P=h.getItem(tt);if(!P)continue;let k=JSON.parse(P);if(k?.platform&&k.platform!=="web")return k.platform}catch{}return null},s=h=>{if(h==="web")return;let P=JSON.stringify({platform:h,ts:Date.now()});for(let k of r())try{k.setItem(tt,P)}catch{}},p=X();if(p)return s(p),p;let d=navigator.userAgent.toLowerCase();if(typeof window.NativeBridge?.postMessage=="function")return d.includes("android")?(s("shell_android"),"shell_android"):(s("shell_ios"),"shell_ios");let l=window,m=!!window.Telegram?.WebApp||typeof l.TelegramWebviewProxy<"u"||typeof l.TelegramGameProxy<"u",c=t("tgWebAppPlatform","tgWebAppVersion","tgWebAppData","tgWebAppLanguage");if(m||c||d.includes("telegram"))return s("telegram"),"telegram";let b=t("vk_app_id","vk_platform","vk_user_id","vk_language","sign"),v=d.includes("vkclient")||d.includes("vk-android")||d.includes("vkontakte");if(b||v)return s("vk"),"vk";let g=o();return g&&g!=="web"?g:"web"}function Rt(i){let n=_t(i),e=n.platform??ie();switch(e==="vk"&&re(n.vk?.pixelCode??null),e){case"shell_ios":case"shell_android":return new K(e);case"telegram":return new q;case"vk":return new z;default:return new Q}}function _t(i){return i?typeof i=="string"?{platform:i}:i:{}}import{createContext as Wt,useContext as It,useEffect as Ft,useMemo as Ot}from"react";var nt=null;function Ce(i){nt=i}function U(){return nt}import{jsx as Nt}from"react/jsx-runtime";var rt=Wt(null);function Ht({adapter:i,children:n}){let e=Ot(()=>{let t=new Map;return new Proxy(i,{get(r,o,s){let p=Reflect.get(r,o,s);if(typeof p!="function")return p;let d=t.get(o);return d||(d=p.bind(r),t.set(o,d)),d}})},[i]);return Ft(()=>(Ce(e),()=>{Ce(null)}),[e]),Nt(rt.Provider,{value:e,children:n})}function G(){let i=It(rt);if(!i)throw new Error("useMiniAppAdapter must be used inside <AdapterProvider/>.");return i}import{useCallback as it,useEffect as ot,useMemo as Dt,useState as at}from"react";var st="mini-app-adapter:theme-preference";function Kt(){let i=G(),[n,e]=at(()=>{let{appearance:a}=i.getEnvironment();return i.onAppearanceChange&&a?a==="dark":typeof window<"u"&&window.matchMedia?window.matchMedia("(prefers-color-scheme: dark)").matches:!1}),[t,r]=at(()=>{try{let a=localStorage.getItem(st);if(a==="light"||a==="dark"||a==="system")return a}catch{}return"system"});ot(()=>{if(i.onAppearanceChange)return i.onAppearanceChange(a=>{a&&e(a==="dark")});if(typeof window<"u"&&window.matchMedia){let a=window.matchMedia("(prefers-color-scheme: dark)"),l=m=>e(m.matches);return a.addEventListener("change",l),()=>a.removeEventListener("change",l)}},[i]);let o=Dt(()=>!!(t==="dark"||t==="system"&&n),[t,n]),s=o?"dark":"light";ot(()=>{let a=document.documentElement;o?a.classList.add("dark"):a.classList.remove("dark");let l=getComputedStyle(a),m=l.getPropertyValue("--primary").trim(),c=l.getPropertyValue("--background").trim();(m||c)&&i.setColors({...m?{header:m}:{},...c?{background:c,footer:c}:{}})},[o,i]);let p=it(a=>{r(a);try{localStorage.setItem(st,a)}catch{}},[]),d=it(()=>{document.documentElement.classList.add("theme-transition"),setTimeout(()=>{setTimeout(()=>{document.documentElement.classList.remove("theme-transition")},400)},50),p(t==="dark"?"light":"dark")},[t,p]);return{isDark:o,appearance:s,preference:t,setPreference:p,toggle:d}}import{useCallback as qt,useEffect as zt,useState as Qt}from"react";var pt={top:0,right:0,bottom:0,left:0};function Ut(){let i=G(),n=qt(()=>i.computeSafeArea()??pt,[i]),[e,t]=Qt(n);return zt(()=>{t(n());let r=i.subscribe?.(()=>{t(n())});return()=>r?.()},[i,n]),e??pt}function Gt(i){re(i)}function jt(i,n){dt()?.trackConversionEvent(i,n)}function $t(i,n){dt()?.trackPixelEvent(i,n)}function dt(){let i=U();return i&&i.platform==="vk"?i:null}var j=null;function Yt(){let i=U();if(i)return i.platform!=="web"&&(j=i.platform),i.platform;if(j&&j!=="web")return j;let n=ie();return n!=="web"&&(j=n),n}export{Ht as AdapterProvider,S as BaseMiniAppAdapter,K as ShellMiniAppAdapter,q as TelegramMiniAppAdapter,z as VKMiniAppAdapter,Q as WebMiniAppAdapter,Gt as configureVkPixel,Rt as createAdapter,ee as createShellAPI,ie as detectPlatform,U as getActiveAdapter,Yt as getPlatform,Oe as isShell,bt as isShellAndroid,wt as isShellIOS,X as readShellPlatform,ve as requestShellPushPermission,At as shell,kt as storeShellToken,jt as trackConversionEvent,$t as trackPixelEvent,Kt as useAdapterTheme,G as useMiniAppAdapter,Ut as useSafeArea};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wowlabtech/mini-app-adapter",
3
- "version": "0.2.85",
3
+ "version": "0.2.86",
4
4
  "description": "Cross-platform adapter toolkit for Telegram, VK, and MAX mini apps.",
5
5
  "type": "module",
6
6
  "private": false,