@retion-miniapp/react-native 0.7.3 → 0.7.5

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
@@ -163,7 +163,7 @@ interface MiniAppBridgeOptions {
163
163
  showToast?: (message: string) => void;
164
164
  /** Web gọi haptic(type) (lệnh 1 chiều). Không truyền → bỏ qua. */
165
165
  haptic?: (type: MiniAppHapticType) => void;
166
- /** Web gọi openWebview(url). Mặc định Linking.openURL. */
166
+ /** Web gọi openWebview(url) / openLink(url). Mặc định Linking.openURL. */
167
167
  openUrl?: (url: string) => Promise<void> | void;
168
168
  /** Trả cho web qua getSystemInfo(). */
169
169
  app_version?: string;
@@ -474,8 +474,19 @@ declare const getMiniAppCatalogEntry: (app_id: string) => MiniAppCatalogEntry |
474
474
  */
475
475
  declare const ensureMiniApp: (app_id: string) => Promise<MiniAppLocalBundle | null | undefined>;
476
476
 
477
+ /** Đủ thông tin để ghi bản ghi bundle trong máy (bản tải từ mạng hoặc bản đóng sẵn trong app). */
478
+ type BundleRecordSource = Pick<MiniAppManifest, 'app_id' | 'version'> & Partial<Pick<MiniAppManifest, 'entry' | 'context_update' | 'permissions'>>;
477
479
  /** Bundle đang có trong máy (sync). null nếu chưa tải lần nào. */
478
480
  declare const getLocalMiniApp: (app_id: string) => MiniAppLocalBundle | null;
481
+ /**
482
+ * Cài bản mini app đóng sẵn trong ứng dụng (zip nằm trong máy, không tải mạng) — vd ứng dụng chạy mini app
483
+ * chính ngay lần mở đầu, không bắt người dùng chờ tải. Trong máy đã có bản bằng / mới hơn (đã cập nhật qua
484
+ * Console) → giữ nguyên. Không xoá file zip (thường là asset của ứng dụng).
485
+ */
486
+ declare const installBundledMiniApp: ({ manifest, zip_path }: {
487
+ manifest: BundleRecordSource & Partial<Pick<MiniAppManifest, "sha256">>;
488
+ zip_path: string;
489
+ }) => Promise<MiniAppLocalBundle>;
479
490
 
480
491
  /**
481
492
  * App → web: gửi event xuống web của mini app — web nhận y như `WebView.postMessage` (sự kiện `message`).
@@ -489,4 +500,4 @@ declare class BridgeError extends Error {
489
500
  constructor(code: string, message: string);
490
501
  }
491
502
 
492
- 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, onMiniAppEvent, openMiniApp, pauseMiniApp, pauseMiniAppDownloads, preloadMiniApp, restoreMiniApp, resumeMiniApp, resumeMiniAppDownloads, sendEventToWeb, syncMiniAppCatalog, uninstallMiniApp, updateMiniApp, useMiniAppDownload, useMiniAppDownloadsPaused };
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 };
package/dist/index.d.ts CHANGED
@@ -163,7 +163,7 @@ interface MiniAppBridgeOptions {
163
163
  showToast?: (message: string) => void;
164
164
  /** Web gọi haptic(type) (lệnh 1 chiều). Không truyền → bỏ qua. */
165
165
  haptic?: (type: MiniAppHapticType) => void;
166
- /** Web gọi openWebview(url). Mặc định Linking.openURL. */
166
+ /** Web gọi openWebview(url) / openLink(url). Mặc định Linking.openURL. */
167
167
  openUrl?: (url: string) => Promise<void> | void;
168
168
  /** Trả cho web qua getSystemInfo(). */
169
169
  app_version?: string;
@@ -474,8 +474,19 @@ declare const getMiniAppCatalogEntry: (app_id: string) => MiniAppCatalogEntry |
474
474
  */
475
475
  declare const ensureMiniApp: (app_id: string) => Promise<MiniAppLocalBundle | null | undefined>;
476
476
 
477
+ /** Đủ thông tin để ghi bản ghi bundle trong máy (bản tải từ mạng hoặc bản đóng sẵn trong app). */
478
+ type BundleRecordSource = Pick<MiniAppManifest, 'app_id' | 'version'> & Partial<Pick<MiniAppManifest, 'entry' | 'context_update' | 'permissions'>>;
477
479
  /** Bundle đang có trong máy (sync). null nếu chưa tải lần nào. */
478
480
  declare const getLocalMiniApp: (app_id: string) => MiniAppLocalBundle | null;
481
+ /**
482
+ * Cài bản mini app đóng sẵn trong ứng dụng (zip nằm trong máy, không tải mạng) — vd ứng dụng chạy mini app
483
+ * chính ngay lần mở đầu, không bắt người dùng chờ tải. Trong máy đã có bản bằng / mới hơn (đã cập nhật qua
484
+ * Console) → giữ nguyên. Không xoá file zip (thường là asset của ứng dụng).
485
+ */
486
+ declare const installBundledMiniApp: ({ manifest, zip_path }: {
487
+ manifest: BundleRecordSource & Partial<Pick<MiniAppManifest, "sha256">>;
488
+ zip_path: string;
489
+ }) => Promise<MiniAppLocalBundle>;
479
490
 
480
491
  /**
481
492
  * App → web: gửi event xuống web của mini app — web nhận y như `WebView.postMessage` (sự kiện `message`).
@@ -489,4 +500,4 @@ declare class BridgeError extends Error {
489
500
  constructor(code: string, message: string);
490
501
  }
491
502
 
492
- 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, onMiniAppEvent, openMiniApp, pauseMiniApp, pauseMiniAppDownloads, preloadMiniApp, restoreMiniApp, resumeMiniApp, resumeMiniAppDownloads, sendEventToWeb, syncMiniAppCatalog, uninstallMiniApp, updateMiniApp, useMiniAppDownload, useMiniAppDownloadsPaused };
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 };
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var Gt=Object.create;var ge=Object.defineProperty;var Xt=Object.getOwnPropertyDescriptor;var Zt=Object.getOwnPropertyNames;var en=Object.getPrototypeOf,tn=Object.prototype.hasOwnProperty;var nn=(e,t)=>{for(var n in t)ge(e,n,{get:t[n],enumerable:!0})},Ye=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Zt(t))!tn.call(e,s)&&s!==n&&ge(e,s,{get:()=>t[s],enumerable:!(r=Xt(t,s))||r.enumerable});return e};var Qe=(e,t,n)=>(n=e!=null?Gt(en(e)):{},Ye(t||!e||!e.__esModule?ge(n,"default",{value:e,enumerable:!0}):n,e)),rn=e=>Ye(ge({},"__esModule",{value:!0}),e);var _n={};nn(_n,{DefaultMiniAppSplash:()=>Ue,MINIAPP_PLATFORM_URL:()=>fe,MiniAppHost:()=>Ht,MiniAppHostError:()=>T,closeMiniApp:()=>te,configureMiniApp:()=>Xe,createMmkvStorage:()=>tt,createRnfsFileSystem:()=>et,ensureMiniApp:()=>le,getLocalMiniApp:()=>b,getMiniAppCatalog:()=>Bt,getMiniAppCatalogEntry:()=>ne,getMiniAppStatuses:()=>Ct,getMiniAppUpdate:()=>Be,onMiniAppEvent:()=>Pt,openMiniApp:()=>St,pauseMiniApp:()=>Dt,pauseMiniAppDownloads:()=>$t,preloadMiniApp:()=>bt,restoreMiniApp:()=>It,resumeMiniApp:()=>Lt,resumeMiniAppDownloads:()=>Nt,sendEventToWeb:()=>vt,syncMiniAppCatalog:()=>Re,uninstallMiniApp:()=>kt,updateMiniApp:()=>Ft,useMiniAppDownload:()=>xe,useMiniAppDownloadsPaused:()=>Tt});module.exports=rn(_n);var fe="https://retion-miniapp-platform.vercel.app",X=null,Ge=new Set,Xe=e=>{X=e,Ge.forEach(t=>t())},R=()=>{if(!X)throw new Error("[miniapp] Ch\u01B0a g\u1ECDi configureMiniApp()");return X},Ze=e=>{Ge.add(e),X&&e()},F=(...e)=>{X!=null&&X.debug&&console.log("[miniapp]",...e)};var et=(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:c}=e.downloadFile({fromUrl:n,toFile:r,progressInterval:250,begin:()=>{},progress:({bytesWritten:l,contentLength:i})=>s==null?void 0:s(l,i)});return{promise:c.then(({statusCode:l})=>({status:l})),cancel:()=>e.stopDownload(o)}}}),tt=e=>({getString:t=>e.getString(t),setString:(t,n)=>e.set(t,n)});var g=Qe(require("react")),_=require("react-native"),Vt=Qe(require("react-native-webview"));var he=require("react-native"),Ae=1,T=class extends Error{constructor(n,r){super(r);this.code=n}},rt=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;`,it=(e,t)=>me({id:e,result:t}),ot=(e,t)=>me({id:e,error:{code:t.code,message:t.message}}),ke=e=>me({event:"context",data:e});var st=()=>`(function () {
1
+ "use strict";var en=Object.create;var Ae=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)Ae(e,n,{get:t[n],enumerable:!0})},Xe=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of nn(t))!on.call(e,s)&&s!==n&&Ae(e,s,{get:()=>t[s],enumerable:!(r=tn(t,s))||r.enumerable});return e};var Ze=(e,t,n)=>(n=e!=null?en(rn(e)):{},Xe(t||!e||!e.__esModule?Ae(n,"default",{value:e,enumerable:!0}):n,e)),an=e=>Xe(Ae({},"__esModule",{value:!0}),e);var xn={};sn(xn,{DefaultMiniAppSplash:()=>je,MINIAPP_PLATFORM_URL:()=>me,MiniAppHost:()=>Kt,MiniAppHostError:()=>E,closeMiniApp:()=>ie,configureMiniApp:()=>tt,createMmkvStorage:()=>it,createRnfsFileSystem:()=>rt,ensureMiniApp:()=>ge,getLocalMiniApp:()=>S,getMiniAppCatalog:()=>Ht,getMiniAppCatalogEntry:()=>oe,getMiniAppStatuses:()=>Dt,getMiniAppUpdate:()=>He,installBundledMiniApp:()=>_t,onMiniAppEvent:()=>It,openMiniApp:()=>Rt,pauseMiniApp:()=>Bt,pauseMiniAppDownloads:()=>Jt,preloadMiniApp:()=>Tt,restoreMiniApp:()=>Nt,resumeMiniApp:()=>Ft,resumeMiniAppDownloads:()=>Ut,sendEventToWeb:()=>xt,syncMiniAppCatalog:()=>Pe,uninstallMiniApp:()=>$t,updateMiniApp:()=>Vt,useMiniAppDownload:()=>Re,useMiniAppDownloadsPaused:()=>Ot});module.exports=an(xn);var me="https://retion-miniapp-platform.vercel.app",ee=null,et=new Set,tt=e=>{ee=e,et.forEach(t=>t())},x=()=>{if(!ee)throw new Error("[miniapp] Ch\u01B0a g\u1ECDi configureMiniApp()");return ee},nt=e=>{et.add(e),ee&&e()},N=(...e)=>{ee!=null&&ee.debug&&console.log("[miniapp]",...e)};var rt=(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)}}}),it=e=>({getString:t=>e.getString(t),setString:(t,n)=>e.set(t,n)});var d=Ze(require("react")),_=require("react-native"),qt=Ze(require("react-native-webview"));var ce=require("react-native"),Me=1,E=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}),pt=(e,t)=>ye({id:e,error:{code:t.code,message:t.message}}),De=e=>ye({event:"context",data:e});var ct=()=>`(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: ${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 @@
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;`,at=()=>`(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: ${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 @@
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;`,pt=e=>me({event:e}),ct=(e,t)=>{let n=lt(t);return`try { history.replaceState(history.state, '', location.pathname + ${JSON.stringify(n?`?${n}`:"")} + location.hash); } catch (e) {}
42
- ${ke(e)}`},lt=e=>Object.entries(e).filter(([,t])=>t!=null&&t!=="").map(([t,n])=>`${encodeURIComponent(t)}=${encodeURIComponent(String(n))}`).join("&"),ut=(e,t={})=>{let n=lt(t);return`window.__RETION_MINIAPP_HOST__ = { protocol: ${Ae} };
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;`},dt={partner:"partner_token",chatbox:"chatbox_token"},gt=(e,t)=>{let n={...e};for(let r of Object.values(dt))t.includes(r)||delete n[r];return n},Ce=new Set,nt=async(e,t)=>{if(Ce.has(e))throw new T("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)}},on=new Set(["selection","impactLight","impactMedium","impactHeavy","rigid","soft","notificationSuccess","notificationWarning","notificationError"]),Oe=(e,t)=>{if(typeof e!="string"||!e)throw new T("INVALID_PARAMS",`Thi\u1EBFu ${t}`);return e},ft=async({method:e,params:t},{getHostData:n,getPermissions:r,is_dark:s,close:o,app_id:c,instance_id:l,options:i})=>{var x,m,h,$,w;let u=i==null?void 0:i.handlers,y={app_id:c,instance_id:l,close:o},M=()=>new T("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF \u1EE9ng d\u1EE5ng n\xE0y`);switch(e){case"requestPayment":{let d=u==null?void 0:u.requestPayment;if(!d)throw M();let a=t==null?void 0:t.amount;if(typeof a!="number"||!Number.isFinite(a)||a<=0)throw new T("INVALID_PARAMS","amount ph\u1EA3i l\xE0 s\u1ED1 > 0");let P={...t,amount:a,currency:Oe(t==null?void 0:t.currency,"currency")};return nt(e,()=>d(P,y))}case"printImage":{let d=u==null?void 0:u.printImage;if(!d)throw M();let a=Oe(t==null?void 0:t.image,"image");await nt(e,()=>d({image:a},y));return}case"openScreen":if(!(u!=null&&u.openScreen))throw M();await u.openScreen({screen:Oe(t==null?void 0:t.screen,"screen"),params:t==null?void 0:t.params},y);return;case"closeApp":o();return;case"openWebview":{let d=String((x=t==null?void 0:t.url)!=null?x:"");if(!/^https?:\/\//i.test(d))throw new T("INVALID_PARAMS","url ph\u1EA3i l\xE0 http(s)");await(i!=null&&i.openUrl?i.openUrl(d):he.Linking.openURL(d));return}case"showToast":(h=i==null?void 0:i.showToast)==null||h.call(i,String((m=t==null?void 0:t.message)!=null?m:""));return;case"haptic":{let d=on.has(t==null?void 0:t.type)?t.type:"selection";($=i==null?void 0:i.haptic)==null||$.call(i,d);return}case"getSystemInfo":return{platform:he.Platform.OS==="ios"?"ios":"android",appVersion:(w=i==null?void 0:i.app_version)!=null?w:"",theme:s?"dark":"light"};case"getAccessToken":{let d=n().access_token;if(!d)throw new T("HOST_ERROR","Mini app ch\u01B0a c\xF3 token cho page n\xE0y");return d}case"getToken":{let d=t==null?void 0:t.type;if(d==="access"){let re=n().access_token;if(!re)throw new T("HOST_ERROR","Mini app ch\u01B0a c\xF3 token cho page n\xE0y");return re}if(d!=="partner"&&d!=="chatbox")throw new T("HOST_ERROR",`Lo\u1EA1i token kh\xF4ng h\u1EE3p l\u1EC7: ${String(d)}`);let a=dt[d];if(!r().includes(a))throw new T("PERMISSION_DENIED",`Mini app ch\u01B0a \u0111\u01B0\u1EE3c c\u1EA5p quy\u1EC1n ${a} (Console \u2192 Quy\u1EC1n l\u1EA5y token)`);let P=d==="partner"?n().partner_token:n().chatbox_token;if(!P)throw new T("HOST_ERROR",`Kh\xF4ng c\xF3 ${a}`);return P}case"getUserInfo":{let d=n().user;if(!d)throw new T("HOST_ERROR","Kh\xF4ng l\u1EA5y \u0111\u01B0\u1EE3c th\xF4ng tin nh\xE2n vi\xEAn");return d}case"getPageInfo":{let d=n().page;if(!d)throw new T("HOST_ERROR","Kh\xF4ng l\u1EA5y \u0111\u01B0\u1EE3c th\xF4ng tin page");return d}case"sendMessage":case"insertText":throw new T("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF phi\xEAn b\u1EA3n app n\xE0y`);default:throw new T("NOT_SUPPORTED",`API kh\xF4ng t\u1ED3n t\u1EA1i: ${e}`)}};var Ie=e=>`bundle:${e}`,De=()=>`${R().file_system.document_dir}/miniapps`,Le=De,mt=(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}},ht=e=>{var t;R().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:[]}))},sn=(e,t)=>/^https?:\/\//.test(t)?t:`${e.replace(/[^/]*$/,"")}${t}`,b=e=>{let t=R().storage.getString(Ie(e));if(!t)return null;try{let{version:n,entry:r,context_update:s,permissions:o}=JSON.parse(t);return mt(e,n,r,!!s,Array.isArray(o)?o:[])}catch{return null}},q=e=>R().file_system.exists(e.entry_uri.replace("file://","")),$e=async e=>{let t=b(e.app_id);return(t==null?void 0:t.version)===e.version&&await q(t)},an=async(e,t)=>{let n=R().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=pe[e])==null?void 0:t.catch(()=>{})),R().storage.setString(Ie(e),""),await R().file_system.remove(`${Le()}/${e}`).catch(()=>{})},ee=class extends Error{constructor(){super("cancelled"),this.name="MiniAppInstallCancelled"}},pe={},Ne=(e,{base_url:t,onProgress:n}={})=>{var x;let r=R().file_system,s=null,o=!1,c=`${r.cache_dir}/${e.app_id}-${e.version}.zip`,l=()=>{if(o)throw new ee},i=async()=>{var $;l();let m=b(e.app_id);if((m==null?void 0:m.version)===e.version&&await r.exists(m.dir))return ht(e),b(e.app_id);l();let h=r.download({url:t?sn(t,e.bundle_url):e.bundle_url,to_file:c,onProgress:(w,d)=>{var P;let a=d>0?d:(P=e.size)!=null?P:0;a>0&&(n==null||n(Math.min(1,w/a)))}});s=h;try{let{status:w}=await h.promise;if(l(),w!==200)throw new Error(`bundle ${w}`);if(e.sha256)if(r.sha256){if(await r.sha256(c)!==e.sha256)throw new Error("sha256 mismatch")}else F("b\u1ECF qua ki\u1EC3m tra sha256 (file_system kh\xF4ng c\xF3 sha256)",e.app_id);l();let d=mt(e.app_id,e.version,e.entry,!!e.context_update,($=e.permissions)!=null?$:[]);return await r.remove(d.dir).catch(()=>{}),await r.mkdir(d.dir),await r.unzip(c,d.dir),ht(e),an(e.app_id,[e.version,m==null?void 0:m.version].filter(Boolean)),d}catch(w){throw o?new ee:w}finally{s=null,r.remove(c).catch(()=>{})}},y=((x=pe[e.app_id])!=null?x:Promise.resolve()).catch(()=>{}).then(i),M=y.catch(()=>{});return pe[e.app_id]=M,M.then(()=>{pe[e.app_id]===M&&delete pe[e.app_id]}),{promise:y,cancel:()=>{o=!0,s==null||s.cancel()}}},ae={},pn=__DEV__?0:60*1e3,At={},yt=(e,t)=>{var r,s;let n=b(e);return n&&Date.now()-((r=At[t])!=null?r:0)<pn?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 c=await o.json(),l=await Ne(c,{base_url:t}).promise;return At[t]=Date.now(),l})().catch(o=>(console.warn("[miniapp] sync failed",e,o==null?void 0:o.message),b(e))).finally(()=>{ae[e]=void 0})),ae[e])};var Me=new Map,wt=(e,t)=>(Me.set(e,t),()=>{Me.get(e)===t&&Me.delete(e)}),vt=(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(),c=r.current;if(c&&c.state===o&&c.selector===t)return c.value;let l=t(o),i=c&&n(c.value,l)?c.value:l;return r.current={state:o,selector:t,value:i},i};return(0,ye.useSyncExternalStore)(e.subscribe,s)};var B=we({active_key:null,instances:{}}),_t=({app:e,instance_id:t,context:n={},url_params:r={},host_data:s={}},o)=>{var l;let c=(l=R().keep_alive)==null?void 0:l.max_webviews;B.setState(i=>{let u=t!=null?t:e.app_id,y={...i.instances,[u]:{key:u,app:e,context:n,url_params:r,host_data:s,last_used_at:Date.now()}},M=Object.keys(y);return c&&c>0&&M.length>c&&M.filter(x=>x!==u).sort((x,m)=>y[x].last_used_at-y[m].last_used_at).slice(0,M.length-c).forEach(x=>{delete y[x]}),o?{active_key:u,instances:y}:{instances:y}})},St=e=>_t(e,!0),bt=e=>_t(e,!1),te=()=>B.setState({active_key:null}),ve=e=>{B.setState(t=>{if(t.active_key===e||!t.instances[e])return{};let n={...t.instances};return delete n[e],{instances:n}})};var xt="catalog",cn="paused_apps",ln="removed_apps",un=10*1e3,dn=2,gn=3e3,fn=()=>{var e;try{return JSON.parse((e=R().storage.getString(xt))!=null?e:"{}")}catch{return{}}},v=we({catalog:{},downloads:{},pause_reasons:[],updates:{},apply_ticks:{}}),Et=e=>{var t;return!!((t=R().manual_update)!=null&&t.includes(e))},be=new Set,Rt=e=>{let t=new Set,n=()=>R().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=R().storage.getString(e))!=null?r:"[]");Array.isArray(s)&&s.forEach(o=>{typeof o=="string"&&t.add(o)})}catch{}}}},U=Rt(cn),Y=Rt(ln);Ze(()=>{U.load(),Y.load();let e=fn(),t={};Object.keys(e).filter(n=>!Y.has(n)).forEach(n=>{let r=b(n);r?t[n]={status:"installed",progress:1,version:r.version,has_local:!0}:U.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),Tt=()=>H(v,e=>e.pause_reasons.length>0),J=(...e)=>F("queue",...e),C=[],W={},A=null,_e=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)}})},Pt=e=>(Fe.add(e),()=>{Fe.delete(e)}),Ct=()=>v.getState().downloads,k=(e,t)=>{let n=!!b(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(c=>({downloads:{...c.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]},hn=()=>v.getState().pause_reasons.length>0,z=e=>{var l;if(A)return;let t=e?C.indexOf(e):hn()?-1:C.findIndex(i=>!U.has(i));if(t<0||t>=C.length)return;let[n]=C.splice(t,1),r=v.getState().catalog[n];if(!r){Se(n,b(n)),z();return}let s=Date.now();W[n]=((l=W[n])!=null?l:0)+1,k(n,{status:"downloading",progress:0,version:r.version,error:void 0});let o=0,c=Ne(r,{onProgress:i=>{let u=Math.floor(i*100);u!==o&&(o=u,k(n,{progress:u/100,version:r.version}))}});A={app_id:n,handle:c,forced:!!e},J("start",n,r.version,e?"(forced)":""),c.promise.then(i=>{J("installed",n,r.version,`${Date.now()-s}ms`),k(n,{status:"installed",progress:1,version:r.version}),Se(n,i)}).catch(i=>{var y;if(i instanceof ee){if(_e.has(n))return;J("paused",n),W[n]-=1,C.unshift(n),k(n,{status:U.has(n)?"paused":"queued",progress:0,version:r.version});return}let u=String((y=i==null?void 0:i.message)!=null?y:i);if(console.warn("[miniapp-queue] failed",n,u),W[n]<dn){k(n,{status:"queued",progress:0,version:r.version,error:u}),setTimeout(()=>{var M;C.includes(n)||(A==null?void 0:A.app_id)===n||(C.push(n),z((M=Z[n])!=null&&M.length?n:void 0))},gn);return}k(n,{status:"failed",progress:0,version:r.version,error:u}),Se(n,b(n))}).finally(()=>{A=null;let i=C.find(u=>{var y;return(y=Z[u])==null?void 0:y.length});z(i)})},Ee=(e,{front:t=!1}={})=>{if((A==null?void 0:A.app_id)===e)return;let n=C.indexOf(e);if(n>=0){if(!t)return;C.splice(n,1)}t?C.unshift(e):C.push(e)},An=async e=>{let{host_id:t,client_token:n}=R(),r=new AbortController,s=setTimeout(()=>r.abort(),un);try{let o=`${fe}/api/hosts/${encodeURIComponent(t)}/miniapps?channel=${e}`,c=await fetch(o,{headers:{Authorization:`Bearer ${n}`,"Cache-Control":"no-cache"},signal:r.signal});if(!c.ok)throw new Error(`host list ${e} ${c.status}`);return(await c.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(R().channels.map(An)),r={};[...n].reverse().flat().forEach(i=>{r[i.app_id]=i});let s=Object.keys(v.getState().catalog).filter(i=>!r[i]);R().storage.setString(xt,JSON.stringify(r)),v.setState({catalog:r}),await Promise.all(s.map(i=>Ot(i,{by_user:!1}))),s.forEach(i=>Y.delete(i));let o=Object.keys(r).filter(i=>!Y.has(i)),c=[],l={};for(let i of o.map(u=>r[u])){if(await $e(i)){k(i.app_id,{status:"installed",progress:1,version:i.version});continue}let u=b(i.app_id);if(Et(i.app_id)&&!be.has(i.app_id)&&u&&await q(u)){k(i.app_id,{status:"installed",progress:1,version:u.version}),l[i.app_id]={app_id:i.app_id,current_version:u.version,next_version:i.version};continue}c.push(i)}return v.setState({updates:l}),c.forEach(i=>{W[i.app_id]=0,k(i.app_id,{status:U.has(i.app_id)?"paused":"queued",progress:0,version:i.version,error:void 0}),Ee(i.app_id)}),J("catalog",o.length,"apps, outdated",c.map(i=>i.app_id),"removed",s,`${Date.now()-e}ms`),K({type:"sync_complete",app_ids:o,removed:s}),Object.values(l).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),Ot=async(e,{by_user:t})=>{var s,o,c,l;if(t&&Y.add(e),_e.has(e))return;_e.add(e),U.delete(e);let n=C.indexOf(e);n>=0&&C.splice(n,1),(A==null?void 0:A.app_id)===e&&A.handle.cancel();let r=(l=(c=(s=v.getState().downloads[e])==null?void 0:s.version)!=null?c:(o=b(e))==null?void 0:o.version)!=null?l:"";k(e,{status:"uninstalling",progress:0,version:r}),await Mt(e),ve(e),v.setState(i=>{let u={...i.downloads};return delete u[e],{downloads:u}}),delete W[e],_e.delete(e),Se(e,null),J("uninstalled",e,t?"(user)":"(not in list)"),K({type:"uninstalled",app_id:e})},kt=e=>Ot(e,{by_user:!0}),It=e=>{let t=ne(e);return t?(Y.delete(e),(A==null?void 0:A.app_id)===e||C.includes(e)||(W[e]=0,k(e,{status:U.has(e)?"paused":"queued",progress:0,version:t.version,error:void 0}),Ee(e),z(),J("restore",e)),!0):!1},Dt=e=>{if(U.has(e))return;if(U.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];C.includes(e)&&t&&k(e,{status:"paused",progress:0,version:t.version})},Lt=e=>{if(!U.delete(e))return;J("resume app",e);let t=v.getState().downloads[e];(t==null?void 0:t.status)==="paused"&&!C.includes(e)&&ne(e)&&(W[e]=0,Ee(e)),C.includes(e)&&t&&k(e,{status:"queued",progress:0,version:t.version}),z()},$t=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())},Nt=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()},Be=e=>v.getState().updates[e],Ft=async e=>{var n,r;let t=Be(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(c=>{var i;let l={...c.updates};return delete l[e],{updates:l,apply_ticks:{...c.apply_ticks,[e]:((i=c.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)}},Bt=()=>Object.values(v.getState().catalog).map(e=>({...e,installed:!!b(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(U.delete(e),Y.delete(e),await $e(t))return b(e);let n=b(e);if(Et(e)&&!be.has(e)&&n&&await q(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:(W[e]=0,Ee(e,{front:!0}),A&&!A.forced?A.handle.cancel():z(e)),r};var S=require("react/jsx-runtime"),Je=e=>(e!=null?e:"").replace(/\?[^#]*/,""),Jt=0,mn=()=>{let e=new Set;return{emit:t=>e.forEach(n=>n(t)),subscribe:t=>(e.add(t),()=>{e.delete(t)})}},Mn=g.default.memo(({instance_key:e,is_active:t,is_front:n,is_dark:r,reload_tick:s,web_at_top:o,splash:c,bridge:l,opaque_background:i,allow_embedded_miniapps:u,onWebLoadEnd:y})=>{var Ke,ze;let M=(0,g.useRef)(null),x=(0,g.useRef)(!1),m=H(B,p=>p.instances[e]),h=m==null?void 0:m.app.app_id,$=m==null?void 0:m.app.manifest_url,w=m==null?void 0:m.context,d=m==null?void 0:m.url_params,[a,P]=(0,g.useState)(()=>h?b(h):null),[re,ie]=(0,g.useState)(!1),[Wt,Ve]=(0,g.useState)(0),[jt,oe]=(0,g.useState)(0),[qt,I]=(0,g.useState)(!1),V=(0,g.useRef)(null),He=p=>{V.current&&clearTimeout(V.current),V.current=setTimeout(()=>{V.current=null,I(!0)},p)};(0,g.useEffect)(()=>()=>{V.current&&clearTimeout(V.current)},[]),(0,g.useEffect)(()=>{if(!h||!t&&a)return;let p=!0;return ie(!1),(async()=>{let f=b(h),O=f?await q(f):!1;if(!p||(P(O?N=>!N||N.version!==f.version||N.permissions.join(",")!==f.permissions.join(",")?f:N:null),__DEV__&&Date.now()-Jt>1e4&&(Jt=Date.now(),await Re()),!p))return;let j=await le(h),Q=j!==void 0?j:$?await yt(h,$):b(h);if(p){if(!Q){ie(!0);return}P(N=>N!=null?N:Q)}})(),()=>{p=!1}},[t,h,$,Wt]),(0,g.useEffect)(()=>wt(e,p=>M.current?(M.current.postMessage(p),!0):!1),[e]);let Kt=H(v,p=>{let f=h?p.downloads[h]:void 0;return(f==null?void 0:f.status)==="installed"?f.version:void 0});(0,g.useEffect)(()=>{if(t||!h||!a)return;let p=b(h);if(!p||p.version===a.version)return;let f=!0;return q(p).then(O=>{!f||!O||(F(`webview:${e}`,"\u0111\u1ED5i bundle (\u1EA9n)",a.version,"\u2192",p.version),P(p))}),()=>{f=!1}},[t,h,Kt,a==null?void 0:a.version]);let We=H(v,p=>{var f;return h&&(f=p.apply_ticks[h])!=null?f:0});(0,g.useEffect)(()=>{if(!We||!h)return;let p=b(h);if(!p||p.version===(a==null?void 0:a.version))return;let f=!0;return q(p).then(O=>{!f||!O||(F(`webview:${e}`,"c\u1EADp nh\u1EADt",a==null?void 0:a.version,"\u2192",p.version),I(!1),P(p))}),()=>{f=!1}},[We]),(0,g.useEffect)(()=>{var O;let p=(O=R().keep_alive)==null?void 0:O.idle_close_ms;if(t||!p||p<=0)return;let f=setTimeout(()=>{ve(e)},p);return()=>clearTimeout(f)},[t,e]),(0,g.useEffect)(()=>{s>0&&(ie(!1),I(!1),oe(p=>p+1),Ve(p=>p+1))},[s]);let je=(0,g.useRef)(t);(0,g.useEffect)(()=>{var p;je.current!==t&&(je.current=t,x.current&&((p=M.current)==null||p.injectJavaScript(pt(t?"resumed":"paused"))))},[t]);let ue=`${(Ke=a==null?void 0:a.version)!=null?Ke:"none"}:${(ze=a==null?void 0:a.permissions.join(","))!=null?ze:""}:${jt}`,se=(0,g.useMemo)(()=>JSON.stringify([w!=null?w:{},d!=null?d:{}]),[w,d]),Te=(0,g.useMemo)(()=>{var p;return gt(d!=null?d:{},(p=a==null?void 0:a.permissions)!=null?p:[])},[se,a==null?void 0:a.permissions]),zt=(0,g.useMemo)(()=>ut(w!=null?w:{},Te)+at()+(R().debug?st():""),[Te]),de=(0,g.useRef)(null),qe=(0,g.useRef)(null);(0,g.useEffect)(()=>{var f,O,j;if(!a)return;if(qe.current!==ue){qe.current=ue,de.current=se;return}if(de.current===se)return;let p=((O=JSON.parse((f=de.current)!=null?f:"[]")[0])!=null?O:{}).org_id;if(de.current=se,p===(w==null?void 0:w.org_id)&&x.current){I(!1),He(1500),(j=M.current)==null||j.injectJavaScript(ct(w!=null?w:{},Te));return}I(!1),oe(Q=>Q+1)},[se,a,ue]);let Yt=(0,g.useCallback)(async p=>{var O,j,Q,N,Pe;let f=rt(p.nativeEvent.data);if(!f){if(h&&(l!=null&&l.onWebEvent))try{Promise.resolve(l.onWebEvent(p.nativeEvent.data,{app_id:h,instance_id:e})).catch(E=>{console.warn("[miniapp] onWebEvent l\u1ED7i",h,E)})}catch(E){console.warn("[miniapp] onWebEvent l\u1ED7i",h,E)}return}if(f.method==="log"){let{level:E,text:D}=f;F(`web:${e}`,E!=null?E:"log",D!=null?D:"");return}if(f.method==="pong"){V.current||I(!0);return}if(f.method==="touchAtTop"){o.emit(!!f.at_top);return}if(f.method==="contextApplied"){V.current&&clearTimeout(V.current),V.current=null,I(!0);return}if(f.method==="ready"){x.current=!0,I(!0);let E=(O=B.getState().instances[e])==null?void 0:O.context;E&&((j=M.current)==null||j.injectJavaScript(ke(E)));return}try{let E=await ft(f,{getHostData:()=>{var D,G;return(G=(D=B.getState().instances[e])==null?void 0:D.host_data)!=null?G:{}},getPermissions:()=>{var D,G;return h?(G=(D=b(h))==null?void 0:D.permissions)!=null?G:[]:[]},is_dark:r,close:te,app_id:h!=null?h:"",instance_id:e,options:l});f.id&&((Q=M.current)==null||Q.injectJavaScript(it(f.id,E)))}catch(E){if(!f.id)return;let D=E==null?void 0:E.code,G=E instanceof T?E:new T(typeof D=="string"?D:"HOST_ERROR",String((N=E==null?void 0:E.message)!=null?N:E));(Pe=M.current)==null||Pe.injectJavaScript(ot(f.id,G))}},[e,r,h,o,l]),Qt=(0,g.useCallback)(()=>{ie(!1),oe(p=>p+1),Ve(p=>p+1)},[]);return(0,S.jsxs)(_.View,{style:[_.StyleSheet.absoluteFill,i&&{backgroundColor:r?"#09090B":"#FFFFFF"},!n&&L.behind],pointerEvents:t?"auto":"none",children:[a?(0,S.jsx)(Vt.default,{ref:M,source:{uri:a.entry_uri},originWhitelist:["*"],allowingReadAccessToURL:`file://${u?De():a.dir}`,allowFileAccess:!0,allowFileAccessFromFileURLs:!0,allowUniversalAccessFromFileURLs:!0,injectedJavaScriptBeforeContentLoaded:zt,onMessage:Yt,bounces:!1,overScrollMode:"never",onLoadStart:p=>{F(`webview:${e}`,"load start",Je(p.nativeEvent.url)),x.current=!1,I(!1)},onError:p=>{F(`webview:${e}`,"load error",Je(p.nativeEvent.url),p.nativeEvent.description),ie(!0),I(!1)},onLoadEnd:p=>{let f=p.nativeEvent.url;F(`webview:${e}`,"load end",Je(f)),h&&(y==null||y({app_id:h,instance_id:e,url:f})),He(1500)},onContentProcessDidTerminate:()=>{x.current=!1,I(!1),oe(p=>p+1)},onRenderProcessGone:()=>(x.current=!1,I(!1),oe(p=>p+1),!0),style:L.webview},ue):null,m&&(0,S.jsx)(wn,{visible:!a||!qt,interactive:re,children:(0,S.jsx)(yn,{splash:c,app:m.app,is_dark:r,error:re,has_bundle:!!a,retry:Qt})})]})}),yn=g.default.memo(({splash:e,app:t,is_dark:n,error:r,has_bundle:s,retry:o})=>{let c=e,l=xe(t.app_id),i=r?"error":!s&&(l==null?void 0:l.status)==="downloading"?"downloading":"loading";return(0,S.jsx)(c,{app:t,is_dark:n,status:i,progress:i==="downloading"?l==null?void 0:l.progress:void 0,retry:o})}),wn=({visible:e,interactive:t,children:n})=>{let r=(0,g.useRef)(new _.Animated.Value(e?1:0)).current,[s,o]=(0,g.useState)(e);return(0,g.useEffect)(()=>{if(e){o(!0),r.setValue(1);return}let c=_.Animated.timing(r,{toValue:0,duration:180,useNativeDriver:!0});return c.start(({finished:l})=>{l&&o(!1)}),()=>c.stop()},[e,r]),s?(0,S.jsx)(_.Animated.View,{style:[_.StyleSheet.absoluteFill,{opacity:r}],pointerEvents:t?"auto":"none",children:n}):null},Ue=({app:e,is_dark:t,status:n,progress:r,retry:s})=>{let o=t?"#FAFAFA":"#18181B";return(0,S.jsxs)(_.View,{style:[L.splash,{backgroundColor:t?"#09090B":"#FFFFFF"}],children:[(0,S.jsx)(_.View,{style:[L.splash_icon,{backgroundColor:t?"#18181B":"#F4F4F5"}],children:e.icon?(0,S.jsx)(_.Image,{source:{uri:e.icon},style:L.splash_icon_image}):(0,S.jsx)(_.Text,{style:L.splash_letter,children:(e.name||"?").slice(0,1).toUpperCase()})}),(0,S.jsx)(_.Text,{style:[L.splash_name,{color:o}],children:e.name}),n==="error"?(0,S.jsxs)(S.Fragment,{children:[(0,S.jsx)(_.Text,{style:L.splash_hint,children:"Kh\xF4ng t\u1EA3i \u0111\u01B0\u1EE3c mini app"}),(0,S.jsx)(_.TouchableOpacity,{activeOpacity:.7,style:[L.retry_button,{backgroundColor:t?"#27272A":"#F4F4F5"}],onPress:s,children:(0,S.jsx)(_.Text,{style:[L.retry_text,{color:o}],children:"Th\u1EED l\u1EA1i"})})]}):(0,S.jsxs)(S.Fragment,{children:[(0,S.jsx)(_.ActivityIndicator,{style:L.splash_spinner,color:t?"#A1A1AA":"#71717A"}),n==="downloading"&&(0,S.jsxs)(_.Text,{style:L.splash_hint,children:["\u0110ang t\u1EA3i mini app",r?` ${Math.round(r*100)}%`:"\u2026"]})]})]})},Ut=(e,t)=>{let n=(0,g.useRef)(t),r=(0,g.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.`))},vn=({container:e,splash:t=Ue,is_dark:n=!1,bridge:r,close_on_back:s=!0,opaque_background:o=!0,allow_embedded_miniapps:c=!1,onWebLoadEnd:l})=>{Ut("container",e),Ut("splash",t);let i=e,u=H(B,a=>a.active_key),y=(0,g.useRef)(u);u&&(y.current=u);let M=H(B,a=>Object.keys(a.instances).join("|")),x=H(B,a=>{var P;return a.active_key?(P=a.instances[a.active_key])==null?void 0:P.app.name:void 0}),m=(0,g.useMemo)(()=>M?M.split("|"):[],[M]),[h,$]=(0,g.useState)({}),w=(0,g.useRef)(mn()).current;(0,g.useEffect)(()=>{if(!u||!s)return;let a=_.BackHandler.addEventListener("hardwareBackPress",()=>(te(),!0));return()=>a.remove()},[u,s]);let d=(0,g.useCallback)(()=>{let a=B.getState().active_key;a&&$(P=>({...P,[a]:(P[a]||0)+1}))},[]);return m.length?(0,S.jsx)(i,{visible:!!u,title:x!=null?x:"",is_dark:n,close:te,reload:d,subscribeWebAtTop:w.subscribe,children:m.map(a=>(0,S.jsx)(Mn,{instance_key:a,is_active:u===a,is_front:(u!=null?u:y.current)===a,is_dark:n,reload_tick:h[a]||0,web_at_top:w,splash:t,bridge:r,opaque_background:o,allow_embedded_miniapps:c,onWebLoadEnd:l},a))}):null},L=_.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"}}),Ht=g.default.memo(vn);0&&(module.exports={DefaultMiniAppSplash,MINIAPP_PLATFORM_URL,MiniAppHost,MiniAppHostError,closeMiniApp,configureMiniApp,createMmkvStorage,createRnfsFileSystem,ensureMiniApp,getLocalMiniApp,getMiniAppCatalog,getMiniAppCatalogEntry,getMiniAppStatuses,getMiniAppUpdate,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,ot=async(e,t)=>{if(Oe.has(e))throw new E("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"]),Ie=(e,t)=>{if(typeof e!="string"||!e)throw new E("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 w,m,f,F,P,D,l,C;let c=i==null?void 0:i.handlers,M={app_id:a,instance_id:u,close:o},y=()=>new E("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF \u1EE9ng d\u1EE5ng n\xE0y`);switch(e){case"requestPayment":{let h=c==null?void 0:c.requestPayment;if(!h)throw y();let T=t==null?void 0:t.amount;if(typeof T!="number"||!Number.isFinite(T)||T<=0)throw new E("INVALID_PARAMS","amount ph\u1EA3i l\xE0 s\u1ED1 > 0");let ne={...t,amount:T,currency:Ie(t==null?void 0:t.currency,"currency")};return ot(e,()=>h(ne,M))}case"printImage":{let h=c==null?void 0:c.printImage;if(!h)throw y();let T=Ie(t==null?void 0:t.image,"image");await ot(e,()=>h({image:T},M));return}case"openScreen":if(!(c!=null&&c.openScreen))throw y();await c.openScreen({screen:Ie(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 E("INVALID_PARAMS","url ph\u1EA3i l\xE0 http(s)");await(i!=null&&i.openUrl?i.openUrl(h):ce.Linking.openURL(h));return}case"openLink":{let h=String((m=t==null?void 0:t.url)!=null?m:"").trim();if(!/^[a-z][a-z0-9+.-]*:/i.test(h)||/^(javascript|file|data|about|blob):/i.test(h))throw new E("INVALID_PARAMS","url kh\xF4ng h\u1EE3p l\u1EC7");try{await(i!=null&&i.openUrl?i.openUrl(h):ce.Linking.openURL(h))}catch(T){throw new E("NOT_SUPPORTED",String((F=(f=T==null?void 0:T.message)!=null?f:T)!=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 h=pn.has(t==null?void 0:t.type)?t.type:"selection";(l=i==null?void 0:i.haptic)==null||l.call(i,h);return}case"getSystemInfo":return{platform:ce.Platform.OS==="ios"?"ios":"android",appVersion:(C=i==null?void 0:i.app_version)!=null?C:"",theme:s?"dark":"light"};case"getAccessToken":{let h=n().access_token;if(!h)throw new E("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 se=n().access_token;if(!se)throw new E("HOST_ERROR","Mini app ch\u01B0a c\xF3 token cho page n\xE0y");return se}if(h!=="partner"&&h!=="chatbox")throw new E("HOST_ERROR",`Lo\u1EA1i token kh\xF4ng h\u1EE3p l\u1EC7: ${String(h)}`);let T=ht[h];if(!r().includes(T))throw new E("PERMISSION_DENIED",`Mini app ch\u01B0a \u0111\u01B0\u1EE3c c\u1EA5p quy\u1EC1n ${T} (Console \u2192 Quy\u1EC1n l\u1EA5y token)`);let ne=h==="partner"?n().partner_token:n().chatbox_token;if(!ne)throw new E("HOST_ERROR",`Kh\xF4ng c\xF3 ${T}`);return ne}case"getUserInfo":{let h=n().user;if(!h)throw new E("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 E("HOST_ERROR","Kh\xF4ng l\u1EA5y \u0111\u01B0\u1EE3c th\xF4ng tin page");return h}case"sendMessage":case"insertText":throw new E("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF phi\xEAn b\u1EA3n app n\xE0y`);default:throw new E("NOT_SUPPORTED",`API kh\xF4ng t\u1ED3n t\u1EA1i: ${e}`)}};var $e=e=>`bundle:${e}`,Ne=()=>`${x().file_system.document_dir}/miniapps`,Be=Ne,Fe=(e,t,n="index.html",r=!1,s=[])=>{let o=`${Be()}/${e}/${t}`;return{app_id:e,version:t,dir:o,entry_uri:`file://${o}/${n}`,context_update:r,permissions:s}},Le=e=>{var t;x().storage.setString($e(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($e(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=>x().file_system.exists(e.entry_uri.replace("file://","")),Je=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=x().file_system,r=`${Be()}/${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(()=>{})),x().storage.setString($e(e),""),await x().file_system.remove(`${Be()}/${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},ln=(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=x().file_system,r=S(e.app_id);if(r&&ln(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),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}),Ue=(e,{base_url:t,onProgress:n}={})=>{let r=x().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 c=S(e.app_id);if((c==null?void 0:c.version)===e.version&&await r.exists(c.dir))return Le(e),S(e.app_id);u();let M=r.download({url:t?cn(t,e.bundle_url):e.bundle_url,to_file:a,onProgress:(w,m)=>{var F;let f=m>0?m:(F=e.size)!=null?F: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(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=Fe(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),Le(e),yt(e.app_id,[e.version,c==null?void 0:c.version].filter(Boolean)),m}catch(w){throw o?new re:w}finally{s=null,r.remove(a).catch(()=>{})}};return{promise:vt(e.app_id,i),cancel:()=>{o=!0,s==null||s.cancel()}}},le={},un=__DEV__?0:60*1e3,Mt={},St=(e,t)=>{var r,s;let n=S(e);return n&&Date.now()-((r=Mt[t])!=null?r:0)<un?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 Ue(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(()=>{le[e]=void 0})),le[e])};var we=new Map,bt=(e,t)=>(we.set(e,t),()=>{we.get(e)===t&&we.delete(e)}),xt=(e,t)=>{let n=we.get(e);return n?n(t):!1};var ve=require("react"),_e=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,ve.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,ve.useSyncExternalStore)(e.subscribe,s)};var U=_e({active_key:null,instances:{}}),Et=({app:e,instance_id:t,context:n={},url_params:r={},host_data:s={}},o)=>{var u;let a=(u=x().keep_alive)==null?void 0:u.max_webviews;U.setState(i=>{let c=t!=null?t:e.app_id,M={...i.instances,[c]:{key:c,app:e,context:n,url_params:r,host_data:s,last_used_at:Date.now()}},y=Object.keys(M);return a&&a>0&&y.length>a&&y.filter(w=>w!==c).sort((w,m)=>M[w].last_used_at-M[m].last_used_at).slice(0,y.length-a).forEach(w=>{delete M[w]}),o?{active_key:c,instances:M}:{instances:M}})},Rt=e=>Et(e,!0),Tt=e=>Et(e,!1),ie=()=>U.setState({active_key:null}),Se=e=>{U.setState(t=>{if(t.active_key===e||!t.instances[e])return{};let n={...t.instances};return delete n[e],{instances:n}})};var Pt="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(Pt))!=null?e:"{}")}catch{return{}}},v=_e({catalog:{},downloads:{},pause_reasons:[],updates:{},apply_ticks:{}}),kt=e=>{var t;return!!((t=x().manual_update)!=null&&t.includes(e))},Ee=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{}}}},H=Ct(dn),G=Ct(gn);nt(()=>{H.load(),G.load();let e=mn(),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}:H.has(n)&&(t[n]={status:"paused",progress:0,version:e[n].version,has_local:!1})}),v.setState({catalog:e,downloads:t})});var Re=e=>j(v,t=>e?t.downloads[e]:void 0),Ot=()=>j(v,e=>e.pause_reasons.length>0),V=(...e)=>N("queue",...e),k=[],K={},A=null,be=new Set,te={},Ve=new Set,Y=e=>{Ve.forEach(t=>{try{t(e)}catch(n){console.warn("[miniapp-queue] event listener error",n==null?void 0:n.message)}})},It=e=>(Ve.add(e),()=>{Ve.delete(e)}),Dt=()=>v.getState().downloads,I=(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(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})},xe=(e,t)=>{var n;(n=te[e])==null||n.forEach(r=>r(t)),delete te[e]},Mn=()=>v.getState().pause_reasons.length>0,Q=e=>{var u;if(A)return;let t=e?k.indexOf(e):Mn()?-1:k.findIndex(i=>!H.has(i));if(t<0||t>=k.length)return;let[n]=k.splice(t,1),r=v.getState().catalog[n];if(!r){xe(n,S(n)),Q();return}let s=Date.now();K[n]=((u=K[n])!=null?u:0)+1,I(n,{status:"downloading",progress:0,version:r.version,error:void 0});let o=0,a=Ue(r,{onProgress:i=>{let c=Math.floor(i*100);c!==o&&(o=c,I(n,{progress:c/100,version:r.version}))}});A={app_id:n,handle:a,forced:!!e},V("start",n,r.version,e?"(forced)":""),a.promise.then(i=>{V("installed",n,r.version,`${Date.now()-s}ms`),I(n,{status:"installed",progress:1,version:r.version}),xe(n,i)}).catch(i=>{var M;if(i instanceof re){if(be.has(n))return;V("paused",n),K[n]-=1,k.unshift(n),I(n,{status:H.has(n)?"paused":"queued",progress:0,version:r.version});return}let c=String((M=i==null?void 0:i.message)!=null?M:i);if(console.warn("[miniapp-queue] failed",n,c),K[n]<hn){I(n,{status:"queued",progress:0,version:r.version,error:c}),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))},An);return}I(n,{status:"failed",progress:0,version:r.version,error:c}),xe(n,S(n))}).finally(()=>{A=null;let i=k.find(c=>{var M;return(M=te[c])==null?void 0:M.length});Q(i)})},Te=(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)},yn=async e=>{let{host_id:t,client_token:n}=x(),r=new AbortController,s=setTimeout(()=>r.abort(),fn);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,Pe=()=>(de!=null||(de=(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(Pt,JSON.stringify(r)),v.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(c=>r[c])){if(await Je(i)){I(i.app_id,{status:"installed",progress:1,version:i.version});continue}let c=S(i.app_id);if(kt(i.app_id)&&!Ee.has(i.app_id)&&c&&await q(c)){I(i.app_id,{status:"installed",progress:1,version:c.version}),u[i.app_id]={app_id:i.app_id,current_version:c.version,next_version:i.version};continue}a.push(i)}return v.setState({updates:u}),a.forEach(i=>{K[i.app_id]=0,I(i.app_id,{status:H.has(i.app_id)?"paused":"queued",progress:0,version:i.version,error:void 0}),Te(i.app_id)}),V("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),be.has(e))return;be.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=v.getState().downloads[e])==null?void 0:s.version)!=null?a:(o=S(e))==null?void 0:o.version)!=null?u:"";I(e,{status:"uninstalling",progress:0,version:r}),await wt(e),Se(e),v.setState(i=>{let c={...i.downloads};return delete c[e],{downloads:c}}),delete K[e],be.delete(e),xe(e,null),V("uninstalled",e,t?"(user)":"(not in list)"),Y({type:"uninstalled",app_id:e})},$t=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,I(e,{status:H.has(e)?"paused":"queued",progress:0,version:t.version,error:void 0}),Te(e),Q(),V("restore",e)),!0):!1},Bt=e=>{if(H.has(e))return;if(H.add(e),V("pause app",e),(A==null?void 0:A.app_id)===e&&!A.forced){A.handle.cancel();return}let t=v.getState().downloads[e];k.includes(e)&&t&&I(e,{status:"paused",progress:0,version:t.version})},Ft=e=>{if(!H.delete(e))return;V("resume app",e);let t=v.getState().downloads[e];(t==null?void 0:t.status)==="paused"&&!k.includes(e)&&oe(e)&&(K[e]=0,Te(e)),k.includes(e)&&t&&I(e,{status:"queued",progress:0,version:t.version}),Q()},Jt=e=>{let{pause_reasons:t}=v.getState();t.includes(e)||(v.setState({pause_reasons:[...t,e]}),V("pause",e),t.length===0&&Y({type:"pause_change",paused:!0,reasons:[e]}),A&&!A.forced&&A.handle.cancel())},Ut=e=>{let{pause_reasons:t}=v.getState();if(!t.includes(e))return;let n=t.filter(r=>r!==e);v.setState({pause_reasons:n}),V("resume",e),n.length===0&&Y({type:"pause_change",paused:!1,reasons:n}),Q()},He=e=>v.getState().updates[e],Vt=async e=>{var n,r;let t=He(e);Ee.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:(v.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}}}),V("updated",e,t==null?void 0:t.current_version,"\u2192",s.version),!0)}finally{Ee.delete(e)}},Ht=()=>Object.values(v.getState().catalog).map(e=>({...e,installed:!!S(e.app_id),removed_by_user:G.has(e.app_id)})),oe=e=>v.getState().catalog[e],ge=async e=>{let t=oe(e);if(!t)return;if(H.delete(e),G.delete(e),await Je(t))return S(e);let n=S(e);if(kt(e)&&!Ee.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,Te(e,{front:!0}),A&&!A.forced?A.handle.cancel():Q(e)),r};var b=require("react/jsx-runtime"),We=e=>(e!=null?e:"").replace(/\?[^#]*/,""),Wt=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:a,bridge:u,opaque_background:i,allow_embedded_miniapps:c,onWebLoadEnd:M})=>{var Qe,Ge;let y=(0,d.useRef)(null),w=(0,d.useRef)(!1),m=j(U,p=>p.instances[e]),f=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)(()=>f?S(f):null),[h,T]=(0,d.useState)(!1),[ne,se]=(0,d.useState)(0),[zt,ae]=(0,d.useState)(0),[Yt,L]=(0,d.useState)(!1),W=(0,d.useRef)(null),qe=p=>{W.current&&clearTimeout(W.current),W.current=setTimeout(()=>{W.current=null,L(!0)},p)};(0,d.useEffect)(()=>()=>{W.current&&clearTimeout(W.current)},[]),(0,d.useEffect)(()=>{if(!f||!t&&l)return;let p=!0;return T(!1),(async()=>{let g=S(f),O=g?await q(g):!1;if(!p||(C(O?J=>!J||J.version!==g.version||J.permissions.join(",")!==g.permissions.join(",")?g:J:null),__DEV__&&Date.now()-Wt>1e4&&(Wt=Date.now(),await Pe()),!p))return;let z=await ge(f),X=z!==void 0?z:F?await St(f,F):S(f);if(p){if(!X){T(!0);return}C(J=>J!=null?J:X)}})(),()=>{p=!1}},[t,f,F,ne]),(0,d.useEffect)(()=>bt(e,p=>y.current?(y.current.postMessage(p),!0):!1),[e]);let Qt=j(v,p=>{let g=f?p.downloads[f]:void 0;return(g==null?void 0:g.status)==="installed"?g.version:void 0});(0,d.useEffect)(()=>{if(t||!f||!l)return;let p=S(f);if(!p||p.version===l.version)return;let g=!0;return q(p).then(O=>{!g||!O||(N(`webview:${e}`,"\u0111\u1ED5i bundle (\u1EA9n)",l.version,"\u2192",p.version),C(p))}),()=>{g=!1}},[t,f,Qt,l==null?void 0:l.version]);let Ke=j(v,p=>{var g;return f&&(g=p.apply_ticks[f])!=null?g:0});(0,d.useEffect)(()=>{if(!Ke||!f)return;let p=S(f);if(!p||p.version===(l==null?void 0:l.version))return;let g=!0;return q(p).then(O=>{!g||!O||(N(`webview:${e}`,"c\u1EADp nh\u1EADt",l==null?void 0:l.version,"\u2192",p.version),L(!1),C(p))}),()=>{g=!1}},[Ke]),(0,d.useEffect)(()=>{var O;let p=(O=x().keep_alive)==null?void 0:O.idle_close_ms;if(t||!p||p<=0)return;let g=setTimeout(()=>{Se(e)},p);return()=>clearTimeout(g)},[t,e]),(0,d.useEffect)(()=>{s>0&&(T(!1),L(!1),ae(p=>p+1),se(p=>p+1))},[s]);let ze=(0,d.useRef)(t);(0,d.useEffect)(()=>{var p;ze.current!==t&&(ze.current=t,w.current&&((p=y.current)==null||p.injectJavaScript(ut(t?"resumed":"paused"))))},[t]);let fe=`${(Qe=l==null?void 0:l.version)!=null?Qe:"none"}:${(Ge=l==null?void 0:l.permissions.join(","))!=null?Ge:""}:${zt}`,pe=(0,d.useMemo)(()=>JSON.stringify([P!=null?P:{},D!=null?D:{}]),[P,D]),ke=(0,d.useMemo)(()=>{var p;return At(D!=null?D:{},(p=l==null?void 0:l.permissions)!=null?p:[])},[pe,l==null?void 0:l.permissions]),Gt=(0,d.useMemo)(()=>ft(P!=null?P:{},ke)+lt()+(x().debug?ct():""),[ke]),he=(0,d.useRef)(null),Ye=(0,d.useRef)(null);(0,d.useEffect)(()=>{var g,O,z;if(!l)return;if(Ye.current!==fe){Ye.current=fe,he.current=pe;return}if(he.current===pe)return;let p=((O=JSON.parse((g=he.current)!=null?g:"[]")[0])!=null?O:{}).org_id;if(he.current=pe,p===(P==null?void 0:P.org_id)&&w.current){L(!1),qe(1500),(z=y.current)==null||z.injectJavaScript(dt(P!=null?P:{},ke));return}L(!1),ae(X=>X+1)},[pe,l,fe]);let Xt=(0,d.useCallback)(async p=>{var O,z,X,J,Ce;let g=st(p.nativeEvent.data);if(!g){if(f&&(u!=null&&u.onWebEvent))try{Promise.resolve(u.onWebEvent(p.nativeEvent.data,{app_id:f,instance_id:e})).catch(R=>{console.warn("[miniapp] onWebEvent l\u1ED7i",f,R)})}catch(R){console.warn("[miniapp] onWebEvent l\u1ED7i",f,R)}return}if(g.method==="log"){let{level:R,text:$}=g;N(`web:${e}`,R!=null?R:"log",$!=null?$:"");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"){w.current=!0,L(!0);let R=(O=U.getState().instances[e])==null?void 0:O.context;R&&((z=y.current)==null||z.injectJavaScript(De(R)));return}try{let R=await mt(g,{getHostData:()=>{var $,Z;return(Z=($=U.getState().instances[e])==null?void 0:$.host_data)!=null?Z:{}},getPermissions:()=>{var $,Z;return f?(Z=($=S(f))==null?void 0:$.permissions)!=null?Z:[]:[]},is_dark:r,close:ie,app_id:f!=null?f:"",instance_id:e,options:u});g.id&&((X=y.current)==null||X.injectJavaScript(at(g.id,R)))}catch(R){if(!g.id)return;let $=R==null?void 0:R.code,Z=R instanceof E?R:new E(typeof $=="string"?$:"HOST_ERROR",String((J=R==null?void 0:R.message)!=null?J:R));(Ce=y.current)==null||Ce.injectJavaScript(pt(g.id,Z))}},[e,r,f,o,u]),Zt=(0,d.useCallback)(()=>{T(!1),ae(p=>p+1),se(p=>p+1)},[]);return(0,b.jsxs)(_.View,{style:[_.StyleSheet.absoluteFill,i&&{backgroundColor:r?"#09090B":"#FFFFFF"},!n&&B.behind],pointerEvents:t?"auto":"none",children:[l?(0,b.jsx)(qt.default,{ref:y,source:{uri:l.entry_uri},originWhitelist:["*"],allowingReadAccessToURL:`file://${c?Ne():l.dir}`,allowFileAccess:!0,allowFileAccessFromFileURLs:!0,allowUniversalAccessFromFileURLs:!0,injectedJavaScriptBeforeContentLoaded:Gt,onMessage:Xt,bounces:!1,overScrollMode:"never",onLoadStart:p=>{N(`webview:${e}`,"load start",We(p.nativeEvent.url)),w.current=!1,L(!1)},onError:p=>{N(`webview:${e}`,"load error",We(p.nativeEvent.url),p.nativeEvent.description),T(!0),L(!1)},onLoadEnd:p=>{let g=p.nativeEvent.url;N(`webview:${e}`,"load end",We(g)),f&&(M==null||M({app_id:f,instance_id:e,url:g})),qe(1500)},onContentProcessDidTerminate:()=>{w.current=!1,L(!1),ae(p=>p+1)},onRenderProcessGone:()=>(w.current=!1,L(!1),ae(p=>p+1),!0),style:B.webview},fe):null,m&&(0,b.jsx)(Sn,{visible:!l||!Yt,interactive:h,children:(0,b.jsx)(_n,{splash:a,app:m.app,is_dark:r,error:h,has_bundle:!!l,retry:Zt})})]})}),_n=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,b.jsx)(a,{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 a=_.Animated.timing(r,{toValue:0,duration:180,useNativeDriver:!0});return a.start(({finished:u})=>{u&&o(!1)}),()=>a.stop()},[e,r]),s?(0,b.jsx)(_.Animated.View,{style:[_.StyleSheet.absoluteFill,{opacity:r}],pointerEvents:t?"auto":"none",children:n}):null},je=({app:e,is_dark:t,status:n,progress:r,retry:s})=>{let o=t?"#FAFAFA":"#18181B";return(0,b.jsxs)(_.View,{style:[B.splash,{backgroundColor:t?"#09090B":"#FFFFFF"}],children:[(0,b.jsx)(_.View,{style:[B.splash_icon,{backgroundColor:t?"#18181B":"#F4F4F5"}],children:e.icon?(0,b.jsx)(_.Image,{source:{uri:e.icon},style:B.splash_icon_image}):(0,b.jsx)(_.Text,{style:B.splash_letter,children:(e.name||"?").slice(0,1).toUpperCase()})}),(0,b.jsx)(_.Text,{style:[B.splash_name,{color:o}],children:e.name}),n==="error"?(0,b.jsxs)(b.Fragment,{children:[(0,b.jsx)(_.Text,{style:B.splash_hint,children:"Kh\xF4ng t\u1EA3i \u0111\u01B0\u1EE3c mini app"}),(0,b.jsx)(_.TouchableOpacity,{activeOpacity:.7,style:[B.retry_button,{backgroundColor:t?"#27272A":"#F4F4F5"}],onPress:s,children:(0,b.jsx)(_.Text,{style:[B.retry_text,{color:o}],children:"Th\u1EED l\u1EA1i"})})]}):(0,b.jsxs)(b.Fragment,{children:[(0,b.jsx)(_.ActivityIndicator,{style:B.splash_spinner,color:t?"#A1A1AA":"#71717A"}),n==="downloading"&&(0,b.jsxs)(_.Text,{style:B.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.`))},bn=({container:e,splash:t=je,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,c=j(U,l=>l.active_key),M=(0,d.useRef)(c);c&&(M.current=c);let y=j(U,l=>Object.keys(l.instances).join("|")),w=j(U,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]),[f,F]=(0,d.useState)({}),P=(0,d.useRef)(wn()).current;(0,d.useEffect)(()=>{if(!c||!s)return;let l=_.BackHandler.addEventListener("hardwareBackPress",()=>(ie(),!0));return()=>l.remove()},[c,s]);let D=(0,d.useCallback)(()=>{let l=U.getState().active_key;l&&F(C=>({...C,[l]:(C[l]||0)+1}))},[]);return m.length?(0,b.jsx)(i,{visible:!!c,title:w!=null?w:"",is_dark:n,close:ie,reload:D,subscribeWebAtTop:P.subscribe,children:m.map(l=>(0,b.jsx)(vn,{instance_key:l,is_active:c===l,is_front:(c!=null?c:M.current)===l,is_dark:n,reload_tick:f[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(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});
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- var Te="https://retion-miniapp-platform.vercel.app",X=null,Ze=new Set,Nt=e=>{X=e,Ze.forEach(t=>t())},b=()=>{if(!X)throw new Error("[miniapp] Ch\u01B0a g\u1ECDi configureMiniApp()");return X},et=e=>{Ze.add(e),X&&e()},$=(...e)=>{X!=null&&X.debug&&console.log("[miniapp]",...e)};var Ft=(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(a=>a.name)).catch(()=>[]),sha256:n=>e.hash(n,"sha256"),unzip:async(n,r)=>{await t(n,r)},download:({url:n,to_file:r,onProgress:a})=>{let{jobId:o,promise:c}=e.downloadFile({fromUrl:n,toFile:r,progressInterval:250,begin:()=>{},progress:({bytesWritten:l,contentLength:i})=>a==null?void 0:a(l,i)});return{promise:c.then(({statusCode:l})=>({status:l})),cancel:()=>e.stopDownload(o)}}}),Bt=e=>({getString:t=>e.getString(t),setString:(t,n)=>e.set(t,n)});import We,{useCallback as Ve,useEffect as J,useMemo as xe,useRef as U,useState as ee}from"react";import{ActivityIndicator as mn,Animated as Je,BackHandler as Mn,Image as yn,StyleSheet as je,Text as ue,TouchableOpacity as wn,View as He}from"react-native";import vn from"react-native-webview";import{Linking as Jt,Platform as Ut}from"react-native";var he=1,x=class extends Error{constructor(n,r){super(r);this.code=n}},nt=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;`,rt=(e,t)=>Ae({id:e,result:t}),it=(e,t)=>Ae({id:e,error:{code:t.code,message:t.message}}),Oe=e=>Ae({event:"context",data:e});var ot=()=>`(function () {
1
+ var ke="https://retion-miniapp-platform.vercel.app",ee=null,nt=new Set,Jt=e=>{ee=e,nt.forEach(t=>t())},_=()=>{if(!ee)throw new Error("[miniapp] Ch\u01B0a g\u1ECDi configureMiniApp()");return ee},rt=e=>{nt.add(e),ee&&e()},L=(...e)=>{ee!=null&&ee.debug&&console.log("[miniapp]",...e)};var Ut=(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)}}}),Vt=e=>({getString:t=>e.getString(t),setString:(t,n)=>e.set(t,n)});import ze,{useCallback as qe,useEffect as V,useMemo as Re,useRef as H,useState as ne}from"react";import{ActivityIndicator as wn,Animated as We,BackHandler as vn,Image as _n,StyleSheet as Ye,Text as ge,TouchableOpacity as Sn,View as Ke}from"react-native";import bn from"react-native-webview";import{Linking as it,Platform as Ht}from"react-native";var me=1,b=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}},Me=e=>`window.__RETION_MINIAPP__ && window.__RETION_MINIAPP__.receive(${JSON.stringify(e)}); true;`,at=(e,t)=>Me({id:e,result:t}),pt=(e,t)=>Me({id:e,error:{code:t.code,message:t.message}}),Ie=e=>Me({event:"context",data:e});var ct=()=>`(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,Ze=new Set,Nt=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,Ze=new Set,Nt=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;`,st=()=>`(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,Ze=new Set,Nt=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,Ze=new Set,Nt=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;`,at=e=>Ae({event:e}),pt=(e,t)=>{let n=ct(t);return`try { history.replaceState(history.state, '', location.pathname + ${JSON.stringify(n?`?${n}`:"")} + location.hash); } catch (e) {}
42
- ${Oe(e)}`},ct=e=>Object.entries(e).filter(([,t])=>t!=null&&t!=="").map(([t,n])=>`${encodeURIComponent(t)}=${encodeURIComponent(String(n))}`).join("&"),lt=(e,t={})=>{let n=ct(t);return`window.__RETION_MINIAPP_HOST__ = { protocol: ${he} };
41
+ })(); true;`,ut=e=>Me({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
+ ${Ie(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;`},ut={partner:"partner_token",chatbox:"chatbox_token"},dt=(e,t)=>{let n={...e};for(let r of Object.values(ut))t.includes(r)||delete n[r];return n},Pe=new Set,tt=async(e,t)=>{if(Pe.has(e))throw new x("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)}},Vt=new Set(["selection","impactLight","impactMedium","impactHeavy","rigid","soft","notificationSuccess","notificationWarning","notificationError"]),Ce=(e,t)=>{if(typeof e!="string"||!e)throw new x("INVALID_PARAMS",`Thi\u1EBFu ${t}`);return e},gt=async({method:e,params:t},{getHostData:n,getPermissions:r,is_dark:a,close:o,app_id:c,instance_id:l,options:i})=>{var _,A,f,D,y;let u=i==null?void 0:i.handlers,M={app_id:c,instance_id:l,close:o},m=()=>new x("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF \u1EE9ng d\u1EE5ng n\xE0y`);switch(e){case"requestPayment":{let d=u==null?void 0:u.requestPayment;if(!d)throw m();let s=t==null?void 0:t.amount;if(typeof s!="number"||!Number.isFinite(s)||s<=0)throw new x("INVALID_PARAMS","amount ph\u1EA3i l\xE0 s\u1ED1 > 0");let E={...t,amount:s,currency:Ce(t==null?void 0:t.currency,"currency")};return tt(e,()=>d(E,M))}case"printImage":{let d=u==null?void 0:u.printImage;if(!d)throw m();let s=Ce(t==null?void 0:t.image,"image");await tt(e,()=>d({image:s},M));return}case"openScreen":if(!(u!=null&&u.openScreen))throw m();await u.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 d=String((_=t==null?void 0:t.url)!=null?_:"");if(!/^https?:\/\//i.test(d))throw new x("INVALID_PARAMS","url ph\u1EA3i l\xE0 http(s)");await(i!=null&&i.openUrl?i.openUrl(d):Jt.openURL(d));return}case"showToast":(f=i==null?void 0:i.showToast)==null||f.call(i,String((A=t==null?void 0:t.message)!=null?A:""));return;case"haptic":{let d=Vt.has(t==null?void 0:t.type)?t.type:"selection";(D=i==null?void 0:i.haptic)==null||D.call(i,d);return}case"getSystemInfo":return{platform:Ut.OS==="ios"?"ios":"android",appVersion:(y=i==null?void 0:i.app_version)!=null?y:"",theme:a?"dark":"light"};case"getAccessToken":{let d=n().access_token;if(!d)throw new x("HOST_ERROR","Mini app ch\u01B0a c\xF3 token cho page n\xE0y");return d}case"getToken":{let d=t==null?void 0:t.type;if(d==="access"){let ne=n().access_token;if(!ne)throw new x("HOST_ERROR","Mini app ch\u01B0a c\xF3 token cho page n\xE0y");return ne}if(d!=="partner"&&d!=="chatbox")throw new x("HOST_ERROR",`Lo\u1EA1i token kh\xF4ng h\u1EE3p l\u1EC7: ${String(d)}`);let s=ut[d];if(!r().includes(s))throw new x("PERMISSION_DENIED",`Mini app ch\u01B0a \u0111\u01B0\u1EE3c c\u1EA5p quy\u1EC1n ${s} (Console \u2192 Quy\u1EC1n l\u1EA5y token)`);let E=d==="partner"?n().partner_token:n().chatbox_token;if(!E)throw new x("HOST_ERROR",`Kh\xF4ng c\xF3 ${s}`);return E}case"getUserInfo":{let d=n().user;if(!d)throw new x("HOST_ERROR","Kh\xF4ng l\u1EA5y \u0111\u01B0\u1EE3c th\xF4ng tin nh\xE2n vi\xEAn");return d}case"getPageInfo":{let d=n().page;if(!d)throw new x("HOST_ERROR","Kh\xF4ng l\u1EA5y \u0111\u01B0\u1EE3c th\xF4ng tin page");return d}case"sendMessage":case"insertText":throw new x("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF phi\xEAn b\u1EA3n app n\xE0y`);default:throw new x("NOT_SUPPORTED",`API kh\xF4ng t\u1ED3n t\u1EA1i: ${e}`)}};var ke=e=>`bundle:${e}`,Ie=()=>`${b().file_system.document_dir}/miniapps`,De=Ie,At=(e,t,n="index.html",r=!1,a=[])=>{let o=`${De()}/${e}/${t}`;return{app_id:e,version:t,dir:o,entry_uri:`file://${o}/${n}`,context_update:r,permissions:a}},ft=e=>{var t;b().storage.setString(ke(e.app_id),JSON.stringify({version:e.version,entry:e.entry,context_update:!!e.context_update,permissions:(t=e.permissions)!=null?t:[]}))},Ht=(e,t)=>/^https?:\/\//.test(t)?t:`${e.replace(/[^/]*$/,"")}${t}`,v=e=>{let t=b().storage.getString(ke(e));if(!t)return null;try{let{version:n,entry:r,context_update:a,permissions:o}=JSON.parse(t);return At(e,n,r,!!a,Array.isArray(o)?o:[])}catch{return null}},q=e=>b().file_system.exists(e.entry_uri.replace("file://","")),Le=async e=>{let t=v(e.app_id);return(t==null?void 0:t.version)===e.version&&await q(t)},Wt=async(e,t)=>{let n=b().file_system,r=`${De()}/${e}`,a=await n.listDir(r).catch(()=>[]);await Promise.all(a.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(()=>{})),b().storage.setString(ke(e),""),await b().file_system.remove(`${De()}/${e}`).catch(()=>{})},te=class extends Error{constructor(){super("cancelled"),this.name="MiniAppInstallCancelled"}},ae={},$e=(e,{base_url:t,onProgress:n}={})=>{var _;let r=b().file_system,a=null,o=!1,c=`${r.cache_dir}/${e.app_id}-${e.version}.zip`,l=()=>{if(o)throw new te},i=async()=>{var D;l();let A=v(e.app_id);if((A==null?void 0:A.version)===e.version&&await r.exists(A.dir))return ft(e),v(e.app_id);l();let f=r.download({url:t?Ht(t,e.bundle_url):e.bundle_url,to_file:c,onProgress:(y,d)=>{var E;let s=d>0?d:(E=e.size)!=null?E:0;s>0&&(n==null||n(Math.min(1,y/s)))}});a=f;try{let{status:y}=await f.promise;if(l(),y!==200)throw new Error(`bundle ${y}`);if(e.sha256)if(r.sha256){if(await r.sha256(c)!==e.sha256)throw new Error("sha256 mismatch")}else $("b\u1ECF qua ki\u1EC3m tra sha256 (file_system kh\xF4ng c\xF3 sha256)",e.app_id);l();let d=At(e.app_id,e.version,e.entry,!!e.context_update,(D=e.permissions)!=null?D:[]);return await r.remove(d.dir).catch(()=>{}),await r.mkdir(d.dir),await r.unzip(c,d.dir),ft(e),Wt(e.app_id,[e.version,A==null?void 0:A.version].filter(Boolean)),d}catch(y){throw o?new te:y}finally{a=null,r.remove(c).catch(()=>{})}},M=((_=ae[e.app_id])!=null?_:Promise.resolve()).catch(()=>{}).then(i),m=M.catch(()=>{});return ae[e.app_id]=m,m.then(()=>{ae[e.app_id]===m&&delete ae[e.app_id]}),{promise:M,cancel:()=>{o=!0,a==null||a.cancel()}}},se={},jt=__DEV__?0:60*1e3,ht={},Mt=(e,t)=>{var r,a;let n=v(e);return n&&Date.now()-((r=ht[t])!=null?r:0)<jt?Promise.resolve(n):((a=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 c=await o.json(),l=await $e(c,{base_url:t}).promise;return ht[t]=Date.now(),l})().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,yt=(e,t)=>(me.set(e,t),()=>{me.get(e)===t&&me.delete(e)}),qt=(e,t)=>{let n=me.get(e);return n?n(t):!1};import{useRef as Kt,useSyncExternalStore as zt}from"react";var Me=e=>{let t=e,n=new Set;return{getState:()=>t,setState:r=>{let a=typeof r=="function"?r(t):r;t={...t,...a},n.forEach(o=>o())},subscribe:r=>(n.add(r),()=>{n.delete(r)})}},H=(e,t,n=Object.is)=>{let r=Kt(null),a=()=>{let o=e.getState(),c=r.current;if(c&&c.state===o&&c.selector===t)return c.value;let l=t(o),i=c&&n(c.value,l)?c.value:l;return r.current={state:o,selector:t,value:i},i};return zt(e.subscribe,a)};var N=Me({active_key:null,instances:{}}),wt=({app:e,instance_id:t,context:n={},url_params:r={},host_data:a={}},o)=>{var l;let c=(l=b().keep_alive)==null?void 0:l.max_webviews;N.setState(i=>{let u=t!=null?t:e.app_id,M={...i.instances,[u]:{key:u,app:e,context:n,url_params:r,host_data:a,last_used_at:Date.now()}},m=Object.keys(M);return c&&c>0&&m.length>c&&m.filter(_=>_!==u).sort((_,A)=>M[_].last_used_at-M[A].last_used_at).slice(0,m.length-c).forEach(_=>{delete M[_]}),o?{active_key:u,instances:M}:{instances:M}})},Yt=e=>wt(e,!0),Qt=e=>wt(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 vt="catalog",Gt="paused_apps",Xt="removed_apps",Zt=10*1e3,en=2,tn=3e3,nn=()=>{var e;try{return JSON.parse((e=b().storage.getString(vt))!=null?e:"{}")}catch{return{}}},w=Me({catalog:{},downloads:{},pause_reasons:[],updates:{},apply_ticks:{}}),_t=e=>{var t;return!!((t=b().manual_update)!=null&&t.includes(e))},_e=new Set,St=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 a=JSON.parse((r=b().storage.getString(e))!=null?r:"[]");Array.isArray(a)&&a.forEach(o=>{typeof o=="string"&&t.add(o)})}catch{}}}},B=St(Gt),Y=St(Xt);et(()=>{B.load(),Y.load();let e=nn(),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}:B.has(n)&&(t[n]={status:"paused",progress:0,version:e[n].version,has_local:!1})}),w.setState({catalog:e,downloads:t})});var Fe=e=>H(w,t=>e?t.downloads[e]:void 0),rn=()=>H(w,e=>e.pause_reasons.length>0),F=(...e)=>$("queue",...e),R=[],W={},h=null,we=new Set,Z={},Ne=new Set,K=e=>{Ne.forEach(t=>{try{t(e)}catch(n){console.warn("[miniapp-queue] event listener error",n==null?void 0:n.message)}})},on=e=>(Ne.add(e),()=>{Ne.delete(e)}),sn=()=>w.getState().downloads,C=(e,t)=>{let n=!!v(e),r=w.getState().downloads[e],a=t.status==="downloading"&&n?"updating":t.status,o={...r!=null?r:{status:"queued",progress:0},...t,...a?{status:a}:{},has_local:n};w.setState(c=>({downloads:{...c.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]},an=()=>w.getState().pause_reasons.length>0,z=e=>{var l;if(h)return;let t=e?R.indexOf(e):an()?-1:R.findIndex(i=>!B.has(i));if(t<0||t>=R.length)return;let[n]=R.splice(t,1),r=w.getState().catalog[n];if(!r){ve(n,v(n)),z();return}let a=Date.now();W[n]=((l=W[n])!=null?l:0)+1,C(n,{status:"downloading",progress:0,version:r.version,error:void 0});let o=0,c=$e(r,{onProgress:i=>{let u=Math.floor(i*100);u!==o&&(o=u,C(n,{progress:u/100,version:r.version}))}});h={app_id:n,handle:c,forced:!!e},F("start",n,r.version,e?"(forced)":""),c.promise.then(i=>{F("installed",n,r.version,`${Date.now()-a}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;F("paused",n),W[n]-=1,R.unshift(n),C(n,{status:B.has(n)?"paused":"queued",progress:0,version:r.version});return}let u=String((M=i==null?void 0:i.message)!=null?M:i);if(console.warn("[miniapp-queue] failed",n,u),W[n]<en){C(n,{status:"queued",progress:0,version:r.version,error:u}),setTimeout(()=>{var m;R.includes(n)||(h==null?void 0:h.app_id)===n||(R.push(n),z((m=Z[n])!=null&&m.length?n:void 0))},tn);return}C(n,{status:"failed",progress:0,version:r.version,error:u}),ve(n,v(n))}).finally(()=>{h=null;let i=R.find(u=>{var M;return(M=Z[u])==null?void 0:M.length});z(i)})},Se=(e,{front:t=!1}={})=>{if((h==null?void 0:h.app_id)===e)return;let n=R.indexOf(e);if(n>=0){if(!t)return;R.splice(n,1)}t?R.unshift(e):R.push(e)},pn=async e=>{let{host_id:t,client_token:n}=b(),r=new AbortController,a=setTimeout(()=>r.abort(),Zt);try{let o=`${Te}/api/hosts/${encodeURIComponent(t)}/miniapps?channel=${e}`,c=await fetch(o,{headers:{Authorization:`Bearer ${n}`,"Cache-Control":"no-cache"},signal:r.signal});if(!c.ok)throw new Error(`host list ${e} ${c.status}`);return(await c.json()).apps.map(i=>({...i,channel:e}))}finally{clearTimeout(a)}},ce=null,Be=()=>(ce!=null||(ce=(async()=>{var t;let e=Date.now();try{let n=await Promise.all(b().channels.map(pn)),r={};[...n].reverse().flat().forEach(i=>{r[i.app_id]=i});let a=Object.keys(w.getState().catalog).filter(i=>!r[i]);b().storage.setString(vt,JSON.stringify(r)),w.setState({catalog:r}),await Promise.all(a.map(i=>bt(i,{by_user:!1}))),a.forEach(i=>Y.delete(i));let o=Object.keys(r).filter(i=>!Y.has(i)),c=[],l={};for(let i of o.map(u=>r[u])){if(await Le(i)){C(i.app_id,{status:"installed",progress:1,version:i.version});continue}let u=v(i.app_id);if(_t(i.app_id)&&!_e.has(i.app_id)&&u&&await q(u)){C(i.app_id,{status:"installed",progress:1,version:u.version}),l[i.app_id]={app_id:i.app_id,current_version:u.version,next_version:i.version};continue}c.push(i)}return w.setState({updates:l}),c.forEach(i=>{W[i.app_id]=0,C(i.app_id,{status:B.has(i.app_id)?"paused":"queued",progress:0,version:i.version,error:void 0}),Se(i.app_id)}),F("catalog",o.length,"apps, outdated",c.map(i=>i.app_id),"removed",a,`${Date.now()-e}ms`),K({type:"sync_complete",app_ids:o,removed:a}),Object.values(l).forEach(i=>K({type:"update_available",...i})),z(),{ok:!0,app_ids:o,removed:a}}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),bt=async(e,{by_user:t})=>{var a,o,c,l;if(t&&Y.add(e),we.has(e))return;we.add(e),B.delete(e);let n=R.indexOf(e);n>=0&&R.splice(n,1),(h==null?void 0:h.app_id)===e&&h.handle.cancel();let r=(l=(c=(a=w.getState().downloads[e])==null?void 0:a.version)!=null?c:(o=v(e))==null?void 0:o.version)!=null?l:"";C(e,{status:"uninstalling",progress:0,version:r}),await mt(e),ye(e),w.setState(i=>{let u={...i.downloads};return delete u[e],{downloads:u}}),delete W[e],we.delete(e),ve(e,null),F("uninstalled",e,t?"(user)":"(not in list)"),K({type:"uninstalled",app_id:e})},cn=e=>bt(e,{by_user:!0}),ln=e=>{let t=le(e);return t?(Y.delete(e),(h==null?void 0:h.app_id)===e||R.includes(e)||(W[e]=0,C(e,{status:B.has(e)?"paused":"queued",progress:0,version:t.version,error:void 0}),Se(e),z(),F("restore",e)),!0):!1},un=e=>{if(B.has(e))return;if(B.add(e),F("pause app",e),(h==null?void 0:h.app_id)===e&&!h.forced){h.handle.cancel();return}let t=w.getState().downloads[e];R.includes(e)&&t&&C(e,{status:"paused",progress:0,version:t.version})},dn=e=>{if(!B.delete(e))return;F("resume app",e);let t=w.getState().downloads[e];(t==null?void 0:t.status)==="paused"&&!R.includes(e)&&le(e)&&(W[e]=0,Se(e)),R.includes(e)&&t&&C(e,{status:"queued",progress:0,version:t.version}),z()},gn=e=>{let{pause_reasons:t}=w.getState();t.includes(e)||(w.setState({pause_reasons:[...t,e]}),F("pause",e),t.length===0&&K({type:"pause_change",paused:!0,reasons:[e]}),h&&!h.forced&&h.handle.cancel())},fn=e=>{let{pause_reasons:t}=w.getState();if(!t.includes(e))return;let n=t.filter(r=>r!==e);w.setState({pause_reasons:n}),F("resume",e),n.length===0&&K({type:"pause_change",paused:!1,reasons:n}),z()},xt=e=>w.getState().updates[e],hn=async e=>{var n,r;let t=xt(e);_e.add(e);try{let a=await be(e),o=(r=t==null?void 0:t.next_version)!=null?r:(n=le(e))==null?void 0:n.version;return!a||!o||a.version!==o?!1:(w.setState(c=>{var i;let l={...c.updates};return delete l[e],{updates:l,apply_ticks:{...c.apply_ticks,[e]:((i=c.apply_ticks[e])!=null?i:0)+1}}}),F("updated",e,t==null?void 0:t.current_version,"\u2192",a.version),!0)}finally{_e.delete(e)}},An=()=>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(B.delete(e),Y.delete(e),await Le(t))return v(e);let n=v(e);if(_t(e)&&!_e.has(e)&&n&&await q(n))return n;let r=new Promise(a=>{var o;((o=Z[e])!=null?o:Z[e]=[]).push(a)});return(h==null?void 0:h.app_id)===e?h.forced=!0:(W[e]=0,Se(e,{front:!0}),h&&!h.forced?h.handle.cancel():z(e)),r};import{Fragment as Tt,jsx as T,jsxs as de}from"react/jsx-runtime";var Ue=e=>(e!=null?e:"").replace(/\?[^#]*/,""),Et=0,_n=()=>{let e=new Set;return{emit:t=>e.forEach(n=>n(t)),subscribe:t=>(e.add(t),()=>{e.delete(t)})}},Sn=We.memo(({instance_key:e,is_active:t,is_front:n,is_dark:r,reload_tick:a,web_at_top:o,splash:c,bridge:l,opaque_background:i,allow_embedded_miniapps:u,onWebLoadEnd:M})=>{var Ge,Xe;let m=U(null),_=U(!1),A=H(N,p=>p.instances[e]),f=A==null?void 0:A.app.app_id,D=A==null?void 0:A.app.manifest_url,y=A==null?void 0:A.context,d=A==null?void 0:A.url_params,[s,E]=ee(()=>f?v(f):null),[ne,re]=ee(!1),[Ct,qe]=ee(0),[Ot,ie]=ee(0),[kt,O]=ee(!1),V=U(null),Ke=p=>{V.current&&clearTimeout(V.current),V.current=setTimeout(()=>{V.current=null,O(!0)},p)};J(()=>()=>{V.current&&clearTimeout(V.current)},[]),J(()=>{if(!f||!t&&s)return;let p=!0;return re(!1),(async()=>{let g=v(f),P=g?await q(g):!1;if(!p||(E(P?L=>!L||L.version!==g.version||L.permissions.join(",")!==g.permissions.join(",")?g:L:null),__DEV__&&Date.now()-Et>1e4&&(Et=Date.now(),await Be()),!p))return;let j=await be(f),Q=j!==void 0?j:D?await Mt(f,D):v(f);if(p){if(!Q){re(!0);return}E(L=>L!=null?L:Q)}})(),()=>{p=!1}},[t,f,D,Ct]),J(()=>yt(e,p=>m.current?(m.current.postMessage(p),!0):!1),[e]);let It=H(w,p=>{let g=f?p.downloads[f]:void 0;return(g==null?void 0:g.status)==="installed"?g.version:void 0});J(()=>{if(t||!f||!s)return;let p=v(f);if(!p||p.version===s.version)return;let g=!0;return q(p).then(P=>{!g||!P||($(`webview:${e}`,"\u0111\u1ED5i bundle (\u1EA9n)",s.version,"\u2192",p.version),E(p))}),()=>{g=!1}},[t,f,It,s==null?void 0:s.version]);let ze=H(w,p=>{var g;return f&&(g=p.apply_ticks[f])!=null?g:0});J(()=>{if(!ze||!f)return;let p=v(f);if(!p||p.version===(s==null?void 0:s.version))return;let g=!0;return q(p).then(P=>{!g||!P||($(`webview:${e}`,"c\u1EADp nh\u1EADt",s==null?void 0:s.version,"\u2192",p.version),O(!1),E(p))}),()=>{g=!1}},[ze]),J(()=>{var P;let p=(P=b().keep_alive)==null?void 0:P.idle_close_ms;if(t||!p||p<=0)return;let g=setTimeout(()=>{ye(e)},p);return()=>clearTimeout(g)},[t,e]),J(()=>{a>0&&(re(!1),O(!1),ie(p=>p+1),qe(p=>p+1))},[a]);let Ye=U(t);J(()=>{var p;Ye.current!==t&&(Ye.current=t,_.current&&((p=m.current)==null||p.injectJavaScript(at(t?"resumed":"paused"))))},[t]);let ge=`${(Ge=s==null?void 0:s.version)!=null?Ge:"none"}:${(Xe=s==null?void 0:s.permissions.join(","))!=null?Xe:""}:${Ot}`,oe=xe(()=>JSON.stringify([y!=null?y:{},d!=null?d:{}]),[y,d]),Ee=xe(()=>{var p;return dt(d!=null?d:{},(p=s==null?void 0:s.permissions)!=null?p:[])},[oe,s==null?void 0:s.permissions]),Dt=xe(()=>lt(y!=null?y:{},Ee)+st()+(b().debug?ot():""),[Ee]),fe=U(null),Qe=U(null);J(()=>{var g,P,j;if(!s)return;if(Qe.current!==ge){Qe.current=ge,fe.current=oe;return}if(fe.current===oe)return;let p=((P=JSON.parse((g=fe.current)!=null?g:"[]")[0])!=null?P:{}).org_id;if(fe.current=oe,p===(y==null?void 0:y.org_id)&&_.current){O(!1),Ke(1500),(j=m.current)==null||j.injectJavaScript(pt(y!=null?y:{},Ee));return}O(!1),ie(Q=>Q+1)},[oe,s,ge]);let Lt=Ve(async p=>{var P,j,Q,L,Re;let g=nt(p.nativeEvent.data);if(!g){if(f&&(l!=null&&l.onWebEvent))try{Promise.resolve(l.onWebEvent(p.nativeEvent.data,{app_id:f,instance_id:e})).catch(S=>{console.warn("[miniapp] onWebEvent l\u1ED7i",f,S)})}catch(S){console.warn("[miniapp] onWebEvent l\u1ED7i",f,S)}return}if(g.method==="log"){let{level:S,text:k}=g;$(`web:${e}`,S!=null?S:"log",k!=null?k:"");return}if(g.method==="pong"){V.current||O(!0);return}if(g.method==="touchAtTop"){o.emit(!!g.at_top);return}if(g.method==="contextApplied"){V.current&&clearTimeout(V.current),V.current=null,O(!0);return}if(g.method==="ready"){_.current=!0,O(!0);let S=(P=N.getState().instances[e])==null?void 0:P.context;S&&((j=m.current)==null||j.injectJavaScript(Oe(S)));return}try{let S=await gt(g,{getHostData:()=>{var k,G;return(G=(k=N.getState().instances[e])==null?void 0:k.host_data)!=null?G:{}},getPermissions:()=>{var k,G;return f?(G=(k=v(f))==null?void 0:k.permissions)!=null?G:[]:[]},is_dark:r,close:pe,app_id:f!=null?f:"",instance_id:e,options:l});g.id&&((Q=m.current)==null||Q.injectJavaScript(rt(g.id,S)))}catch(S){if(!g.id)return;let k=S==null?void 0:S.code,G=S instanceof x?S:new x(typeof k=="string"?k:"HOST_ERROR",String((L=S==null?void 0:S.message)!=null?L:S));(Re=m.current)==null||Re.injectJavaScript(it(g.id,G))}},[e,r,f,o,l]),$t=Ve(()=>{re(!1),ie(p=>p+1),qe(p=>p+1)},[]);return de(He,{style:[je.absoluteFill,i&&{backgroundColor:r?"#09090B":"#FFFFFF"},!n&&I.behind],pointerEvents:t?"auto":"none",children:[s?T(vn,{ref:m,source:{uri:s.entry_uri},originWhitelist:["*"],allowingReadAccessToURL:`file://${u?Ie():s.dir}`,allowFileAccess:!0,allowFileAccessFromFileURLs:!0,allowUniversalAccessFromFileURLs:!0,injectedJavaScriptBeforeContentLoaded:Dt,onMessage:Lt,bounces:!1,overScrollMode:"never",onLoadStart:p=>{$(`webview:${e}`,"load start",Ue(p.nativeEvent.url)),_.current=!1,O(!1)},onError:p=>{$(`webview:${e}`,"load error",Ue(p.nativeEvent.url),p.nativeEvent.description),re(!0),O(!1)},onLoadEnd:p=>{let g=p.nativeEvent.url;$(`webview:${e}`,"load end",Ue(g)),f&&(M==null||M({app_id:f,instance_id:e,url:g})),Ke(1500)},onContentProcessDidTerminate:()=>{_.current=!1,O(!1),ie(p=>p+1)},onRenderProcessGone:()=>(_.current=!1,O(!1),ie(p=>p+1),!0),style:I.webview},ge):null,A&&T(xn,{visible:!s||!kt,interactive:ne,children:T(bn,{splash:c,app:A.app,is_dark:r,error:ne,has_bundle:!!s,retry:$t})})]})}),bn=We.memo(({splash:e,app:t,is_dark:n,error:r,has_bundle:a,retry:o})=>{let c=e,l=Fe(t.app_id),i=r?"error":!a&&(l==null?void 0:l.status)==="downloading"?"downloading":"loading";return T(c,{app:t,is_dark:n,status:i,progress:i==="downloading"?l==null?void 0:l.progress:void 0,retry:o})}),xn=({visible:e,interactive:t,children:n})=>{let r=U(new Je.Value(e?1:0)).current,[a,o]=ee(e);return J(()=>{if(e){o(!0),r.setValue(1);return}let c=Je.timing(r,{toValue:0,duration:180,useNativeDriver:!0});return c.start(({finished:l})=>{l&&o(!1)}),()=>c.stop()},[e,r]),a?T(Je.View,{style:[je.absoluteFill,{opacity:r}],pointerEvents:t?"auto":"none",children:n}):null},Pt=({app:e,is_dark:t,status:n,progress:r,retry:a})=>{let o=t?"#FAFAFA":"#18181B";return de(He,{style:[I.splash,{backgroundColor:t?"#09090B":"#FFFFFF"}],children:[T(He,{style:[I.splash_icon,{backgroundColor:t?"#18181B":"#F4F4F5"}],children:e.icon?T(yn,{source:{uri:e.icon},style:I.splash_icon_image}):T(ue,{style:I.splash_letter,children:(e.name||"?").slice(0,1).toUpperCase()})}),T(ue,{style:[I.splash_name,{color:o}],children:e.name}),n==="error"?de(Tt,{children:[T(ue,{style:I.splash_hint,children:"Kh\xF4ng t\u1EA3i \u0111\u01B0\u1EE3c mini app"}),T(wn,{activeOpacity:.7,style:[I.retry_button,{backgroundColor:t?"#27272A":"#F4F4F5"}],onPress:a,children:T(ue,{style:[I.retry_text,{color:o}],children:"Th\u1EED l\u1EA1i"})})]}):de(Tt,{children:[T(mn,{style:I.splash_spinner,color:t?"#A1A1AA":"#71717A"}),n==="downloading"&&de(ue,{style:I.splash_hint,children:["\u0110ang t\u1EA3i mini app",r?` ${Math.round(r*100)}%`:"\u2026"]})]})]})},Rt=(e,t)=>{let n=U(t),r=U(!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.`))},En=({container:e,splash:t=Pt,is_dark:n=!1,bridge:r,close_on_back:a=!0,opaque_background:o=!0,allow_embedded_miniapps:c=!1,onWebLoadEnd:l})=>{Rt("container",e),Rt("splash",t);let i=e,u=H(N,s=>s.active_key),M=U(u);u&&(M.current=u);let m=H(N,s=>Object.keys(s.instances).join("|")),_=H(N,s=>{var E;return s.active_key?(E=s.instances[s.active_key])==null?void 0:E.app.name:void 0}),A=xe(()=>m?m.split("|"):[],[m]),[f,D]=ee({}),y=U(_n()).current;J(()=>{if(!u||!a)return;let s=Mn.addEventListener("hardwareBackPress",()=>(pe(),!0));return()=>s.remove()},[u,a]);let d=Ve(()=>{let s=N.getState().active_key;s&&D(E=>({...E,[s]:(E[s]||0)+1}))},[]);return A.length?T(i,{visible:!!u,title:_!=null?_:"",is_dark:n,close:pe,reload:d,subscribeWebAtTop:y.subscribe,children:A.map(s=>T(Sn,{instance_key:s,is_active:u===s,is_front:(u!=null?u:M.current)===s,is_dark:n,reload_tick:f[s]||0,web_at_top:y,splash:t,bridge:r,opaque_background:o,allow_embedded_miniapps:c,onWebLoadEnd:l},s))}):null},I=je.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"}}),Rn=We.memo(En);export{Pt as DefaultMiniAppSplash,Te as MINIAPP_PLATFORM_URL,Rn as MiniAppHost,x as MiniAppHostError,pe as closeMiniApp,Nt as configureMiniApp,Bt as createMmkvStorage,Ft as createRnfsFileSystem,be as ensureMiniApp,v as getLocalMiniApp,An as getMiniAppCatalog,le as getMiniAppCatalogEntry,sn as getMiniAppStatuses,xt as getMiniAppUpdate,on as onMiniAppEvent,Yt as openMiniApp,un as pauseMiniApp,gn as pauseMiniAppDownloads,Qt as preloadMiniApp,ln as restoreMiniApp,dn as resumeMiniApp,fn as resumeMiniAppDownloads,qt as sendEventToWeb,Be as syncMiniAppCatalog,cn as uninstallMiniApp,hn as updateMiniApp,Fe as useMiniAppDownload,rn 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},Ce=new Set,ot=async(e,t)=>{if(Ce.has(e))throw new b("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)}},Wt=new Set(["selection","impactLight","impactMedium","impactHeavy","rigid","soft","notificationSuccess","notificationWarning","notificationError"]),Oe=(e,t)=>{if(typeof e!="string"||!e)throw new b("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 y,A,g,N,E,O,l,P;let c=i==null?void 0:i.handlers,m={app_id:a,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=c==null?void 0:c.requestPayment;if(!f)throw M();let x=t==null?void 0:t.amount;if(typeof x!="number"||!Number.isFinite(x)||x<=0)throw new b("INVALID_PARAMS","amount ph\u1EA3i l\xE0 s\u1ED1 > 0");let re={...t,amount:x,currency:Oe(t==null?void 0:t.currency,"currency")};return ot(e,()=>f(re,m))}case"printImage":{let f=c==null?void 0:c.printImage;if(!f)throw M();let x=Oe(t==null?void 0:t.image,"image");await ot(e,()=>f({image:x},m));return}case"openScreen":if(!(c!=null&&c.openScreen))throw M();await c.openScreen({screen:Oe(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):it.openURL(f));return}case"openLink":{let f=String((A=t==null?void 0:t.url)!=null?A:"").trim();if(!/^[a-z][a-z0-9+.-]*:/i.test(f)||/^(javascript|file|data|about|blob):/i.test(f))throw new b("INVALID_PARAMS","url kh\xF4ng h\u1EE3p l\u1EC7");try{await(i!=null&&i.openUrl?i.openUrl(f):it.openURL(f))}catch(x){throw new b("NOT_SUPPORTED",String((N=(g=x==null?void 0:x.message)!=null?g:x)!=null?N:"Kh\xF4ng m\u1EDF \u0111\u01B0\u1EE3c link"))}return}case"showToast":(O=i==null?void 0:i.showToast)==null||O.call(i,String((E=t==null?void 0:t.message)!=null?E:""));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:(P=i==null?void 0:i.app_version)!=null?P:"",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 oe=n().access_token;if(!oe)throw new b("HOST_ERROR","Mini app ch\u01B0a c\xF3 token cho page n\xE0y");return oe}if(f!=="partner"&&f!=="chatbox")throw new b("HOST_ERROR",`Lo\u1EA1i token kh\xF4ng h\u1EE3p l\u1EC7: ${String(f)}`);let x=ht[f];if(!r().includes(x))throw new b("PERMISSION_DENIED",`Mini app ch\u01B0a \u0111\u01B0\u1EE3c c\u1EA5p quy\u1EC1n ${x} (Console \u2192 Quy\u1EC1n l\u1EA5y token)`);let re=f==="partner"?n().partner_token:n().chatbox_token;if(!re)throw new b("HOST_ERROR",`Kh\xF4ng c\xF3 ${x}`);return re}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 Le=e=>`bundle:${e}`,$e=()=>`${_().file_system.document_dir}/miniapps`,Ne=$e,Be=(e,t,n="index.html",r=!1,s=[])=>{let o=`${Ne()}/${e}/${t}`;return{app_id:e,version:t,dir:o,entry_uri:`file://${o}/${n}`,context_update:r,permissions:s}},De=e=>{var t;_().storage.setString(Le(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(Le(e));if(!t)return null;try{let{version:n,entry:r,context_update:s,permissions:o}=JSON.parse(t);return Be(e,n,r,!!s,Array.isArray(o)?o:[])}catch{return null}},q=e=>_().file_system.exists(e.entry_uri.replace("file://","")),Fe=async e=>{let t=v(e.app_id);return(t==null?void 0:t.version)===e.version&&await q(t)},yt=async(e,t)=>{let n=_().file_system,r=`${Ne()}/${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=ce[e])==null?void 0:t.catch(()=>{})),_().storage.setString(Le(e),""),await _().file_system.remove(`${Ne()}/${e}`).catch(()=>{})},ie=class extends Error{constructor(){super("cancelled"),this.name="MiniAppInstallCancelled"}},ce={},vt=(e,t)=>{var o;let r=((o=ce[e])!=null?o:Promise.resolve()).catch(()=>{}).then(t),s=r.catch(()=>{});return ce[e]=s,s.then(()=>{ce[e]===s&&delete ce[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=_().file_system,r=v(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=Be(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),De(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}),Je=(e,{base_url:t,onProgress:n}={})=>{let r=_().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 c=v(e.app_id);if((c==null?void 0:c.version)===e.version&&await r.exists(c.dir))return De(e),v(e.app_id);u();let m=r.download({url:t?jt(t,e.bundle_url):e.bundle_url,to_file:a,onProgress:(y,A)=>{var N;let g=A>0?A:(N=e.size)!=null?N: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(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=Be(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),De(e),yt(e.app_id,[e.version,c==null?void 0:c.version].filter(Boolean)),A}catch(y){throw o?new ie:y}finally{s=null,r.remove(a).catch(()=>{})}};return{promise:vt(e.app_id,i),cancel:()=>{o=!0,s==null||s.cancel()}}},pe={},zt=__DEV__?0:60*1e3,Mt={},_t=(e,t)=>{var r,s;let n=v(e);return n&&Date.now()-((r=Mt[t])!=null?r:0)<zt?Promise.resolve(n):((s=pe[e])!=null||(pe[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),v(e))).finally(()=>{pe[e]=void 0})),pe[e])};var ye=new Map,St=(e,t)=>(ye.set(e,t),()=>{ye.get(e)===t&&ye.delete(e)}),Yt=(e,t)=>{let n=ye.get(e);return n?n(t):!1};import{useRef as Qt,useSyncExternalStore as Gt}from"react";var 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)})}},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=we({active_key:null,instances:{}}),bt=({app:e,instance_id:t,context:n={},url_params:r={},host_data:s={}},o)=>{var u;let a=(u=_().keep_alive)==null?void 0:u.max_webviews;F.setState(i=>{let c=t!=null?t:e.app_id,m={...i.instances,[c]:{key:c,app:e,context:n,url_params:r,host_data:s,last_used_at:Date.now()}},M=Object.keys(m);return a&&a>0&&M.length>a&&M.filter(y=>y!==c).sort((y,A)=>m[y].last_used_at-m[A].last_used_at).slice(0,M.length-a).forEach(y=>{delete m[y]}),o?{active_key:c,instances:m}:{instances:m}})},Xt=e=>bt(e,!0),Zt=e=>bt(e,!1),le=()=>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 xt="catalog",en="paused_apps",tn="removed_apps",nn=10*1e3,rn=2,on=3e3,sn=()=>{var e;try{return JSON.parse((e=_().storage.getString(xt))!=null?e:"{}")}catch{return{}}},w=we({catalog:{},downloads:{},pause_reasons:[],updates:{},apply_ticks:{}}),Et=e=>{var t;return!!((t=_().manual_update)!=null&&t.includes(e))},be=new Set,Rt=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{}}}},U=Rt(en),G=Rt(tn);rt(()=>{U.load(),G.load();let e=sn(),t={};Object.keys(e).filter(n=>!G.has(n)).forEach(n=>{let r=v(n);r?t[n]={status:"installed",progress:1,version:r.version,has_local:!0}:U.has(n)&&(t[n]={status:"paused",progress:0,version:e[n].version,has_local:!1})}),w.setState({catalog:e,downloads:t})});var Ve=e=>j(w,t=>e?t.downloads[e]:void 0),an=()=>j(w,e=>e.pause_reasons.length>0),J=(...e)=>L("queue",...e),R=[],K={},h=null,_e=new Set,te={},Ue=new Set,Y=e=>{Ue.forEach(t=>{try{t(e)}catch(n){console.warn("[miniapp-queue] event listener error",n==null?void 0:n.message)}})},pn=e=>(Ue.add(e),()=>{Ue.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(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})},Se=(e,t)=>{var n;(n=te[e])==null||n.forEach(r=>r(t)),delete te[e]},ln=()=>w.getState().pause_reasons.length>0,Q=e=>{var u;if(h)return;let t=e?R.indexOf(e):ln()?-1:R.findIndex(i=>!U.has(i));if(t<0||t>=R.length)return;let[n]=R.splice(t,1),r=w.getState().catalog[n];if(!r){Se(n,v(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=Je(r,{onProgress:i=>{let c=Math.floor(i*100);c!==o&&(o=c,C(n,{progress:c/100,version:r.version}))}});h={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`),C(n,{status:"installed",progress:1,version:r.version}),Se(n,i)}).catch(i=>{var m;if(i instanceof ie){if(_e.has(n))return;J("paused",n),K[n]-=1,R.unshift(n),C(n,{status:U.has(n)?"paused":"queued",progress:0,version:r.version});return}let c=String((m=i==null?void 0:i.message)!=null?m:i);if(console.warn("[miniapp-queue] failed",n,c),K[n]<rn){C(n,{status:"queued",progress:0,version:r.version,error:c}),setTimeout(()=>{var M;R.includes(n)||(h==null?void 0:h.app_id)===n||(R.push(n),Q((M=te[n])!=null&&M.length?n:void 0))},on);return}C(n,{status:"failed",progress:0,version:r.version,error:c}),Se(n,v(n))}).finally(()=>{h=null;let i=R.find(c=>{var m;return(m=te[c])==null?void 0:m.length});Q(i)})},xe=(e,{front:t=!1}={})=>{if((h==null?void 0:h.app_id)===e)return;let n=R.indexOf(e);if(n>=0){if(!t)return;R.splice(n,1)}t?R.unshift(e):R.push(e)},un=async e=>{let{host_id:t,client_token:n}=_(),r=new AbortController,s=setTimeout(()=>r.abort(),nn);try{let o=`${ke}/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,He=()=>(ue!=null||(ue=(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(xt,JSON.stringify(r)),w.setState({catalog:r}),await Promise.all(s.map(i=>Tt(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(c=>r[c])){if(await Fe(i)){C(i.app_id,{status:"installed",progress:1,version:i.version});continue}let c=v(i.app_id);if(Et(i.app_id)&&!be.has(i.app_id)&&c&&await q(c)){C(i.app_id,{status:"installed",progress:1,version:c.version}),u[i.app_id]={app_id:i.app_id,current_version:c.version,next_version:i.version};continue}a.push(i)}return w.setState({updates:u}),a.forEach(i=>{K[i.app_id]=0,C(i.app_id,{status:U.has(i.app_id)?"paused":"queued",progress:0,version:i.version,error:void 0}),xe(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{ue=null}})()),ue),Tt=async(e,{by_user:t})=>{var s,o,a,u;if(t&&G.add(e),_e.has(e))return;_e.add(e),U.delete(e);let n=R.indexOf(e);n>=0&&R.splice(n,1),(h==null?void 0:h.app_id)===e&&h.handle.cancel();let r=(u=(a=(s=w.getState().downloads[e])==null?void 0:s.version)!=null?a:(o=v(e))==null?void 0:o.version)!=null?u:"";C(e,{status:"uninstalling",progress:0,version:r}),await wt(e),ve(e),w.setState(i=>{let c={...i.downloads};return delete c[e],{downloads:c}}),delete K[e],_e.delete(e),Se(e,null),J("uninstalled",e,t?"(user)":"(not in list)"),Y({type:"uninstalled",app_id:e})},dn=e=>Tt(e,{by_user:!0}),gn=e=>{let t=de(e);return t?(G.delete(e),(h==null?void 0:h.app_id)===e||R.includes(e)||(K[e]=0,C(e,{status:U.has(e)?"paused":"queued",progress:0,version:t.version,error:void 0}),xe(e),Q(),J("restore",e)),!0):!1},fn=e=>{if(U.has(e))return;if(U.add(e),J("pause app",e),(h==null?void 0:h.app_id)===e&&!h.forced){h.handle.cancel();return}let t=w.getState().downloads[e];R.includes(e)&&t&&C(e,{status:"paused",progress:0,version:t.version})},hn=e=>{if(!U.delete(e))return;J("resume app",e);let t=w.getState().downloads[e];(t==null?void 0:t.status)==="paused"&&!R.includes(e)&&de(e)&&(K[e]=0,xe(e)),R.includes(e)&&t&&C(e,{status:"queued",progress:0,version:t.version}),Q()},An=e=>{let{pause_reasons:t}=w.getState();t.includes(e)||(w.setState({pause_reasons:[...t,e]}),J("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}=w.getState();if(!t.includes(e))return;let n=t.filter(r=>r!==e);w.setState({pause_reasons:n}),J("resume",e),n.length===0&&Y({type:"pause_change",paused:!1,reasons:n}),Q()},Pt=e=>w.getState().updates[e],Mn=async e=>{var n,r;let t=Pt(e);be.add(e);try{let s=await Ee(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:(w.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{be.delete(e)}},yn=()=>Object.values(w.getState().catalog).map(e=>({...e,installed:!!v(e.app_id),removed_by_user:G.has(e.app_id)})),de=e=>w.getState().catalog[e],Ee=async e=>{let t=de(e);if(!t)return;if(U.delete(e),G.delete(e),await Fe(t))return v(e);let n=v(e);if(Et(e)&&!be.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,xe(e,{front:!0}),h&&!h.forced?h.handle.cancel():Q(e)),r};import{Fragment as Ot,jsx as T,jsxs as fe}from"react/jsx-runtime";var je=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=ze.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:c,onWebLoadEnd:m})=>{var et,tt;let M=H(null),y=H(!1),A=j(F,p=>p.instances[e]),g=A==null?void 0:A.app.app_id,N=A==null?void 0:A.app.manifest_url,E=A==null?void 0:A.context,O=A==null?void 0:A.url_params,[l,P]=ne(()=>g?v(g):null),[f,x]=ne(!1),[re,oe]=ne(0),[Dt,se]=ne(0),[Lt,I]=ne(!1),W=H(null),Qe=p=>{W.current&&clearTimeout(W.current),W.current=setTimeout(()=>{W.current=null,I(!0)},p)};V(()=>()=>{W.current&&clearTimeout(W.current)},[]),V(()=>{if(!g||!t&&l)return;let p=!0;return x(!1),(async()=>{let d=v(g),k=d?await q(d):!1;if(!p||(P(k?B=>!B||B.version!==d.version||B.permissions.join(",")!==d.permissions.join(",")?d:B:null),__DEV__&&Date.now()-kt>1e4&&(kt=Date.now(),await He()),!p))return;let z=await Ee(g),X=z!==void 0?z:N?await _t(g,N):v(g);if(p){if(!X){x(!0);return}P(B=>B!=null?B:X)}})(),()=>{p=!1}},[t,g,N,re]),V(()=>St(e,p=>M.current?(M.current.postMessage(p),!0):!1),[e]);let $t=j(w,p=>{let d=g?p.downloads[g]:void 0;return(d==null?void 0:d.status)==="installed"?d.version:void 0});V(()=>{if(t||!g||!l)return;let p=v(g);if(!p||p.version===l.version)return;let d=!0;return q(p).then(k=>{!d||!k||(L(`webview:${e}`,"\u0111\u1ED5i bundle (\u1EA9n)",l.version,"\u2192",p.version),P(p))}),()=>{d=!1}},[t,g,$t,l==null?void 0:l.version]);let Ge=j(w,p=>{var d;return g&&(d=p.apply_ticks[g])!=null?d:0});V(()=>{if(!Ge||!g)return;let p=v(g);if(!p||p.version===(l==null?void 0:l.version))return;let d=!0;return q(p).then(k=>{!d||!k||(L(`webview:${e}`,"c\u1EADp nh\u1EADt",l==null?void 0:l.version,"\u2192",p.version),I(!1),P(p))}),()=>{d=!1}},[Ge]),V(()=>{var k;let p=(k=_().keep_alive)==null?void 0:k.idle_close_ms;if(t||!p||p<=0)return;let d=setTimeout(()=>{ve(e)},p);return()=>clearTimeout(d)},[t,e]),V(()=>{s>0&&(x(!1),I(!1),se(p=>p+1),oe(p=>p+1))},[s]);let Xe=H(t);V(()=>{var p;Xe.current!==t&&(Xe.current=t,y.current&&((p=M.current)==null||p.injectJavaScript(ut(t?"resumed":"paused"))))},[t]);let he=`${(et=l==null?void 0:l.version)!=null?et:"none"}:${(tt=l==null?void 0:l.permissions.join(","))!=null?tt:""}:${Dt}`,ae=Re(()=>JSON.stringify([E!=null?E:{},O!=null?O:{}]),[E,O]),Te=Re(()=>{var p;return At(O!=null?O:{},(p=l==null?void 0:l.permissions)!=null?p:[])},[ae,l==null?void 0:l.permissions]),Nt=Re(()=>ft(E!=null?E:{},Te)+lt()+(_().debug?ct():""),[Te]),Ae=H(null),Ze=H(null);V(()=>{var d,k,z;if(!l)return;if(Ze.current!==he){Ze.current=he,Ae.current=ae;return}if(Ae.current===ae)return;let p=((k=JSON.parse((d=Ae.current)!=null?d:"[]")[0])!=null?k:{}).org_id;if(Ae.current=ae,p===(E==null?void 0:E.org_id)&&y.current){I(!1),Qe(1500),(z=M.current)==null||z.injectJavaScript(dt(E!=null?E:{},Te));return}I(!1),se(X=>X+1)},[ae,l,he]);let Bt=qe(async p=>{var k,z,X,B,Pe;let d=st(p.nativeEvent.data);if(!d){if(g&&(u!=null&&u.onWebEvent))try{Promise.resolve(u.onWebEvent(p.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:D}=d;L(`web:${e}`,S!=null?S:"log",D!=null?D:"");return}if(d.method==="pong"){W.current||I(!0);return}if(d.method==="touchAtTop"){o.emit(!!d.at_top);return}if(d.method==="contextApplied"){W.current&&clearTimeout(W.current),W.current=null,I(!0);return}if(d.method==="ready"){y.current=!0,I(!0);let S=(k=F.getState().instances[e])==null?void 0:k.context;S&&((z=M.current)==null||z.injectJavaScript(Ie(S)));return}try{let S=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 g?(Z=(D=v(g))==null?void 0:D.permissions)!=null?Z:[]:[]},is_dark:r,close:le,app_id:g!=null?g:"",instance_id:e,options:u});d.id&&((X=M.current)==null||X.injectJavaScript(at(d.id,S)))}catch(S){if(!d.id)return;let D=S==null?void 0:S.code,Z=S instanceof b?S:new b(typeof D=="string"?D:"HOST_ERROR",String((B=S==null?void 0:S.message)!=null?B:S));(Pe=M.current)==null||Pe.injectJavaScript(pt(d.id,Z))}},[e,r,g,o,u]),Ft=qe(()=>{x(!1),se(p=>p+1),oe(p=>p+1)},[]);return fe(Ke,{style:[Ye.absoluteFill,i&&{backgroundColor:r?"#09090B":"#FFFFFF"},!n&&$.behind],pointerEvents:t?"auto":"none",children:[l?T(bn,{ref:M,source:{uri:l.entry_uri},originWhitelist:["*"],allowingReadAccessToURL:`file://${c?$e():l.dir}`,allowFileAccess:!0,allowFileAccessFromFileURLs:!0,allowUniversalAccessFromFileURLs:!0,injectedJavaScriptBeforeContentLoaded:Nt,onMessage:Bt,bounces:!1,overScrollMode:"never",onLoadStart:p=>{L(`webview:${e}`,"load start",je(p.nativeEvent.url)),y.current=!1,I(!1)},onError:p=>{L(`webview:${e}`,"load error",je(p.nativeEvent.url),p.nativeEvent.description),x(!0),I(!1)},onLoadEnd:p=>{let d=p.nativeEvent.url;L(`webview:${e}`,"load end",je(d)),g&&(m==null||m({app_id:g,instance_id:e,url:d})),Qe(1500)},onContentProcessDidTerminate:()=>{y.current=!1,I(!1),se(p=>p+1)},onRenderProcessGone:()=>(y.current=!1,I(!1),se(p=>p+1),!0),style:$.webview},he):null,A&&T(Tn,{visible:!l||!Lt,interactive:f,children:T(Rn,{splash:a,app:A.app,is_dark:r,error:f,has_bundle:!!l,retry:Ft})})]})}),Rn=ze.memo(({splash:e,app:t,is_dark:n,error:r,has_bundle:s,retry:o})=>{let a=e,u=Ve(t.app_id),i=r?"error":!s&&(u==null?void 0:u.status)==="downloading"?"downloading":"loading";return T(a,{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=H(new We.Value(e?1:0)).current,[s,o]=ne(e);return V(()=>{if(e){o(!0),r.setValue(1);return}let a=We.timing(r,{toValue:0,duration:180,useNativeDriver:!0});return a.start(({finished:u})=>{u&&o(!1)}),()=>a.stop()},[e,r]),s?T(We.View,{style:[Ye.absoluteFill,{opacity:r}],pointerEvents:t?"auto":"none",children:n}):null},It=({app:e,is_dark:t,status:n,progress:r,retry:s})=>{let o=t?"#FAFAFA":"#18181B";return fe(Ke,{style:[$.splash,{backgroundColor:t?"#09090B":"#FFFFFF"}],children:[T(Ke,{style:[$.splash_icon,{backgroundColor:t?"#18181B":"#F4F4F5"}],children:e.icon?T(_n,{source:{uri:e.icon},style:$.splash_icon_image}):T(ge,{style:$.splash_letter,children:(e.name||"?").slice(0,1).toUpperCase()})}),T(ge,{style:[$.splash_name,{color:o}],children:e.name}),n==="error"?fe(Ot,{children:[T(ge,{style:$.splash_hint,children:"Kh\xF4ng t\u1EA3i \u0111\u01B0\u1EE3c mini app"}),T(Sn,{activeOpacity:.7,style:[$.retry_button,{backgroundColor:t?"#27272A":"#F4F4F5"}],onPress:s,children:T(ge,{style:[$.retry_text,{color:o}],children:"Th\u1EED l\u1EA1i"})})]}):fe(Ot,{children:[T(wn,{style:$.splash_spinner,color:t?"#A1A1AA":"#71717A"}),n==="downloading"&&fe(ge,{style:$.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=It,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,c=j(F,l=>l.active_key),m=H(c);c&&(m.current=c);let M=j(F,l=>Object.keys(l.instances).join("|")),y=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]),[g,N]=ne({}),E=H(xn()).current;V(()=>{if(!c||!s)return;let l=vn.addEventListener("hardwareBackPress",()=>(le(),!0));return()=>l.remove()},[c,s]);let O=qe(()=>{let l=F.getState().active_key;l&&N(P=>({...P,[l]:(P[l]||0)+1}))},[]);return A.length?T(i,{visible:!!c,title:y!=null?y:"",is_dark:n,close:le,reload:O,subscribeWebAtTop:E.subscribe,children:A.map(l=>T(En,{instance_key:l,is_active:c===l,is_front:(c!=null?c:m.current)===l,is_dark:n,reload_tick:g[l]||0,web_at_top:E,splash:t,bridge:r,opaque_background:o,allow_embedded_miniapps:a,onWebLoadEnd:u},l))}):null},$=Ye.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=ze.memo(Pn);export{It as DefaultMiniAppSplash,ke as MINIAPP_PLATFORM_URL,kn as MiniAppHost,b as MiniAppHostError,le as closeMiniApp,Jt as configureMiniApp,Vt as createMmkvStorage,Ut as createRnfsFileSystem,Ee as ensureMiniApp,v as getLocalMiniApp,yn as getMiniAppCatalog,de as getMiniAppCatalogEntry,cn as getMiniAppStatuses,Pt 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,He as syncMiniAppCatalog,dn as uninstallMiniApp,Mn as updateMiniApp,Ve 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.3",
3
+ "version": "0.7.5",
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": {