@retion-miniapp/react-native 0.7.4 → 0.7.6

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.d.mts CHANGED
@@ -159,11 +159,13 @@ interface MiniAppNativeHandlers {
159
159
  type MiniAppHapticType = 'selection' | 'impactLight' | 'impactMedium' | 'impactHeavy' | 'rigid' | 'soft' | 'notificationSuccess' | 'notificationWarning' | 'notificationError';
160
160
  /** Hành vi bridge phụ thuộc ứng dụng. */
161
161
  interface MiniAppBridgeOptions {
162
+ /** Built-in biometric adapter; omit to disable biometric APIs. */
163
+ biometrics?: MiniAppBiometrics;
162
164
  /** Web gọi showToast(). Không truyền → bỏ qua. */
163
165
  showToast?: (message: string) => void;
164
166
  /** Web gọi haptic(type) (lệnh 1 chiều). Không truyền → bỏ qua. */
165
167
  haptic?: (type: MiniAppHapticType) => void;
166
- /** Web gọi openWebview(url). Mặc định Linking.openURL. */
168
+ /** Web gọi openWebview(url) / openLink(url). Mặc định Linking.openURL. */
167
169
  openUrl?: (url: string) => Promise<void> | void;
168
170
  /** Trả cho web qua getSystemInfo(). */
169
171
  app_version?: string;
@@ -178,6 +180,22 @@ interface MiniAppBridgeOptions {
178
180
  instance_id: string;
179
181
  }) => void | Promise<void>;
180
182
  }
183
+ /** Biometric verification on this device; does not issue a backend login token. */
184
+ type MiniAppBiometryType = 'FaceID' | 'TouchID' | 'Biometrics';
185
+ interface MiniAppBiometricAvailability {
186
+ available: boolean;
187
+ biometryType?: MiniAppBiometryType;
188
+ }
189
+ interface MiniAppBiometricRequest {
190
+ reason: string;
191
+ cancelButtonText?: string;
192
+ }
193
+ interface MiniAppBiometrics {
194
+ getAvailability: () => Promise<MiniAppBiometricAvailability>;
195
+ authenticate: (request: MiniAppBiometricRequest) => Promise<{
196
+ success: true;
197
+ }>;
198
+ }
181
199
 
182
200
  /** Giới hạn WebView sống — không truyền thì giữ mọi WebView (mở lại tức thì, tốn RAM hơn). */
183
201
  interface MiniAppKeepAlive {
@@ -500,4 +518,23 @@ declare class BridgeError extends Error {
500
518
  constructor(code: string, message: string);
501
519
  }
502
520
 
503
- export { DefaultMiniAppSplash, MINIAPP_PLATFORM_URL, type MiniAppBridgeOptions, type MiniAppCatalogEntry, type MiniAppCatalogItem, type MiniAppChannel, type MiniAppConfig, type MiniAppContainerProps, type MiniAppContext, type MiniAppDownloadState, type MiniAppDownloadStatus, type MiniAppDownloadTask, type MiniAppEvent, type MiniAppFileSystem, type MiniAppHandlerContext, type MiniAppHapticType, _default as MiniAppHost, type MiniAppHostData, BridgeError as MiniAppHostError, type MiniAppHostProps, type MiniAppKeepAlive, type MiniAppLaunch, type MiniAppLocalBundle, type MiniAppManifest, type MiniAppNativeHandlers, type MiniAppPaymentRequest, type MiniAppPaymentResult, type MiniAppPermission, type MiniAppSplashProps, type MiniAppStorage, type MiniAppSyncResult, type MiniAppUpdate, type OpenMiniAppArgs, closeMiniApp, configureMiniApp, createMmkvStorage, createRnfsFileSystem, ensureMiniApp, getLocalMiniApp, getMiniAppCatalog, getMiniAppCatalogEntry, getMiniAppStatuses, getMiniAppUpdate, installBundledMiniApp, onMiniAppEvent, openMiniApp, pauseMiniApp, pauseMiniAppDownloads, preloadMiniApp, restoreMiniApp, resumeMiniApp, resumeMiniAppDownloads, sendEventToWeb, syncMiniAppCatalog, uninstallMiniApp, updateMiniApp, useMiniAppDownload, useMiniAppDownloadsPaused };
521
+ /** Pass a react-native-biometrics instance created with allowDeviceCredentials: false. */
522
+ interface ReactNativeBiometricsLike {
523
+ isSensorAvailable(): Promise<{
524
+ available: boolean;
525
+ biometryType?: string;
526
+ error?: string;
527
+ }>;
528
+ simplePrompt(options: {
529
+ promptMessage: string;
530
+ cancelButtonText?: string;
531
+ fallbackPromptMessage: string;
532
+ }): Promise<{
533
+ success: boolean;
534
+ error?: string;
535
+ }>;
536
+ }
537
+ /** Native-module injection keeps the host package independent of the app's native dependencies. */
538
+ declare const createReactNativeBiometrics: (native: ReactNativeBiometricsLike) => MiniAppBiometrics;
539
+
540
+ export { DefaultMiniAppSplash, MINIAPP_PLATFORM_URL, type MiniAppBiometricAvailability, type MiniAppBiometricRequest, type MiniAppBiometrics, type MiniAppBiometryType, type MiniAppBridgeOptions, type MiniAppCatalogEntry, type MiniAppCatalogItem, type MiniAppChannel, type MiniAppConfig, type MiniAppContainerProps, type MiniAppContext, type MiniAppDownloadState, type MiniAppDownloadStatus, type MiniAppDownloadTask, type MiniAppEvent, type MiniAppFileSystem, type MiniAppHandlerContext, type MiniAppHapticType, _default as MiniAppHost, type MiniAppHostData, BridgeError as MiniAppHostError, type MiniAppHostProps, type MiniAppKeepAlive, type MiniAppLaunch, type MiniAppLocalBundle, type MiniAppManifest, type MiniAppNativeHandlers, type MiniAppPaymentRequest, type MiniAppPaymentResult, type MiniAppPermission, type MiniAppSplashProps, type MiniAppStorage, type MiniAppSyncResult, type MiniAppUpdate, type OpenMiniAppArgs, type ReactNativeBiometricsLike, closeMiniApp, configureMiniApp, createMmkvStorage, createReactNativeBiometrics, createRnfsFileSystem, ensureMiniApp, getLocalMiniApp, getMiniAppCatalog, getMiniAppCatalogEntry, getMiniAppStatuses, getMiniAppUpdate, installBundledMiniApp, onMiniAppEvent, openMiniApp, pauseMiniApp, pauseMiniAppDownloads, preloadMiniApp, restoreMiniApp, resumeMiniApp, resumeMiniAppDownloads, sendEventToWeb, syncMiniAppCatalog, uninstallMiniApp, updateMiniApp, useMiniAppDownload, useMiniAppDownloadsPaused };
package/dist/index.d.ts CHANGED
@@ -159,11 +159,13 @@ interface MiniAppNativeHandlers {
159
159
  type MiniAppHapticType = 'selection' | 'impactLight' | 'impactMedium' | 'impactHeavy' | 'rigid' | 'soft' | 'notificationSuccess' | 'notificationWarning' | 'notificationError';
160
160
  /** Hành vi bridge phụ thuộc ứng dụng. */
161
161
  interface MiniAppBridgeOptions {
162
+ /** Built-in biometric adapter; omit to disable biometric APIs. */
163
+ biometrics?: MiniAppBiometrics;
162
164
  /** Web gọi showToast(). Không truyền → bỏ qua. */
163
165
  showToast?: (message: string) => void;
164
166
  /** Web gọi haptic(type) (lệnh 1 chiều). Không truyền → bỏ qua. */
165
167
  haptic?: (type: MiniAppHapticType) => void;
166
- /** Web gọi openWebview(url). Mặc định Linking.openURL. */
168
+ /** Web gọi openWebview(url) / openLink(url). Mặc định Linking.openURL. */
167
169
  openUrl?: (url: string) => Promise<void> | void;
168
170
  /** Trả cho web qua getSystemInfo(). */
169
171
  app_version?: string;
@@ -178,6 +180,22 @@ interface MiniAppBridgeOptions {
178
180
  instance_id: string;
179
181
  }) => void | Promise<void>;
180
182
  }
183
+ /** Biometric verification on this device; does not issue a backend login token. */
184
+ type MiniAppBiometryType = 'FaceID' | 'TouchID' | 'Biometrics';
185
+ interface MiniAppBiometricAvailability {
186
+ available: boolean;
187
+ biometryType?: MiniAppBiometryType;
188
+ }
189
+ interface MiniAppBiometricRequest {
190
+ reason: string;
191
+ cancelButtonText?: string;
192
+ }
193
+ interface MiniAppBiometrics {
194
+ getAvailability: () => Promise<MiniAppBiometricAvailability>;
195
+ authenticate: (request: MiniAppBiometricRequest) => Promise<{
196
+ success: true;
197
+ }>;
198
+ }
181
199
 
182
200
  /** Giới hạn WebView sống — không truyền thì giữ mọi WebView (mở lại tức thì, tốn RAM hơn). */
183
201
  interface MiniAppKeepAlive {
@@ -500,4 +518,23 @@ declare class BridgeError extends Error {
500
518
  constructor(code: string, message: string);
501
519
  }
502
520
 
503
- export { DefaultMiniAppSplash, MINIAPP_PLATFORM_URL, type MiniAppBridgeOptions, type MiniAppCatalogEntry, type MiniAppCatalogItem, type MiniAppChannel, type MiniAppConfig, type MiniAppContainerProps, type MiniAppContext, type MiniAppDownloadState, type MiniAppDownloadStatus, type MiniAppDownloadTask, type MiniAppEvent, type MiniAppFileSystem, type MiniAppHandlerContext, type MiniAppHapticType, _default as MiniAppHost, type MiniAppHostData, BridgeError as MiniAppHostError, type MiniAppHostProps, type MiniAppKeepAlive, type MiniAppLaunch, type MiniAppLocalBundle, type MiniAppManifest, type MiniAppNativeHandlers, type MiniAppPaymentRequest, type MiniAppPaymentResult, type MiniAppPermission, type MiniAppSplashProps, type MiniAppStorage, type MiniAppSyncResult, type MiniAppUpdate, type OpenMiniAppArgs, closeMiniApp, configureMiniApp, createMmkvStorage, createRnfsFileSystem, ensureMiniApp, getLocalMiniApp, getMiniAppCatalog, getMiniAppCatalogEntry, getMiniAppStatuses, getMiniAppUpdate, installBundledMiniApp, onMiniAppEvent, openMiniApp, pauseMiniApp, pauseMiniAppDownloads, preloadMiniApp, restoreMiniApp, resumeMiniApp, resumeMiniAppDownloads, sendEventToWeb, syncMiniAppCatalog, uninstallMiniApp, updateMiniApp, useMiniAppDownload, useMiniAppDownloadsPaused };
521
+ /** Pass a react-native-biometrics instance created with allowDeviceCredentials: false. */
522
+ interface ReactNativeBiometricsLike {
523
+ isSensorAvailable(): Promise<{
524
+ available: boolean;
525
+ biometryType?: string;
526
+ error?: string;
527
+ }>;
528
+ simplePrompt(options: {
529
+ promptMessage: string;
530
+ cancelButtonText?: string;
531
+ fallbackPromptMessage: string;
532
+ }): Promise<{
533
+ success: boolean;
534
+ error?: string;
535
+ }>;
536
+ }
537
+ /** Native-module injection keeps the host package independent of the app's native dependencies. */
538
+ declare const createReactNativeBiometrics: (native: ReactNativeBiometricsLike) => MiniAppBiometrics;
539
+
540
+ export { DefaultMiniAppSplash, MINIAPP_PLATFORM_URL, type MiniAppBiometricAvailability, type MiniAppBiometricRequest, type MiniAppBiometrics, type MiniAppBiometryType, type MiniAppBridgeOptions, type MiniAppCatalogEntry, type MiniAppCatalogItem, type MiniAppChannel, type MiniAppConfig, type MiniAppContainerProps, type MiniAppContext, type MiniAppDownloadState, type MiniAppDownloadStatus, type MiniAppDownloadTask, type MiniAppEvent, type MiniAppFileSystem, type MiniAppHandlerContext, type MiniAppHapticType, _default as MiniAppHost, type MiniAppHostData, BridgeError as MiniAppHostError, type MiniAppHostProps, type MiniAppKeepAlive, type MiniAppLaunch, type MiniAppLocalBundle, type MiniAppManifest, type MiniAppNativeHandlers, type MiniAppPaymentRequest, type MiniAppPaymentResult, type MiniAppPermission, type MiniAppSplashProps, type MiniAppStorage, type MiniAppSyncResult, type MiniAppUpdate, type OpenMiniAppArgs, type ReactNativeBiometricsLike, closeMiniApp, configureMiniApp, createMmkvStorage, createReactNativeBiometrics, createRnfsFileSystem, ensureMiniApp, getLocalMiniApp, getMiniAppCatalog, getMiniAppCatalogEntry, getMiniAppStatuses, getMiniAppUpdate, installBundledMiniApp, onMiniAppEvent, openMiniApp, pauseMiniApp, pauseMiniAppDownloads, preloadMiniApp, restoreMiniApp, resumeMiniApp, resumeMiniAppDownloads, sendEventToWeb, syncMiniAppCatalog, uninstallMiniApp, updateMiniApp, useMiniAppDownload, useMiniAppDownloadsPaused };
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var en=Object.create;var ge=Object.defineProperty;var tn=Object.getOwnPropertyDescriptor;var nn=Object.getOwnPropertyNames;var rn=Object.getPrototypeOf,on=Object.prototype.hasOwnProperty;var sn=(e,t)=>{for(var n in t)ge(e,n,{get:t[n],enumerable:!0})},Ge=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of nn(t))!on.call(e,s)&&s!==n&&ge(e,s,{get:()=>t[s],enumerable:!(r=tn(t,s))||r.enumerable});return e};var Xe=(e,t,n)=>(n=e!=null?en(rn(e)):{},Ge(t||!e||!e.__esModule?ge(n,"default",{value:e,enumerable:!0}):n,e)),an=e=>Ge(ge({},"__esModule",{value:!0}),e);var xn={};sn(xn,{DefaultMiniAppSplash:()=>He,MINIAPP_PLATFORM_URL:()=>fe,MiniAppHost:()=>qt,MiniAppHostError:()=>R,closeMiniApp:()=>te,configureMiniApp:()=>et,createMmkvStorage:()=>rt,createRnfsFileSystem:()=>nt,ensureMiniApp:()=>le,getLocalMiniApp:()=>S,getMiniAppCatalog:()=>Ut,getMiniAppCatalogEntry:()=>ne,getMiniAppStatuses:()=>It,getMiniAppUpdate:()=>Ve,installBundledMiniApp:()=>vt,onMiniAppEvent:()=>Ot,openMiniApp:()=>Et,pauseMiniApp:()=>Nt,pauseMiniAppDownloads:()=>Ft,preloadMiniApp:()=>Rt,restoreMiniApp:()=>$t,resumeMiniApp:()=>Bt,resumeMiniAppDownloads:()=>Jt,sendEventToWeb:()=>bt,syncMiniAppCatalog:()=>Re,uninstallMiniApp:()=>Lt,updateMiniApp:()=>Vt,useMiniAppDownload:()=>xe,useMiniAppDownloadsPaused:()=>kt});module.exports=an(xn);var fe="https://retion-miniapp-platform.vercel.app",X=null,Ze=new Set,et=e=>{X=e,Ze.forEach(t=>t())},x=()=>{if(!X)throw new Error("[miniapp] Ch\u01B0a g\u1ECDi configureMiniApp()");return X},tt=e=>{Ze.add(e),X&&e()},L=(...e)=>{X!=null&&X.debug&&console.log("[miniapp]",...e)};var nt=(e,t)=>({document_dir:e.DocumentDirectoryPath,cache_dir:e.CachesDirectoryPath,exists:n=>e.exists(n),mkdir:n=>e.mkdir(n),remove:n=>e.unlink(n).catch(()=>{}),listDir:n=>e.readDir(n).then(r=>r.map(s=>s.name)).catch(()=>[]),sha256:n=>e.hash(n,"sha256"),unzip:async(n,r)=>{await t(n,r)},download:({url:n,to_file:r,onProgress:s})=>{let{jobId:o,promise:p}=e.downloadFile({fromUrl:n,toFile:r,progressInterval:250,begin:()=>{},progress:({bytesWritten:u,contentLength:i})=>s==null?void 0:s(u,i)});return{promise:p.then(({statusCode:u})=>({status:u})),cancel:()=>e.stopDownload(o)}}}),rt=e=>({getString:t=>e.getString(t),setString:(t,n)=>e.set(t,n)});var d=Xe(require("react")),_=require("react-native"),jt=Xe(require("react-native-webview"));var he=require("react-native"),Ae=1,R=class extends Error{constructor(n,r){super(r);this.code=n}},ot=e=>{try{let t=JSON.parse(e);return(t==null?void 0:t.__retion)===Ae&&typeof t.method=="string"?t:null}catch{return null}},me=e=>`window.__RETION_MINIAPP__ && window.__RETION_MINIAPP__.receive(${JSON.stringify(e)}); true;`,st=(e,t)=>me({id:e,result:t}),at=(e,t)=>me({id:e,error:{code:t.code,message:t.message}}),Oe=e=>me({event:"context",data:e});var pt=()=>`(function () {
1
+ "use strict";var tn=Object.create;var Ae=Object.defineProperty;var nn=Object.getOwnPropertyDescriptor;var rn=Object.getOwnPropertyNames;var on=Object.getPrototypeOf,sn=Object.prototype.hasOwnProperty;var an=(e,t)=>{for(var n in t)Ae(e,n,{get:t[n],enumerable:!0})},Ze=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of rn(t))!sn.call(e,s)&&s!==n&&Ae(e,s,{get:()=>t[s],enumerable:!(r=nn(t,s))||r.enumerable});return e};var et=(e,t,n)=>(n=e!=null?tn(on(e)):{},Ze(t||!e||!e.__esModule?Ae(n,"default",{value:e,enumerable:!0}):n,e)),cn=e=>Ze(Ae({},"__esModule",{value:!0}),e);var En={};an(En,{DefaultMiniAppSplash:()=>qe,MINIAPP_PLATFORM_URL:()=>me,MiniAppHost:()=>Kt,MiniAppHostError:()=>M,closeMiniApp:()=>ie,configureMiniApp:()=>nt,createMmkvStorage:()=>ot,createReactNativeBiometrics:()=>zt,createRnfsFileSystem:()=>it,ensureMiniApp:()=>ge,getLocalMiniApp:()=>x,getMiniAppCatalog:()=>Ht,getMiniAppCatalogEntry:()=>oe,getMiniAppStatuses:()=>Dt,getMiniAppUpdate:()=>We,installBundledMiniApp:()=>_t,onMiniAppEvent:()=>Ot,openMiniApp:()=>Tt,pauseMiniApp:()=>$t,pauseMiniAppDownloads:()=>Ut,preloadMiniApp:()=>Rt,restoreMiniApp:()=>Nt,resumeMiniApp:()=>Ft,resumeMiniAppDownloads:()=>Vt,sendEventToWeb:()=>xt,syncMiniAppCatalog:()=>ke,uninstallMiniApp:()=>Bt,updateMiniApp:()=>Jt,useMiniAppDownload:()=>Re,useMiniAppDownloadsPaused:()=>It});module.exports=cn(En);var me="https://retion-miniapp-platform.vercel.app",ee=null,tt=new Set,nt=e=>{ee=e,tt.forEach(t=>t())},T=()=>{if(!ee)throw new Error("[miniapp] Ch\u01B0a g\u1ECDi configureMiniApp()");return ee},rt=e=>{tt.add(e),ee&&e()},N=(...e)=>{ee!=null&&ee.debug&&console.log("[miniapp]",...e)};var it=(e,t)=>({document_dir:e.DocumentDirectoryPath,cache_dir:e.CachesDirectoryPath,exists:n=>e.exists(n),mkdir:n=>e.mkdir(n),remove:n=>e.unlink(n).catch(()=>{}),listDir:n=>e.readDir(n).then(r=>r.map(s=>s.name)).catch(()=>[]),sha256:n=>e.hash(n,"sha256"),unzip:async(n,r)=>{await t(n,r)},download:({url:n,to_file:r,onProgress:s})=>{let{jobId:o,promise:a}=e.downloadFile({fromUrl:n,toFile:r,progressInterval:250,begin:()=>{},progress:({bytesWritten:u,contentLength:i})=>s==null?void 0:s(u,i)});return{promise:a.then(({statusCode:u})=>({status:u})),cancel:()=>e.stopDownload(o)}}}),ot=e=>({getString:t=>e.getString(t),setString:(t,n)=>e.set(t,n)});var d=et(require("react")),b=require("react-native"),qt=et(require("react-native-webview"));var pe=require("react-native"),ye=1,M=class extends Error{constructor(n,r){super(r);this.code=n}},st=e=>{try{let t=JSON.parse(e);return(t==null?void 0:t.__retion)===ye&&typeof t.method=="string"?t:null}catch{return null}},we=e=>`window.__RETION_MINIAPP__ && window.__RETION_MINIAPP__.receive(${JSON.stringify(e)}); true;`,at=(e,t)=>we({id:e,result:t}),ct=(e,t)=>we({id:e,error:{code:t.code,message:t.message}}),Le=e=>we({event:"context",data:e});var pt=()=>`(function () {
2
2
  var post = function (level, args) {
3
3
  try {
4
4
  var parts = [];
@@ -8,7 +8,7 @@
8
8
  else if (typeof a === 'object') { try { parts.push(JSON.stringify(a).slice(0, 800)); } catch (e) { parts.push(String(a)); } }
9
9
  else { parts.push(String(a)); }
10
10
  }
11
- window.ReactNativeWebView && window.ReactNativeWebView.postMessage(JSON.stringify({ __retion: ${Ae}, method: 'log', level: level, text: parts.join(' ') }));
11
+ window.ReactNativeWebView && window.ReactNativeWebView.postMessage(JSON.stringify({ __retion: ${ye}, method: 'log', level: level, text: parts.join(' ') }));
12
12
  } catch (e) {}
13
13
  };
14
14
  ['log', 'info', 'warn', 'error'].forEach(function (level) {
@@ -19,7 +19,7 @@
19
19
  window.addEventListener('unhandledrejection', function (e) { post('error', ['[unhandledrejection]', e.reason]); });
20
20
  // Kh\xF4ng log query (c\xF3 th\u1EC3 ch\u1EE9a token) \u2014 ch\u1EC9 \u0111\u01B0\u1EDDng d\u1EABn + route.
21
21
  post('info', ['[page] ' + location.pathname + location.hash]);
22
- })(); true;`,ct=()=>`(function () {
22
+ })(); true;`,lt=()=>`(function () {
23
23
  function atTop(el) {
24
24
  for (var n = el; n && n !== document.documentElement; n = n.parentElement) {
25
25
  if (n.scrollTop > 0) { return false; }
@@ -30,7 +30,7 @@
30
30
  function report(at_top) {
31
31
  if (at_top === last) { return; }
32
32
  last = at_top;
33
- window.ReactNativeWebView && window.ReactNativeWebView.postMessage(JSON.stringify({ __retion: ${Ae}, method: 'touchAtTop', at_top: at_top }));
33
+ window.ReactNativeWebView && window.ReactNativeWebView.postMessage(JSON.stringify({ __retion: ${ye}, method: 'touchAtTop', at_top: at_top }));
34
34
  }
35
35
  document.addEventListener('touchstart', function (e) { report(atTop(e.target)); }, { capture: true, passive: true });
36
36
  // Cu\u1ED9n r\u1EDDi \u0111\u1EA7u trang \u2192 b\xE1o ngay, kh\xF4ng \u0111\u1EE3i l\u1EA7n ch\u1EA1m sau (tr\xE1nh host d\xF9ng gi\xE1 tr\u1ECB c\u0169 "\u0111ang \u1EDF \u0111\u1EA7u").
@@ -38,8 +38,8 @@
38
38
  var el = e.target === document ? document.documentElement : e.target;
39
39
  if (el && el.scrollTop > 0) { report(false); }
40
40
  }, { capture: true, passive: true });
41
- })(); true;`,lt=e=>me({event:e}),ut=(e,t)=>{let n=dt(t);return`try { history.replaceState(history.state, '', location.pathname + ${JSON.stringify(n?`?${n}`:"")} + location.hash); } catch (e) {}
42
- ${Oe(e)}`},dt=e=>Object.entries(e).filter(([,t])=>t!=null&&t!=="").map(([t,n])=>`${encodeURIComponent(t)}=${encodeURIComponent(String(n))}`).join("&"),gt=(e,t={})=>{let n=dt(t);return`window.__RETION_MINIAPP_HOST__ = { protocol: ${Ae} };
41
+ })(); true;`,ut=e=>we({event:e}),dt=(e,t)=>{let n=gt(t);return`try { history.replaceState(history.state, '', location.pathname + ${JSON.stringify(n?`?${n}`:"")} + location.hash); } catch (e) {}
42
+ ${Le(e)}`},gt=e=>Object.entries(e).filter(([,t])=>t!=null&&t!=="").map(([t,n])=>`${encodeURIComponent(t)}=${encodeURIComponent(String(n))}`).join("&"),ft=(e,t={})=>{let n=gt(t);return`window.__RETION_MINIAPP_HOST__ = { protocol: ${ye} };
43
43
  window.__RETION_MINIAPP_CONTEXT__ = ${JSON.stringify(e)};
44
44
  ${n?`try { history.replaceState(history.state, '', location.pathname + '?' + ${JSON.stringify(n)} + location.hash); } catch (e) {}`:""}
45
- true;`},ft={partner:"partner_token",chatbox:"chatbox_token"},ht=(e,t)=>{let n={...e};for(let r of Object.values(ft))t.includes(r)||delete n[r];return n},Ce=new Set,it=async(e,t)=>{if(Ce.has(e))throw new R("BUSY",`${e} \u0111ang ch\u1EA1y \u2014 ch\u1EDD l\u01B0\u1EE3t tr\u01B0\u1EDBc xong`);Ce.add(e);try{return await t()}finally{Ce.delete(e)}},pn=new Set(["selection","impactLight","impactMedium","impactHeavy","rigid","soft","notificationSuccess","notificationWarning","notificationError"]),ke=(e,t)=>{if(typeof e!="string"||!e)throw new R("INVALID_PARAMS",`Thi\u1EBFu ${t}`);return e},At=async({method:e,params:t},{getHostData:n,getPermissions:r,is_dark:s,close:o,app_id:p,instance_id:u,options:i})=>{var w,m,f,N,T;let l=i==null?void 0:i.handlers,M={app_id:p,instance_id:u,close:o},y=()=>new R("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF \u1EE9ng d\u1EE5ng n\xE0y`);switch(e){case"requestPayment":{let h=l==null?void 0:l.requestPayment;if(!h)throw y();let a=t==null?void 0:t.amount;if(typeof a!="number"||!Number.isFinite(a)||a<=0)throw new R("INVALID_PARAMS","amount ph\u1EA3i l\xE0 s\u1ED1 > 0");let C={...t,amount:a,currency:ke(t==null?void 0:t.currency,"currency")};return it(e,()=>h(C,M))}case"printImage":{let h=l==null?void 0:l.printImage;if(!h)throw y();let a=ke(t==null?void 0:t.image,"image");await it(e,()=>h({image:a},M));return}case"openScreen":if(!(l!=null&&l.openScreen))throw y();await l.openScreen({screen:ke(t==null?void 0:t.screen,"screen"),params:t==null?void 0:t.params},M);return;case"closeApp":o();return;case"openWebview":{let h=String((w=t==null?void 0:t.url)!=null?w:"");if(!/^https?:\/\//i.test(h))throw new R("INVALID_PARAMS","url ph\u1EA3i l\xE0 http(s)");await(i!=null&&i.openUrl?i.openUrl(h):he.Linking.openURL(h));return}case"showToast":(f=i==null?void 0:i.showToast)==null||f.call(i,String((m=t==null?void 0:t.message)!=null?m:""));return;case"haptic":{let h=pn.has(t==null?void 0:t.type)?t.type:"selection";(N=i==null?void 0:i.haptic)==null||N.call(i,h);return}case"getSystemInfo":return{platform:he.Platform.OS==="ios"?"ios":"android",appVersion:(T=i==null?void 0:i.app_version)!=null?T:"",theme:s?"dark":"light"};case"getAccessToken":{let h=n().access_token;if(!h)throw new R("HOST_ERROR","Mini app ch\u01B0a c\xF3 token cho page n\xE0y");return h}case"getToken":{let h=t==null?void 0:t.type;if(h==="access"){let re=n().access_token;if(!re)throw new R("HOST_ERROR","Mini app ch\u01B0a c\xF3 token cho page n\xE0y");return re}if(h!=="partner"&&h!=="chatbox")throw new R("HOST_ERROR",`Lo\u1EA1i token kh\xF4ng h\u1EE3p l\u1EC7: ${String(h)}`);let a=ft[h];if(!r().includes(a))throw new R("PERMISSION_DENIED",`Mini app ch\u01B0a \u0111\u01B0\u1EE3c c\u1EA5p quy\u1EC1n ${a} (Console \u2192 Quy\u1EC1n l\u1EA5y token)`);let C=h==="partner"?n().partner_token:n().chatbox_token;if(!C)throw new R("HOST_ERROR",`Kh\xF4ng c\xF3 ${a}`);return C}case"getUserInfo":{let h=n().user;if(!h)throw new R("HOST_ERROR","Kh\xF4ng l\u1EA5y \u0111\u01B0\u1EE3c th\xF4ng tin nh\xE2n vi\xEAn");return h}case"getPageInfo":{let h=n().page;if(!h)throw new R("HOST_ERROR","Kh\xF4ng l\u1EA5y \u0111\u01B0\u1EE3c th\xF4ng tin page");return h}case"sendMessage":case"insertText":throw new R("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF phi\xEAn b\u1EA3n app n\xE0y`);default:throw new R("NOT_SUPPORTED",`API kh\xF4ng t\u1ED3n t\u1EA1i: ${e}`)}};var De=e=>`bundle:${e}`,Le=()=>`${x().file_system.document_dir}/miniapps`,$e=Le,Ne=(e,t,n="index.html",r=!1,s=[])=>{let o=`${$e()}/${e}/${t}`;return{app_id:e,version:t,dir:o,entry_uri:`file://${o}/${n}`,context_update:r,permissions:s}},Ie=e=>{var t;x().storage.setString(De(e.app_id),JSON.stringify({version:e.version,entry:e.entry,context_update:!!e.context_update,permissions:(t=e.permissions)!=null?t:[]}))},cn=(e,t)=>/^https?:\/\//.test(t)?t:`${e.replace(/[^/]*$/,"")}${t}`,S=e=>{let t=x().storage.getString(De(e));if(!t)return null;try{let{version:n,entry:r,context_update:s,permissions:o}=JSON.parse(t);return Ne(e,n,r,!!s,Array.isArray(o)?o:[])}catch{return null}},W=e=>x().file_system.exists(e.entry_uri.replace("file://","")),Be=async e=>{let t=S(e.app_id);return(t==null?void 0:t.version)===e.version&&await W(t)},Mt=async(e,t)=>{let n=x().file_system,r=`${$e()}/${e}`,s=await n.listDir(r).catch(()=>[]);await Promise.all(s.filter(o=>!t.includes(o)).map(o=>n.remove(`${r}/${o}`).catch(()=>{})))},yt=async e=>{var t;await((t=pe[e])==null?void 0:t.catch(()=>{})),x().storage.setString(De(e),""),await x().file_system.remove(`${$e()}/${e}`).catch(()=>{})},ee=class extends Error{constructor(){super("cancelled"),this.name="MiniAppInstallCancelled"}},pe={},wt=(e,t)=>{var o;let r=((o=pe[e])!=null?o:Promise.resolve()).catch(()=>{}).then(t),s=r.catch(()=>{});return pe[e]=s,s.then(()=>{pe[e]===s&&delete pe[e]}),r},ln=(e,t)=>{var s,o;let n=e.split(".").map(p=>parseInt(p,10)||0),r=t.split(".").map(p=>parseInt(p,10)||0);for(let p=0;p<Math.max(n.length,r.length);p++){let u=((s=n[p])!=null?s:0)-((o=r[p])!=null?o:0);if(u)return u}return 0},vt=({manifest:e,zip_path:t})=>wt(e.app_id,async()=>{var o;let n=x().file_system,r=S(e.app_id);if(r&&ln(r.version,e.version)>=0&&await W(r))return r;if(e.sha256&&n.sha256&&await n.sha256(t)!==e.sha256)throw new Error("sha256 mismatch");let s=Ne(e.app_id,e.version,e.entry,!!e.context_update,(o=e.permissions)!=null?o:[]);return await n.remove(s.dir).catch(()=>{}),await n.mkdir(s.dir),await n.unzip(t,s.dir),Ie(e),L("\u0111\xE3 c\xE0i b\u1EA3n \u0111\xF3ng s\u1EB5n",e.app_id,e.version),Mt(e.app_id,[e.version,r==null?void 0:r.version].filter(Boolean)),s}),Fe=(e,{base_url:t,onProgress:n}={})=>{let r=x().file_system,s=null,o=!1,p=`${r.cache_dir}/${e.app_id}-${e.version}.zip`,u=()=>{if(o)throw new ee},i=async()=>{var y;u();let l=S(e.app_id);if((l==null?void 0:l.version)===e.version&&await r.exists(l.dir))return Ie(e),S(e.app_id);u();let M=r.download({url:t?cn(t,e.bundle_url):e.bundle_url,to_file:p,onProgress:(w,m)=>{var N;let f=m>0?m:(N=e.size)!=null?N:0;f>0&&(n==null||n(Math.min(1,w/f)))}});s=M;try{let{status:w}=await M.promise;if(u(),w!==200)throw new Error(`bundle ${w}`);if(e.sha256)if(r.sha256){if(await r.sha256(p)!==e.sha256)throw new Error("sha256 mismatch")}else L("b\u1ECF qua ki\u1EC3m tra sha256 (file_system kh\xF4ng c\xF3 sha256)",e.app_id);u();let m=Ne(e.app_id,e.version,e.entry,!!e.context_update,(y=e.permissions)!=null?y:[]);return await r.remove(m.dir).catch(()=>{}),await r.mkdir(m.dir),await r.unzip(p,m.dir),Ie(e),Mt(e.app_id,[e.version,l==null?void 0:l.version].filter(Boolean)),m}catch(w){throw o?new ee:w}finally{s=null,r.remove(p).catch(()=>{})}};return{promise:wt(e.app_id,i),cancel:()=>{o=!0,s==null||s.cancel()}}},ae={},un=__DEV__?0:60*1e3,mt={},_t=(e,t)=>{var r,s;let n=S(e);return n&&Date.now()-((r=mt[t])!=null?r:0)<un?Promise.resolve(n):((s=ae[e])!=null||(ae[e]=(async()=>{let o=await fetch(t,{headers:{"Cache-Control":"no-cache"}});if(!o.ok)throw new Error(`manifest ${o.status}`);let p=await o.json(),u=await Fe(p,{base_url:t}).promise;return mt[t]=Date.now(),u})().catch(o=>(console.warn("[miniapp] sync failed",e,o==null?void 0:o.message),S(e))).finally(()=>{ae[e]=void 0})),ae[e])};var Me=new Map,St=(e,t)=>(Me.set(e,t),()=>{Me.get(e)===t&&Me.delete(e)}),bt=(e,t)=>{let n=Me.get(e);return n?n(t):!1};var ye=require("react"),we=e=>{let t=e,n=new Set;return{getState:()=>t,setState:r=>{let s=typeof r=="function"?r(t):r;t={...t,...s},n.forEach(o=>o())},subscribe:r=>(n.add(r),()=>{n.delete(r)})}},H=(e,t,n=Object.is)=>{let r=(0,ye.useRef)(null),s=()=>{let o=e.getState(),p=r.current;if(p&&p.state===o&&p.selector===t)return p.value;let u=t(o),i=p&&n(p.value,u)?p.value:u;return r.current={state:o,selector:t,value:i},i};return(0,ye.useSyncExternalStore)(e.subscribe,s)};var F=we({active_key:null,instances:{}}),xt=({app:e,instance_id:t,context:n={},url_params:r={},host_data:s={}},o)=>{var u;let p=(u=x().keep_alive)==null?void 0:u.max_webviews;F.setState(i=>{let l=t!=null?t:e.app_id,M={...i.instances,[l]:{key:l,app:e,context:n,url_params:r,host_data:s,last_used_at:Date.now()}},y=Object.keys(M);return p&&p>0&&y.length>p&&y.filter(w=>w!==l).sort((w,m)=>M[w].last_used_at-M[m].last_used_at).slice(0,y.length-p).forEach(w=>{delete M[w]}),o?{active_key:l,instances:M}:{instances:M}})},Et=e=>xt(e,!0),Rt=e=>xt(e,!1),te=()=>F.setState({active_key:null}),ve=e=>{F.setState(t=>{if(t.active_key===e||!t.instances[e])return{};let n={...t.instances};return delete n[e],{instances:n}})};var Tt="catalog",dn="paused_apps",gn="removed_apps",fn=10*1e3,hn=2,An=3e3,mn=()=>{var e;try{return JSON.parse((e=x().storage.getString(Tt))!=null?e:"{}")}catch{return{}}},v=we({catalog:{},downloads:{},pause_reasons:[],updates:{},apply_ticks:{}}),Pt=e=>{var t;return!!((t=x().manual_update)!=null&&t.includes(e))},be=new Set,Ct=e=>{let t=new Set,n=()=>x().storage.setString(e,JSON.stringify([...t]));return{has:r=>t.has(r),values:()=>[...t],add:r=>t.has(r)?!1:(t.add(r),n(),!0),delete:r=>t.delete(r)?(n(),!0):!1,load:()=>{var r;t.clear();try{let s=JSON.parse((r=x().storage.getString(e))!=null?r:"[]");Array.isArray(s)&&s.forEach(o=>{typeof o=="string"&&t.add(o)})}catch{}}}},V=Ct(dn),Y=Ct(gn);tt(()=>{V.load(),Y.load();let e=mn(),t={};Object.keys(e).filter(n=>!Y.has(n)).forEach(n=>{let r=S(n);r?t[n]={status:"installed",progress:1,version:r.version,has_local:!0}:V.has(n)&&(t[n]={status:"paused",progress:0,version:e[n].version,has_local:!1})}),v.setState({catalog:e,downloads:t})});var xe=e=>H(v,t=>e?t.downloads[e]:void 0),kt=()=>H(v,e=>e.pause_reasons.length>0),J=(...e)=>L("queue",...e),P=[],j={},A=null,_e=new Set,Z={},Je=new Set,K=e=>{Je.forEach(t=>{try{t(e)}catch(n){console.warn("[miniapp-queue] event listener error",n==null?void 0:n.message)}})},Ot=e=>(Je.add(e),()=>{Je.delete(e)}),It=()=>v.getState().downloads,O=(e,t)=>{let n=!!S(e),r=v.getState().downloads[e],s=t.status==="downloading"&&n?"updating":t.status,o={...r!=null?r:{status:"queued",progress:0},...t,...s?{status:s}:{},has_local:n};v.setState(p=>({downloads:{...p.downloads,[e]:o}})),(r==null?void 0:r.status)!==o.status||(r==null?void 0:r.version)!==o.version||(r==null?void 0:r.has_local)!==o.has_local?K({type:"status_change",app_id:e,state:o}):r.progress!==o.progress&&K({type:"progress",app_id:e,progress:o.progress,version:o.version})},Se=(e,t)=>{var n;(n=Z[e])==null||n.forEach(r=>r(t)),delete Z[e]},Mn=()=>v.getState().pause_reasons.length>0,z=e=>{var u;if(A)return;let t=e?P.indexOf(e):Mn()?-1:P.findIndex(i=>!V.has(i));if(t<0||t>=P.length)return;let[n]=P.splice(t,1),r=v.getState().catalog[n];if(!r){Se(n,S(n)),z();return}let s=Date.now();j[n]=((u=j[n])!=null?u:0)+1,O(n,{status:"downloading",progress:0,version:r.version,error:void 0});let o=0,p=Fe(r,{onProgress:i=>{let l=Math.floor(i*100);l!==o&&(o=l,O(n,{progress:l/100,version:r.version}))}});A={app_id:n,handle:p,forced:!!e},J("start",n,r.version,e?"(forced)":""),p.promise.then(i=>{J("installed",n,r.version,`${Date.now()-s}ms`),O(n,{status:"installed",progress:1,version:r.version}),Se(n,i)}).catch(i=>{var M;if(i instanceof ee){if(_e.has(n))return;J("paused",n),j[n]-=1,P.unshift(n),O(n,{status:V.has(n)?"paused":"queued",progress:0,version:r.version});return}let l=String((M=i==null?void 0:i.message)!=null?M:i);if(console.warn("[miniapp-queue] failed",n,l),j[n]<hn){O(n,{status:"queued",progress:0,version:r.version,error:l}),setTimeout(()=>{var y;P.includes(n)||(A==null?void 0:A.app_id)===n||(P.push(n),z((y=Z[n])!=null&&y.length?n:void 0))},An);return}O(n,{status:"failed",progress:0,version:r.version,error:l}),Se(n,S(n))}).finally(()=>{A=null;let i=P.find(l=>{var M;return(M=Z[l])==null?void 0:M.length});z(i)})},Ee=(e,{front:t=!1}={})=>{if((A==null?void 0:A.app_id)===e)return;let n=P.indexOf(e);if(n>=0){if(!t)return;P.splice(n,1)}t?P.unshift(e):P.push(e)},yn=async e=>{let{host_id:t,client_token:n}=x(),r=new AbortController,s=setTimeout(()=>r.abort(),fn);try{let o=`${fe}/api/hosts/${encodeURIComponent(t)}/miniapps?channel=${e}`,p=await fetch(o,{headers:{Authorization:`Bearer ${n}`,"Cache-Control":"no-cache"},signal:r.signal});if(!p.ok)throw new Error(`host list ${e} ${p.status}`);return(await p.json()).apps.map(i=>({...i,channel:e}))}finally{clearTimeout(s)}},ce=null,Re=()=>(ce!=null||(ce=(async()=>{var t;let e=Date.now();try{let n=await Promise.all(x().channels.map(yn)),r={};[...n].reverse().flat().forEach(i=>{r[i.app_id]=i});let s=Object.keys(v.getState().catalog).filter(i=>!r[i]);x().storage.setString(Tt,JSON.stringify(r)),v.setState({catalog:r}),await Promise.all(s.map(i=>Dt(i,{by_user:!1}))),s.forEach(i=>Y.delete(i));let o=Object.keys(r).filter(i=>!Y.has(i)),p=[],u={};for(let i of o.map(l=>r[l])){if(await Be(i)){O(i.app_id,{status:"installed",progress:1,version:i.version});continue}let l=S(i.app_id);if(Pt(i.app_id)&&!be.has(i.app_id)&&l&&await W(l)){O(i.app_id,{status:"installed",progress:1,version:l.version}),u[i.app_id]={app_id:i.app_id,current_version:l.version,next_version:i.version};continue}p.push(i)}return v.setState({updates:u}),p.forEach(i=>{j[i.app_id]=0,O(i.app_id,{status:V.has(i.app_id)?"paused":"queued",progress:0,version:i.version,error:void 0}),Ee(i.app_id)}),J("catalog",o.length,"apps, outdated",p.map(i=>i.app_id),"removed",s,`${Date.now()-e}ms`),K({type:"sync_complete",app_ids:o,removed:s}),Object.values(u).forEach(i=>K({type:"update_available",...i})),z(),{ok:!0,app_ids:o,removed:s}}catch(n){let r=String((n==null?void 0:n.name)==="AbortError"?"timeout":(t=n==null?void 0:n.message)!=null?t:n);return console.warn("[miniapp-queue] sync catalog failed",r),K({type:"sync_failed",error:r}),{ok:!1,error:r}}finally{ce=null}})()),ce),Dt=async(e,{by_user:t})=>{var s,o,p,u;if(t&&Y.add(e),_e.has(e))return;_e.add(e),V.delete(e);let n=P.indexOf(e);n>=0&&P.splice(n,1),(A==null?void 0:A.app_id)===e&&A.handle.cancel();let r=(u=(p=(s=v.getState().downloads[e])==null?void 0:s.version)!=null?p:(o=S(e))==null?void 0:o.version)!=null?u:"";O(e,{status:"uninstalling",progress:0,version:r}),await yt(e),ve(e),v.setState(i=>{let l={...i.downloads};return delete l[e],{downloads:l}}),delete j[e],_e.delete(e),Se(e,null),J("uninstalled",e,t?"(user)":"(not in list)"),K({type:"uninstalled",app_id:e})},Lt=e=>Dt(e,{by_user:!0}),$t=e=>{let t=ne(e);return t?(Y.delete(e),(A==null?void 0:A.app_id)===e||P.includes(e)||(j[e]=0,O(e,{status:V.has(e)?"paused":"queued",progress:0,version:t.version,error:void 0}),Ee(e),z(),J("restore",e)),!0):!1},Nt=e=>{if(V.has(e))return;if(V.add(e),J("pause app",e),(A==null?void 0:A.app_id)===e&&!A.forced){A.handle.cancel();return}let t=v.getState().downloads[e];P.includes(e)&&t&&O(e,{status:"paused",progress:0,version:t.version})},Bt=e=>{if(!V.delete(e))return;J("resume app",e);let t=v.getState().downloads[e];(t==null?void 0:t.status)==="paused"&&!P.includes(e)&&ne(e)&&(j[e]=0,Ee(e)),P.includes(e)&&t&&O(e,{status:"queued",progress:0,version:t.version}),z()},Ft=e=>{let{pause_reasons:t}=v.getState();t.includes(e)||(v.setState({pause_reasons:[...t,e]}),J("pause",e),t.length===0&&K({type:"pause_change",paused:!0,reasons:[e]}),A&&!A.forced&&A.handle.cancel())},Jt=e=>{let{pause_reasons:t}=v.getState();if(!t.includes(e))return;let n=t.filter(r=>r!==e);v.setState({pause_reasons:n}),J("resume",e),n.length===0&&K({type:"pause_change",paused:!1,reasons:n}),z()},Ve=e=>v.getState().updates[e],Vt=async e=>{var n,r;let t=Ve(e);be.add(e);try{let s=await le(e),o=(r=t==null?void 0:t.next_version)!=null?r:(n=ne(e))==null?void 0:n.version;return!s||!o||s.version!==o?!1:(v.setState(p=>{var i;let u={...p.updates};return delete u[e],{updates:u,apply_ticks:{...p.apply_ticks,[e]:((i=p.apply_ticks[e])!=null?i:0)+1}}}),J("updated",e,t==null?void 0:t.current_version,"\u2192",s.version),!0)}finally{be.delete(e)}},Ut=()=>Object.values(v.getState().catalog).map(e=>({...e,installed:!!S(e.app_id),removed_by_user:Y.has(e.app_id)})),ne=e=>v.getState().catalog[e],le=async e=>{let t=ne(e);if(!t)return;if(V.delete(e),Y.delete(e),await Be(t))return S(e);let n=S(e);if(Pt(e)&&!be.has(e)&&n&&await W(n))return n;let r=new Promise(s=>{var o;((o=Z[e])!=null?o:Z[e]=[]).push(s)});return(A==null?void 0:A.app_id)===e?A.forced=!0:(j[e]=0,Ee(e,{front:!0}),A&&!A.forced?A.handle.cancel():z(e)),r};var b=require("react/jsx-runtime"),Ue=e=>(e!=null?e:"").replace(/\?[^#]*/,""),Ht=0,wn=()=>{let e=new Set;return{emit:t=>e.forEach(n=>n(t)),subscribe:t=>(e.add(t),()=>{e.delete(t)})}},vn=d.default.memo(({instance_key:e,is_active:t,is_front:n,is_dark:r,reload_tick:s,web_at_top:o,splash:p,bridge:u,opaque_background:i,allow_embedded_miniapps:l,onWebLoadEnd:M})=>{var Ye,Qe;let y=(0,d.useRef)(null),w=(0,d.useRef)(!1),m=H(F,c=>c.instances[e]),f=m==null?void 0:m.app.app_id,N=m==null?void 0:m.app.manifest_url,T=m==null?void 0:m.context,h=m==null?void 0:m.url_params,[a,C]=(0,d.useState)(()=>f?S(f):null),[re,ie]=(0,d.useState)(!1),[Kt,We]=(0,d.useState)(0),[zt,oe]=(0,d.useState)(0),[Yt,I]=(0,d.useState)(!1),U=(0,d.useRef)(null),je=c=>{U.current&&clearTimeout(U.current),U.current=setTimeout(()=>{U.current=null,I(!0)},c)};(0,d.useEffect)(()=>()=>{U.current&&clearTimeout(U.current)},[]),(0,d.useEffect)(()=>{if(!f||!t&&a)return;let c=!0;return ie(!1),(async()=>{let g=S(f),k=g?await W(g):!1;if(!c||(C(k?B=>!B||B.version!==g.version||B.permissions.join(",")!==g.permissions.join(",")?g:B:null),__DEV__&&Date.now()-Ht>1e4&&(Ht=Date.now(),await Re()),!c))return;let q=await le(f),Q=q!==void 0?q:N?await _t(f,N):S(f);if(c){if(!Q){ie(!0);return}C(B=>B!=null?B:Q)}})(),()=>{c=!1}},[t,f,N,Kt]),(0,d.useEffect)(()=>St(e,c=>y.current?(y.current.postMessage(c),!0):!1),[e]);let Qt=H(v,c=>{let g=f?c.downloads[f]:void 0;return(g==null?void 0:g.status)==="installed"?g.version:void 0});(0,d.useEffect)(()=>{if(t||!f||!a)return;let c=S(f);if(!c||c.version===a.version)return;let g=!0;return W(c).then(k=>{!g||!k||(L(`webview:${e}`,"\u0111\u1ED5i bundle (\u1EA9n)",a.version,"\u2192",c.version),C(c))}),()=>{g=!1}},[t,f,Qt,a==null?void 0:a.version]);let qe=H(v,c=>{var g;return f&&(g=c.apply_ticks[f])!=null?g:0});(0,d.useEffect)(()=>{if(!qe||!f)return;let c=S(f);if(!c||c.version===(a==null?void 0:a.version))return;let g=!0;return W(c).then(k=>{!g||!k||(L(`webview:${e}`,"c\u1EADp nh\u1EADt",a==null?void 0:a.version,"\u2192",c.version),I(!1),C(c))}),()=>{g=!1}},[qe]),(0,d.useEffect)(()=>{var k;let c=(k=x().keep_alive)==null?void 0:k.idle_close_ms;if(t||!c||c<=0)return;let g=setTimeout(()=>{ve(e)},c);return()=>clearTimeout(g)},[t,e]),(0,d.useEffect)(()=>{s>0&&(ie(!1),I(!1),oe(c=>c+1),We(c=>c+1))},[s]);let Ke=(0,d.useRef)(t);(0,d.useEffect)(()=>{var c;Ke.current!==t&&(Ke.current=t,w.current&&((c=y.current)==null||c.injectJavaScript(lt(t?"resumed":"paused"))))},[t]);let ue=`${(Ye=a==null?void 0:a.version)!=null?Ye:"none"}:${(Qe=a==null?void 0:a.permissions.join(","))!=null?Qe:""}:${zt}`,se=(0,d.useMemo)(()=>JSON.stringify([T!=null?T:{},h!=null?h:{}]),[T,h]),Te=(0,d.useMemo)(()=>{var c;return ht(h!=null?h:{},(c=a==null?void 0:a.permissions)!=null?c:[])},[se,a==null?void 0:a.permissions]),Gt=(0,d.useMemo)(()=>gt(T!=null?T:{},Te)+ct()+(x().debug?pt():""),[Te]),de=(0,d.useRef)(null),ze=(0,d.useRef)(null);(0,d.useEffect)(()=>{var g,k,q;if(!a)return;if(ze.current!==ue){ze.current=ue,de.current=se;return}if(de.current===se)return;let c=((k=JSON.parse((g=de.current)!=null?g:"[]")[0])!=null?k:{}).org_id;if(de.current=se,c===(T==null?void 0:T.org_id)&&w.current){I(!1),je(1500),(q=y.current)==null||q.injectJavaScript(ut(T!=null?T:{},Te));return}I(!1),oe(Q=>Q+1)},[se,a,ue]);let Xt=(0,d.useCallback)(async c=>{var k,q,Q,B,Pe;let g=ot(c.nativeEvent.data);if(!g){if(f&&(u!=null&&u.onWebEvent))try{Promise.resolve(u.onWebEvent(c.nativeEvent.data,{app_id:f,instance_id:e})).catch(E=>{console.warn("[miniapp] onWebEvent l\u1ED7i",f,E)})}catch(E){console.warn("[miniapp] onWebEvent l\u1ED7i",f,E)}return}if(g.method==="log"){let{level:E,text:D}=g;L(`web:${e}`,E!=null?E:"log",D!=null?D:"");return}if(g.method==="pong"){U.current||I(!0);return}if(g.method==="touchAtTop"){o.emit(!!g.at_top);return}if(g.method==="contextApplied"){U.current&&clearTimeout(U.current),U.current=null,I(!0);return}if(g.method==="ready"){w.current=!0,I(!0);let E=(k=F.getState().instances[e])==null?void 0:k.context;E&&((q=y.current)==null||q.injectJavaScript(Oe(E)));return}try{let E=await At(g,{getHostData:()=>{var D,G;return(G=(D=F.getState().instances[e])==null?void 0:D.host_data)!=null?G:{}},getPermissions:()=>{var D,G;return f?(G=(D=S(f))==null?void 0:D.permissions)!=null?G:[]:[]},is_dark:r,close:te,app_id:f!=null?f:"",instance_id:e,options:u});g.id&&((Q=y.current)==null||Q.injectJavaScript(st(g.id,E)))}catch(E){if(!g.id)return;let D=E==null?void 0:E.code,G=E instanceof R?E:new R(typeof D=="string"?D:"HOST_ERROR",String((B=E==null?void 0:E.message)!=null?B:E));(Pe=y.current)==null||Pe.injectJavaScript(at(g.id,G))}},[e,r,f,o,u]),Zt=(0,d.useCallback)(()=>{ie(!1),oe(c=>c+1),We(c=>c+1)},[]);return(0,b.jsxs)(_.View,{style:[_.StyleSheet.absoluteFill,i&&{backgroundColor:r?"#09090B":"#FFFFFF"},!n&&$.behind],pointerEvents:t?"auto":"none",children:[a?(0,b.jsx)(jt.default,{ref:y,source:{uri:a.entry_uri},originWhitelist:["*"],allowingReadAccessToURL:`file://${l?Le():a.dir}`,allowFileAccess:!0,allowFileAccessFromFileURLs:!0,allowUniversalAccessFromFileURLs:!0,injectedJavaScriptBeforeContentLoaded:Gt,onMessage:Xt,bounces:!1,overScrollMode:"never",onLoadStart:c=>{L(`webview:${e}`,"load start",Ue(c.nativeEvent.url)),w.current=!1,I(!1)},onError:c=>{L(`webview:${e}`,"load error",Ue(c.nativeEvent.url),c.nativeEvent.description),ie(!0),I(!1)},onLoadEnd:c=>{let g=c.nativeEvent.url;L(`webview:${e}`,"load end",Ue(g)),f&&(M==null||M({app_id:f,instance_id:e,url:g})),je(1500)},onContentProcessDidTerminate:()=>{w.current=!1,I(!1),oe(c=>c+1)},onRenderProcessGone:()=>(w.current=!1,I(!1),oe(c=>c+1),!0),style:$.webview},ue):null,m&&(0,b.jsx)(Sn,{visible:!a||!Yt,interactive:re,children:(0,b.jsx)(_n,{splash:p,app:m.app,is_dark:r,error:re,has_bundle:!!a,retry:Zt})})]})}),_n=d.default.memo(({splash:e,app:t,is_dark:n,error:r,has_bundle:s,retry:o})=>{let p=e,u=xe(t.app_id),i=r?"error":!s&&(u==null?void 0:u.status)==="downloading"?"downloading":"loading";return(0,b.jsx)(p,{app:t,is_dark:n,status:i,progress:i==="downloading"?u==null?void 0:u.progress:void 0,retry:o})}),Sn=({visible:e,interactive:t,children:n})=>{let r=(0,d.useRef)(new _.Animated.Value(e?1:0)).current,[s,o]=(0,d.useState)(e);return(0,d.useEffect)(()=>{if(e){o(!0),r.setValue(1);return}let p=_.Animated.timing(r,{toValue:0,duration:180,useNativeDriver:!0});return p.start(({finished:u})=>{u&&o(!1)}),()=>p.stop()},[e,r]),s?(0,b.jsx)(_.Animated.View,{style:[_.StyleSheet.absoluteFill,{opacity:r}],pointerEvents:t?"auto":"none",children:n}):null},He=({app:e,is_dark:t,status:n,progress:r,retry:s})=>{let o=t?"#FAFAFA":"#18181B";return(0,b.jsxs)(_.View,{style:[$.splash,{backgroundColor:t?"#09090B":"#FFFFFF"}],children:[(0,b.jsx)(_.View,{style:[$.splash_icon,{backgroundColor:t?"#18181B":"#F4F4F5"}],children:e.icon?(0,b.jsx)(_.Image,{source:{uri:e.icon},style:$.splash_icon_image}):(0,b.jsx)(_.Text,{style:$.splash_letter,children:(e.name||"?").slice(0,1).toUpperCase()})}),(0,b.jsx)(_.Text,{style:[$.splash_name,{color:o}],children:e.name}),n==="error"?(0,b.jsxs)(b.Fragment,{children:[(0,b.jsx)(_.Text,{style:$.splash_hint,children:"Kh\xF4ng t\u1EA3i \u0111\u01B0\u1EE3c mini app"}),(0,b.jsx)(_.TouchableOpacity,{activeOpacity:.7,style:[$.retry_button,{backgroundColor:t?"#27272A":"#F4F4F5"}],onPress:s,children:(0,b.jsx)(_.Text,{style:[$.retry_text,{color:o}],children:"Th\u1EED l\u1EA1i"})})]}):(0,b.jsxs)(b.Fragment,{children:[(0,b.jsx)(_.ActivityIndicator,{style:$.splash_spinner,color:t?"#A1A1AA":"#71717A"}),n==="downloading"&&(0,b.jsxs)(_.Text,{style:$.splash_hint,children:["\u0110ang t\u1EA3i mini app",r?` ${Math.round(r*100)}%`:"\u2026"]})]})]})},Wt=(e,t)=>{let n=(0,d.useRef)(t),r=(0,d.useRef)(!1);__DEV__&&!r.current&&n.current!==t&&(r.current=!0,console.warn(`[miniapp] MiniAppHost prop "${e}" \u0111\u1ED5i gi\u1EEFa c\xE1c l\u1EA7n render \u2192 m\u1ECDi WebView b\u1ECB mount l\u1EA1i. Khai b\xE1o component b\xEAn ngo\xE0i render.`))},bn=({container:e,splash:t=He,is_dark:n=!1,bridge:r,close_on_back:s=!0,opaque_background:o=!0,allow_embedded_miniapps:p=!1,onWebLoadEnd:u})=>{Wt("container",e),Wt("splash",t);let i=e,l=H(F,a=>a.active_key),M=(0,d.useRef)(l);l&&(M.current=l);let y=H(F,a=>Object.keys(a.instances).join("|")),w=H(F,a=>{var C;return a.active_key?(C=a.instances[a.active_key])==null?void 0:C.app.name:void 0}),m=(0,d.useMemo)(()=>y?y.split("|"):[],[y]),[f,N]=(0,d.useState)({}),T=(0,d.useRef)(wn()).current;(0,d.useEffect)(()=>{if(!l||!s)return;let a=_.BackHandler.addEventListener("hardwareBackPress",()=>(te(),!0));return()=>a.remove()},[l,s]);let h=(0,d.useCallback)(()=>{let a=F.getState().active_key;a&&N(C=>({...C,[a]:(C[a]||0)+1}))},[]);return m.length?(0,b.jsx)(i,{visible:!!l,title:w!=null?w:"",is_dark:n,close:te,reload:h,subscribeWebAtTop:T.subscribe,children:m.map(a=>(0,b.jsx)(vn,{instance_key:a,is_active:l===a,is_front:(l!=null?l:M.current)===a,is_dark:n,reload_tick:f[a]||0,web_at_top:T,splash:t,bridge:r,opaque_background:o,allow_embedded_miniapps:p,onWebLoadEnd:u},a))}):null},$=_.StyleSheet.create({webview:{flex:1,backgroundColor:"transparent"},behind:{zIndex:-1},splash:{flex:1,alignItems:"center",justifyContent:"center",gap:12},splash_icon:{width:72,height:72,borderRadius:20,alignItems:"center",justifyContent:"center",overflow:"hidden"},splash_icon_image:{width:72,height:72},splash_letter:{fontSize:28,fontWeight:"700",color:"#1D4ED8"},splash_name:{fontSize:16,fontWeight:"600"},splash_hint:{color:"#71717A"},splash_spinner:{marginTop:8},retry_button:{marginTop:4,paddingHorizontal:20,paddingVertical:10,borderRadius:999},retry_text:{fontWeight:"600"}}),qt=d.default.memo(bn);0&&(module.exports={DefaultMiniAppSplash,MINIAPP_PLATFORM_URL,MiniAppHost,MiniAppHostError,closeMiniApp,configureMiniApp,createMmkvStorage,createRnfsFileSystem,ensureMiniApp,getLocalMiniApp,getMiniAppCatalog,getMiniAppCatalogEntry,getMiniAppStatuses,getMiniAppUpdate,installBundledMiniApp,onMiniAppEvent,openMiniApp,pauseMiniApp,pauseMiniAppDownloads,preloadMiniApp,restoreMiniApp,resumeMiniApp,resumeMiniAppDownloads,sendEventToWeb,syncMiniAppCatalog,uninstallMiniApp,updateMiniApp,useMiniAppDownload,useMiniAppDownloadsPaused});
45
+ true;`},ht={partner:"partner_token",chatbox:"chatbox_token"},At=(e,t)=>{let n={...e};for(let r of Object.values(ht))t.includes(r)||delete n[r];return n},Oe=new Set,De=async(e,t)=>{if(Oe.has(e))throw new M("BUSY",`${e} \u0111ang ch\u1EA1y \u2014 ch\u1EDD l\u01B0\u1EE3t tr\u01B0\u1EDBc xong`);Oe.add(e);try{return await t()}finally{Oe.delete(e)}},pn=new Set(["selection","impactLight","impactMedium","impactHeavy","rigid","soft","notificationSuccess","notificationWarning","notificationError"]),Me=(e,t)=>{if(typeof e!="string"||!e)throw new M("INVALID_PARAMS",`Thi\u1EBFu ${t}`);return e},mt=async({method:e,params:t},{getHostData:n,getPermissions:r,is_dark:s,close:o,app_id:a,instance_id:u,options:i})=>{var _,m,h,F,P,D,l,C;let p=i==null?void 0:i.handlers,v={app_id:a,instance_id:u,close:o},y=()=>new M("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF \u1EE9ng d\u1EE5ng n\xE0y`);switch(e){case"getBiometricAvailability":return i!=null&&i.biometrics?i.biometrics.getAvailability():{available:!1};case"authenticateBiometric":{if(!(i!=null&&i.biometrics))throw y();let f=Me(t==null?void 0:t.reason,"reason").trim();if(!f||f.length>200)throw new M("INVALID_PARAMS","reason must contain 1\u2013200 characters");let w=t==null?void 0:t.cancelButtonText;if(w!==void 0&&(typeof w!="string"||!w.trim()||w.length>80))throw new M("INVALID_PARAMS","Invalid cancelButtonText");return De(e,()=>i.biometrics.authenticate({reason:f,cancelButtonText:w}))}case"requestPayment":{let f=p==null?void 0:p.requestPayment;if(!f)throw y();let w=t==null?void 0:t.amount;if(typeof w!="number"||!Number.isFinite(w)||w<=0)throw new M("INVALID_PARAMS","amount ph\u1EA3i l\xE0 s\u1ED1 > 0");let ne={...t,amount:w,currency:Me(t==null?void 0:t.currency,"currency")};return De(e,()=>f(ne,v))}case"printImage":{let f=p==null?void 0:p.printImage;if(!f)throw y();let w=Me(t==null?void 0:t.image,"image");await De(e,()=>f({image:w},v));return}case"openScreen":if(!(p!=null&&p.openScreen))throw y();await p.openScreen({screen:Me(t==null?void 0:t.screen,"screen"),params:t==null?void 0:t.params},v);return;case"closeApp":o();return;case"openWebview":{let f=String((_=t==null?void 0:t.url)!=null?_:"");if(!/^https?:\/\//i.test(f))throw new M("INVALID_PARAMS","url ph\u1EA3i l\xE0 http(s)");await(i!=null&&i.openUrl?i.openUrl(f):pe.Linking.openURL(f));return}case"openLink":{let f=String((m=t==null?void 0:t.url)!=null?m:"").trim();if(!/^[a-z][a-z0-9+.-]*:/i.test(f)||/^(javascript|file|data|about|blob):/i.test(f))throw new M("INVALID_PARAMS","url kh\xF4ng h\u1EE3p l\u1EC7");try{await(i!=null&&i.openUrl?i.openUrl(f):pe.Linking.openURL(f))}catch(w){throw new M("NOT_SUPPORTED",String((F=(h=w==null?void 0:w.message)!=null?h:w)!=null?F:"Kh\xF4ng m\u1EDF \u0111\u01B0\u1EE3c link"))}return}case"showToast":(D=i==null?void 0:i.showToast)==null||D.call(i,String((P=t==null?void 0:t.message)!=null?P:""));return;case"haptic":{let f=pn.has(t==null?void 0:t.type)?t.type:"selection";(l=i==null?void 0:i.haptic)==null||l.call(i,f);return}case"getSystemInfo":return{platform:pe.Platform.OS==="ios"?"ios":"android",appVersion:(C=i==null?void 0:i.app_version)!=null?C:"",theme:s?"dark":"light"};case"getAccessToken":{let f=n().access_token;if(!f)throw new M("HOST_ERROR","Mini app ch\u01B0a c\xF3 token cho page n\xE0y");return f}case"getToken":{let f=t==null?void 0:t.type;if(f==="access"){let se=n().access_token;if(!se)throw new M("HOST_ERROR","Mini app ch\u01B0a c\xF3 token cho page n\xE0y");return se}if(f!=="partner"&&f!=="chatbox")throw new M("HOST_ERROR",`Lo\u1EA1i token kh\xF4ng h\u1EE3p l\u1EC7: ${String(f)}`);let w=ht[f];if(!r().includes(w))throw new M("PERMISSION_DENIED",`Mini app ch\u01B0a \u0111\u01B0\u1EE3c c\u1EA5p quy\u1EC1n ${w} (Console \u2192 Quy\u1EC1n l\u1EA5y token)`);let ne=f==="partner"?n().partner_token:n().chatbox_token;if(!ne)throw new M("HOST_ERROR",`Kh\xF4ng c\xF3 ${w}`);return ne}case"getUserInfo":{let f=n().user;if(!f)throw new M("HOST_ERROR","Kh\xF4ng l\u1EA5y \u0111\u01B0\u1EE3c th\xF4ng tin nh\xE2n vi\xEAn");return f}case"getPageInfo":{let f=n().page;if(!f)throw new M("HOST_ERROR","Kh\xF4ng l\u1EA5y \u0111\u01B0\u1EE3c th\xF4ng tin page");return f}case"sendMessage":case"insertText":throw new M("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF phi\xEAn b\u1EA3n app n\xE0y`);default:throw new M("NOT_SUPPORTED",`API kh\xF4ng t\u1ED3n t\u1EA1i: ${e}`)}};var Ne=e=>`bundle:${e}`,$e=()=>`${T().file_system.document_dir}/miniapps`,Fe=$e,Ue=(e,t,n="index.html",r=!1,s=[])=>{let o=`${Fe()}/${e}/${t}`;return{app_id:e,version:t,dir:o,entry_uri:`file://${o}/${n}`,context_update:r,permissions:s}},Be=e=>{var t;T().storage.setString(Ne(e.app_id),JSON.stringify({version:e.version,entry:e.entry,context_update:!!e.context_update,permissions:(t=e.permissions)!=null?t:[]}))},ln=(e,t)=>/^https?:\/\//.test(t)?t:`${e.replace(/[^/]*$/,"")}${t}`,x=e=>{let t=T().storage.getString(Ne(e));if(!t)return null;try{let{version:n,entry:r,context_update:s,permissions:o}=JSON.parse(t);return Ue(e,n,r,!!s,Array.isArray(o)?o:[])}catch{return null}},q=e=>T().file_system.exists(e.entry_uri.replace("file://","")),Ve=async e=>{let t=x(e.app_id);return(t==null?void 0:t.version)===e.version&&await q(t)},yt=async(e,t)=>{let n=T().file_system,r=`${Fe()}/${e}`,s=await n.listDir(r).catch(()=>[]);await Promise.all(s.filter(o=>!t.includes(o)).map(o=>n.remove(`${r}/${o}`).catch(()=>{})))},wt=async e=>{var t;await((t=ue[e])==null?void 0:t.catch(()=>{})),T().storage.setString(Ne(e),""),await T().file_system.remove(`${Fe()}/${e}`).catch(()=>{})},re=class extends Error{constructor(){super("cancelled"),this.name="MiniAppInstallCancelled"}},ue={},vt=(e,t)=>{var o;let r=((o=ue[e])!=null?o:Promise.resolve()).catch(()=>{}).then(t),s=r.catch(()=>{});return ue[e]=s,s.then(()=>{ue[e]===s&&delete ue[e]}),r},un=(e,t)=>{var s,o;let n=e.split(".").map(a=>parseInt(a,10)||0),r=t.split(".").map(a=>parseInt(a,10)||0);for(let a=0;a<Math.max(n.length,r.length);a++){let u=((s=n[a])!=null?s:0)-((o=r[a])!=null?o:0);if(u)return u}return 0},_t=({manifest:e,zip_path:t})=>vt(e.app_id,async()=>{var o;let n=T().file_system,r=x(e.app_id);if(r&&un(r.version,e.version)>=0&&await q(r))return r;if(e.sha256&&n.sha256&&await n.sha256(t)!==e.sha256)throw new Error("sha256 mismatch");let s=Ue(e.app_id,e.version,e.entry,!!e.context_update,(o=e.permissions)!=null?o:[]);return await n.remove(s.dir).catch(()=>{}),await n.mkdir(s.dir),await n.unzip(t,s.dir),Be(e),N("\u0111\xE3 c\xE0i b\u1EA3n \u0111\xF3ng s\u1EB5n",e.app_id,e.version),yt(e.app_id,[e.version,r==null?void 0:r.version].filter(Boolean)),s}),Je=(e,{base_url:t,onProgress:n}={})=>{let r=T().file_system,s=null,o=!1,a=`${r.cache_dir}/${e.app_id}-${e.version}.zip`,u=()=>{if(o)throw new re},i=async()=>{var y;u();let p=x(e.app_id);if((p==null?void 0:p.version)===e.version&&await r.exists(p.dir))return Be(e),x(e.app_id);u();let v=r.download({url:t?ln(t,e.bundle_url):e.bundle_url,to_file:a,onProgress:(_,m)=>{var F;let h=m>0?m:(F=e.size)!=null?F:0;h>0&&(n==null||n(Math.min(1,_/h)))}});s=v;try{let{status:_}=await v.promise;if(u(),_!==200)throw new Error(`bundle ${_}`);if(e.sha256)if(r.sha256){if(await r.sha256(a)!==e.sha256)throw new Error("sha256 mismatch")}else N("b\u1ECF qua ki\u1EC3m tra sha256 (file_system kh\xF4ng c\xF3 sha256)",e.app_id);u();let m=Ue(e.app_id,e.version,e.entry,!!e.context_update,(y=e.permissions)!=null?y:[]);return await r.remove(m.dir).catch(()=>{}),await r.mkdir(m.dir),await r.unzip(a,m.dir),Be(e),yt(e.app_id,[e.version,p==null?void 0:p.version].filter(Boolean)),m}catch(_){throw o?new re:_}finally{s=null,r.remove(a).catch(()=>{})}};return{promise:vt(e.app_id,i),cancel:()=>{o=!0,s==null||s.cancel()}}},le={},dn=__DEV__?0:60*1e3,Mt={},St=(e,t)=>{var r,s;let n=x(e);return n&&Date.now()-((r=Mt[t])!=null?r:0)<dn?Promise.resolve(n):((s=le[e])!=null||(le[e]=(async()=>{let o=await fetch(t,{headers:{"Cache-Control":"no-cache"}});if(!o.ok)throw new Error(`manifest ${o.status}`);let a=await o.json(),u=await Je(a,{base_url:t}).promise;return Mt[t]=Date.now(),u})().catch(o=>(console.warn("[miniapp] sync failed",e,o==null?void 0:o.message),x(e))).finally(()=>{le[e]=void 0})),le[e])};var ve=new Map,bt=(e,t)=>(ve.set(e,t),()=>{ve.get(e)===t&&ve.delete(e)}),xt=(e,t)=>{let n=ve.get(e);return n?n(t):!1};var _e=require("react"),Se=e=>{let t=e,n=new Set;return{getState:()=>t,setState:r=>{let s=typeof r=="function"?r(t):r;t={...t,...s},n.forEach(o=>o())},subscribe:r=>(n.add(r),()=>{n.delete(r)})}},j=(e,t,n=Object.is)=>{let r=(0,_e.useRef)(null),s=()=>{let o=e.getState(),a=r.current;if(a&&a.state===o&&a.selector===t)return a.value;let u=t(o),i=a&&n(a.value,u)?a.value:u;return r.current={state:o,selector:t,value:i},i};return(0,_e.useSyncExternalStore)(e.subscribe,s)};var V=Se({active_key:null,instances:{}}),Et=({app:e,instance_id:t,context:n={},url_params:r={},host_data:s={}},o)=>{var u;let a=(u=T().keep_alive)==null?void 0:u.max_webviews;V.setState(i=>{let p=t!=null?t:e.app_id,v={...i.instances,[p]:{key:p,app:e,context:n,url_params:r,host_data:s,last_used_at:Date.now()}},y=Object.keys(v);return a&&a>0&&y.length>a&&y.filter(_=>_!==p).sort((_,m)=>v[_].last_used_at-v[m].last_used_at).slice(0,y.length-a).forEach(_=>{delete v[_]}),o?{active_key:p,instances:v}:{instances:v}})},Tt=e=>Et(e,!0),Rt=e=>Et(e,!1),ie=()=>V.setState({active_key:null}),be=e=>{V.setState(t=>{if(t.active_key===e||!t.instances[e])return{};let n={...t.instances};return delete n[e],{instances:n}})};var Pt="catalog",gn="paused_apps",fn="removed_apps",hn=10*1e3,An=2,mn=3e3,Mn=()=>{var e;try{return JSON.parse((e=T().storage.getString(Pt))!=null?e:"{}")}catch{return{}}},S=Se({catalog:{},downloads:{},pause_reasons:[],updates:{},apply_ticks:{}}),kt=e=>{var t;return!!((t=T().manual_update)!=null&&t.includes(e))},Te=new Set,Ct=e=>{let t=new Set,n=()=>T().storage.setString(e,JSON.stringify([...t]));return{has:r=>t.has(r),values:()=>[...t],add:r=>t.has(r)?!1:(t.add(r),n(),!0),delete:r=>t.delete(r)?(n(),!0):!1,load:()=>{var r;t.clear();try{let s=JSON.parse((r=T().storage.getString(e))!=null?r:"[]");Array.isArray(s)&&s.forEach(o=>{typeof o=="string"&&t.add(o)})}catch{}}}},H=Ct(gn),G=Ct(fn);rt(()=>{H.load(),G.load();let e=Mn(),t={};Object.keys(e).filter(n=>!G.has(n)).forEach(n=>{let r=x(n);r?t[n]={status:"installed",progress:1,version:r.version,has_local:!0}:H.has(n)&&(t[n]={status:"paused",progress:0,version:e[n].version,has_local:!1})}),S.setState({catalog:e,downloads:t})});var Re=e=>j(S,t=>e?t.downloads[e]:void 0),It=()=>j(S,e=>e.pause_reasons.length>0),J=(...e)=>N("queue",...e),k=[],K={},A=null,xe=new Set,te={},He=new Set,Y=e=>{He.forEach(t=>{try{t(e)}catch(n){console.warn("[miniapp-queue] event listener error",n==null?void 0:n.message)}})},Ot=e=>(He.add(e),()=>{He.delete(e)}),Dt=()=>S.getState().downloads,O=(e,t)=>{let n=!!x(e),r=S.getState().downloads[e],s=t.status==="downloading"&&n?"updating":t.status,o={...r!=null?r:{status:"queued",progress:0},...t,...s?{status:s}:{},has_local:n};S.setState(a=>({downloads:{...a.downloads,[e]:o}})),(r==null?void 0:r.status)!==o.status||(r==null?void 0:r.version)!==o.version||(r==null?void 0:r.has_local)!==o.has_local?Y({type:"status_change",app_id:e,state:o}):r.progress!==o.progress&&Y({type:"progress",app_id:e,progress:o.progress,version:o.version})},Ee=(e,t)=>{var n;(n=te[e])==null||n.forEach(r=>r(t)),delete te[e]},yn=()=>S.getState().pause_reasons.length>0,Q=e=>{var u;if(A)return;let t=e?k.indexOf(e):yn()?-1:k.findIndex(i=>!H.has(i));if(t<0||t>=k.length)return;let[n]=k.splice(t,1),r=S.getState().catalog[n];if(!r){Ee(n,x(n)),Q();return}let s=Date.now();K[n]=((u=K[n])!=null?u:0)+1,O(n,{status:"downloading",progress:0,version:r.version,error:void 0});let o=0,a=Je(r,{onProgress:i=>{let p=Math.floor(i*100);p!==o&&(o=p,O(n,{progress:p/100,version:r.version}))}});A={app_id:n,handle:a,forced:!!e},J("start",n,r.version,e?"(forced)":""),a.promise.then(i=>{J("installed",n,r.version,`${Date.now()-s}ms`),O(n,{status:"installed",progress:1,version:r.version}),Ee(n,i)}).catch(i=>{var v;if(i instanceof re){if(xe.has(n))return;J("paused",n),K[n]-=1,k.unshift(n),O(n,{status:H.has(n)?"paused":"queued",progress:0,version:r.version});return}let p=String((v=i==null?void 0:i.message)!=null?v:i);if(console.warn("[miniapp-queue] failed",n,p),K[n]<An){O(n,{status:"queued",progress:0,version:r.version,error:p}),setTimeout(()=>{var y;k.includes(n)||(A==null?void 0:A.app_id)===n||(k.push(n),Q((y=te[n])!=null&&y.length?n:void 0))},mn);return}O(n,{status:"failed",progress:0,version:r.version,error:p}),Ee(n,x(n))}).finally(()=>{A=null;let i=k.find(p=>{var v;return(v=te[p])==null?void 0:v.length});Q(i)})},Pe=(e,{front:t=!1}={})=>{if((A==null?void 0:A.app_id)===e)return;let n=k.indexOf(e);if(n>=0){if(!t)return;k.splice(n,1)}t?k.unshift(e):k.push(e)},wn=async e=>{let{host_id:t,client_token:n}=T(),r=new AbortController,s=setTimeout(()=>r.abort(),hn);try{let o=`${me}/api/hosts/${encodeURIComponent(t)}/miniapps?channel=${e}`,a=await fetch(o,{headers:{Authorization:`Bearer ${n}`,"Cache-Control":"no-cache"},signal:r.signal});if(!a.ok)throw new Error(`host list ${e} ${a.status}`);return(await a.json()).apps.map(i=>({...i,channel:e}))}finally{clearTimeout(s)}},de=null,ke=()=>(de!=null||(de=(async()=>{var t;let e=Date.now();try{let n=await Promise.all(T().channels.map(wn)),r={};[...n].reverse().flat().forEach(i=>{r[i.app_id]=i});let s=Object.keys(S.getState().catalog).filter(i=>!r[i]);T().storage.setString(Pt,JSON.stringify(r)),S.setState({catalog:r}),await Promise.all(s.map(i=>Lt(i,{by_user:!1}))),s.forEach(i=>G.delete(i));let o=Object.keys(r).filter(i=>!G.has(i)),a=[],u={};for(let i of o.map(p=>r[p])){if(await Ve(i)){O(i.app_id,{status:"installed",progress:1,version:i.version});continue}let p=x(i.app_id);if(kt(i.app_id)&&!Te.has(i.app_id)&&p&&await q(p)){O(i.app_id,{status:"installed",progress:1,version:p.version}),u[i.app_id]={app_id:i.app_id,current_version:p.version,next_version:i.version};continue}a.push(i)}return S.setState({updates:u}),a.forEach(i=>{K[i.app_id]=0,O(i.app_id,{status:H.has(i.app_id)?"paused":"queued",progress:0,version:i.version,error:void 0}),Pe(i.app_id)}),J("catalog",o.length,"apps, outdated",a.map(i=>i.app_id),"removed",s,`${Date.now()-e}ms`),Y({type:"sync_complete",app_ids:o,removed:s}),Object.values(u).forEach(i=>Y({type:"update_available",...i})),Q(),{ok:!0,app_ids:o,removed:s}}catch(n){let r=String((n==null?void 0:n.name)==="AbortError"?"timeout":(t=n==null?void 0:n.message)!=null?t:n);return console.warn("[miniapp-queue] sync catalog failed",r),Y({type:"sync_failed",error:r}),{ok:!1,error:r}}finally{de=null}})()),de),Lt=async(e,{by_user:t})=>{var s,o,a,u;if(t&&G.add(e),xe.has(e))return;xe.add(e),H.delete(e);let n=k.indexOf(e);n>=0&&k.splice(n,1),(A==null?void 0:A.app_id)===e&&A.handle.cancel();let r=(u=(a=(s=S.getState().downloads[e])==null?void 0:s.version)!=null?a:(o=x(e))==null?void 0:o.version)!=null?u:"";O(e,{status:"uninstalling",progress:0,version:r}),await wt(e),be(e),S.setState(i=>{let p={...i.downloads};return delete p[e],{downloads:p}}),delete K[e],xe.delete(e),Ee(e,null),J("uninstalled",e,t?"(user)":"(not in list)"),Y({type:"uninstalled",app_id:e})},Bt=e=>Lt(e,{by_user:!0}),Nt=e=>{let t=oe(e);return t?(G.delete(e),(A==null?void 0:A.app_id)===e||k.includes(e)||(K[e]=0,O(e,{status:H.has(e)?"paused":"queued",progress:0,version:t.version,error:void 0}),Pe(e),Q(),J("restore",e)),!0):!1},$t=e=>{if(H.has(e))return;if(H.add(e),J("pause app",e),(A==null?void 0:A.app_id)===e&&!A.forced){A.handle.cancel();return}let t=S.getState().downloads[e];k.includes(e)&&t&&O(e,{status:"paused",progress:0,version:t.version})},Ft=e=>{if(!H.delete(e))return;J("resume app",e);let t=S.getState().downloads[e];(t==null?void 0:t.status)==="paused"&&!k.includes(e)&&oe(e)&&(K[e]=0,Pe(e)),k.includes(e)&&t&&O(e,{status:"queued",progress:0,version:t.version}),Q()},Ut=e=>{let{pause_reasons:t}=S.getState();t.includes(e)||(S.setState({pause_reasons:[...t,e]}),J("pause",e),t.length===0&&Y({type:"pause_change",paused:!0,reasons:[e]}),A&&!A.forced&&A.handle.cancel())},Vt=e=>{let{pause_reasons:t}=S.getState();if(!t.includes(e))return;let n=t.filter(r=>r!==e);S.setState({pause_reasons:n}),J("resume",e),n.length===0&&Y({type:"pause_change",paused:!1,reasons:n}),Q()},We=e=>S.getState().updates[e],Jt=async e=>{var n,r;let t=We(e);Te.add(e);try{let s=await ge(e),o=(r=t==null?void 0:t.next_version)!=null?r:(n=oe(e))==null?void 0:n.version;return!s||!o||s.version!==o?!1:(S.setState(a=>{var i;let u={...a.updates};return delete u[e],{updates:u,apply_ticks:{...a.apply_ticks,[e]:((i=a.apply_ticks[e])!=null?i:0)+1}}}),J("updated",e,t==null?void 0:t.current_version,"\u2192",s.version),!0)}finally{Te.delete(e)}},Ht=()=>Object.values(S.getState().catalog).map(e=>({...e,installed:!!x(e.app_id),removed_by_user:G.has(e.app_id)})),oe=e=>S.getState().catalog[e],ge=async e=>{let t=oe(e);if(!t)return;if(H.delete(e),G.delete(e),await Ve(t))return x(e);let n=x(e);if(kt(e)&&!Te.has(e)&&n&&await q(n))return n;let r=new Promise(s=>{var o;((o=te[e])!=null?o:te[e]=[]).push(s)});return(A==null?void 0:A.app_id)===e?A.forced=!0:(K[e]=0,Pe(e,{front:!0}),A&&!A.forced?A.handle.cancel():Q(e)),r};var E=require("react/jsx-runtime"),je=e=>(e!=null?e:"").replace(/\?[^#]*/,""),Wt=0,vn=()=>{let e=new Set;return{emit:t=>e.forEach(n=>n(t)),subscribe:t=>(e.add(t),()=>{e.delete(t)})}},_n=d.default.memo(({instance_key:e,is_active:t,is_front:n,is_dark:r,reload_tick:s,web_at_top:o,splash:a,bridge:u,opaque_background:i,allow_embedded_miniapps:p,onWebLoadEnd:v})=>{var Ge,Xe;let y=(0,d.useRef)(null),_=(0,d.useRef)(!1),m=j(V,c=>c.instances[e]),h=m==null?void 0:m.app.app_id,F=m==null?void 0:m.app.manifest_url,P=m==null?void 0:m.context,D=m==null?void 0:m.url_params,[l,C]=(0,d.useState)(()=>h?x(h):null),[f,w]=(0,d.useState)(!1),[ne,se]=(0,d.useState)(0),[Yt,ae]=(0,d.useState)(0),[Qt,L]=(0,d.useState)(!1),W=(0,d.useRef)(null),Ke=c=>{W.current&&clearTimeout(W.current),W.current=setTimeout(()=>{W.current=null,L(!0)},c)};(0,d.useEffect)(()=>()=>{W.current&&clearTimeout(W.current)},[]),(0,d.useEffect)(()=>{if(!h||!t&&l)return;let c=!0;return w(!1),(async()=>{let g=x(h),I=g?await q(g):!1;if(!c||(C(I?U=>!U||U.version!==g.version||U.permissions.join(",")!==g.permissions.join(",")?g:U:null),__DEV__&&Date.now()-Wt>1e4&&(Wt=Date.now(),await ke()),!c))return;let z=await ge(h),X=z!==void 0?z:F?await St(h,F):x(h);if(c){if(!X){w(!0);return}C(U=>U!=null?U:X)}})(),()=>{c=!1}},[t,h,F,ne]),(0,d.useEffect)(()=>bt(e,c=>y.current?(y.current.postMessage(c),!0):!1),[e]);let Gt=j(S,c=>{let g=h?c.downloads[h]:void 0;return(g==null?void 0:g.status)==="installed"?g.version:void 0});(0,d.useEffect)(()=>{if(t||!h||!l)return;let c=x(h);if(!c||c.version===l.version)return;let g=!0;return q(c).then(I=>{!g||!I||(N(`webview:${e}`,"\u0111\u1ED5i bundle (\u1EA9n)",l.version,"\u2192",c.version),C(c))}),()=>{g=!1}},[t,h,Gt,l==null?void 0:l.version]);let ze=j(S,c=>{var g;return h&&(g=c.apply_ticks[h])!=null?g:0});(0,d.useEffect)(()=>{if(!ze||!h)return;let c=x(h);if(!c||c.version===(l==null?void 0:l.version))return;let g=!0;return q(c).then(I=>{!g||!I||(N(`webview:${e}`,"c\u1EADp nh\u1EADt",l==null?void 0:l.version,"\u2192",c.version),L(!1),C(c))}),()=>{g=!1}},[ze]),(0,d.useEffect)(()=>{var I;let c=(I=T().keep_alive)==null?void 0:I.idle_close_ms;if(t||!c||c<=0)return;let g=setTimeout(()=>{be(e)},c);return()=>clearTimeout(g)},[t,e]),(0,d.useEffect)(()=>{s>0&&(w(!1),L(!1),ae(c=>c+1),se(c=>c+1))},[s]);let Ye=(0,d.useRef)(t);(0,d.useEffect)(()=>{var c;Ye.current!==t&&(Ye.current=t,_.current&&((c=y.current)==null||c.injectJavaScript(ut(t?"resumed":"paused"))))},[t]);let fe=`${(Ge=l==null?void 0:l.version)!=null?Ge:"none"}:${(Xe=l==null?void 0:l.permissions.join(","))!=null?Xe:""}:${Yt}`,ce=(0,d.useMemo)(()=>JSON.stringify([P!=null?P:{},D!=null?D:{}]),[P,D]),Ce=(0,d.useMemo)(()=>{var c;return At(D!=null?D:{},(c=l==null?void 0:l.permissions)!=null?c:[])},[ce,l==null?void 0:l.permissions]),Xt=(0,d.useMemo)(()=>ft(P!=null?P:{},Ce)+lt()+(T().debug?pt():""),[Ce]),he=(0,d.useRef)(null),Qe=(0,d.useRef)(null);(0,d.useEffect)(()=>{var g,I,z;if(!l)return;if(Qe.current!==fe){Qe.current=fe,he.current=ce;return}if(he.current===ce)return;let c=((I=JSON.parse((g=he.current)!=null?g:"[]")[0])!=null?I:{}).org_id;if(he.current=ce,c===(P==null?void 0:P.org_id)&&_.current){L(!1),Ke(1500),(z=y.current)==null||z.injectJavaScript(dt(P!=null?P:{},Ce));return}L(!1),ae(X=>X+1)},[ce,l,fe]);let Zt=(0,d.useCallback)(async c=>{var I,z,X,U,Ie;let g=st(c.nativeEvent.data);if(!g){if(h&&(u!=null&&u.onWebEvent))try{Promise.resolve(u.onWebEvent(c.nativeEvent.data,{app_id:h,instance_id:e})).catch(R=>{console.warn("[miniapp] onWebEvent l\u1ED7i",h,R)})}catch(R){console.warn("[miniapp] onWebEvent l\u1ED7i",h,R)}return}if(g.method==="log"){let{level:R,text:B}=g;N(`web:${e}`,R!=null?R:"log",B!=null?B:"");return}if(g.method==="pong"){W.current||L(!0);return}if(g.method==="touchAtTop"){o.emit(!!g.at_top);return}if(g.method==="contextApplied"){W.current&&clearTimeout(W.current),W.current=null,L(!0);return}if(g.method==="ready"){_.current=!0,L(!0);let R=(I=V.getState().instances[e])==null?void 0:I.context;R&&((z=y.current)==null||z.injectJavaScript(Le(R)));return}try{let R=await mt(g,{getHostData:()=>{var B,Z;return(Z=(B=V.getState().instances[e])==null?void 0:B.host_data)!=null?Z:{}},getPermissions:()=>{var B,Z;return h?(Z=(B=x(h))==null?void 0:B.permissions)!=null?Z:[]:[]},is_dark:r,close:ie,app_id:h!=null?h:"",instance_id:e,options:u});g.id&&((X=y.current)==null||X.injectJavaScript(at(g.id,R)))}catch(R){if(!g.id)return;let B=R==null?void 0:R.code,Z=R instanceof M?R:new M(typeof B=="string"?B:"HOST_ERROR",String((U=R==null?void 0:R.message)!=null?U:R));(Ie=y.current)==null||Ie.injectJavaScript(ct(g.id,Z))}},[e,r,h,o,u]),en=(0,d.useCallback)(()=>{w(!1),ae(c=>c+1),se(c=>c+1)},[]);return(0,E.jsxs)(b.View,{style:[b.StyleSheet.absoluteFill,i&&{backgroundColor:r?"#09090B":"#FFFFFF"},!n&&$.behind],pointerEvents:t?"auto":"none",children:[l?(0,E.jsx)(qt.default,{ref:y,source:{uri:l.entry_uri},originWhitelist:["*"],allowingReadAccessToURL:`file://${p?$e():l.dir}`,allowFileAccess:!0,allowFileAccessFromFileURLs:!0,allowUniversalAccessFromFileURLs:!0,injectedJavaScriptBeforeContentLoaded:Xt,onMessage:Zt,bounces:!1,overScrollMode:"never",onLoadStart:c=>{N(`webview:${e}`,"load start",je(c.nativeEvent.url)),_.current=!1,L(!1)},onError:c=>{N(`webview:${e}`,"load error",je(c.nativeEvent.url),c.nativeEvent.description),w(!0),L(!1)},onLoadEnd:c=>{let g=c.nativeEvent.url;N(`webview:${e}`,"load end",je(g)),h&&(v==null||v({app_id:h,instance_id:e,url:g})),Ke(1500)},onContentProcessDidTerminate:()=>{_.current=!1,L(!1),ae(c=>c+1)},onRenderProcessGone:()=>(_.current=!1,L(!1),ae(c=>c+1),!0),style:$.webview},fe):null,m&&(0,E.jsx)(bn,{visible:!l||!Qt,interactive:f,children:(0,E.jsx)(Sn,{splash:a,app:m.app,is_dark:r,error:f,has_bundle:!!l,retry:en})})]})}),Sn=d.default.memo(({splash:e,app:t,is_dark:n,error:r,has_bundle:s,retry:o})=>{let a=e,u=Re(t.app_id),i=r?"error":!s&&(u==null?void 0:u.status)==="downloading"?"downloading":"loading";return(0,E.jsx)(a,{app:t,is_dark:n,status:i,progress:i==="downloading"?u==null?void 0:u.progress:void 0,retry:o})}),bn=({visible:e,interactive:t,children:n})=>{let r=(0,d.useRef)(new b.Animated.Value(e?1:0)).current,[s,o]=(0,d.useState)(e);return(0,d.useEffect)(()=>{if(e){o(!0),r.setValue(1);return}let a=b.Animated.timing(r,{toValue:0,duration:180,useNativeDriver:!0});return a.start(({finished:u})=>{u&&o(!1)}),()=>a.stop()},[e,r]),s?(0,E.jsx)(b.Animated.View,{style:[b.StyleSheet.absoluteFill,{opacity:r}],pointerEvents:t?"auto":"none",children:n}):null},qe=({app:e,is_dark:t,status:n,progress:r,retry:s})=>{let o=t?"#FAFAFA":"#18181B";return(0,E.jsxs)(b.View,{style:[$.splash,{backgroundColor:t?"#09090B":"#FFFFFF"}],children:[(0,E.jsx)(b.View,{style:[$.splash_icon,{backgroundColor:t?"#18181B":"#F4F4F5"}],children:e.icon?(0,E.jsx)(b.Image,{source:{uri:e.icon},style:$.splash_icon_image}):(0,E.jsx)(b.Text,{style:$.splash_letter,children:(e.name||"?").slice(0,1).toUpperCase()})}),(0,E.jsx)(b.Text,{style:[$.splash_name,{color:o}],children:e.name}),n==="error"?(0,E.jsxs)(E.Fragment,{children:[(0,E.jsx)(b.Text,{style:$.splash_hint,children:"Kh\xF4ng t\u1EA3i \u0111\u01B0\u1EE3c mini app"}),(0,E.jsx)(b.TouchableOpacity,{activeOpacity:.7,style:[$.retry_button,{backgroundColor:t?"#27272A":"#F4F4F5"}],onPress:s,children:(0,E.jsx)(b.Text,{style:[$.retry_text,{color:o}],children:"Th\u1EED l\u1EA1i"})})]}):(0,E.jsxs)(E.Fragment,{children:[(0,E.jsx)(b.ActivityIndicator,{style:$.splash_spinner,color:t?"#A1A1AA":"#71717A"}),n==="downloading"&&(0,E.jsxs)(b.Text,{style:$.splash_hint,children:["\u0110ang t\u1EA3i mini app",r?` ${Math.round(r*100)}%`:"\u2026"]})]})]})},jt=(e,t)=>{let n=(0,d.useRef)(t),r=(0,d.useRef)(!1);__DEV__&&!r.current&&n.current!==t&&(r.current=!0,console.warn(`[miniapp] MiniAppHost prop "${e}" \u0111\u1ED5i gi\u1EEFa c\xE1c l\u1EA7n render \u2192 m\u1ECDi WebView b\u1ECB mount l\u1EA1i. Khai b\xE1o component b\xEAn ngo\xE0i render.`))},xn=({container:e,splash:t=qe,is_dark:n=!1,bridge:r,close_on_back:s=!0,opaque_background:o=!0,allow_embedded_miniapps:a=!1,onWebLoadEnd:u})=>{jt("container",e),jt("splash",t);let i=e,p=j(V,l=>l.active_key),v=(0,d.useRef)(p);p&&(v.current=p);let y=j(V,l=>Object.keys(l.instances).join("|")),_=j(V,l=>{var C;return l.active_key?(C=l.instances[l.active_key])==null?void 0:C.app.name:void 0}),m=(0,d.useMemo)(()=>y?y.split("|"):[],[y]),[h,F]=(0,d.useState)({}),P=(0,d.useRef)(vn()).current;(0,d.useEffect)(()=>{if(!p||!s)return;let l=b.BackHandler.addEventListener("hardwareBackPress",()=>(ie(),!0));return()=>l.remove()},[p,s]);let D=(0,d.useCallback)(()=>{let l=V.getState().active_key;l&&F(C=>({...C,[l]:(C[l]||0)+1}))},[]);return m.length?(0,E.jsx)(i,{visible:!!p,title:_!=null?_:"",is_dark:n,close:ie,reload:D,subscribeWebAtTop:P.subscribe,children:m.map(l=>(0,E.jsx)(_n,{instance_key:l,is_active:p===l,is_front:(p!=null?p:v.current)===l,is_dark:n,reload_tick:h[l]||0,web_at_top:P,splash:t,bridge:r,opaque_background:o,allow_embedded_miniapps:a,onWebLoadEnd:u},l))}):null},$=b.StyleSheet.create({webview:{flex:1,backgroundColor:"transparent"},behind:{zIndex:-1},splash:{flex:1,alignItems:"center",justifyContent:"center",gap:12},splash_icon:{width:72,height:72,borderRadius:20,alignItems:"center",justifyContent:"center",overflow:"hidden"},splash_icon_image:{width:72,height:72},splash_letter:{fontSize:28,fontWeight:"700",color:"#1D4ED8"},splash_name:{fontSize:16,fontWeight:"600"},splash_hint:{color:"#71717A"},splash_spinner:{marginTop:8},retry_button:{marginTop:4,paddingHorizontal:20,paddingVertical:10,borderRadius:999},retry_text:{fontWeight:"600"}}),Kt=d.default.memo(xn);var zt=e=>({getAvailability:async()=>{var r;let t=await e.isSensorAvailable(),n=["FaceID","TouchID","Biometrics"].includes((r=t.biometryType)!=null?r:"")?t.biometryType:void 0;return{available:t.available,...n?{biometryType:n}:{}}},authenticate:async({reason:t,cancelButtonText:n})=>{try{let{available:r}=await e.isSensorAvailable();if(!r)throw new M("BIOMETRIC_UNAVAILABLE","Biometrics unavailable, not enrolled or permission denied");let s=await e.simplePrompt({promptMessage:t,cancelButtonText:n,fallbackPromptMessage:""});if(!s.success)throw new M("CANCELLED",s.error||"Biometric authentication cancelled");return{success:!0}}catch(r){throw r instanceof M?r:new M("AUTHENTICATION_FAILED",r instanceof Error?r.message:String(r))}}});0&&(module.exports={DefaultMiniAppSplash,MINIAPP_PLATFORM_URL,MiniAppHost,MiniAppHostError,closeMiniApp,configureMiniApp,createMmkvStorage,createReactNativeBiometrics,createRnfsFileSystem,ensureMiniApp,getLocalMiniApp,getMiniAppCatalog,getMiniAppCatalogEntry,getMiniAppStatuses,getMiniAppUpdate,installBundledMiniApp,onMiniAppEvent,openMiniApp,pauseMiniApp,pauseMiniAppDownloads,preloadMiniApp,restoreMiniApp,resumeMiniApp,resumeMiniAppDownloads,sendEventToWeb,syncMiniAppCatalog,uninstallMiniApp,updateMiniApp,useMiniAppDownload,useMiniAppDownloadsPaused});
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- var Te="https://retion-miniapp-platform.vercel.app",X=null,tt=new Set,Ft=e=>{X=e,tt.forEach(t=>t())},_=()=>{if(!X)throw new Error("[miniapp] Ch\u01B0a g\u1ECDi configureMiniApp()");return X},nt=e=>{tt.add(e),X&&e()},I=(...e)=>{X!=null&&X.debug&&console.log("[miniapp]",...e)};var Jt=(e,t)=>({document_dir:e.DocumentDirectoryPath,cache_dir:e.CachesDirectoryPath,exists:n=>e.exists(n),mkdir:n=>e.mkdir(n),remove:n=>e.unlink(n).catch(()=>{}),listDir:n=>e.readDir(n).then(r=>r.map(s=>s.name)).catch(()=>[]),sha256:n=>e.hash(n,"sha256"),unzip:async(n,r)=>{await t(n,r)},download:({url:n,to_file:r,onProgress:s})=>{let{jobId:o,promise:p}=e.downloadFile({fromUrl:n,toFile:r,progressInterval:250,begin:()=>{},progress:({bytesWritten:u,contentLength:i})=>s==null?void 0:s(u,i)});return{promise:p.then(({statusCode:u})=>({status:u})),cancel:()=>e.stopDownload(o)}}}),Vt=e=>({getString:t=>e.getString(t),setString:(t,n)=>e.set(t,n)});import qe,{useCallback as We,useEffect as J,useMemo as xe,useRef as V,useState as ee}from"react";import{ActivityIndicator as wn,Animated as Ue,BackHandler as vn,Image as _n,StyleSheet as Ke,Text as ue,TouchableOpacity as Sn,View as je}from"react-native";import bn from"react-native-webview";import{Linking as Ut,Platform as Ht}from"react-native";var he=1,b=class extends Error{constructor(n,r){super(r);this.code=n}},it=e=>{try{let t=JSON.parse(e);return(t==null?void 0:t.__retion)===he&&typeof t.method=="string"?t:null}catch{return null}},Ae=e=>`window.__RETION_MINIAPP__ && window.__RETION_MINIAPP__.receive(${JSON.stringify(e)}); true;`,ot=(e,t)=>Ae({id:e,result:t}),st=(e,t)=>Ae({id:e,error:{code:t.code,message:t.message}}),ke=e=>Ae({event:"context",data:e});var at=()=>`(function () {
1
+ var Ce="https://retion-miniapp-platform.vercel.app",ee=null,rt=new Set,Ut=e=>{ee=e,rt.forEach(t=>t())},b=()=>{if(!ee)throw new Error("[miniapp] Ch\u01B0a g\u1ECDi configureMiniApp()");return ee},it=e=>{rt.add(e),ee&&e()},L=(...e)=>{ee!=null&&ee.debug&&console.log("[miniapp]",...e)};var Vt=(e,t)=>({document_dir:e.DocumentDirectoryPath,cache_dir:e.CachesDirectoryPath,exists:n=>e.exists(n),mkdir:n=>e.mkdir(n),remove:n=>e.unlink(n).catch(()=>{}),listDir:n=>e.readDir(n).then(r=>r.map(s=>s.name)).catch(()=>[]),sha256:n=>e.hash(n,"sha256"),unzip:async(n,r)=>{await t(n,r)},download:({url:n,to_file:r,onProgress:s})=>{let{jobId:o,promise:a}=e.downloadFile({fromUrl:n,toFile:r,progressInterval:250,begin:()=>{},progress:({bytesWritten:u,contentLength:i})=>s==null?void 0:s(u,i)});return{promise:a.then(({statusCode:u})=>({status:u})),cancel:()=>e.stopDownload(o)}}}),Jt=e=>({getString:t=>e.getString(t),setString:(t,n)=>e.set(t,n)});import Ye,{useCallback as Ke,useEffect as J,useMemo as Re,useRef as H,useState as ne}from"react";import{ActivityIndicator as wn,Animated as je,BackHandler as vn,Image as _n,StyleSheet as Qe,Text as ge,TouchableOpacity as Sn,View as ze}from"react-native";import bn from"react-native-webview";import{Linking as ot,Platform as Ht}from"react-native";var Me=1,m=class extends Error{constructor(n,r){super(r);this.code=n}},st=e=>{try{let t=JSON.parse(e);return(t==null?void 0:t.__retion)===Me&&typeof t.method=="string"?t:null}catch{return null}},ye=e=>`window.__RETION_MINIAPP__ && window.__RETION_MINIAPP__.receive(${JSON.stringify(e)}); true;`,at=(e,t)=>ye({id:e,result:t}),ct=(e,t)=>ye({id:e,error:{code:t.code,message:t.message}}),De=e=>ye({event:"context",data:e});var pt=()=>`(function () {
2
2
  var post = function (level, args) {
3
3
  try {
4
4
  var parts = [];
@@ -8,7 +8,7 @@ var Te="https://retion-miniapp-platform.vercel.app",X=null,tt=new Set,Ft=e=>{X=e
8
8
  else if (typeof a === 'object') { try { parts.push(JSON.stringify(a).slice(0, 800)); } catch (e) { parts.push(String(a)); } }
9
9
  else { parts.push(String(a)); }
10
10
  }
11
- window.ReactNativeWebView && window.ReactNativeWebView.postMessage(JSON.stringify({ __retion: ${he}, method: 'log', level: level, text: parts.join(' ') }));
11
+ window.ReactNativeWebView && window.ReactNativeWebView.postMessage(JSON.stringify({ __retion: ${Me}, method: 'log', level: level, text: parts.join(' ') }));
12
12
  } catch (e) {}
13
13
  };
14
14
  ['log', 'info', 'warn', 'error'].forEach(function (level) {
@@ -19,7 +19,7 @@ var Te="https://retion-miniapp-platform.vercel.app",X=null,tt=new Set,Ft=e=>{X=e
19
19
  window.addEventListener('unhandledrejection', function (e) { post('error', ['[unhandledrejection]', e.reason]); });
20
20
  // Kh\xF4ng log query (c\xF3 th\u1EC3 ch\u1EE9a token) \u2014 ch\u1EC9 \u0111\u01B0\u1EDDng d\u1EABn + route.
21
21
  post('info', ['[page] ' + location.pathname + location.hash]);
22
- })(); true;`,pt=()=>`(function () {
22
+ })(); true;`,lt=()=>`(function () {
23
23
  function atTop(el) {
24
24
  for (var n = el; n && n !== document.documentElement; n = n.parentElement) {
25
25
  if (n.scrollTop > 0) { return false; }
@@ -30,7 +30,7 @@ var Te="https://retion-miniapp-platform.vercel.app",X=null,tt=new Set,Ft=e=>{X=e
30
30
  function report(at_top) {
31
31
  if (at_top === last) { return; }
32
32
  last = at_top;
33
- window.ReactNativeWebView && window.ReactNativeWebView.postMessage(JSON.stringify({ __retion: ${he}, method: 'touchAtTop', at_top: at_top }));
33
+ window.ReactNativeWebView && window.ReactNativeWebView.postMessage(JSON.stringify({ __retion: ${Me}, method: 'touchAtTop', at_top: at_top }));
34
34
  }
35
35
  document.addEventListener('touchstart', function (e) { report(atTop(e.target)); }, { capture: true, passive: true });
36
36
  // Cu\u1ED9n r\u1EDDi \u0111\u1EA7u trang \u2192 b\xE1o ngay, kh\xF4ng \u0111\u1EE3i l\u1EA7n ch\u1EA1m sau (tr\xE1nh host d\xF9ng gi\xE1 tr\u1ECB c\u0169 "\u0111ang \u1EDF \u0111\u1EA7u").
@@ -38,8 +38,8 @@ var Te="https://retion-miniapp-platform.vercel.app",X=null,tt=new Set,Ft=e=>{X=e
38
38
  var el = e.target === document ? document.documentElement : e.target;
39
39
  if (el && el.scrollTop > 0) { report(false); }
40
40
  }, { capture: true, passive: true });
41
- })(); true;`,ct=e=>Ae({event:e}),lt=(e,t)=>{let n=ut(t);return`try { history.replaceState(history.state, '', location.pathname + ${JSON.stringify(n?`?${n}`:"")} + location.hash); } catch (e) {}
42
- ${ke(e)}`},ut=e=>Object.entries(e).filter(([,t])=>t!=null&&t!=="").map(([t,n])=>`${encodeURIComponent(t)}=${encodeURIComponent(String(n))}`).join("&"),dt=(e,t={})=>{let n=ut(t);return`window.__RETION_MINIAPP_HOST__ = { protocol: ${he} };
41
+ })(); true;`,ut=e=>ye({event:e}),dt=(e,t)=>{let n=gt(t);return`try { history.replaceState(history.state, '', location.pathname + ${JSON.stringify(n?`?${n}`:"")} + location.hash); } catch (e) {}
42
+ ${De(e)}`},gt=e=>Object.entries(e).filter(([,t])=>t!=null&&t!=="").map(([t,n])=>`${encodeURIComponent(t)}=${encodeURIComponent(String(n))}`).join("&"),ft=(e,t={})=>{let n=gt(t);return`window.__RETION_MINIAPP_HOST__ = { protocol: ${Me} };
43
43
  window.__RETION_MINIAPP_CONTEXT__ = ${JSON.stringify(e)};
44
44
  ${n?`try { history.replaceState(history.state, '', location.pathname + '?' + ${JSON.stringify(n)} + location.hash); } catch (e) {}`:""}
45
- true;`},gt={partner:"partner_token",chatbox:"chatbox_token"},ft=(e,t)=>{let n={...e};for(let r of Object.values(gt))t.includes(r)||delete n[r];return n},Pe=new Set,rt=async(e,t)=>{if(Pe.has(e))throw new b("BUSY",`${e} \u0111ang ch\u1EA1y \u2014 ch\u1EDD l\u01B0\u1EE3t tr\u01B0\u1EDBc xong`);Pe.add(e);try{return await t()}finally{Pe.delete(e)}},Wt=new Set(["selection","impactLight","impactMedium","impactHeavy","rigid","soft","notificationSuccess","notificationWarning","notificationError"]),Ce=(e,t)=>{if(typeof e!="string"||!e)throw new b("INVALID_PARAMS",`Thi\u1EBFu ${t}`);return e},ht=async({method:e,params:t},{getHostData:n,getPermissions:r,is_dark:s,close:o,app_id:p,instance_id:u,options:i})=>{var y,A,g,L,x;let l=i==null?void 0:i.handlers,m={app_id:p,instance_id:u,close:o},M=()=>new b("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF \u1EE9ng d\u1EE5ng n\xE0y`);switch(e){case"requestPayment":{let f=l==null?void 0:l.requestPayment;if(!f)throw M();let a=t==null?void 0:t.amount;if(typeof a!="number"||!Number.isFinite(a)||a<=0)throw new b("INVALID_PARAMS","amount ph\u1EA3i l\xE0 s\u1ED1 > 0");let R={...t,amount:a,currency:Ce(t==null?void 0:t.currency,"currency")};return rt(e,()=>f(R,m))}case"printImage":{let f=l==null?void 0:l.printImage;if(!f)throw M();let a=Ce(t==null?void 0:t.image,"image");await rt(e,()=>f({image:a},m));return}case"openScreen":if(!(l!=null&&l.openScreen))throw M();await l.openScreen({screen:Ce(t==null?void 0:t.screen,"screen"),params:t==null?void 0:t.params},m);return;case"closeApp":o();return;case"openWebview":{let f=String((y=t==null?void 0:t.url)!=null?y:"");if(!/^https?:\/\//i.test(f))throw new b("INVALID_PARAMS","url ph\u1EA3i l\xE0 http(s)");await(i!=null&&i.openUrl?i.openUrl(f):Ut.openURL(f));return}case"showToast":(g=i==null?void 0:i.showToast)==null||g.call(i,String((A=t==null?void 0:t.message)!=null?A:""));return;case"haptic":{let f=Wt.has(t==null?void 0:t.type)?t.type:"selection";(L=i==null?void 0:i.haptic)==null||L.call(i,f);return}case"getSystemInfo":return{platform:Ht.OS==="ios"?"ios":"android",appVersion:(x=i==null?void 0:i.app_version)!=null?x:"",theme:s?"dark":"light"};case"getAccessToken":{let f=n().access_token;if(!f)throw new b("HOST_ERROR","Mini app ch\u01B0a c\xF3 token cho page n\xE0y");return f}case"getToken":{let f=t==null?void 0:t.type;if(f==="access"){let ne=n().access_token;if(!ne)throw new b("HOST_ERROR","Mini app ch\u01B0a c\xF3 token cho page n\xE0y");return ne}if(f!=="partner"&&f!=="chatbox")throw new b("HOST_ERROR",`Lo\u1EA1i token kh\xF4ng h\u1EE3p l\u1EC7: ${String(f)}`);let a=gt[f];if(!r().includes(a))throw new b("PERMISSION_DENIED",`Mini app ch\u01B0a \u0111\u01B0\u1EE3c c\u1EA5p quy\u1EC1n ${a} (Console \u2192 Quy\u1EC1n l\u1EA5y token)`);let R=f==="partner"?n().partner_token:n().chatbox_token;if(!R)throw new b("HOST_ERROR",`Kh\xF4ng c\xF3 ${a}`);return R}case"getUserInfo":{let f=n().user;if(!f)throw new b("HOST_ERROR","Kh\xF4ng l\u1EA5y \u0111\u01B0\u1EE3c th\xF4ng tin nh\xE2n vi\xEAn");return f}case"getPageInfo":{let f=n().page;if(!f)throw new b("HOST_ERROR","Kh\xF4ng l\u1EA5y \u0111\u01B0\u1EE3c th\xF4ng tin page");return f}case"sendMessage":case"insertText":throw new b("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF phi\xEAn b\u1EA3n app n\xE0y`);default:throw new b("NOT_SUPPORTED",`API kh\xF4ng t\u1ED3n t\u1EA1i: ${e}`)}};var Ie=e=>`bundle:${e}`,De=()=>`${_().file_system.document_dir}/miniapps`,Le=De,$e=(e,t,n="index.html",r=!1,s=[])=>{let o=`${Le()}/${e}/${t}`;return{app_id:e,version:t,dir:o,entry_uri:`file://${o}/${n}`,context_update:r,permissions:s}},Oe=e=>{var t;_().storage.setString(Ie(e.app_id),JSON.stringify({version:e.version,entry:e.entry,context_update:!!e.context_update,permissions:(t=e.permissions)!=null?t:[]}))},jt=(e,t)=>/^https?:\/\//.test(t)?t:`${e.replace(/[^/]*$/,"")}${t}`,v=e=>{let t=_().storage.getString(Ie(e));if(!t)return null;try{let{version:n,entry:r,context_update:s,permissions:o}=JSON.parse(t);return $e(e,n,r,!!s,Array.isArray(o)?o:[])}catch{return null}},W=e=>_().file_system.exists(e.entry_uri.replace("file://","")),Ne=async e=>{let t=v(e.app_id);return(t==null?void 0:t.version)===e.version&&await W(t)},mt=async(e,t)=>{let n=_().file_system,r=`${Le()}/${e}`,s=await n.listDir(r).catch(()=>[]);await Promise.all(s.filter(o=>!t.includes(o)).map(o=>n.remove(`${r}/${o}`).catch(()=>{})))},Mt=async e=>{var t;await((t=ae[e])==null?void 0:t.catch(()=>{})),_().storage.setString(Ie(e),""),await _().file_system.remove(`${Le()}/${e}`).catch(()=>{})},te=class extends Error{constructor(){super("cancelled"),this.name="MiniAppInstallCancelled"}},ae={},yt=(e,t)=>{var o;let r=((o=ae[e])!=null?o:Promise.resolve()).catch(()=>{}).then(t),s=r.catch(()=>{});return ae[e]=s,s.then(()=>{ae[e]===s&&delete ae[e]}),r},qt=(e,t)=>{var s,o;let n=e.split(".").map(p=>parseInt(p,10)||0),r=t.split(".").map(p=>parseInt(p,10)||0);for(let p=0;p<Math.max(n.length,r.length);p++){let u=((s=n[p])!=null?s:0)-((o=r[p])!=null?o:0);if(u)return u}return 0},Kt=({manifest:e,zip_path:t})=>yt(e.app_id,async()=>{var o;let n=_().file_system,r=v(e.app_id);if(r&&qt(r.version,e.version)>=0&&await W(r))return r;if(e.sha256&&n.sha256&&await n.sha256(t)!==e.sha256)throw new Error("sha256 mismatch");let s=$e(e.app_id,e.version,e.entry,!!e.context_update,(o=e.permissions)!=null?o:[]);return await n.remove(s.dir).catch(()=>{}),await n.mkdir(s.dir),await n.unzip(t,s.dir),Oe(e),I("\u0111\xE3 c\xE0i b\u1EA3n \u0111\xF3ng s\u1EB5n",e.app_id,e.version),mt(e.app_id,[e.version,r==null?void 0:r.version].filter(Boolean)),s}),Be=(e,{base_url:t,onProgress:n}={})=>{let r=_().file_system,s=null,o=!1,p=`${r.cache_dir}/${e.app_id}-${e.version}.zip`,u=()=>{if(o)throw new te},i=async()=>{var M;u();let l=v(e.app_id);if((l==null?void 0:l.version)===e.version&&await r.exists(l.dir))return Oe(e),v(e.app_id);u();let m=r.download({url:t?jt(t,e.bundle_url):e.bundle_url,to_file:p,onProgress:(y,A)=>{var L;let g=A>0?A:(L=e.size)!=null?L:0;g>0&&(n==null||n(Math.min(1,y/g)))}});s=m;try{let{status:y}=await m.promise;if(u(),y!==200)throw new Error(`bundle ${y}`);if(e.sha256)if(r.sha256){if(await r.sha256(p)!==e.sha256)throw new Error("sha256 mismatch")}else I("b\u1ECF qua ki\u1EC3m tra sha256 (file_system kh\xF4ng c\xF3 sha256)",e.app_id);u();let A=$e(e.app_id,e.version,e.entry,!!e.context_update,(M=e.permissions)!=null?M:[]);return await r.remove(A.dir).catch(()=>{}),await r.mkdir(A.dir),await r.unzip(p,A.dir),Oe(e),mt(e.app_id,[e.version,l==null?void 0:l.version].filter(Boolean)),A}catch(y){throw o?new te:y}finally{s=null,r.remove(p).catch(()=>{})}};return{promise:yt(e.app_id,i),cancel:()=>{o=!0,s==null||s.cancel()}}},se={},zt=__DEV__?0:60*1e3,At={},wt=(e,t)=>{var r,s;let n=v(e);return n&&Date.now()-((r=At[t])!=null?r:0)<zt?Promise.resolve(n):((s=se[e])!=null||(se[e]=(async()=>{let o=await fetch(t,{headers:{"Cache-Control":"no-cache"}});if(!o.ok)throw new Error(`manifest ${o.status}`);let p=await o.json(),u=await Be(p,{base_url:t}).promise;return At[t]=Date.now(),u})().catch(o=>(console.warn("[miniapp] sync failed",e,o==null?void 0:o.message),v(e))).finally(()=>{se[e]=void 0})),se[e])};var me=new Map,vt=(e,t)=>(me.set(e,t),()=>{me.get(e)===t&&me.delete(e)}),Yt=(e,t)=>{let n=me.get(e);return n?n(t):!1};import{useRef as Qt,useSyncExternalStore as Gt}from"react";var Me=e=>{let t=e,n=new Set;return{getState:()=>t,setState:r=>{let s=typeof r=="function"?r(t):r;t={...t,...s},n.forEach(o=>o())},subscribe:r=>(n.add(r),()=>{n.delete(r)})}},H=(e,t,n=Object.is)=>{let r=Qt(null),s=()=>{let o=e.getState(),p=r.current;if(p&&p.state===o&&p.selector===t)return p.value;let u=t(o),i=p&&n(p.value,u)?p.value:u;return r.current={state:o,selector:t,value:i},i};return Gt(e.subscribe,s)};var N=Me({active_key:null,instances:{}}),_t=({app:e,instance_id:t,context:n={},url_params:r={},host_data:s={}},o)=>{var u;let p=(u=_().keep_alive)==null?void 0:u.max_webviews;N.setState(i=>{let l=t!=null?t:e.app_id,m={...i.instances,[l]:{key:l,app:e,context:n,url_params:r,host_data:s,last_used_at:Date.now()}},M=Object.keys(m);return p&&p>0&&M.length>p&&M.filter(y=>y!==l).sort((y,A)=>m[y].last_used_at-m[A].last_used_at).slice(0,M.length-p).forEach(y=>{delete m[y]}),o?{active_key:l,instances:m}:{instances:m}})},Xt=e=>_t(e,!0),Zt=e=>_t(e,!1),pe=()=>N.setState({active_key:null}),ye=e=>{N.setState(t=>{if(t.active_key===e||!t.instances[e])return{};let n={...t.instances};return delete n[e],{instances:n}})};var St="catalog",en="paused_apps",tn="removed_apps",nn=10*1e3,rn=2,on=3e3,sn=()=>{var e;try{return JSON.parse((e=_().storage.getString(St))!=null?e:"{}")}catch{return{}}},w=Me({catalog:{},downloads:{},pause_reasons:[],updates:{},apply_ticks:{}}),bt=e=>{var t;return!!((t=_().manual_update)!=null&&t.includes(e))},_e=new Set,xt=e=>{let t=new Set,n=()=>_().storage.setString(e,JSON.stringify([...t]));return{has:r=>t.has(r),values:()=>[...t],add:r=>t.has(r)?!1:(t.add(r),n(),!0),delete:r=>t.delete(r)?(n(),!0):!1,load:()=>{var r;t.clear();try{let s=JSON.parse((r=_().storage.getString(e))!=null?r:"[]");Array.isArray(s)&&s.forEach(o=>{typeof o=="string"&&t.add(o)})}catch{}}}},F=xt(en),Y=xt(tn);nt(()=>{F.load(),Y.load();let e=sn(),t={};Object.keys(e).filter(n=>!Y.has(n)).forEach(n=>{let r=v(n);r?t[n]={status:"installed",progress:1,version:r.version,has_local:!0}:F.has(n)&&(t[n]={status:"paused",progress:0,version:e[n].version,has_local:!1})}),w.setState({catalog:e,downloads:t})});var Je=e=>H(w,t=>e?t.downloads[e]:void 0),an=()=>H(w,e=>e.pause_reasons.length>0),B=(...e)=>I("queue",...e),E=[],j={},h=null,we=new Set,Z={},Fe=new Set,K=e=>{Fe.forEach(t=>{try{t(e)}catch(n){console.warn("[miniapp-queue] event listener error",n==null?void 0:n.message)}})},pn=e=>(Fe.add(e),()=>{Fe.delete(e)}),cn=()=>w.getState().downloads,C=(e,t)=>{let n=!!v(e),r=w.getState().downloads[e],s=t.status==="downloading"&&n?"updating":t.status,o={...r!=null?r:{status:"queued",progress:0},...t,...s?{status:s}:{},has_local:n};w.setState(p=>({downloads:{...p.downloads,[e]:o}})),(r==null?void 0:r.status)!==o.status||(r==null?void 0:r.version)!==o.version||(r==null?void 0:r.has_local)!==o.has_local?K({type:"status_change",app_id:e,state:o}):r.progress!==o.progress&&K({type:"progress",app_id:e,progress:o.progress,version:o.version})},ve=(e,t)=>{var n;(n=Z[e])==null||n.forEach(r=>r(t)),delete Z[e]},ln=()=>w.getState().pause_reasons.length>0,z=e=>{var u;if(h)return;let t=e?E.indexOf(e):ln()?-1:E.findIndex(i=>!F.has(i));if(t<0||t>=E.length)return;let[n]=E.splice(t,1),r=w.getState().catalog[n];if(!r){ve(n,v(n)),z();return}let s=Date.now();j[n]=((u=j[n])!=null?u:0)+1,C(n,{status:"downloading",progress:0,version:r.version,error:void 0});let o=0,p=Be(r,{onProgress:i=>{let l=Math.floor(i*100);l!==o&&(o=l,C(n,{progress:l/100,version:r.version}))}});h={app_id:n,handle:p,forced:!!e},B("start",n,r.version,e?"(forced)":""),p.promise.then(i=>{B("installed",n,r.version,`${Date.now()-s}ms`),C(n,{status:"installed",progress:1,version:r.version}),ve(n,i)}).catch(i=>{var m;if(i instanceof te){if(we.has(n))return;B("paused",n),j[n]-=1,E.unshift(n),C(n,{status:F.has(n)?"paused":"queued",progress:0,version:r.version});return}let l=String((m=i==null?void 0:i.message)!=null?m:i);if(console.warn("[miniapp-queue] failed",n,l),j[n]<rn){C(n,{status:"queued",progress:0,version:r.version,error:l}),setTimeout(()=>{var M;E.includes(n)||(h==null?void 0:h.app_id)===n||(E.push(n),z((M=Z[n])!=null&&M.length?n:void 0))},on);return}C(n,{status:"failed",progress:0,version:r.version,error:l}),ve(n,v(n))}).finally(()=>{h=null;let i=E.find(l=>{var m;return(m=Z[l])==null?void 0:m.length});z(i)})},Se=(e,{front:t=!1}={})=>{if((h==null?void 0:h.app_id)===e)return;let n=E.indexOf(e);if(n>=0){if(!t)return;E.splice(n,1)}t?E.unshift(e):E.push(e)},un=async e=>{let{host_id:t,client_token:n}=_(),r=new AbortController,s=setTimeout(()=>r.abort(),nn);try{let o=`${Te}/api/hosts/${encodeURIComponent(t)}/miniapps?channel=${e}`,p=await fetch(o,{headers:{Authorization:`Bearer ${n}`,"Cache-Control":"no-cache"},signal:r.signal});if(!p.ok)throw new Error(`host list ${e} ${p.status}`);return(await p.json()).apps.map(i=>({...i,channel:e}))}finally{clearTimeout(s)}},ce=null,Ve=()=>(ce!=null||(ce=(async()=>{var t;let e=Date.now();try{let n=await Promise.all(_().channels.map(un)),r={};[...n].reverse().flat().forEach(i=>{r[i.app_id]=i});let s=Object.keys(w.getState().catalog).filter(i=>!r[i]);_().storage.setString(St,JSON.stringify(r)),w.setState({catalog:r}),await Promise.all(s.map(i=>Et(i,{by_user:!1}))),s.forEach(i=>Y.delete(i));let o=Object.keys(r).filter(i=>!Y.has(i)),p=[],u={};for(let i of o.map(l=>r[l])){if(await Ne(i)){C(i.app_id,{status:"installed",progress:1,version:i.version});continue}let l=v(i.app_id);if(bt(i.app_id)&&!_e.has(i.app_id)&&l&&await W(l)){C(i.app_id,{status:"installed",progress:1,version:l.version}),u[i.app_id]={app_id:i.app_id,current_version:l.version,next_version:i.version};continue}p.push(i)}return w.setState({updates:u}),p.forEach(i=>{j[i.app_id]=0,C(i.app_id,{status:F.has(i.app_id)?"paused":"queued",progress:0,version:i.version,error:void 0}),Se(i.app_id)}),B("catalog",o.length,"apps, outdated",p.map(i=>i.app_id),"removed",s,`${Date.now()-e}ms`),K({type:"sync_complete",app_ids:o,removed:s}),Object.values(u).forEach(i=>K({type:"update_available",...i})),z(),{ok:!0,app_ids:o,removed:s}}catch(n){let r=String((n==null?void 0:n.name)==="AbortError"?"timeout":(t=n==null?void 0:n.message)!=null?t:n);return console.warn("[miniapp-queue] sync catalog failed",r),K({type:"sync_failed",error:r}),{ok:!1,error:r}}finally{ce=null}})()),ce),Et=async(e,{by_user:t})=>{var s,o,p,u;if(t&&Y.add(e),we.has(e))return;we.add(e),F.delete(e);let n=E.indexOf(e);n>=0&&E.splice(n,1),(h==null?void 0:h.app_id)===e&&h.handle.cancel();let r=(u=(p=(s=w.getState().downloads[e])==null?void 0:s.version)!=null?p:(o=v(e))==null?void 0:o.version)!=null?u:"";C(e,{status:"uninstalling",progress:0,version:r}),await Mt(e),ye(e),w.setState(i=>{let l={...i.downloads};return delete l[e],{downloads:l}}),delete j[e],we.delete(e),ve(e,null),B("uninstalled",e,t?"(user)":"(not in list)"),K({type:"uninstalled",app_id:e})},dn=e=>Et(e,{by_user:!0}),gn=e=>{let t=le(e);return t?(Y.delete(e),(h==null?void 0:h.app_id)===e||E.includes(e)||(j[e]=0,C(e,{status:F.has(e)?"paused":"queued",progress:0,version:t.version,error:void 0}),Se(e),z(),B("restore",e)),!0):!1},fn=e=>{if(F.has(e))return;if(F.add(e),B("pause app",e),(h==null?void 0:h.app_id)===e&&!h.forced){h.handle.cancel();return}let t=w.getState().downloads[e];E.includes(e)&&t&&C(e,{status:"paused",progress:0,version:t.version})},hn=e=>{if(!F.delete(e))return;B("resume app",e);let t=w.getState().downloads[e];(t==null?void 0:t.status)==="paused"&&!E.includes(e)&&le(e)&&(j[e]=0,Se(e)),E.includes(e)&&t&&C(e,{status:"queued",progress:0,version:t.version}),z()},An=e=>{let{pause_reasons:t}=w.getState();t.includes(e)||(w.setState({pause_reasons:[...t,e]}),B("pause",e),t.length===0&&K({type:"pause_change",paused:!0,reasons:[e]}),h&&!h.forced&&h.handle.cancel())},mn=e=>{let{pause_reasons:t}=w.getState();if(!t.includes(e))return;let n=t.filter(r=>r!==e);w.setState({pause_reasons:n}),B("resume",e),n.length===0&&K({type:"pause_change",paused:!1,reasons:n}),z()},Rt=e=>w.getState().updates[e],Mn=async e=>{var n,r;let t=Rt(e);_e.add(e);try{let s=await be(e),o=(r=t==null?void 0:t.next_version)!=null?r:(n=le(e))==null?void 0:n.version;return!s||!o||s.version!==o?!1:(w.setState(p=>{var i;let u={...p.updates};return delete u[e],{updates:u,apply_ticks:{...p.apply_ticks,[e]:((i=p.apply_ticks[e])!=null?i:0)+1}}}),B("updated",e,t==null?void 0:t.current_version,"\u2192",s.version),!0)}finally{_e.delete(e)}},yn=()=>Object.values(w.getState().catalog).map(e=>({...e,installed:!!v(e.app_id),removed_by_user:Y.has(e.app_id)})),le=e=>w.getState().catalog[e],be=async e=>{let t=le(e);if(!t)return;if(F.delete(e),Y.delete(e),await Ne(t))return v(e);let n=v(e);if(bt(e)&&!_e.has(e)&&n&&await W(n))return n;let r=new Promise(s=>{var o;((o=Z[e])!=null?o:Z[e]=[]).push(s)});return(h==null?void 0:h.app_id)===e?h.forced=!0:(j[e]=0,Se(e,{front:!0}),h&&!h.forced?h.handle.cancel():z(e)),r};import{Fragment as Ct,jsx as T,jsxs as de}from"react/jsx-runtime";var He=e=>(e!=null?e:"").replace(/\?[^#]*/,""),Tt=0,xn=()=>{let e=new Set;return{emit:t=>e.forEach(n=>n(t)),subscribe:t=>(e.add(t),()=>{e.delete(t)})}},En=qe.memo(({instance_key:e,is_active:t,is_front:n,is_dark:r,reload_tick:s,web_at_top:o,splash:p,bridge:u,opaque_background:i,allow_embedded_miniapps:l,onWebLoadEnd:m})=>{var Ze,et;let M=V(null),y=V(!1),A=H(N,c=>c.instances[e]),g=A==null?void 0:A.app.app_id,L=A==null?void 0:A.app.manifest_url,x=A==null?void 0:A.context,f=A==null?void 0:A.url_params,[a,R]=ee(()=>g?v(g):null),[ne,re]=ee(!1),[Ot,ze]=ee(0),[It,ie]=ee(0),[Dt,k]=ee(!1),U=V(null),Ye=c=>{U.current&&clearTimeout(U.current),U.current=setTimeout(()=>{U.current=null,k(!0)},c)};J(()=>()=>{U.current&&clearTimeout(U.current)},[]),J(()=>{if(!g||!t&&a)return;let c=!0;return re(!1),(async()=>{let d=v(g),P=d?await W(d):!1;if(!c||(R(P?$=>!$||$.version!==d.version||$.permissions.join(",")!==d.permissions.join(",")?d:$:null),__DEV__&&Date.now()-Tt>1e4&&(Tt=Date.now(),await Ve()),!c))return;let q=await be(g),Q=q!==void 0?q:L?await wt(g,L):v(g);if(c){if(!Q){re(!0);return}R($=>$!=null?$:Q)}})(),()=>{c=!1}},[t,g,L,Ot]),J(()=>vt(e,c=>M.current?(M.current.postMessage(c),!0):!1),[e]);let Lt=H(w,c=>{let d=g?c.downloads[g]:void 0;return(d==null?void 0:d.status)==="installed"?d.version:void 0});J(()=>{if(t||!g||!a)return;let c=v(g);if(!c||c.version===a.version)return;let d=!0;return W(c).then(P=>{!d||!P||(I(`webview:${e}`,"\u0111\u1ED5i bundle (\u1EA9n)",a.version,"\u2192",c.version),R(c))}),()=>{d=!1}},[t,g,Lt,a==null?void 0:a.version]);let Qe=H(w,c=>{var d;return g&&(d=c.apply_ticks[g])!=null?d:0});J(()=>{if(!Qe||!g)return;let c=v(g);if(!c||c.version===(a==null?void 0:a.version))return;let d=!0;return W(c).then(P=>{!d||!P||(I(`webview:${e}`,"c\u1EADp nh\u1EADt",a==null?void 0:a.version,"\u2192",c.version),k(!1),R(c))}),()=>{d=!1}},[Qe]),J(()=>{var P;let c=(P=_().keep_alive)==null?void 0:P.idle_close_ms;if(t||!c||c<=0)return;let d=setTimeout(()=>{ye(e)},c);return()=>clearTimeout(d)},[t,e]),J(()=>{s>0&&(re(!1),k(!1),ie(c=>c+1),ze(c=>c+1))},[s]);let Ge=V(t);J(()=>{var c;Ge.current!==t&&(Ge.current=t,y.current&&((c=M.current)==null||c.injectJavaScript(ct(t?"resumed":"paused"))))},[t]);let ge=`${(Ze=a==null?void 0:a.version)!=null?Ze:"none"}:${(et=a==null?void 0:a.permissions.join(","))!=null?et:""}:${It}`,oe=xe(()=>JSON.stringify([x!=null?x:{},f!=null?f:{}]),[x,f]),Ee=xe(()=>{var c;return ft(f!=null?f:{},(c=a==null?void 0:a.permissions)!=null?c:[])},[oe,a==null?void 0:a.permissions]),$t=xe(()=>dt(x!=null?x:{},Ee)+pt()+(_().debug?at():""),[Ee]),fe=V(null),Xe=V(null);J(()=>{var d,P,q;if(!a)return;if(Xe.current!==ge){Xe.current=ge,fe.current=oe;return}if(fe.current===oe)return;let c=((P=JSON.parse((d=fe.current)!=null?d:"[]")[0])!=null?P:{}).org_id;if(fe.current=oe,c===(x==null?void 0:x.org_id)&&y.current){k(!1),Ye(1500),(q=M.current)==null||q.injectJavaScript(lt(x!=null?x:{},Ee));return}k(!1),ie(Q=>Q+1)},[oe,a,ge]);let Nt=We(async c=>{var P,q,Q,$,Re;let d=it(c.nativeEvent.data);if(!d){if(g&&(u!=null&&u.onWebEvent))try{Promise.resolve(u.onWebEvent(c.nativeEvent.data,{app_id:g,instance_id:e})).catch(S=>{console.warn("[miniapp] onWebEvent l\u1ED7i",g,S)})}catch(S){console.warn("[miniapp] onWebEvent l\u1ED7i",g,S)}return}if(d.method==="log"){let{level:S,text:O}=d;I(`web:${e}`,S!=null?S:"log",O!=null?O:"");return}if(d.method==="pong"){U.current||k(!0);return}if(d.method==="touchAtTop"){o.emit(!!d.at_top);return}if(d.method==="contextApplied"){U.current&&clearTimeout(U.current),U.current=null,k(!0);return}if(d.method==="ready"){y.current=!0,k(!0);let S=(P=N.getState().instances[e])==null?void 0:P.context;S&&((q=M.current)==null||q.injectJavaScript(ke(S)));return}try{let S=await ht(d,{getHostData:()=>{var O,G;return(G=(O=N.getState().instances[e])==null?void 0:O.host_data)!=null?G:{}},getPermissions:()=>{var O,G;return g?(G=(O=v(g))==null?void 0:O.permissions)!=null?G:[]:[]},is_dark:r,close:pe,app_id:g!=null?g:"",instance_id:e,options:u});d.id&&((Q=M.current)==null||Q.injectJavaScript(ot(d.id,S)))}catch(S){if(!d.id)return;let O=S==null?void 0:S.code,G=S instanceof b?S:new b(typeof O=="string"?O:"HOST_ERROR",String(($=S==null?void 0:S.message)!=null?$:S));(Re=M.current)==null||Re.injectJavaScript(st(d.id,G))}},[e,r,g,o,u]),Bt=We(()=>{re(!1),ie(c=>c+1),ze(c=>c+1)},[]);return de(je,{style:[Ke.absoluteFill,i&&{backgroundColor:r?"#09090B":"#FFFFFF"},!n&&D.behind],pointerEvents:t?"auto":"none",children:[a?T(bn,{ref:M,source:{uri:a.entry_uri},originWhitelist:["*"],allowingReadAccessToURL:`file://${l?De():a.dir}`,allowFileAccess:!0,allowFileAccessFromFileURLs:!0,allowUniversalAccessFromFileURLs:!0,injectedJavaScriptBeforeContentLoaded:$t,onMessage:Nt,bounces:!1,overScrollMode:"never",onLoadStart:c=>{I(`webview:${e}`,"load start",He(c.nativeEvent.url)),y.current=!1,k(!1)},onError:c=>{I(`webview:${e}`,"load error",He(c.nativeEvent.url),c.nativeEvent.description),re(!0),k(!1)},onLoadEnd:c=>{let d=c.nativeEvent.url;I(`webview:${e}`,"load end",He(d)),g&&(m==null||m({app_id:g,instance_id:e,url:d})),Ye(1500)},onContentProcessDidTerminate:()=>{y.current=!1,k(!1),ie(c=>c+1)},onRenderProcessGone:()=>(y.current=!1,k(!1),ie(c=>c+1),!0),style:D.webview},ge):null,A&&T(Tn,{visible:!a||!Dt,interactive:ne,children:T(Rn,{splash:p,app:A.app,is_dark:r,error:ne,has_bundle:!!a,retry:Bt})})]})}),Rn=qe.memo(({splash:e,app:t,is_dark:n,error:r,has_bundle:s,retry:o})=>{let p=e,u=Je(t.app_id),i=r?"error":!s&&(u==null?void 0:u.status)==="downloading"?"downloading":"loading";return T(p,{app:t,is_dark:n,status:i,progress:i==="downloading"?u==null?void 0:u.progress:void 0,retry:o})}),Tn=({visible:e,interactive:t,children:n})=>{let r=V(new Ue.Value(e?1:0)).current,[s,o]=ee(e);return J(()=>{if(e){o(!0),r.setValue(1);return}let p=Ue.timing(r,{toValue:0,duration:180,useNativeDriver:!0});return p.start(({finished:u})=>{u&&o(!1)}),()=>p.stop()},[e,r]),s?T(Ue.View,{style:[Ke.absoluteFill,{opacity:r}],pointerEvents:t?"auto":"none",children:n}):null},kt=({app:e,is_dark:t,status:n,progress:r,retry:s})=>{let o=t?"#FAFAFA":"#18181B";return de(je,{style:[D.splash,{backgroundColor:t?"#09090B":"#FFFFFF"}],children:[T(je,{style:[D.splash_icon,{backgroundColor:t?"#18181B":"#F4F4F5"}],children:e.icon?T(_n,{source:{uri:e.icon},style:D.splash_icon_image}):T(ue,{style:D.splash_letter,children:(e.name||"?").slice(0,1).toUpperCase()})}),T(ue,{style:[D.splash_name,{color:o}],children:e.name}),n==="error"?de(Ct,{children:[T(ue,{style:D.splash_hint,children:"Kh\xF4ng t\u1EA3i \u0111\u01B0\u1EE3c mini app"}),T(Sn,{activeOpacity:.7,style:[D.retry_button,{backgroundColor:t?"#27272A":"#F4F4F5"}],onPress:s,children:T(ue,{style:[D.retry_text,{color:o}],children:"Th\u1EED l\u1EA1i"})})]}):de(Ct,{children:[T(wn,{style:D.splash_spinner,color:t?"#A1A1AA":"#71717A"}),n==="downloading"&&de(ue,{style:D.splash_hint,children:["\u0110ang t\u1EA3i mini app",r?` ${Math.round(r*100)}%`:"\u2026"]})]})]})},Pt=(e,t)=>{let n=V(t),r=V(!1);__DEV__&&!r.current&&n.current!==t&&(r.current=!0,console.warn(`[miniapp] MiniAppHost prop "${e}" \u0111\u1ED5i gi\u1EEFa c\xE1c l\u1EA7n render \u2192 m\u1ECDi WebView b\u1ECB mount l\u1EA1i. Khai b\xE1o component b\xEAn ngo\xE0i render.`))},Pn=({container:e,splash:t=kt,is_dark:n=!1,bridge:r,close_on_back:s=!0,opaque_background:o=!0,allow_embedded_miniapps:p=!1,onWebLoadEnd:u})=>{Pt("container",e),Pt("splash",t);let i=e,l=H(N,a=>a.active_key),m=V(l);l&&(m.current=l);let M=H(N,a=>Object.keys(a.instances).join("|")),y=H(N,a=>{var R;return a.active_key?(R=a.instances[a.active_key])==null?void 0:R.app.name:void 0}),A=xe(()=>M?M.split("|"):[],[M]),[g,L]=ee({}),x=V(xn()).current;J(()=>{if(!l||!s)return;let a=vn.addEventListener("hardwareBackPress",()=>(pe(),!0));return()=>a.remove()},[l,s]);let f=We(()=>{let a=N.getState().active_key;a&&L(R=>({...R,[a]:(R[a]||0)+1}))},[]);return A.length?T(i,{visible:!!l,title:y!=null?y:"",is_dark:n,close:pe,reload:f,subscribeWebAtTop:x.subscribe,children:A.map(a=>T(En,{instance_key:a,is_active:l===a,is_front:(l!=null?l:m.current)===a,is_dark:n,reload_tick:g[a]||0,web_at_top:x,splash:t,bridge:r,opaque_background:o,allow_embedded_miniapps:p,onWebLoadEnd:u},a))}):null},D=Ke.create({webview:{flex:1,backgroundColor:"transparent"},behind:{zIndex:-1},splash:{flex:1,alignItems:"center",justifyContent:"center",gap:12},splash_icon:{width:72,height:72,borderRadius:20,alignItems:"center",justifyContent:"center",overflow:"hidden"},splash_icon_image:{width:72,height:72},splash_letter:{fontSize:28,fontWeight:"700",color:"#1D4ED8"},splash_name:{fontSize:16,fontWeight:"600"},splash_hint:{color:"#71717A"},splash_spinner:{marginTop:8},retry_button:{marginTop:4,paddingHorizontal:20,paddingVertical:10,borderRadius:999},retry_text:{fontWeight:"600"}}),Cn=qe.memo(Pn);export{kt as DefaultMiniAppSplash,Te as MINIAPP_PLATFORM_URL,Cn as MiniAppHost,b as MiniAppHostError,pe as closeMiniApp,Ft as configureMiniApp,Vt as createMmkvStorage,Jt as createRnfsFileSystem,be as ensureMiniApp,v as getLocalMiniApp,yn as getMiniAppCatalog,le as getMiniAppCatalogEntry,cn as getMiniAppStatuses,Rt as getMiniAppUpdate,Kt as installBundledMiniApp,pn as onMiniAppEvent,Xt as openMiniApp,fn as pauseMiniApp,An as pauseMiniAppDownloads,Zt as preloadMiniApp,gn as restoreMiniApp,hn as resumeMiniApp,mn as resumeMiniAppDownloads,Yt as sendEventToWeb,Ve as syncMiniAppCatalog,dn as uninstallMiniApp,Mn as updateMiniApp,Je as useMiniAppDownload,an as useMiniAppDownloadsPaused};
45
+ true;`},ht={partner:"partner_token",chatbox:"chatbox_token"},At=(e,t)=>{let n={...e};for(let r of Object.values(ht))t.includes(r)||delete n[r];return n},Ie=new Set,Oe=async(e,t)=>{if(Ie.has(e))throw new m("BUSY",`${e} \u0111ang ch\u1EA1y \u2014 ch\u1EDD l\u01B0\u1EE3t tr\u01B0\u1EDBc xong`);Ie.add(e);try{return await t()}finally{Ie.delete(e)}},Wt=new Set(["selection","impactLight","impactMedium","impactHeavy","rigid","soft","notificationSuccess","notificationWarning","notificationError"]),me=(e,t)=>{if(typeof e!="string"||!e)throw new m("INVALID_PARAMS",`Thi\u1EBFu ${t}`);return e},mt=async({method:e,params:t},{getHostData:n,getPermissions:r,is_dark:s,close:o,app_id:a,instance_id:u,options:i})=>{var v,A,f,N,E,I,l,P;let p=i==null?void 0:i.handlers,w={app_id:a,instance_id:u,close:o},M=()=>new m("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF \u1EE9ng d\u1EE5ng n\xE0y`);switch(e){case"getBiometricAvailability":return i!=null&&i.biometrics?i.biometrics.getAvailability():{available:!1};case"authenticateBiometric":{if(!(i!=null&&i.biometrics))throw M();let g=me(t==null?void 0:t.reason,"reason").trim();if(!g||g.length>200)throw new m("INVALID_PARAMS","reason must contain 1\u2013200 characters");let y=t==null?void 0:t.cancelButtonText;if(y!==void 0&&(typeof y!="string"||!y.trim()||y.length>80))throw new m("INVALID_PARAMS","Invalid cancelButtonText");return Oe(e,()=>i.biometrics.authenticate({reason:g,cancelButtonText:y}))}case"requestPayment":{let g=p==null?void 0:p.requestPayment;if(!g)throw M();let y=t==null?void 0:t.amount;if(typeof y!="number"||!Number.isFinite(y)||y<=0)throw new m("INVALID_PARAMS","amount ph\u1EA3i l\xE0 s\u1ED1 > 0");let re={...t,amount:y,currency:me(t==null?void 0:t.currency,"currency")};return Oe(e,()=>g(re,w))}case"printImage":{let g=p==null?void 0:p.printImage;if(!g)throw M();let y=me(t==null?void 0:t.image,"image");await Oe(e,()=>g({image:y},w));return}case"openScreen":if(!(p!=null&&p.openScreen))throw M();await p.openScreen({screen:me(t==null?void 0:t.screen,"screen"),params:t==null?void 0:t.params},w);return;case"closeApp":o();return;case"openWebview":{let g=String((v=t==null?void 0:t.url)!=null?v:"");if(!/^https?:\/\//i.test(g))throw new m("INVALID_PARAMS","url ph\u1EA3i l\xE0 http(s)");await(i!=null&&i.openUrl?i.openUrl(g):ot.openURL(g));return}case"openLink":{let g=String((A=t==null?void 0:t.url)!=null?A:"").trim();if(!/^[a-z][a-z0-9+.-]*:/i.test(g)||/^(javascript|file|data|about|blob):/i.test(g))throw new m("INVALID_PARAMS","url kh\xF4ng h\u1EE3p l\u1EC7");try{await(i!=null&&i.openUrl?i.openUrl(g):ot.openURL(g))}catch(y){throw new m("NOT_SUPPORTED",String((N=(f=y==null?void 0:y.message)!=null?f:y)!=null?N:"Kh\xF4ng m\u1EDF \u0111\u01B0\u1EE3c link"))}return}case"showToast":(I=i==null?void 0:i.showToast)==null||I.call(i,String((E=t==null?void 0:t.message)!=null?E:""));return;case"haptic":{let g=Wt.has(t==null?void 0:t.type)?t.type:"selection";(l=i==null?void 0:i.haptic)==null||l.call(i,g);return}case"getSystemInfo":return{platform:Ht.OS==="ios"?"ios":"android",appVersion:(P=i==null?void 0:i.app_version)!=null?P:"",theme:s?"dark":"light"};case"getAccessToken":{let g=n().access_token;if(!g)throw new m("HOST_ERROR","Mini app ch\u01B0a c\xF3 token cho page n\xE0y");return g}case"getToken":{let g=t==null?void 0:t.type;if(g==="access"){let oe=n().access_token;if(!oe)throw new m("HOST_ERROR","Mini app ch\u01B0a c\xF3 token cho page n\xE0y");return oe}if(g!=="partner"&&g!=="chatbox")throw new m("HOST_ERROR",`Lo\u1EA1i token kh\xF4ng h\u1EE3p l\u1EC7: ${String(g)}`);let y=ht[g];if(!r().includes(y))throw new m("PERMISSION_DENIED",`Mini app ch\u01B0a \u0111\u01B0\u1EE3c c\u1EA5p quy\u1EC1n ${y} (Console \u2192 Quy\u1EC1n l\u1EA5y token)`);let re=g==="partner"?n().partner_token:n().chatbox_token;if(!re)throw new m("HOST_ERROR",`Kh\xF4ng c\xF3 ${y}`);return re}case"getUserInfo":{let g=n().user;if(!g)throw new m("HOST_ERROR","Kh\xF4ng l\u1EA5y \u0111\u01B0\u1EE3c th\xF4ng tin nh\xE2n vi\xEAn");return g}case"getPageInfo":{let g=n().page;if(!g)throw new m("HOST_ERROR","Kh\xF4ng l\u1EA5y \u0111\u01B0\u1EE3c th\xF4ng tin page");return g}case"sendMessage":case"insertText":throw new m("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF phi\xEAn b\u1EA3n app n\xE0y`);default:throw new m("NOT_SUPPORTED",`API kh\xF4ng t\u1ED3n t\u1EA1i: ${e}`)}};var Be=e=>`bundle:${e}`,Ne=()=>`${b().file_system.document_dir}/miniapps`,$e=Ne,Fe=(e,t,n="index.html",r=!1,s=[])=>{let o=`${$e()}/${e}/${t}`;return{app_id:e,version:t,dir:o,entry_uri:`file://${o}/${n}`,context_update:r,permissions:s}},Le=e=>{var t;b().storage.setString(Be(e.app_id),JSON.stringify({version:e.version,entry:e.entry,context_update:!!e.context_update,permissions:(t=e.permissions)!=null?t:[]}))},jt=(e,t)=>/^https?:\/\//.test(t)?t:`${e.replace(/[^/]*$/,"")}${t}`,S=e=>{let t=b().storage.getString(Be(e));if(!t)return null;try{let{version:n,entry:r,context_update:s,permissions:o}=JSON.parse(t);return Fe(e,n,r,!!s,Array.isArray(o)?o:[])}catch{return null}},q=e=>b().file_system.exists(e.entry_uri.replace("file://","")),Ue=async e=>{let t=S(e.app_id);return(t==null?void 0:t.version)===e.version&&await q(t)},yt=async(e,t)=>{let n=b().file_system,r=`${$e()}/${e}`,s=await n.listDir(r).catch(()=>[]);await Promise.all(s.filter(o=>!t.includes(o)).map(o=>n.remove(`${r}/${o}`).catch(()=>{})))},wt=async e=>{var t;await((t=pe[e])==null?void 0:t.catch(()=>{})),b().storage.setString(Be(e),""),await b().file_system.remove(`${$e()}/${e}`).catch(()=>{})},ie=class extends Error{constructor(){super("cancelled"),this.name="MiniAppInstallCancelled"}},pe={},vt=(e,t)=>{var o;let r=((o=pe[e])!=null?o:Promise.resolve()).catch(()=>{}).then(t),s=r.catch(()=>{});return pe[e]=s,s.then(()=>{pe[e]===s&&delete pe[e]}),r},qt=(e,t)=>{var s,o;let n=e.split(".").map(a=>parseInt(a,10)||0),r=t.split(".").map(a=>parseInt(a,10)||0);for(let a=0;a<Math.max(n.length,r.length);a++){let u=((s=n[a])!=null?s:0)-((o=r[a])!=null?o:0);if(u)return u}return 0},Kt=({manifest:e,zip_path:t})=>vt(e.app_id,async()=>{var o;let n=b().file_system,r=S(e.app_id);if(r&&qt(r.version,e.version)>=0&&await q(r))return r;if(e.sha256&&n.sha256&&await n.sha256(t)!==e.sha256)throw new Error("sha256 mismatch");let s=Fe(e.app_id,e.version,e.entry,!!e.context_update,(o=e.permissions)!=null?o:[]);return await n.remove(s.dir).catch(()=>{}),await n.mkdir(s.dir),await n.unzip(t,s.dir),Le(e),L("\u0111\xE3 c\xE0i b\u1EA3n \u0111\xF3ng s\u1EB5n",e.app_id,e.version),yt(e.app_id,[e.version,r==null?void 0:r.version].filter(Boolean)),s}),Ve=(e,{base_url:t,onProgress:n}={})=>{let r=b().file_system,s=null,o=!1,a=`${r.cache_dir}/${e.app_id}-${e.version}.zip`,u=()=>{if(o)throw new ie},i=async()=>{var M;u();let p=S(e.app_id);if((p==null?void 0:p.version)===e.version&&await r.exists(p.dir))return Le(e),S(e.app_id);u();let w=r.download({url:t?jt(t,e.bundle_url):e.bundle_url,to_file:a,onProgress:(v,A)=>{var N;let f=A>0?A:(N=e.size)!=null?N:0;f>0&&(n==null||n(Math.min(1,v/f)))}});s=w;try{let{status:v}=await w.promise;if(u(),v!==200)throw new Error(`bundle ${v}`);if(e.sha256)if(r.sha256){if(await r.sha256(a)!==e.sha256)throw new Error("sha256 mismatch")}else L("b\u1ECF qua ki\u1EC3m tra sha256 (file_system kh\xF4ng c\xF3 sha256)",e.app_id);u();let A=Fe(e.app_id,e.version,e.entry,!!e.context_update,(M=e.permissions)!=null?M:[]);return await r.remove(A.dir).catch(()=>{}),await r.mkdir(A.dir),await r.unzip(a,A.dir),Le(e),yt(e.app_id,[e.version,p==null?void 0:p.version].filter(Boolean)),A}catch(v){throw o?new ie:v}finally{s=null,r.remove(a).catch(()=>{})}};return{promise:vt(e.app_id,i),cancel:()=>{o=!0,s==null||s.cancel()}}},ce={},zt=__DEV__?0:60*1e3,Mt={},_t=(e,t)=>{var r,s;let n=S(e);return n&&Date.now()-((r=Mt[t])!=null?r:0)<zt?Promise.resolve(n):((s=ce[e])!=null||(ce[e]=(async()=>{let o=await fetch(t,{headers:{"Cache-Control":"no-cache"}});if(!o.ok)throw new Error(`manifest ${o.status}`);let a=await o.json(),u=await Ve(a,{base_url:t}).promise;return Mt[t]=Date.now(),u})().catch(o=>(console.warn("[miniapp] sync failed",e,o==null?void 0:o.message),S(e))).finally(()=>{ce[e]=void 0})),ce[e])};var we=new Map,St=(e,t)=>(we.set(e,t),()=>{we.get(e)===t&&we.delete(e)}),Yt=(e,t)=>{let n=we.get(e);return n?n(t):!1};import{useRef as Qt,useSyncExternalStore as Gt}from"react";var ve=e=>{let t=e,n=new Set;return{getState:()=>t,setState:r=>{let s=typeof r=="function"?r(t):r;t={...t,...s},n.forEach(o=>o())},subscribe:r=>(n.add(r),()=>{n.delete(r)})}},j=(e,t,n=Object.is)=>{let r=Qt(null),s=()=>{let o=e.getState(),a=r.current;if(a&&a.state===o&&a.selector===t)return a.value;let u=t(o),i=a&&n(a.value,u)?a.value:u;return r.current={state:o,selector:t,value:i},i};return Gt(e.subscribe,s)};var F=ve({active_key:null,instances:{}}),bt=({app:e,instance_id:t,context:n={},url_params:r={},host_data:s={}},o)=>{var u;let a=(u=b().keep_alive)==null?void 0:u.max_webviews;F.setState(i=>{let p=t!=null?t:e.app_id,w={...i.instances,[p]:{key:p,app:e,context:n,url_params:r,host_data:s,last_used_at:Date.now()}},M=Object.keys(w);return a&&a>0&&M.length>a&&M.filter(v=>v!==p).sort((v,A)=>w[v].last_used_at-w[A].last_used_at).slice(0,M.length-a).forEach(v=>{delete w[v]}),o?{active_key:p,instances:w}:{instances:w}})},Xt=e=>bt(e,!0),Zt=e=>bt(e,!1),le=()=>F.setState({active_key:null}),_e=e=>{F.setState(t=>{if(t.active_key===e||!t.instances[e])return{};let n={...t.instances};return delete n[e],{instances:n}})};var xt="catalog",en="paused_apps",tn="removed_apps",nn=10*1e3,rn=2,on=3e3,sn=()=>{var e;try{return JSON.parse((e=b().storage.getString(xt))!=null?e:"{}")}catch{return{}}},_=ve({catalog:{},downloads:{},pause_reasons:[],updates:{},apply_ticks:{}}),Et=e=>{var t;return!!((t=b().manual_update)!=null&&t.includes(e))},xe=new Set,Tt=e=>{let t=new Set,n=()=>b().storage.setString(e,JSON.stringify([...t]));return{has:r=>t.has(r),values:()=>[...t],add:r=>t.has(r)?!1:(t.add(r),n(),!0),delete:r=>t.delete(r)?(n(),!0):!1,load:()=>{var r;t.clear();try{let s=JSON.parse((r=b().storage.getString(e))!=null?r:"[]");Array.isArray(s)&&s.forEach(o=>{typeof o=="string"&&t.add(o)})}catch{}}}},V=Tt(en),G=Tt(tn);it(()=>{V.load(),G.load();let e=sn(),t={};Object.keys(e).filter(n=>!G.has(n)).forEach(n=>{let r=S(n);r?t[n]={status:"installed",progress:1,version:r.version,has_local:!0}:V.has(n)&&(t[n]={status:"paused",progress:0,version:e[n].version,has_local:!1})}),_.setState({catalog:e,downloads:t})});var He=e=>j(_,t=>e?t.downloads[e]:void 0),an=()=>j(_,e=>e.pause_reasons.length>0),U=(...e)=>L("queue",...e),T=[],K={},h=null,Se=new Set,te={},Je=new Set,Y=e=>{Je.forEach(t=>{try{t(e)}catch(n){console.warn("[miniapp-queue] event listener error",n==null?void 0:n.message)}})},cn=e=>(Je.add(e),()=>{Je.delete(e)}),pn=()=>_.getState().downloads,C=(e,t)=>{let n=!!S(e),r=_.getState().downloads[e],s=t.status==="downloading"&&n?"updating":t.status,o={...r!=null?r:{status:"queued",progress:0},...t,...s?{status:s}:{},has_local:n};_.setState(a=>({downloads:{...a.downloads,[e]:o}})),(r==null?void 0:r.status)!==o.status||(r==null?void 0:r.version)!==o.version||(r==null?void 0:r.has_local)!==o.has_local?Y({type:"status_change",app_id:e,state:o}):r.progress!==o.progress&&Y({type:"progress",app_id:e,progress:o.progress,version:o.version})},be=(e,t)=>{var n;(n=te[e])==null||n.forEach(r=>r(t)),delete te[e]},ln=()=>_.getState().pause_reasons.length>0,Q=e=>{var u;if(h)return;let t=e?T.indexOf(e):ln()?-1:T.findIndex(i=>!V.has(i));if(t<0||t>=T.length)return;let[n]=T.splice(t,1),r=_.getState().catalog[n];if(!r){be(n,S(n)),Q();return}let s=Date.now();K[n]=((u=K[n])!=null?u:0)+1,C(n,{status:"downloading",progress:0,version:r.version,error:void 0});let o=0,a=Ve(r,{onProgress:i=>{let p=Math.floor(i*100);p!==o&&(o=p,C(n,{progress:p/100,version:r.version}))}});h={app_id:n,handle:a,forced:!!e},U("start",n,r.version,e?"(forced)":""),a.promise.then(i=>{U("installed",n,r.version,`${Date.now()-s}ms`),C(n,{status:"installed",progress:1,version:r.version}),be(n,i)}).catch(i=>{var w;if(i instanceof ie){if(Se.has(n))return;U("paused",n),K[n]-=1,T.unshift(n),C(n,{status:V.has(n)?"paused":"queued",progress:0,version:r.version});return}let p=String((w=i==null?void 0:i.message)!=null?w:i);if(console.warn("[miniapp-queue] failed",n,p),K[n]<rn){C(n,{status:"queued",progress:0,version:r.version,error:p}),setTimeout(()=>{var M;T.includes(n)||(h==null?void 0:h.app_id)===n||(T.push(n),Q((M=te[n])!=null&&M.length?n:void 0))},on);return}C(n,{status:"failed",progress:0,version:r.version,error:p}),be(n,S(n))}).finally(()=>{h=null;let i=T.find(p=>{var w;return(w=te[p])==null?void 0:w.length});Q(i)})},Ee=(e,{front:t=!1}={})=>{if((h==null?void 0:h.app_id)===e)return;let n=T.indexOf(e);if(n>=0){if(!t)return;T.splice(n,1)}t?T.unshift(e):T.push(e)},un=async e=>{let{host_id:t,client_token:n}=b(),r=new AbortController,s=setTimeout(()=>r.abort(),nn);try{let o=`${Ce}/api/hosts/${encodeURIComponent(t)}/miniapps?channel=${e}`,a=await fetch(o,{headers:{Authorization:`Bearer ${n}`,"Cache-Control":"no-cache"},signal:r.signal});if(!a.ok)throw new Error(`host list ${e} ${a.status}`);return(await a.json()).apps.map(i=>({...i,channel:e}))}finally{clearTimeout(s)}},ue=null,We=()=>(ue!=null||(ue=(async()=>{var t;let e=Date.now();try{let n=await Promise.all(b().channels.map(un)),r={};[...n].reverse().flat().forEach(i=>{r[i.app_id]=i});let s=Object.keys(_.getState().catalog).filter(i=>!r[i]);b().storage.setString(xt,JSON.stringify(r)),_.setState({catalog:r}),await Promise.all(s.map(i=>Rt(i,{by_user:!1}))),s.forEach(i=>G.delete(i));let o=Object.keys(r).filter(i=>!G.has(i)),a=[],u={};for(let i of o.map(p=>r[p])){if(await Ue(i)){C(i.app_id,{status:"installed",progress:1,version:i.version});continue}let p=S(i.app_id);if(Et(i.app_id)&&!xe.has(i.app_id)&&p&&await q(p)){C(i.app_id,{status:"installed",progress:1,version:p.version}),u[i.app_id]={app_id:i.app_id,current_version:p.version,next_version:i.version};continue}a.push(i)}return _.setState({updates:u}),a.forEach(i=>{K[i.app_id]=0,C(i.app_id,{status:V.has(i.app_id)?"paused":"queued",progress:0,version:i.version,error:void 0}),Ee(i.app_id)}),U("catalog",o.length,"apps, outdated",a.map(i=>i.app_id),"removed",s,`${Date.now()-e}ms`),Y({type:"sync_complete",app_ids:o,removed:s}),Object.values(u).forEach(i=>Y({type:"update_available",...i})),Q(),{ok:!0,app_ids:o,removed:s}}catch(n){let r=String((n==null?void 0:n.name)==="AbortError"?"timeout":(t=n==null?void 0:n.message)!=null?t:n);return console.warn("[miniapp-queue] sync catalog failed",r),Y({type:"sync_failed",error:r}),{ok:!1,error:r}}finally{ue=null}})()),ue),Rt=async(e,{by_user:t})=>{var s,o,a,u;if(t&&G.add(e),Se.has(e))return;Se.add(e),V.delete(e);let n=T.indexOf(e);n>=0&&T.splice(n,1),(h==null?void 0:h.app_id)===e&&h.handle.cancel();let r=(u=(a=(s=_.getState().downloads[e])==null?void 0:s.version)!=null?a:(o=S(e))==null?void 0:o.version)!=null?u:"";C(e,{status:"uninstalling",progress:0,version:r}),await wt(e),_e(e),_.setState(i=>{let p={...i.downloads};return delete p[e],{downloads:p}}),delete K[e],Se.delete(e),be(e,null),U("uninstalled",e,t?"(user)":"(not in list)"),Y({type:"uninstalled",app_id:e})},dn=e=>Rt(e,{by_user:!0}),gn=e=>{let t=de(e);return t?(G.delete(e),(h==null?void 0:h.app_id)===e||T.includes(e)||(K[e]=0,C(e,{status:V.has(e)?"paused":"queued",progress:0,version:t.version,error:void 0}),Ee(e),Q(),U("restore",e)),!0):!1},fn=e=>{if(V.has(e))return;if(V.add(e),U("pause app",e),(h==null?void 0:h.app_id)===e&&!h.forced){h.handle.cancel();return}let t=_.getState().downloads[e];T.includes(e)&&t&&C(e,{status:"paused",progress:0,version:t.version})},hn=e=>{if(!V.delete(e))return;U("resume app",e);let t=_.getState().downloads[e];(t==null?void 0:t.status)==="paused"&&!T.includes(e)&&de(e)&&(K[e]=0,Ee(e)),T.includes(e)&&t&&C(e,{status:"queued",progress:0,version:t.version}),Q()},An=e=>{let{pause_reasons:t}=_.getState();t.includes(e)||(_.setState({pause_reasons:[...t,e]}),U("pause",e),t.length===0&&Y({type:"pause_change",paused:!0,reasons:[e]}),h&&!h.forced&&h.handle.cancel())},mn=e=>{let{pause_reasons:t}=_.getState();if(!t.includes(e))return;let n=t.filter(r=>r!==e);_.setState({pause_reasons:n}),U("resume",e),n.length===0&&Y({type:"pause_change",paused:!1,reasons:n}),Q()},Pt=e=>_.getState().updates[e],Mn=async e=>{var n,r;let t=Pt(e);xe.add(e);try{let s=await Te(e),o=(r=t==null?void 0:t.next_version)!=null?r:(n=de(e))==null?void 0:n.version;return!s||!o||s.version!==o?!1:(_.setState(a=>{var i;let u={...a.updates};return delete u[e],{updates:u,apply_ticks:{...a.apply_ticks,[e]:((i=a.apply_ticks[e])!=null?i:0)+1}}}),U("updated",e,t==null?void 0:t.current_version,"\u2192",s.version),!0)}finally{xe.delete(e)}},yn=()=>Object.values(_.getState().catalog).map(e=>({...e,installed:!!S(e.app_id),removed_by_user:G.has(e.app_id)})),de=e=>_.getState().catalog[e],Te=async e=>{let t=de(e);if(!t)return;if(V.delete(e),G.delete(e),await Ue(t))return S(e);let n=S(e);if(Et(e)&&!xe.has(e)&&n&&await q(n))return n;let r=new Promise(s=>{var o;((o=te[e])!=null?o:te[e]=[]).push(s)});return(h==null?void 0:h.app_id)===e?h.forced=!0:(K[e]=0,Ee(e,{front:!0}),h&&!h.forced?h.handle.cancel():Q(e)),r};import{Fragment as It,jsx as R,jsxs as fe}from"react/jsx-runtime";var qe=e=>(e!=null?e:"").replace(/\?[^#]*/,""),kt=0,xn=()=>{let e=new Set;return{emit:t=>e.forEach(n=>n(t)),subscribe:t=>(e.add(t),()=>{e.delete(t)})}},En=Ye.memo(({instance_key:e,is_active:t,is_front:n,is_dark:r,reload_tick:s,web_at_top:o,splash:a,bridge:u,opaque_background:i,allow_embedded_miniapps:p,onWebLoadEnd:w})=>{var tt,nt;let M=H(null),v=H(!1),A=j(F,c=>c.instances[e]),f=A==null?void 0:A.app.app_id,N=A==null?void 0:A.app.manifest_url,E=A==null?void 0:A.context,I=A==null?void 0:A.url_params,[l,P]=ne(()=>f?S(f):null),[g,y]=ne(!1),[re,oe]=ne(0),[Dt,se]=ne(0),[Lt,O]=ne(!1),W=H(null),Ge=c=>{W.current&&clearTimeout(W.current),W.current=setTimeout(()=>{W.current=null,O(!0)},c)};J(()=>()=>{W.current&&clearTimeout(W.current)},[]),J(()=>{if(!f||!t&&l)return;let c=!0;return y(!1),(async()=>{let d=S(f),k=d?await q(d):!1;if(!c||(P(k?$=>!$||$.version!==d.version||$.permissions.join(",")!==d.permissions.join(",")?d:$:null),__DEV__&&Date.now()-kt>1e4&&(kt=Date.now(),await We()),!c))return;let z=await Te(f),X=z!==void 0?z:N?await _t(f,N):S(f);if(c){if(!X){y(!0);return}P($=>$!=null?$:X)}})(),()=>{c=!1}},[t,f,N,re]),J(()=>St(e,c=>M.current?(M.current.postMessage(c),!0):!1),[e]);let Bt=j(_,c=>{let d=f?c.downloads[f]:void 0;return(d==null?void 0:d.status)==="installed"?d.version:void 0});J(()=>{if(t||!f||!l)return;let c=S(f);if(!c||c.version===l.version)return;let d=!0;return q(c).then(k=>{!d||!k||(L(`webview:${e}`,"\u0111\u1ED5i bundle (\u1EA9n)",l.version,"\u2192",c.version),P(c))}),()=>{d=!1}},[t,f,Bt,l==null?void 0:l.version]);let Xe=j(_,c=>{var d;return f&&(d=c.apply_ticks[f])!=null?d:0});J(()=>{if(!Xe||!f)return;let c=S(f);if(!c||c.version===(l==null?void 0:l.version))return;let d=!0;return q(c).then(k=>{!d||!k||(L(`webview:${e}`,"c\u1EADp nh\u1EADt",l==null?void 0:l.version,"\u2192",c.version),O(!1),P(c))}),()=>{d=!1}},[Xe]),J(()=>{var k;let c=(k=b().keep_alive)==null?void 0:k.idle_close_ms;if(t||!c||c<=0)return;let d=setTimeout(()=>{_e(e)},c);return()=>clearTimeout(d)},[t,e]),J(()=>{s>0&&(y(!1),O(!1),se(c=>c+1),oe(c=>c+1))},[s]);let Ze=H(t);J(()=>{var c;Ze.current!==t&&(Ze.current=t,v.current&&((c=M.current)==null||c.injectJavaScript(ut(t?"resumed":"paused"))))},[t]);let he=`${(tt=l==null?void 0:l.version)!=null?tt:"none"}:${(nt=l==null?void 0:l.permissions.join(","))!=null?nt:""}:${Dt}`,ae=Re(()=>JSON.stringify([E!=null?E:{},I!=null?I:{}]),[E,I]),Pe=Re(()=>{var c;return At(I!=null?I:{},(c=l==null?void 0:l.permissions)!=null?c:[])},[ae,l==null?void 0:l.permissions]),Nt=Re(()=>ft(E!=null?E:{},Pe)+lt()+(b().debug?pt():""),[Pe]),Ae=H(null),et=H(null);J(()=>{var d,k,z;if(!l)return;if(et.current!==he){et.current=he,Ae.current=ae;return}if(Ae.current===ae)return;let c=((k=JSON.parse((d=Ae.current)!=null?d:"[]")[0])!=null?k:{}).org_id;if(Ae.current=ae,c===(E==null?void 0:E.org_id)&&v.current){O(!1),Ge(1500),(z=M.current)==null||z.injectJavaScript(dt(E!=null?E:{},Pe));return}O(!1),se(X=>X+1)},[ae,l,he]);let $t=Ke(async c=>{var k,z,X,$,ke;let d=st(c.nativeEvent.data);if(!d){if(f&&(u!=null&&u.onWebEvent))try{Promise.resolve(u.onWebEvent(c.nativeEvent.data,{app_id:f,instance_id:e})).catch(x=>{console.warn("[miniapp] onWebEvent l\u1ED7i",f,x)})}catch(x){console.warn("[miniapp] onWebEvent l\u1ED7i",f,x)}return}if(d.method==="log"){let{level:x,text:D}=d;L(`web:${e}`,x!=null?x:"log",D!=null?D:"");return}if(d.method==="pong"){W.current||O(!0);return}if(d.method==="touchAtTop"){o.emit(!!d.at_top);return}if(d.method==="contextApplied"){W.current&&clearTimeout(W.current),W.current=null,O(!0);return}if(d.method==="ready"){v.current=!0,O(!0);let x=(k=F.getState().instances[e])==null?void 0:k.context;x&&((z=M.current)==null||z.injectJavaScript(De(x)));return}try{let x=await mt(d,{getHostData:()=>{var D,Z;return(Z=(D=F.getState().instances[e])==null?void 0:D.host_data)!=null?Z:{}},getPermissions:()=>{var D,Z;return f?(Z=(D=S(f))==null?void 0:D.permissions)!=null?Z:[]:[]},is_dark:r,close:le,app_id:f!=null?f:"",instance_id:e,options:u});d.id&&((X=M.current)==null||X.injectJavaScript(at(d.id,x)))}catch(x){if(!d.id)return;let D=x==null?void 0:x.code,Z=x instanceof m?x:new m(typeof D=="string"?D:"HOST_ERROR",String(($=x==null?void 0:x.message)!=null?$:x));(ke=M.current)==null||ke.injectJavaScript(ct(d.id,Z))}},[e,r,f,o,u]),Ft=Ke(()=>{y(!1),se(c=>c+1),oe(c=>c+1)},[]);return fe(ze,{style:[Qe.absoluteFill,i&&{backgroundColor:r?"#09090B":"#FFFFFF"},!n&&B.behind],pointerEvents:t?"auto":"none",children:[l?R(bn,{ref:M,source:{uri:l.entry_uri},originWhitelist:["*"],allowingReadAccessToURL:`file://${p?Ne():l.dir}`,allowFileAccess:!0,allowFileAccessFromFileURLs:!0,allowUniversalAccessFromFileURLs:!0,injectedJavaScriptBeforeContentLoaded:Nt,onMessage:$t,bounces:!1,overScrollMode:"never",onLoadStart:c=>{L(`webview:${e}`,"load start",qe(c.nativeEvent.url)),v.current=!1,O(!1)},onError:c=>{L(`webview:${e}`,"load error",qe(c.nativeEvent.url),c.nativeEvent.description),y(!0),O(!1)},onLoadEnd:c=>{let d=c.nativeEvent.url;L(`webview:${e}`,"load end",qe(d)),f&&(w==null||w({app_id:f,instance_id:e,url:d})),Ge(1500)},onContentProcessDidTerminate:()=>{v.current=!1,O(!1),se(c=>c+1)},onRenderProcessGone:()=>(v.current=!1,O(!1),se(c=>c+1),!0),style:B.webview},he):null,A&&R(Rn,{visible:!l||!Lt,interactive:g,children:R(Tn,{splash:a,app:A.app,is_dark:r,error:g,has_bundle:!!l,retry:Ft})})]})}),Tn=Ye.memo(({splash:e,app:t,is_dark:n,error:r,has_bundle:s,retry:o})=>{let a=e,u=He(t.app_id),i=r?"error":!s&&(u==null?void 0:u.status)==="downloading"?"downloading":"loading";return R(a,{app:t,is_dark:n,status:i,progress:i==="downloading"?u==null?void 0:u.progress:void 0,retry:o})}),Rn=({visible:e,interactive:t,children:n})=>{let r=H(new je.Value(e?1:0)).current,[s,o]=ne(e);return J(()=>{if(e){o(!0),r.setValue(1);return}let a=je.timing(r,{toValue:0,duration:180,useNativeDriver:!0});return a.start(({finished:u})=>{u&&o(!1)}),()=>a.stop()},[e,r]),s?R(je.View,{style:[Qe.absoluteFill,{opacity:r}],pointerEvents:t?"auto":"none",children:n}):null},Ot=({app:e,is_dark:t,status:n,progress:r,retry:s})=>{let o=t?"#FAFAFA":"#18181B";return fe(ze,{style:[B.splash,{backgroundColor:t?"#09090B":"#FFFFFF"}],children:[R(ze,{style:[B.splash_icon,{backgroundColor:t?"#18181B":"#F4F4F5"}],children:e.icon?R(_n,{source:{uri:e.icon},style:B.splash_icon_image}):R(ge,{style:B.splash_letter,children:(e.name||"?").slice(0,1).toUpperCase()})}),R(ge,{style:[B.splash_name,{color:o}],children:e.name}),n==="error"?fe(It,{children:[R(ge,{style:B.splash_hint,children:"Kh\xF4ng t\u1EA3i \u0111\u01B0\u1EE3c mini app"}),R(Sn,{activeOpacity:.7,style:[B.retry_button,{backgroundColor:t?"#27272A":"#F4F4F5"}],onPress:s,children:R(ge,{style:[B.retry_text,{color:o}],children:"Th\u1EED l\u1EA1i"})})]}):fe(It,{children:[R(wn,{style:B.splash_spinner,color:t?"#A1A1AA":"#71717A"}),n==="downloading"&&fe(ge,{style:B.splash_hint,children:["\u0110ang t\u1EA3i mini app",r?` ${Math.round(r*100)}%`:"\u2026"]})]})]})},Ct=(e,t)=>{let n=H(t),r=H(!1);__DEV__&&!r.current&&n.current!==t&&(r.current=!0,console.warn(`[miniapp] MiniAppHost prop "${e}" \u0111\u1ED5i gi\u1EEFa c\xE1c l\u1EA7n render \u2192 m\u1ECDi WebView b\u1ECB mount l\u1EA1i. Khai b\xE1o component b\xEAn ngo\xE0i render.`))},Pn=({container:e,splash:t=Ot,is_dark:n=!1,bridge:r,close_on_back:s=!0,opaque_background:o=!0,allow_embedded_miniapps:a=!1,onWebLoadEnd:u})=>{Ct("container",e),Ct("splash",t);let i=e,p=j(F,l=>l.active_key),w=H(p);p&&(w.current=p);let M=j(F,l=>Object.keys(l.instances).join("|")),v=j(F,l=>{var P;return l.active_key?(P=l.instances[l.active_key])==null?void 0:P.app.name:void 0}),A=Re(()=>M?M.split("|"):[],[M]),[f,N]=ne({}),E=H(xn()).current;J(()=>{if(!p||!s)return;let l=vn.addEventListener("hardwareBackPress",()=>(le(),!0));return()=>l.remove()},[p,s]);let I=Ke(()=>{let l=F.getState().active_key;l&&N(P=>({...P,[l]:(P[l]||0)+1}))},[]);return A.length?R(i,{visible:!!p,title:v!=null?v:"",is_dark:n,close:le,reload:I,subscribeWebAtTop:E.subscribe,children:A.map(l=>R(En,{instance_key:l,is_active:p===l,is_front:(p!=null?p:w.current)===l,is_dark:n,reload_tick:f[l]||0,web_at_top:E,splash:t,bridge:r,opaque_background:o,allow_embedded_miniapps:a,onWebLoadEnd:u},l))}):null},B=Qe.create({webview:{flex:1,backgroundColor:"transparent"},behind:{zIndex:-1},splash:{flex:1,alignItems:"center",justifyContent:"center",gap:12},splash_icon:{width:72,height:72,borderRadius:20,alignItems:"center",justifyContent:"center",overflow:"hidden"},splash_icon_image:{width:72,height:72},splash_letter:{fontSize:28,fontWeight:"700",color:"#1D4ED8"},splash_name:{fontSize:16,fontWeight:"600"},splash_hint:{color:"#71717A"},splash_spinner:{marginTop:8},retry_button:{marginTop:4,paddingHorizontal:20,paddingVertical:10,borderRadius:999},retry_text:{fontWeight:"600"}}),kn=Ye.memo(Pn);var Cn=e=>({getAvailability:async()=>{var r;let t=await e.isSensorAvailable(),n=["FaceID","TouchID","Biometrics"].includes((r=t.biometryType)!=null?r:"")?t.biometryType:void 0;return{available:t.available,...n?{biometryType:n}:{}}},authenticate:async({reason:t,cancelButtonText:n})=>{try{let{available:r}=await e.isSensorAvailable();if(!r)throw new m("BIOMETRIC_UNAVAILABLE","Biometrics unavailable, not enrolled or permission denied");let s=await e.simplePrompt({promptMessage:t,cancelButtonText:n,fallbackPromptMessage:""});if(!s.success)throw new m("CANCELLED",s.error||"Biometric authentication cancelled");return{success:!0}}catch(r){throw r instanceof m?r:new m("AUTHENTICATION_FAILED",r instanceof Error?r.message:String(r))}}});export{Ot as DefaultMiniAppSplash,Ce as MINIAPP_PLATFORM_URL,kn as MiniAppHost,m as MiniAppHostError,le as closeMiniApp,Ut as configureMiniApp,Jt as createMmkvStorage,Cn as createReactNativeBiometrics,Vt as createRnfsFileSystem,Te as ensureMiniApp,S as getLocalMiniApp,yn as getMiniAppCatalog,de as getMiniAppCatalogEntry,pn as getMiniAppStatuses,Pt as getMiniAppUpdate,Kt as installBundledMiniApp,cn as onMiniAppEvent,Xt as openMiniApp,fn as pauseMiniApp,An as pauseMiniAppDownloads,Zt as preloadMiniApp,gn as restoreMiniApp,hn as resumeMiniApp,mn as resumeMiniAppDownloads,Yt as sendEventToWeb,We as syncMiniAppCatalog,dn as uninstallMiniApp,Mn as updateMiniApp,He as useMiniAppDownload,an as useMiniAppDownloadsPaused};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@retion-miniapp/react-native",
3
- "version": "0.7.4",
3
+ "version": "0.7.6",
4
4
  "description": "Host chạy Retion Mini App (bundle web) trong app React Native — chỉ cần react-native-webview",
5
5
  "license": "MIT",
6
6
  "repository": {