@retion-miniapp/react-native 0.7.8 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/app.plugin.js CHANGED
@@ -1,5 +1,6 @@
1
1
  // Expo prebuild plugin. Bare React Native hosts set NSFaceIDUsageDescription in Info.plist.
2
2
  const { withInfoPlist, withAndroidManifest } = require('expo/config-plugins');
3
+ const withSpeechRecognition = require('expo-speech-recognition/app.plugin.js');
3
4
 
4
5
  module.exports = function withMiniApp(config, options = {}) {
5
6
  config = withInfoPlist(config, config => {
@@ -8,6 +9,11 @@ module.exports = function withMiniApp(config, options = {}) {
8
9
  || 'Allow this app to use Face ID to verify your identity.';
9
10
  return config;
10
11
  });
12
+ config = withSpeechRecognition(config, {
13
+ microphonePermission: options.microphonePermission,
14
+ speechRecognitionPermission: options.speechRecognitionPermission,
15
+ androidSpeechServicePackages: options.androidSpeechServicePackages,
16
+ });
11
17
  return withAndroidManifest(config, config => {
12
18
  const manifest = config.modResults.manifest;
13
19
  const permissions = manifest['uses-permission'] || [];
package/dist/index.d.mts CHANGED
@@ -541,4 +541,14 @@ interface ReactNativeBiometricsLike {
541
541
  /** Native-module injection keeps the host package independent of the app's native dependencies. */
542
542
  declare const createReactNativeBiometrics: (native: ReactNativeBiometricsLike) => MiniAppBiometrics;
543
543
 
544
- export { DefaultMiniAppSplash, MINIAPP_PLATFORM_URL, type MiniAppBiometricAvailability, type MiniAppBiometricRequest, type MiniAppBiometricResult, type MiniAppBiometrics, type MiniAppBiometryType, type MiniAppBridgeOptions, type MiniAppCatalogEntry, type MiniAppCatalogItem, type MiniAppChannel, type MiniAppConfig, type MiniAppContainerProps, type MiniAppContext, type MiniAppDownloadState, type MiniAppDownloadStatus, type MiniAppDownloadTask, type MiniAppEvent, type MiniAppFileSystem, type MiniAppHandlerContext, type MiniAppHapticType, _default as MiniAppHost, type MiniAppHostData, BridgeError as MiniAppHostError, type MiniAppHostProps, type MiniAppKeepAlive, type MiniAppLaunch, type MiniAppLocalBundle, type MiniAppManifest, type MiniAppNativeHandlers, type MiniAppPaymentRequest, type MiniAppPaymentResult, type MiniAppPermission, type MiniAppSplashProps, type MiniAppStorage, type MiniAppSyncResult, type MiniAppUpdate, type OpenMiniAppArgs, type ReactNativeBiometricsLike, closeMiniApp, configureMiniApp, createMmkvStorage, createReactNativeBiometrics, createRnfsFileSystem, ensureMiniApp, getLocalMiniApp, getMiniAppCatalog, getMiniAppCatalogEntry, getMiniAppStatuses, getMiniAppUpdate, installBundledMiniApp, onMiniAppEvent, openMiniApp, pauseMiniApp, pauseMiniAppDownloads, preloadMiniApp, restoreMiniApp, resumeMiniApp, resumeMiniAppDownloads, sendEventToWeb, syncMiniAppCatalog, uninstallMiniApp, updateMiniApp, useMiniAppDownload, useMiniAppDownloadsPaused };
544
+ interface SpeechOptions {
545
+ lang?: string;
546
+ continuous?: boolean;
547
+ interimResults?: boolean;
548
+ addsPunctuation?: boolean;
549
+ requiresOnDeviceRecognition?: boolean;
550
+ }
551
+ /** Đóng/ẩn mini app: huỷ, không lấy kết quả cuối. Giữ khoá đến native end để tránh event phiên cũ sang phiên mới. */
552
+ declare const releaseSpeechFor: (owner: string) => void;
553
+
554
+ export { DefaultMiniAppSplash, MINIAPP_PLATFORM_URL, type MiniAppBiometricAvailability, type MiniAppBiometricRequest, type MiniAppBiometricResult, type MiniAppBiometrics, type MiniAppBiometryType, type MiniAppBridgeOptions, type MiniAppCatalogEntry, type MiniAppCatalogItem, type MiniAppChannel, type MiniAppConfig, type MiniAppContainerProps, type MiniAppContext, type MiniAppDownloadState, type MiniAppDownloadStatus, type MiniAppDownloadTask, type MiniAppEvent, type MiniAppFileSystem, type MiniAppHandlerContext, type MiniAppHapticType, _default as MiniAppHost, type MiniAppHostData, BridgeError as MiniAppHostError, type MiniAppHostProps, type MiniAppKeepAlive, type MiniAppLaunch, type MiniAppLocalBundle, type MiniAppManifest, type MiniAppNativeHandlers, type MiniAppPaymentRequest, type MiniAppPaymentResult, type MiniAppPermission, type MiniAppSplashProps, type MiniAppStorage, type MiniAppSyncResult, type MiniAppUpdate, type OpenMiniAppArgs, type ReactNativeBiometricsLike, type SpeechOptions, closeMiniApp, configureMiniApp, createMmkvStorage, createReactNativeBiometrics, createRnfsFileSystem, ensureMiniApp, getLocalMiniApp, getMiniAppCatalog, getMiniAppCatalogEntry, getMiniAppStatuses, getMiniAppUpdate, installBundledMiniApp, onMiniAppEvent, openMiniApp, pauseMiniApp, pauseMiniAppDownloads, preloadMiniApp, releaseSpeechFor, restoreMiniApp, resumeMiniApp, resumeMiniAppDownloads, sendEventToWeb, syncMiniAppCatalog, uninstallMiniApp, updateMiniApp, useMiniAppDownload, useMiniAppDownloadsPaused };
package/dist/index.d.ts CHANGED
@@ -541,4 +541,14 @@ interface ReactNativeBiometricsLike {
541
541
  /** Native-module injection keeps the host package independent of the app's native dependencies. */
542
542
  declare const createReactNativeBiometrics: (native: ReactNativeBiometricsLike) => MiniAppBiometrics;
543
543
 
544
- export { DefaultMiniAppSplash, MINIAPP_PLATFORM_URL, type MiniAppBiometricAvailability, type MiniAppBiometricRequest, type MiniAppBiometricResult, type MiniAppBiometrics, type MiniAppBiometryType, type MiniAppBridgeOptions, type MiniAppCatalogEntry, type MiniAppCatalogItem, type MiniAppChannel, type MiniAppConfig, type MiniAppContainerProps, type MiniAppContext, type MiniAppDownloadState, type MiniAppDownloadStatus, type MiniAppDownloadTask, type MiniAppEvent, type MiniAppFileSystem, type MiniAppHandlerContext, type MiniAppHapticType, _default as MiniAppHost, type MiniAppHostData, BridgeError as MiniAppHostError, type MiniAppHostProps, type MiniAppKeepAlive, type MiniAppLaunch, type MiniAppLocalBundle, type MiniAppManifest, type MiniAppNativeHandlers, type MiniAppPaymentRequest, type MiniAppPaymentResult, type MiniAppPermission, type MiniAppSplashProps, type MiniAppStorage, type MiniAppSyncResult, type MiniAppUpdate, type OpenMiniAppArgs, type ReactNativeBiometricsLike, closeMiniApp, configureMiniApp, createMmkvStorage, createReactNativeBiometrics, createRnfsFileSystem, ensureMiniApp, getLocalMiniApp, getMiniAppCatalog, getMiniAppCatalogEntry, getMiniAppStatuses, getMiniAppUpdate, installBundledMiniApp, onMiniAppEvent, openMiniApp, pauseMiniApp, pauseMiniAppDownloads, preloadMiniApp, restoreMiniApp, resumeMiniApp, resumeMiniAppDownloads, sendEventToWeb, syncMiniAppCatalog, uninstallMiniApp, updateMiniApp, useMiniAppDownload, useMiniAppDownloadsPaused };
544
+ interface SpeechOptions {
545
+ lang?: string;
546
+ continuous?: boolean;
547
+ interimResults?: boolean;
548
+ addsPunctuation?: boolean;
549
+ requiresOnDeviceRecognition?: boolean;
550
+ }
551
+ /** Đóng/ẩn mini app: huỷ, không lấy kết quả cuối. Giữ khoá đến native end để tránh event phiên cũ sang phiên mới. */
552
+ declare const releaseSpeechFor: (owner: string) => void;
553
+
554
+ export { DefaultMiniAppSplash, MINIAPP_PLATFORM_URL, type MiniAppBiometricAvailability, type MiniAppBiometricRequest, type MiniAppBiometricResult, type MiniAppBiometrics, type MiniAppBiometryType, type MiniAppBridgeOptions, type MiniAppCatalogEntry, type MiniAppCatalogItem, type MiniAppChannel, type MiniAppConfig, type MiniAppContainerProps, type MiniAppContext, type MiniAppDownloadState, type MiniAppDownloadStatus, type MiniAppDownloadTask, type MiniAppEvent, type MiniAppFileSystem, type MiniAppHandlerContext, type MiniAppHapticType, _default as MiniAppHost, type MiniAppHostData, BridgeError as MiniAppHostError, type MiniAppHostProps, type MiniAppKeepAlive, type MiniAppLaunch, type MiniAppLocalBundle, type MiniAppManifest, type MiniAppNativeHandlers, type MiniAppPaymentRequest, type MiniAppPaymentResult, type MiniAppPermission, type MiniAppSplashProps, type MiniAppStorage, type MiniAppSyncResult, type MiniAppUpdate, type OpenMiniAppArgs, type ReactNativeBiometricsLike, type SpeechOptions, closeMiniApp, configureMiniApp, createMmkvStorage, createReactNativeBiometrics, createRnfsFileSystem, ensureMiniApp, getLocalMiniApp, getMiniAppCatalog, getMiniAppCatalogEntry, getMiniAppStatuses, getMiniAppUpdate, installBundledMiniApp, onMiniAppEvent, openMiniApp, pauseMiniApp, pauseMiniAppDownloads, preloadMiniApp, releaseSpeechFor, restoreMiniApp, resumeMiniApp, resumeMiniAppDownloads, sendEventToWeb, syncMiniAppCatalog, uninstallMiniApp, updateMiniApp, useMiniAppDownload, useMiniAppDownloadsPaused };
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var rn=Object.create;var Ae=Object.defineProperty;var on=Object.getOwnPropertyDescriptor;var sn=Object.getOwnPropertyNames;var an=Object.getPrototypeOf,cn=Object.prototype.hasOwnProperty;var pn=(e,t)=>{for(var n in t)Ae(e,n,{get:t[n],enumerable:!0})},it=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of sn(t))!cn.call(e,s)&&s!==n&&Ae(e,s,{get:()=>t[s],enumerable:!(r=on(t,s))||r.enumerable});return e};var Le=(e,t,n)=>(n=e!=null?rn(an(e)):{},it(t||!e||!e.__esModule?Ae(n,"default",{value:e,enumerable:!0}):n,e)),ln=e=>it(Ae({},"__esModule",{value:!0}),e);var Rn={};pn(Rn,{DefaultMiniAppSplash:()=>Ge,MINIAPP_PLATFORM_URL:()=>Me,MiniAppHost:()=>Gt,MiniAppHostError:()=>M,closeMiniApp:()=>oe,configureMiniApp:()=>st,createMmkvStorage:()=>pt,createReactNativeBiometrics:()=>Be,createRnfsFileSystem:()=>ct,ensureMiniApp:()=>fe,getLocalMiniApp:()=>b,getMiniAppCatalog:()=>Kt,getMiniAppCatalogEntry:()=>se,getMiniAppStatuses:()=>$t,getMiniAppUpdate:()=>Ye,installBundledMiniApp:()=>Et,onMiniAppEvent:()=>Nt,openMiniApp:()=>Ct,pauseMiniApp:()=>Vt,pauseMiniAppDownloads:()=>Wt,preloadMiniApp:()=>Ot,restoreMiniApp:()=>Jt,resumeMiniApp:()=>Ht,resumeMiniAppDownloads:()=>jt,sendEventToWeb:()=>Tt,syncMiniAppCatalog:()=>Oe,uninstallMiniApp:()=>Ut,updateMiniApp:()=>qt,useMiniAppDownload:()=>ke,useMiniAppDownloadsPaused:()=>Bt});module.exports=ln(Rn);var Me="https://retion-miniapp-platform.vercel.app",ne=null,ot=new Set,st=e=>{ne=e,ot.forEach(t=>t())},P=()=>{if(!ne)throw new Error("[miniapp] Ch\u01B0a g\u1ECDi configureMiniApp()");return ne},at=e=>{ot.add(e),ne&&e()},N=(...e)=>{ne!=null&&ne.debug&&console.log("[miniapp]",...e)};var ct=(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)}}}),pt=e=>({getString:t=>e.getString(t),setString:(t,n)=>e.set(t,n)});var d=Le(require("react")),S=require("react-native"),Qt=Le(require("react-native-webview"));var le=require("react-native");var Be=e=>({getAvailability:()=>e.isSensorAvailable(),authenticate:({reason:t,cancelButtonText:n})=>e.simplePrompt({promptMessage:t,cancelButtonText:n,fallbackPromptMessage:""})}),ye,Ne=()=>(ye||(ye=import("react-native-biometrics").then(({default:e})=>Be(new e({allowDeviceCredentials:!1}))).catch(e=>{throw ye=void 0,new M("NOT_SUPPORTED",`Biometric native module unavailable: ${e instanceof Error?e.message:String(e)}`)})),ye);var ve=1,M=class extends Error{constructor(n,r){super(r);this.code=n}},lt=e=>{try{let t=JSON.parse(e);return(t==null?void 0:t.__retion)===ve&&typeof t.method=="string"?t:null}catch{return null}},_e=e=>`window.__RETION_MINIAPP__ && window.__RETION_MINIAPP__.receive(${JSON.stringify(e)}); true;`,ut=(e,t)=>_e({id:e,result:t}),dt=(e,t)=>_e({id:e,error:{code:t.code,message:t.message}}),Ue=e=>_e({event:"context",data:e});var gt=()=>`(function () {
1
+ "use strict";var dn=Object.create;var ve=Object.defineProperty;var gn=Object.getOwnPropertyDescriptor;var fn=Object.getOwnPropertyNames;var hn=Object.getPrototypeOf,mn=Object.prototype.hasOwnProperty;var An=(e,t)=>{for(var n in t)ve(e,n,{get:t[n],enumerable:!0})},pt=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of fn(t))!mn.call(e,o)&&o!==n&&ve(e,o,{get:()=>t[o],enumerable:!(r=gn(t,o))||r.enumerable});return e};var Se=(e,t,n)=>(n=e!=null?dn(hn(e)):{},pt(t||!e||!e.__esModule?ve(n,"default",{value:e,enumerable:!0}):n,e)),wn=e=>pt(ve({},"__esModule",{value:!0}),e);var Nn={};An(Nn,{DefaultMiniAppSplash:()=>tt,MINIAPP_PLATFORM_URL:()=>be,MiniAppHost:()=>an,MiniAppHostError:()=>w,closeMiniApp:()=>ce,configureMiniApp:()=>ut,createMmkvStorage:()=>ft,createReactNativeBiometrics:()=>Fe,createRnfsFileSystem:()=>gt,ensureMiniApp:()=>we,getLocalMiniApp:()=>x,getMiniAppCatalog:()=>nn,getMiniAppCatalogEntry:()=>pe,getMiniAppStatuses:()=>zt,getMiniAppUpdate:()=>Ze,installBundledMiniApp:()=>Lt,onMiniAppEvent:()=>Wt,openMiniApp:()=>Vt,pauseMiniApp:()=>Gt,pauseMiniAppDownloads:()=>Zt,preloadMiniApp:()=>Ut,releaseSpeechFor:()=>W,restoreMiniApp:()=>Qt,resumeMiniApp:()=>Xt,resumeMiniAppDownloads:()=>en,sendEventToWeb:()=>$t,syncMiniAppCatalog:()=>Ne,uninstallMiniApp:()=>Yt,updateMiniApp:()=>tn,useMiniAppDownload:()=>Ie,useMiniAppDownloadsPaused:()=>Ht});module.exports=wn(Nn);var be="https://retion-miniapp-platform.vercel.app",oe=null,lt=new Set,ut=e=>{oe=e,lt.forEach(t=>t())},R=()=>{if(!oe)throw new Error("[miniapp] Ch\u01B0a g\u1ECDi configureMiniApp()");return oe},dt=e=>{lt.add(e),oe&&e()},$=(...e)=>{oe!=null&&oe.debug&&console.log("[miniapp]",...e)};var gt=(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(o=>o.name)).catch(()=>[]),sha256:n=>e.hash(n,"sha256"),unzip:async(n,r)=>{await t(n,r)},download:({url:n,to_file:r,onProgress:o})=>{let{jobId:s,promise:a}=e.downloadFile({fromUrl:n,toFile:r,progressInterval:250,begin:()=>{},progress:({bytesWritten:p,contentLength:i})=>o==null?void 0:o(p,i)});return{promise:a.then(({statusCode:p})=>({status:p})),cancel:()=>e.stopDownload(s)}}}),ft=e=>({getString:t=>e.getString(t),setString:(t,n)=>e.set(t,n)});var d=Se(require("react")),b=require("react-native"),sn=Se(require("react-native-webview"));var ge=require("react-native");var Fe=e=>({getAvailability:()=>e.isSensorAvailable(),authenticate:({reason:t,cancelButtonText:n})=>e.simplePrompt({promptMessage:t,cancelButtonText:n,fallbackPromptMessage:""})}),_e,Ve=()=>(_e||(_e=import("react-native-biometrics").then(({default:e})=>Fe(new e({allowDeviceCredentials:!1}))).catch(e=>{throw _e=void 0,new w("NOT_SUPPORTED",`Biometric native module unavailable: ${e instanceof Error?e.message:String(e)}`)})),_e);var ht=require("react-native");var Y,Ue=e=>{var t;if(Y===e&&(Y=void 0,e.subscriptions.forEach(n=>n.remove()),e.started&&ht.Platform.OS==="ios"))try{(t=e.native)==null||t.setAudioSessionActiveIOS(!1,{notifyOthersOnDeactivation:!0})}catch{}},mt=async(e,t,n,r=()=>!0)=>{var s,a,p,i,u;if(Y)throw new w("BUSY","Micro \u0111ang \u0111\u01B0\u1EE3c mini app kh\xE1c s\u1EED d\u1EE5ng");if(!r())throw new w("CANCELLED","Mini app kh\xF4ng c\xF2n ho\u1EA1t \u0111\u1ED9ng");let o={owner:e,emit:n,cancelled:!1,started:!1,subscriptions:[]};Y=o;try{let M;try{M=await import("expo-speech-recognition")}catch{throw new w("NOT_SUPPORTED","Ch\u01B0a c\xF3 module nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i trong b\u1EA3n native")}let m=M.ExpoSpeechRecognitionModule;if(o.native=m,o.cancelled||!r())throw new w("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");let v=await m.requestPermissionsAsync();if(o.cancelled||!r())throw new w("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");if(!v.granted)throw new w("PERMISSION_DENIED","Ch\u01B0a c\u1EA5p quy\u1EC1n micro / nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i");if(await m.getStateAsync()!=="inactive")throw new w("BUSY","Nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i \u0111ang \u0111\u01B0\u1EE3c t\xEDnh n\u0103ng kh\xE1c s\u1EED d\u1EE5ng");if(o.cancelled||!r())throw new w("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");o.subscriptions.push(M.addSpeechRecognitionListener("result",A=>{var h,C;Y!==o||o.cancelled||n(A.isFinal?"speech.final":"speech.partial",{...A,text:(C=(h=A.results[0])==null?void 0:h.transcript)!=null?C:""})}),M.addSpeechRecognitionListener("error",A=>{Y===o&&!o.cancelled&&n("speech.error",{...A,code:A.error})}),M.addSpeechRecognitionListener("end",()=>{Y===o&&(Ue(o),n("speech.end"))})),o.started=!0,m.start({lang:(s=t.lang)!=null?s:"vi-VN",continuous:(a=t.continuous)!=null?a:!0,interimResults:(p=t.interimResults)!=null?p:!0,addsPunctuation:(i=t.addsPunctuation)!=null?i:!0,requiresOnDeviceRecognition:(u=t.requiresOnDeviceRecognition)!=null?u:!1,iosCategory:{category:M.AVAudioSessionCategory.playAndRecord,categoryOptions:[M.AVAudioSessionCategoryOptions.defaultToSpeaker,M.AVAudioSessionCategoryOptions.allowBluetooth],mode:M.AVAudioSessionMode.measurement}})}catch(M){throw Ue(o),M}},At=e=>{let t=Y;if(!(!t||t.owner!==e)){if(!t.started){t.cancelled=!0;return}t.native.stop()}},W=e=>{let t=Y;if(!(!t||t.owner!==e||t.cancelled)&&(t.cancelled=!0,t.started))try{t.native.abort()}catch{Ue(t)}};var Ee=1,w=class extends Error{constructor(n,r){super(r);this.code=n}},wt=e=>{try{let t=JSON.parse(e);return(t==null?void 0:t.__retion)===Ee&&typeof t.method=="string"?t:null}catch{return null}},fe=e=>`window.__RETION_MINIAPP__ && window.__RETION_MINIAPP__.receive(${JSON.stringify(e)}); true;`,Mt=(e,t)=>fe({id:e,result:t}),yt=(e,t)=>fe({id:e,error:{code:t.code,message:t.message}}),vt=(e,t)=>fe({event:e,data:t}),je=e=>fe({event:"context",data:e});var St=()=>`(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: ${ve}, method: 'log', level: level, text: parts.join(' ') }));
11
+ window.ReactNativeWebView && window.ReactNativeWebView.postMessage(JSON.stringify({ __retion: ${Ee}, 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;`,ft=()=>`(function () {
22
+ })(); true;`,bt=()=>`(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: ${ve}, method: 'touchAtTop', at_top: at_top }));
33
+ window.ReactNativeWebView && window.ReactNativeWebView.postMessage(JSON.stringify({ __retion: ${Ee}, 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;`,ht=e=>_e({event:e}),mt=(e,t)=>{let n=At(t);return`try { history.replaceState(history.state, '', location.pathname + ${JSON.stringify(n?`?${n}`:"")} + location.hash); } catch (e) {}
42
- ${Ue(e)}`},At=e=>Object.entries(e).filter(([,t])=>t!=null&&t!=="").map(([t,n])=>`${encodeURIComponent(t)}=${encodeURIComponent(String(n))}`).join("&"),Mt=(e,t={})=>{let n=At(t);return`window.__RETION_MINIAPP_HOST__ = { protocol: ${ve} };
41
+ })(); true;`,_t=e=>fe({event:e}),xt=(e,t)=>{let n=Et(t);return`try { history.replaceState(history.state, '', location.pathname + ${JSON.stringify(n?`?${n}`:"")} + location.hash); } catch (e) {}
42
+ ${je(e)}`},Et=e=>Object.entries(e).filter(([,t])=>t!=null&&t!=="").map(([t,n])=>`${encodeURIComponent(t)}=${encodeURIComponent(String(n))}`).join("&"),Rt=(e,t={})=>{let n=Et(t);return`window.__RETION_MINIAPP_HOST__ = { protocol: ${Ee} };
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;`},yt={partner:"partner_token",chatbox:"chatbox_token"},wt=(e,t)=>{let n={...e};for(let r of Object.values(yt))t.includes(r)||delete n[r];return n},$e=new Set,Fe=async(e,t)=>{if($e.has(e))throw new M("BUSY",`${e} \u0111ang ch\u1EA1y \u2014 ch\u1EDD l\u01B0\u1EE3t tr\u01B0\u1EDBc xong`);$e.add(e);try{return await t()}finally{$e.delete(e)}},un=new Set(["selection","impactLight","impactMedium","impactHeavy","rigid","soft","notificationSuccess","notificationWarning","notificationError"]),we=(e,t)=>{if(typeof e!="string"||!e)throw new M("INVALID_PARAMS",`Thi\u1EBFu ${t}`);return e},vt=async({method:e,params:t},{getHostData:n,getPermissions:r,is_dark:s,close:o,app_id:a,instance_id:u,options:i})=>{var v,A,h,F,T,D,l,C,ae;let p=i==null?void 0:i.handlers,y={app_id:a,instance_id:u,close:o},w=()=>new M("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF \u1EE9ng d\u1EE5ng n\xE0y`);switch(e){case"getBiometricAvailability":return((v=i==null?void 0:i.biometrics)!=null?v:await Ne()).getAvailability();case"authenticateBiometric":{let g=we(t==null?void 0:t.reason,"reason").trim();if(!g||g.length>200)throw new M("INVALID_PARAMS","reason must contain 1\u2013200 characters");let E=t==null?void 0:t.cancelButtonText;if(E!==void 0&&(typeof E!="string"||!E.trim()||E.length>80))throw new M("INVALID_PARAMS","Invalid cancelButtonText");return Fe(e,async()=>{var Z;return((Z=i==null?void 0:i.biometrics)!=null?Z:await Ne()).authenticate({reason:g,cancelButtonText:E})})}case"requestPayment":{let g=p==null?void 0:p.requestPayment;if(!g)throw w();let E=t==null?void 0:t.amount;if(typeof E!="number"||!Number.isFinite(E)||E<=0)throw new M("INVALID_PARAMS","amount ph\u1EA3i l\xE0 s\u1ED1 > 0");let z={...t,amount:E,currency:we(t==null?void 0:t.currency,"currency")};return Fe(e,()=>g(z,y))}case"printImage":{let g=p==null?void 0:p.printImage;if(!g)throw w();let E=we(t==null?void 0:t.image,"image");await Fe(e,()=>g({image:E},y));return}case"openScreen":if(!(p!=null&&p.openScreen))throw w();await p.openScreen({screen:we(t==null?void 0:t.screen,"screen"),params:t==null?void 0:t.params},y);return;case"closeApp":o();return;case"openWebview":{let g=String((A=t==null?void 0:t.url)!=null?A:"");if(!/^https?:\/\//i.test(g))throw new M("INVALID_PARAMS","url ph\u1EA3i l\xE0 http(s)");await(i!=null&&i.openUrl?i.openUrl(g):le.Linking.openURL(g));return}case"openLink":{let g=String((h=t==null?void 0:t.url)!=null?h:"").trim();if(!/^[a-z][a-z0-9+.-]*:/i.test(g)||/^(javascript|file|data|about|blob):/i.test(g))throw new M("INVALID_PARAMS","url kh\xF4ng h\u1EE3p l\u1EC7");try{await(i!=null&&i.openUrl?i.openUrl(g):le.Linking.openURL(g))}catch(E){throw new M("NOT_SUPPORTED",String((T=(F=E==null?void 0:E.message)!=null?F:E)!=null?T:"Kh\xF4ng m\u1EDF \u0111\u01B0\u1EE3c link"))}return}case"showToast":(l=i==null?void 0:i.showToast)==null||l.call(i,String((D=t==null?void 0:t.message)!=null?D:""));return;case"haptic":{let g=un.has(t==null?void 0:t.type)?t.type:"selection";(C=i==null?void 0:i.haptic)==null||C.call(i,g);return}case"getSystemInfo":return{platform:le.Platform.OS==="ios"?"ios":"android",appVersion:(ae=i==null?void 0:i.app_version)!=null?ae:"",theme:s?"dark":"light"};case"getAccessToken":{let g=n().access_token;if(!g)throw new M("HOST_ERROR","Mini app ch\u01B0a c\xF3 token cho page n\xE0y");return g}case"getToken":{let g=t==null?void 0:t.type;if(g==="access"){let Z=n().access_token;if(!Z)throw new M("HOST_ERROR","Mini app ch\u01B0a c\xF3 token cho page n\xE0y");return Z}if(g!=="partner"&&g!=="chatbox")throw new M("HOST_ERROR",`Lo\u1EA1i token kh\xF4ng h\u1EE3p l\u1EC7: ${String(g)}`);let E=yt[g];if(!r().includes(E))throw new M("PERMISSION_DENIED",`Mini app ch\u01B0a \u0111\u01B0\u1EE3c c\u1EA5p quy\u1EC1n ${E} (Console \u2192 Quy\u1EC1n l\u1EA5y token)`);let z=g==="partner"?n().partner_token:n().chatbox_token;if(!z)throw new M("HOST_ERROR",`Kh\xF4ng c\xF3 ${E}`);return z}case"getUserInfo":{let g=n().user;if(!g)throw new M("HOST_ERROR","Kh\xF4ng l\u1EA5y \u0111\u01B0\u1EE3c th\xF4ng tin nh\xE2n vi\xEAn");return g}case"getPageInfo":{let g=n().page;if(!g)throw new M("HOST_ERROR","Kh\xF4ng l\u1EA5y \u0111\u01B0\u1EE3c th\xF4ng tin page");return g}case"sendMessage":case"insertText":throw new M("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF phi\xEAn b\u1EA3n app n\xE0y`);default:throw new M("NOT_SUPPORTED",`API kh\xF4ng t\u1ED3n t\u1EA1i: ${e}`)}};var Ve=e=>`bundle:${e}`,He=()=>`${P().file_system.document_dir}/miniapps`,We=He,je=(e,t,n="index.html",r=!1,s=[])=>{let o=`${We()}/${e}/${t}`;return{app_id:e,version:t,dir:o,entry_uri:`file://${o}/${n}`,context_update:r,permissions:s}},Je=e=>{var t;P().storage.setString(Ve(e.app_id),JSON.stringify({version:e.version,entry:e.entry,context_update:!!e.context_update,permissions:(t=e.permissions)!=null?t:[]}))},dn=(e,t)=>/^https?:\/\//.test(t)?t:`${e.replace(/[^/]*$/,"")}${t}`,b=e=>{let t=P().storage.getString(Ve(e));if(!t)return null;try{let{version:n,entry:r,context_update:s,permissions:o}=JSON.parse(t);return je(e,n,r,!!s,Array.isArray(o)?o:[])}catch{return null}},q=e=>P().file_system.exists(e.entry_uri.replace("file://","")),qe=async e=>{let t=b(e.app_id);return(t==null?void 0:t.version)===e.version&&await q(t)},St=async(e,t)=>{let n=P().file_system,r=`${We()}/${e}`,s=await n.listDir(r).catch(()=>[]);await Promise.all(s.filter(o=>!t.includes(o)).map(o=>n.remove(`${r}/${o}`).catch(()=>{})))},bt=async e=>{var t;await((t=de[e])==null?void 0:t.catch(()=>{})),P().storage.setString(Ve(e),""),await P().file_system.remove(`${We()}/${e}`).catch(()=>{})},ie=class extends Error{constructor(){super("cancelled"),this.name="MiniAppInstallCancelled"}},de={},xt=(e,t)=>{var o;let r=((o=de[e])!=null?o:Promise.resolve()).catch(()=>{}).then(t),s=r.catch(()=>{});return de[e]=s,s.then(()=>{de[e]===s&&delete de[e]}),r},gn=(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},Et=({manifest:e,zip_path:t})=>xt(e.app_id,async()=>{var o;let n=P().file_system,r=b(e.app_id);if(r&&gn(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=je(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),Je(e),N("\u0111\xE3 c\xE0i b\u1EA3n \u0111\xF3ng s\u1EB5n",e.app_id,e.version),St(e.app_id,[e.version,r==null?void 0:r.version].filter(Boolean)),s}),Ke=(e,{base_url:t,onProgress:n}={})=>{let r=P().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 w;u();let p=b(e.app_id);if((p==null?void 0:p.version)===e.version&&await r.exists(p.dir))return Je(e),b(e.app_id);u();let y=r.download({url:t?dn(t,e.bundle_url):e.bundle_url,to_file:a,onProgress:(v,A)=>{var F;let h=A>0?A:(F=e.size)!=null?F:0;h>0&&(n==null||n(Math.min(1,v/h)))}});s=y;try{let{status:v}=await y.promise;if(u(),v!==200)throw new Error(`bundle ${v}`);if(e.sha256)if(r.sha256){if(await r.sha256(a)!==e.sha256)throw new Error("sha256 mismatch")}else N("b\u1ECF qua ki\u1EC3m tra sha256 (file_system kh\xF4ng c\xF3 sha256)",e.app_id);u();let A=je(e.app_id,e.version,e.entry,!!e.context_update,(w=e.permissions)!=null?w:[]);return await r.remove(A.dir).catch(()=>{}),await r.mkdir(A.dir),await r.unzip(a,A.dir),Je(e),St(e.app_id,[e.version,p==null?void 0:p.version].filter(Boolean)),A}catch(v){throw o?new ie:v}finally{s=null,r.remove(a).catch(()=>{})}};return{promise:xt(e.app_id,i),cancel:()=>{o=!0,s==null||s.cancel()}}},ue={},fn=__DEV__?0:60*1e3,_t={},Pt=(e,t)=>{var r,s;let n=b(e);return n&&Date.now()-((r=_t[t])!=null?r:0)<fn?Promise.resolve(n):((s=ue[e])!=null||(ue[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 Ke(a,{base_url:t}).promise;return _t[t]=Date.now(),u})().catch(o=>(console.warn("[miniapp] sync failed",e,o==null?void 0:o.message),b(e))).finally(()=>{ue[e]=void 0})),ue[e])};var Se=new Map,Rt=(e,t)=>(Se.set(e,t),()=>{Se.get(e)===t&&Se.delete(e)}),Tt=(e,t)=>{let n=Se.get(e);return n?n(t):!1};var be=require("react"),xe=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,be.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,be.useSyncExternalStore)(e.subscribe,s)};var J=xe({active_key:null,instances:{}}),kt=({app:e,instance_id:t,context:n={},url_params:r={},host_data:s={}},o)=>{var u;let a=(u=P().keep_alive)==null?void 0:u.max_webviews;J.setState(i=>{let p=t!=null?t:e.app_id,y={...i.instances,[p]:{key:p,app:e,context:n,url_params:r,host_data:s,last_used_at:Date.now()}},w=Object.keys(y);return a&&a>0&&w.length>a&&w.filter(v=>v!==p).sort((v,A)=>y[v].last_used_at-y[A].last_used_at).slice(0,w.length-a).forEach(v=>{delete y[v]}),o?{active_key:p,instances:y}:{instances:y}})},Ct=e=>kt(e,!0),Ot=e=>kt(e,!1),oe=()=>J.setState({active_key:null}),Ee=e=>{J.setState(t=>{if(t.active_key===e||!t.instances[e])return{};let n={...t.instances};return delete n[e],{instances:n}})};var It="catalog",hn="paused_apps",mn="removed_apps",An=10*1e3,Mn=2,yn=3e3,wn=()=>{var e;try{return JSON.parse((e=P().storage.getString(It))!=null?e:"{}")}catch{return{}}},_=xe({catalog:{},downloads:{},pause_reasons:[],updates:{},apply_ticks:{}}),Dt=e=>{var t;return!!((t=P().manual_update)!=null&&t.includes(e))},Te=new Set,Lt=e=>{let t=new Set,n=()=>P().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=P().storage.getString(e))!=null?r:"[]");Array.isArray(s)&&s.forEach(o=>{typeof o=="string"&&t.add(o)})}catch{}}}},H=Lt(hn),X=Lt(mn);at(()=>{H.load(),X.load();let e=wn(),t={};Object.keys(e).filter(n=>!X.has(n)).forEach(n=>{let r=b(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})}),_.setState({catalog:e,downloads:t})});var ke=e=>j(_,t=>e?t.downloads[e]:void 0),Bt=()=>j(_,e=>e.pause_reasons.length>0),V=(...e)=>N("queue",...e),k=[],K={},m=null,Pe=new Set,re={},ze=new Set,Q=e=>{ze.forEach(t=>{try{t(e)}catch(n){console.warn("[miniapp-queue] event listener error",n==null?void 0:n.message)}})},Nt=e=>(ze.add(e),()=>{ze.delete(e)}),$t=()=>_.getState().downloads,I=(e,t)=>{let n=!!b(e),r=_.getState().downloads[e],s=t.status==="downloading"&&n?"updating":t.status,o={...r!=null?r:{status:"queued",progress:0},...t,...s?{status:s}:{},has_local:n};_.setState(a=>({downloads:{...a.downloads,[e]:o}})),(r==null?void 0:r.status)!==o.status||(r==null?void 0:r.version)!==o.version||(r==null?void 0:r.has_local)!==o.has_local?Q({type:"status_change",app_id:e,state:o}):r.progress!==o.progress&&Q({type:"progress",app_id:e,progress:o.progress,version:o.version})},Re=(e,t)=>{var n;(n=re[e])==null||n.forEach(r=>r(t)),delete re[e]},vn=()=>_.getState().pause_reasons.length>0,G=e=>{var u;if(m)return;let t=e?k.indexOf(e):vn()?-1:k.findIndex(i=>!H.has(i));if(t<0||t>=k.length)return;let[n]=k.splice(t,1),r=_.getState().catalog[n];if(!r){Re(n,b(n)),G();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=Ke(r,{onProgress:i=>{let p=Math.floor(i*100);p!==o&&(o=p,I(n,{progress:p/100,version:r.version}))}});m={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}),Re(n,i)}).catch(i=>{var y;if(i instanceof ie){if(Pe.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 p=String((y=i==null?void 0:i.message)!=null?y:i);if(console.warn("[miniapp-queue] failed",n,p),K[n]<Mn){I(n,{status:"queued",progress:0,version:r.version,error:p}),setTimeout(()=>{var w;k.includes(n)||(m==null?void 0:m.app_id)===n||(k.push(n),G((w=re[n])!=null&&w.length?n:void 0))},yn);return}I(n,{status:"failed",progress:0,version:r.version,error:p}),Re(n,b(n))}).finally(()=>{m=null;let i=k.find(p=>{var y;return(y=re[p])==null?void 0:y.length});G(i)})},Ce=(e,{front:t=!1}={})=>{if((m==null?void 0:m.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)},_n=async e=>{let{host_id:t,client_token:n}=P(),r=new AbortController,s=setTimeout(()=>r.abort(),An);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)}},ge=null,Oe=()=>(ge!=null||(ge=(async()=>{var t;let e=Date.now();try{let n=await Promise.all(P().channels.map(_n)),r={};[...n].reverse().flat().forEach(i=>{r[i.app_id]=i});let s=Object.keys(_.getState().catalog).filter(i=>!r[i]);P().storage.setString(It,JSON.stringify(r)),_.setState({catalog:r}),await Promise.all(s.map(i=>Ft(i,{by_user:!1}))),s.forEach(i=>X.delete(i));let o=Object.keys(r).filter(i=>!X.has(i)),a=[],u={};for(let i of o.map(p=>r[p])){if(await qe(i)){I(i.app_id,{status:"installed",progress:1,version:i.version});continue}let p=b(i.app_id);if(Dt(i.app_id)&&!Te.has(i.app_id)&&p&&await q(p)){I(i.app_id,{status:"installed",progress:1,version:p.version}),u[i.app_id]={app_id:i.app_id,current_version:p.version,next_version:i.version};continue}a.push(i)}return _.setState({updates:u}),a.forEach(i=>{K[i.app_id]=0,I(i.app_id,{status:H.has(i.app_id)?"paused":"queued",progress:0,version:i.version,error:void 0}),Ce(i.app_id)}),V("catalog",o.length,"apps, outdated",a.map(i=>i.app_id),"removed",s,`${Date.now()-e}ms`),Q({type:"sync_complete",app_ids:o,removed:s}),Object.values(u).forEach(i=>Q({type:"update_available",...i})),G(),{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),Q({type:"sync_failed",error:r}),{ok:!1,error:r}}finally{ge=null}})()),ge),Ft=async(e,{by_user:t})=>{var s,o,a,u;if(t&&X.add(e),Pe.has(e))return;Pe.add(e),H.delete(e);let n=k.indexOf(e);n>=0&&k.splice(n,1),(m==null?void 0:m.app_id)===e&&m.handle.cancel();let r=(u=(a=(s=_.getState().downloads[e])==null?void 0:s.version)!=null?a:(o=b(e))==null?void 0:o.version)!=null?u:"";I(e,{status:"uninstalling",progress:0,version:r}),await bt(e),Ee(e),_.setState(i=>{let p={...i.downloads};return delete p[e],{downloads:p}}),delete K[e],Pe.delete(e),Re(e,null),V("uninstalled",e,t?"(user)":"(not in list)"),Q({type:"uninstalled",app_id:e})},Ut=e=>Ft(e,{by_user:!0}),Jt=e=>{let t=se(e);return t?(X.delete(e),(m==null?void 0:m.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}),Ce(e),G(),V("restore",e)),!0):!1},Vt=e=>{if(H.has(e))return;if(H.add(e),V("pause app",e),(m==null?void 0:m.app_id)===e&&!m.forced){m.handle.cancel();return}let t=_.getState().downloads[e];k.includes(e)&&t&&I(e,{status:"paused",progress:0,version:t.version})},Ht=e=>{if(!H.delete(e))return;V("resume app",e);let t=_.getState().downloads[e];(t==null?void 0:t.status)==="paused"&&!k.includes(e)&&se(e)&&(K[e]=0,Ce(e)),k.includes(e)&&t&&I(e,{status:"queued",progress:0,version:t.version}),G()},Wt=e=>{let{pause_reasons:t}=_.getState();t.includes(e)||(_.setState({pause_reasons:[...t,e]}),V("pause",e),t.length===0&&Q({type:"pause_change",paused:!0,reasons:[e]}),m&&!m.forced&&m.handle.cancel())},jt=e=>{let{pause_reasons:t}=_.getState();if(!t.includes(e))return;let n=t.filter(r=>r!==e);_.setState({pause_reasons:n}),V("resume",e),n.length===0&&Q({type:"pause_change",paused:!1,reasons:n}),G()},Ye=e=>_.getState().updates[e],qt=async e=>{var n,r;let t=Ye(e);Te.add(e);try{let s=await fe(e),o=(r=t==null?void 0:t.next_version)!=null?r:(n=se(e))==null?void 0:n.version;return!s||!o||s.version!==o?!1:(_.setState(a=>{var i;let u={...a.updates};return delete u[e],{updates:u,apply_ticks:{...a.apply_ticks,[e]:((i=a.apply_ticks[e])!=null?i:0)+1}}}),V("updated",e,t==null?void 0:t.current_version,"\u2192",s.version),!0)}finally{Te.delete(e)}},Kt=()=>Object.values(_.getState().catalog).map(e=>({...e,installed:!!b(e.app_id),removed_by_user:X.has(e.app_id)})),se=e=>_.getState().catalog[e],fe=async e=>{let t=se(e);if(!t)return;if(H.delete(e),X.delete(e),await qe(t))return b(e);let n=b(e);if(Dt(e)&&!Te.has(e)&&n&&await q(n))return n;let r=new Promise(s=>{var o;((o=re[e])!=null?o:re[e]=[]).push(s)});return(m==null?void 0:m.app_id)===e?m.forced=!0:(K[e]=0,Ce(e,{front:!0}),m&&!m.forced?m.handle.cancel():G(e)),r};var x=require("react/jsx-runtime"),Qe=e=>(e!=null?e:"").replace(/\?[^#]*/,""),zt=0,Sn=()=>{let e=new Set;return{emit:t=>e.forEach(n=>n(t)),subscribe:t=>(e.add(t),()=>{e.delete(t)})}},bn=d.default.memo(({instance_key:e,is_active:t,is_front:n,is_dark:r,reload_tick:s,web_at_top:o,splash:a,bridge:u,opaque_background:i,allow_embedded_miniapps:p,onWebLoadEnd:y})=>{var nt,rt;let w=(0,d.useRef)(null),v=(0,d.useRef)(!1),A=j(J,c=>c.instances[e]),h=A==null?void 0:A.app.app_id,F=A==null?void 0:A.app.manifest_url,T=A==null?void 0:A.context,D=A==null?void 0:A.url_params,[l,C]=(0,d.useState)(()=>h?b(h):null),[ae,g]=(0,d.useState)(!1),[E,z]=(0,d.useState)(0),[Z,ce]=(0,d.useState)(0),[Xt,L]=(0,d.useState)(!1),W=(0,d.useRef)(null),Xe=c=>{W.current&&clearTimeout(W.current),W.current=setTimeout(()=>{W.current=null,L(!0)},c)};(0,d.useEffect)(()=>()=>{W.current&&clearTimeout(W.current)},[]),(0,d.useEffect)(()=>{if(!h||!t&&l)return;let c=!0;return g(!1),(async()=>{let f=b(h),O=f?await q(f):!1;if(!c||(C(O?U=>!U||U.version!==f.version||U.permissions.join(",")!==f.permissions.join(",")?f:U:null),__DEV__&&Date.now()-zt>1e4&&(zt=Date.now(),await Oe()),!c))return;let Y=await fe(h),ee=Y!==void 0?Y:F?await Pt(h,F):b(h);if(c){if(!ee){g(!0);return}C(U=>U!=null?U:ee)}})(),()=>{c=!1}},[t,h,F,E]),(0,d.useEffect)(()=>Rt(e,c=>w.current?(w.current.postMessage(c),!0):!1),[e]);let Zt=j(_,c=>{let f=h?c.downloads[h]:void 0;return(f==null?void 0:f.status)==="installed"?f.version:void 0});(0,d.useEffect)(()=>{if(t||!h||!l)return;let c=b(h);if(!c||c.version===l.version)return;let f=!0;return q(c).then(O=>{!f||!O||(N(`webview:${e}`,"\u0111\u1ED5i bundle (\u1EA9n)",l.version,"\u2192",c.version),C(c))}),()=>{f=!1}},[t,h,Zt,l==null?void 0:l.version]);let Ze=j(_,c=>{var f;return h&&(f=c.apply_ticks[h])!=null?f:0});(0,d.useEffect)(()=>{if(!Ze||!h)return;let c=b(h);if(!c||c.version===(l==null?void 0:l.version))return;let f=!0;return q(c).then(O=>{!f||!O||(N(`webview:${e}`,"c\u1EADp nh\u1EADt",l==null?void 0:l.version,"\u2192",c.version),L(!1),C(c))}),()=>{f=!1}},[Ze]),(0,d.useEffect)(()=>{var O;let c=(O=P().keep_alive)==null?void 0:O.idle_close_ms;if(t||!c||c<=0)return;let f=setTimeout(()=>{Ee(e)},c);return()=>clearTimeout(f)},[t,e]),(0,d.useEffect)(()=>{s>0&&(g(!1),L(!1),ce(c=>c+1),z(c=>c+1))},[s]);let et=(0,d.useRef)(t);(0,d.useEffect)(()=>{var c;et.current!==t&&(et.current=t,v.current&&((c=w.current)==null||c.injectJavaScript(ht(t?"resumed":"paused"))))},[t]);let he=`${(nt=l==null?void 0:l.version)!=null?nt:"none"}:${(rt=l==null?void 0:l.permissions.join(","))!=null?rt:""}:${Z}`,pe=(0,d.useMemo)(()=>JSON.stringify([T!=null?T:{},D!=null?D:{}]),[T,D]),Ie=(0,d.useMemo)(()=>{var c;return wt(D!=null?D:{},(c=l==null?void 0:l.permissions)!=null?c:[])},[pe,l==null?void 0:l.permissions]),en=(0,d.useMemo)(()=>Mt(T!=null?T:{},Ie)+ft()+(P().debug?gt():""),[Ie]),me=(0,d.useRef)(null),tt=(0,d.useRef)(null);(0,d.useEffect)(()=>{var f,O,Y;if(!l)return;if(tt.current!==he){tt.current=he,me.current=pe;return}if(me.current===pe)return;let c=((O=JSON.parse((f=me.current)!=null?f:"[]")[0])!=null?O:{}).org_id;if(me.current=pe,c===(T==null?void 0:T.org_id)&&v.current){L(!1),Xe(1500),(Y=w.current)==null||Y.injectJavaScript(mt(T!=null?T:{},Ie));return}L(!1),ce(ee=>ee+1)},[pe,l,he]);let tn=(0,d.useCallback)(async c=>{var O,Y,ee,U,De;let f=lt(c.nativeEvent.data);if(!f){if(h&&(u!=null&&u.onWebEvent))try{Promise.resolve(u.onWebEvent(c.nativeEvent.data,{app_id:h,instance_id:e})).catch(R=>{console.warn("[miniapp] onWebEvent l\u1ED7i",h,R)})}catch(R){console.warn("[miniapp] onWebEvent l\u1ED7i",h,R)}return}if(f.method==="log"){let{level:R,text:B}=f;N(`web:${e}`,R!=null?R:"log",B!=null?B:"");return}if(f.method==="pong"){W.current||L(!0);return}if(f.method==="touchAtTop"){o.emit(!!f.at_top);return}if(f.method==="contextApplied"){W.current&&clearTimeout(W.current),W.current=null,L(!0);return}if(f.method==="ready"){v.current=!0,L(!0);let R=(O=J.getState().instances[e])==null?void 0:O.context;R&&((Y=w.current)==null||Y.injectJavaScript(Ue(R)));return}try{let R=await vt(f,{getHostData:()=>{var B,te;return(te=(B=J.getState().instances[e])==null?void 0:B.host_data)!=null?te:{}},getPermissions:()=>{var B,te;return h?(te=(B=b(h))==null?void 0:B.permissions)!=null?te:[]:[]},is_dark:r,close:oe,app_id:h!=null?h:"",instance_id:e,options:u});f.id&&((ee=w.current)==null||ee.injectJavaScript(ut(f.id,R)))}catch(R){if(!f.id)return;let B=R==null?void 0:R.code,te=R instanceof M?R:new M(typeof B=="string"?B:"HOST_ERROR",String((U=R==null?void 0:R.message)!=null?U:R));(De=w.current)==null||De.injectJavaScript(dt(f.id,te))}},[e,r,h,o,u]),nn=(0,d.useCallback)(()=>{g(!1),ce(c=>c+1),z(c=>c+1)},[]);return(0,x.jsxs)(S.View,{style:[S.StyleSheet.absoluteFill,i&&{backgroundColor:r?"#09090B":"#FFFFFF"},!n&&$.behind],pointerEvents:t?"auto":"none",children:[l?(0,x.jsx)(Qt.default,{ref:w,source:{uri:l.entry_uri},originWhitelist:["*"],allowingReadAccessToURL:`file://${p?He():l.dir}`,allowFileAccess:!0,allowFileAccessFromFileURLs:!0,allowUniversalAccessFromFileURLs:!0,injectedJavaScriptBeforeContentLoaded:en,onMessage:tn,bounces:!1,overScrollMode:"never",onLoadStart:c=>{N(`webview:${e}`,"load start",Qe(c.nativeEvent.url)),v.current=!1,L(!1)},onError:c=>{N(`webview:${e}`,"load error",Qe(c.nativeEvent.url),c.nativeEvent.description),g(!0),L(!1)},onLoadEnd:c=>{let f=c.nativeEvent.url;N(`webview:${e}`,"load end",Qe(f)),h&&(y==null||y({app_id:h,instance_id:e,url:f})),Xe(1500)},onContentProcessDidTerminate:()=>{v.current=!1,L(!1),ce(c=>c+1)},onRenderProcessGone:()=>(v.current=!1,L(!1),ce(c=>c+1),!0),style:$.webview},he):null,A&&(0,x.jsx)(En,{visible:!l||!Xt,interactive:ae,children:(0,x.jsx)(xn,{splash:a,app:A.app,is_dark:r,error:ae,has_bundle:!!l,retry:nn})})]})}),xn=d.default.memo(({splash:e,app:t,is_dark:n,error:r,has_bundle:s,retry:o})=>{let a=e,u=ke(t.app_id),i=r?"error":!s&&(u==null?void 0:u.status)==="downloading"?"downloading":"loading";return(0,x.jsx)(a,{app:t,is_dark:n,status:i,progress:i==="downloading"?u==null?void 0:u.progress:void 0,retry:o})}),En=({visible:e,interactive:t,children:n})=>{let r=(0,d.useRef)(new S.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=S.Animated.timing(r,{toValue:0,duration:180,useNativeDriver:!0});return a.start(({finished:u})=>{u&&o(!1)}),()=>a.stop()},[e,r]),s?(0,x.jsx)(S.Animated.View,{style:[S.StyleSheet.absoluteFill,{opacity:r}],pointerEvents:t?"auto":"none",children:n}):null},Ge=({app:e,is_dark:t,status:n,progress:r,retry:s})=>{let o=t?"#FAFAFA":"#18181B";return(0,x.jsxs)(S.View,{style:[$.splash,{backgroundColor:t?"#09090B":"#FFFFFF"}],children:[(0,x.jsx)(S.View,{style:[$.splash_icon,{backgroundColor:t?"#18181B":"#F4F4F5"}],children:e.icon?(0,x.jsx)(S.Image,{source:{uri:e.icon},style:$.splash_icon_image}):(0,x.jsx)(S.Text,{style:$.splash_letter,children:(e.name||"?").slice(0,1).toUpperCase()})}),(0,x.jsx)(S.Text,{style:[$.splash_name,{color:o}],children:e.name}),n==="error"?(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(S.Text,{style:$.splash_hint,children:"Kh\xF4ng t\u1EA3i \u0111\u01B0\u1EE3c mini app"}),(0,x.jsx)(S.TouchableOpacity,{activeOpacity:.7,style:[$.retry_button,{backgroundColor:t?"#27272A":"#F4F4F5"}],onPress:s,children:(0,x.jsx)(S.Text,{style:[$.retry_text,{color:o}],children:"Th\u1EED l\u1EA1i"})})]}):(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(S.ActivityIndicator,{style:$.splash_spinner,color:t?"#A1A1AA":"#71717A"}),n==="downloading"&&(0,x.jsxs)(S.Text,{style:$.splash_hint,children:["\u0110ang t\u1EA3i mini app",r?` ${Math.round(r*100)}%`:"\u2026"]})]})]})},Yt=(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.`))},Pn=({container:e,splash:t=Ge,is_dark:n=!1,bridge:r,close_on_back:s=!0,opaque_background:o=!0,allow_embedded_miniapps:a=!1,onWebLoadEnd:u})=>{Yt("container",e),Yt("splash",t);let i=e,p=j(J,l=>l.active_key),y=(0,d.useRef)(p);p&&(y.current=p);let w=j(J,l=>Object.keys(l.instances).join("|")),v=j(J,l=>{var C;return l.active_key?(C=l.instances[l.active_key])==null?void 0:C.app.name:void 0}),A=(0,d.useMemo)(()=>w?w.split("|"):[],[w]),[h,F]=(0,d.useState)({}),T=(0,d.useRef)(Sn()).current;(0,d.useEffect)(()=>{if(!p||!s)return;let l=S.BackHandler.addEventListener("hardwareBackPress",()=>(oe(),!0));return()=>l.remove()},[p,s]);let D=(0,d.useCallback)(()=>{let l=J.getState().active_key;l&&F(C=>({...C,[l]:(C[l]||0)+1}))},[]);return A.length?(0,x.jsx)(i,{visible:!!p,title:v!=null?v:"",is_dark:n,close:oe,reload:D,subscribeWebAtTop:T.subscribe,children:A.map(l=>(0,x.jsx)(bn,{instance_key:l,is_active:p===l,is_front:(p!=null?p:y.current)===l,is_dark:n,reload_tick:h[l]||0,web_at_top:T,splash:t,bridge:r,opaque_background:o,allow_embedded_miniapps:a,onWebLoadEnd:u},l))}):null},$=S.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"}}),Gt=d.default.memo(Pn);0&&(module.exports={DefaultMiniAppSplash,MINIAPP_PLATFORM_URL,MiniAppHost,MiniAppHostError,closeMiniApp,configureMiniApp,createMmkvStorage,createReactNativeBiometrics,createRnfsFileSystem,ensureMiniApp,getLocalMiniApp,getMiniAppCatalog,getMiniAppCatalogEntry,getMiniAppStatuses,getMiniAppUpdate,installBundledMiniApp,onMiniAppEvent,openMiniApp,pauseMiniApp,pauseMiniAppDownloads,preloadMiniApp,restoreMiniApp,resumeMiniApp,resumeMiniAppDownloads,sendEventToWeb,syncMiniAppCatalog,uninstallMiniApp,updateMiniApp,useMiniAppDownload,useMiniAppDownloadsPaused});
45
+ true;`},Pt={partner:"partner_token",chatbox:"chatbox_token"},Tt=(e,t)=>{let n={...e};for(let r of Object.values(Pt))t.includes(r)||delete n[r];return n},Je=new Set,qe=async(e,t)=>{if(Je.has(e))throw new w("BUSY",`${e} \u0111ang ch\u1EA1y \u2014 ch\u1EDD l\u01B0\u1EE3t tr\u01B0\u1EDBc xong`);Je.add(e);try{return await t()}finally{Je.delete(e)}},Mn=new Set(["selection","impactLight","impactMedium","impactHeavy","rigid","soft","notificationSuccess","notificationWarning","notificationError"]),xe=(e,t)=>{if(typeof e!="string"||!e)throw new w("INVALID_PARAMS",`Thi\u1EBFu ${t}`);return e},Ot=async({method:e,params:t},{getHostData:n,getPermissions:r,is_dark:o,close:s,app_id:a,instance_id:p,options:i,emit:u,isActive:M})=>{var h,C,T,N,l,k,le,X,Me;let m=i==null?void 0:i.handlers,v={app_id:a,instance_id:p,close:s},A=()=>new w("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF \u1EE9ng d\u1EE5ng n\xE0y`);switch(e){case"speech.start":{if(!u)throw A();let g={};if((t==null?void 0:t.lang)!==void 0){if(typeof t.lang!="string"||!/^[a-zA-Z]{2,8}(-[a-zA-Z0-9]{1,8})*$/.test(t.lang))throw new w("INVALID_PARAMS","lang ph\u1EA3i l\xE0 m\xE3 ng\xF4n ng\u1EEF nh\u01B0 vi-VN");g.lang=t.lang}for(let S of["continuous","interimResults","addsPunctuation","requiresOnDeviceRecognition"])if((t==null?void 0:t[S])!==void 0){if(typeof t[S]!="boolean")throw new w("INVALID_PARAMS",`${S} ph\u1EA3i l\xE0 boolean`);g[S]=t[S]}return mt(p,g,u,M)}case"speech.stop":return At(p);case"getBiometricAvailability":return((h=i==null?void 0:i.biometrics)!=null?h:await Ve()).getAvailability();case"authenticateBiometric":{let g=xe(t==null?void 0:t.reason,"reason").trim();if(!g||g.length>200)throw new w("INVALID_PARAMS","reason must contain 1\u2013200 characters");let S=t==null?void 0:t.cancelButtonText;if(S!==void 0&&(typeof S!="string"||!S.trim()||S.length>80))throw new w("INVALID_PARAMS","Invalid cancelButtonText");return qe(e,async()=>{var re;return((re=i==null?void 0:i.biometrics)!=null?re:await Ve()).authenticate({reason:g,cancelButtonText:S})})}case"requestPayment":{let g=m==null?void 0:m.requestPayment;if(!g)throw A();let S=t==null?void 0:t.amount;if(typeof S!="number"||!Number.isFinite(S)||S<=0)throw new w("INVALID_PARAMS","amount ph\u1EA3i l\xE0 s\u1ED1 > 0");let U={...t,amount:S,currency:xe(t==null?void 0:t.currency,"currency")};return qe(e,()=>g(U,v))}case"printImage":{let g=m==null?void 0:m.printImage;if(!g)throw A();let S=xe(t==null?void 0:t.image,"image");await qe(e,()=>g({image:S},v));return}case"openScreen":if(!(m!=null&&m.openScreen))throw A();await m.openScreen({screen:xe(t==null?void 0:t.screen,"screen"),params:t==null?void 0:t.params},v);return;case"closeApp":s();return;case"openWebview":{let g=String((C=t==null?void 0:t.url)!=null?C:"");if(!/^https?:\/\//i.test(g))throw new w("INVALID_PARAMS","url ph\u1EA3i l\xE0 http(s)");await(i!=null&&i.openUrl?i.openUrl(g):ge.Linking.openURL(g));return}case"openLink":{let g=String((T=t==null?void 0:t.url)!=null?T:"").trim();if(!/^[a-z][a-z0-9+.-]*:/i.test(g)||/^(javascript|file|data|about|blob):/i.test(g))throw new w("INVALID_PARAMS","url kh\xF4ng h\u1EE3p l\u1EC7");try{await(i!=null&&i.openUrl?i.openUrl(g):ge.Linking.openURL(g))}catch(S){throw new w("NOT_SUPPORTED",String((l=(N=S==null?void 0:S.message)!=null?N:S)!=null?l:"Kh\xF4ng m\u1EDF \u0111\u01B0\u1EE3c link"))}return}case"showToast":(le=i==null?void 0:i.showToast)==null||le.call(i,String((k=t==null?void 0:t.message)!=null?k:""));return;case"haptic":{let g=Mn.has(t==null?void 0:t.type)?t.type:"selection";(X=i==null?void 0:i.haptic)==null||X.call(i,g);return}case"getSystemInfo":return{platform:ge.Platform.OS==="ios"?"ios":"android",appVersion:(Me=i==null?void 0:i.app_version)!=null?Me:"",theme:o?"dark":"light"};case"getAccessToken":{let g=n().access_token;if(!g)throw new w("HOST_ERROR","Mini app ch\u01B0a c\xF3 token cho page n\xE0y");return g}case"getToken":{let g=t==null?void 0:t.type;if(g==="access"){let re=n().access_token;if(!re)throw new w("HOST_ERROR","Mini app ch\u01B0a c\xF3 token cho page n\xE0y");return re}if(g!=="partner"&&g!=="chatbox")throw new w("HOST_ERROR",`Lo\u1EA1i token kh\xF4ng h\u1EE3p l\u1EC7: ${String(g)}`);let S=Pt[g];if(!r().includes(S))throw new w("PERMISSION_DENIED",`Mini app ch\u01B0a \u0111\u01B0\u1EE3c c\u1EA5p quy\u1EC1n ${S} (Console \u2192 Quy\u1EC1n l\u1EA5y token)`);let U=g==="partner"?n().partner_token:n().chatbox_token;if(!U)throw new w("HOST_ERROR",`Kh\xF4ng c\xF3 ${S}`);return U}case"getUserInfo":{let g=n().user;if(!g)throw new w("HOST_ERROR","Kh\xF4ng l\u1EA5y \u0111\u01B0\u1EE3c th\xF4ng tin nh\xE2n vi\xEAn");return g}case"getPageInfo":{let g=n().page;if(!g)throw new w("HOST_ERROR","Kh\xF4ng l\u1EA5y \u0111\u01B0\u1EE3c th\xF4ng tin page");return g}case"sendMessage":case"insertText":throw new w("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF phi\xEAn b\u1EA3n app n\xE0y`);default:throw new w("NOT_SUPPORTED",`API kh\xF4ng t\u1ED3n t\u1EA1i: ${e}`)}};var We=e=>`bundle:${e}`,ze=()=>`${R().file_system.document_dir}/miniapps`,Ke=ze,Ye=(e,t,n="index.html",r=!1,o=[])=>{let s=`${Ke()}/${e}/${t}`;return{app_id:e,version:t,dir:s,entry_uri:`file://${s}/${n}`,context_update:r,permissions:o}},He=e=>{var t;R().storage.setString(We(e.app_id),JSON.stringify({version:e.version,entry:e.entry,context_update:!!e.context_update,permissions:(t=e.permissions)!=null?t:[]}))},yn=(e,t)=>/^https?:\/\//.test(t)?t:`${e.replace(/[^/]*$/,"")}${t}`,x=e=>{let t=R().storage.getString(We(e));if(!t)return null;try{let{version:n,entry:r,context_update:o,permissions:s}=JSON.parse(t);return Ye(e,n,r,!!o,Array.isArray(s)?s:[])}catch{return null}},Q=e=>R().file_system.exists(e.entry_uri.replace("file://","")),Qe=async e=>{let t=x(e.app_id);return(t==null?void 0:t.version)===e.version&&await Q(t)},kt=async(e,t)=>{let n=R().file_system,r=`${Ke()}/${e}`,o=await n.listDir(r).catch(()=>[]);await Promise.all(o.filter(s=>!t.includes(s)).map(s=>n.remove(`${r}/${s}`).catch(()=>{})))},Dt=async e=>{var t;await((t=me[e])==null?void 0:t.catch(()=>{})),R().storage.setString(We(e),""),await R().file_system.remove(`${Ke()}/${e}`).catch(()=>{})},ae=class extends Error{constructor(){super("cancelled"),this.name="MiniAppInstallCancelled"}},me={},It=(e,t)=>{var s;let r=((s=me[e])!=null?s:Promise.resolve()).catch(()=>{}).then(t),o=r.catch(()=>{});return me[e]=o,o.then(()=>{me[e]===o&&delete me[e]}),r},vn=(e,t)=>{var o,s;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 p=((o=n[a])!=null?o:0)-((s=r[a])!=null?s:0);if(p)return p}return 0},Lt=({manifest:e,zip_path:t})=>It(e.app_id,async()=>{var s;let n=R().file_system,r=x(e.app_id);if(r&&vn(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 o=Ye(e.app_id,e.version,e.entry,!!e.context_update,(s=e.permissions)!=null?s:[]);return await n.remove(o.dir).catch(()=>{}),await n.mkdir(o.dir),await n.unzip(t,o.dir),He(e),$("\u0111\xE3 c\xE0i b\u1EA3n \u0111\xF3ng s\u1EB5n",e.app_id,e.version),kt(e.app_id,[e.version,r==null?void 0:r.version].filter(Boolean)),o}),Ge=(e,{base_url:t,onProgress:n}={})=>{let r=R().file_system,o=null,s=!1,a=`${r.cache_dir}/${e.app_id}-${e.version}.zip`,p=()=>{if(s)throw new ae},i=async()=>{var m;p();let u=x(e.app_id);if((u==null?void 0:u.version)===e.version&&await r.exists(u.dir))return He(e),x(e.app_id);p();let M=r.download({url:t?yn(t,e.bundle_url):e.bundle_url,to_file:a,onProgress:(v,A)=>{var C;let h=A>0?A:(C=e.size)!=null?C:0;h>0&&(n==null||n(Math.min(1,v/h)))}});o=M;try{let{status:v}=await M.promise;if(p(),v!==200)throw new Error(`bundle ${v}`);if(e.sha256)if(r.sha256){if(await r.sha256(a)!==e.sha256)throw new Error("sha256 mismatch")}else $("b\u1ECF qua ki\u1EC3m tra sha256 (file_system kh\xF4ng c\xF3 sha256)",e.app_id);p();let A=Ye(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),He(e),kt(e.app_id,[e.version,u==null?void 0:u.version].filter(Boolean)),A}catch(v){throw s?new ae:v}finally{o=null,r.remove(a).catch(()=>{})}};return{promise:It(e.app_id,i),cancel:()=>{s=!0,o==null||o.cancel()}}},he={},Sn=__DEV__?0:60*1e3,Ct={},Nt=(e,t)=>{var r,o;let n=x(e);return n&&Date.now()-((r=Ct[t])!=null?r:0)<Sn?Promise.resolve(n):((o=he[e])!=null||(he[e]=(async()=>{let s=await fetch(t,{headers:{"Cache-Control":"no-cache"}});if(!s.ok)throw new Error(`manifest ${s.status}`);let a=await s.json(),p=await Ge(a,{base_url:t}).promise;return Ct[t]=Date.now(),p})().catch(s=>(console.warn("[miniapp] sync failed",e,s==null?void 0:s.message),x(e))).finally(()=>{he[e]=void 0})),he[e])};var Re=new Map,Bt=(e,t)=>(Re.set(e,t),()=>{Re.get(e)===t&&Re.delete(e)}),$t=(e,t)=>{let n=Re.get(e);return n?n(t):!1};var Pe=require("react"),Te=e=>{let t=e,n=new Set;return{getState:()=>t,setState:r=>{let o=typeof r=="function"?r(t):r;t={...t,...o},n.forEach(s=>s())},subscribe:r=>(n.add(r),()=>{n.delete(r)})}},z=(e,t,n=Object.is)=>{let r=(0,Pe.useRef)(null),o=()=>{let s=e.getState(),a=r.current;if(a&&a.state===s&&a.selector===t)return a.value;let p=t(s),i=a&&n(a.value,p)?a.value:p;return r.current={state:s,selector:t,value:i},i};return(0,Pe.useSyncExternalStore)(e.subscribe,o)};var F=Te({active_key:null,instances:{}}),Ft=({app:e,instance_id:t,context:n={},url_params:r={},host_data:o={}},s)=>{var p;let a=(p=R().keep_alive)==null?void 0:p.max_webviews;F.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:o,last_used_at:Date.now()}},m=Object.keys(M);return a&&a>0&&m.length>a&&m.filter(v=>v!==u).sort((v,A)=>M[v].last_used_at-M[A].last_used_at).slice(0,m.length-a).forEach(v=>{delete M[v]}),s?{active_key:u,instances:M}:{instances:M}})},Vt=e=>Ft(e,!0),Ut=e=>Ft(e,!1),ce=()=>F.setState({active_key:null}),Oe=e=>{F.setState(t=>{if(t.active_key===e||!t.instances[e])return{};let n={...t.instances};return delete n[e],{instances:n}})};var Jt="catalog",bn="paused_apps",_n="removed_apps",xn=10*1e3,En=2,Rn=3e3,Pn=()=>{var e;try{return JSON.parse((e=R().storage.getString(Jt))!=null?e:"{}")}catch{return{}}},_=Te({catalog:{},downloads:{},pause_reasons:[],updates:{},apply_ticks:{}}),qt=e=>{var t;return!!((t=R().manual_update)!=null&&t.includes(e))},De=new Set,jt=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 o=JSON.parse((r=R().storage.getString(e))!=null?r:"[]");Array.isArray(o)&&o.forEach(s=>{typeof s=="string"&&t.add(s)})}catch{}}}},j=jt(bn),ne=jt(_n);dt(()=>{j.load(),ne.load();let e=Pn(),t={};Object.keys(e).filter(n=>!ne.has(n)).forEach(n=>{let r=x(n);r?t[n]={status:"installed",progress:1,version:r.version,has_local:!0}:j.has(n)&&(t[n]={status:"paused",progress:0,version:e[n].version,has_local:!1})}),_.setState({catalog:e,downloads:t})});var Ie=e=>z(_,t=>e?t.downloads[e]:void 0),Ht=()=>z(_,e=>e.pause_reasons.length>0),q=(...e)=>$("queue",...e),O=[],G={},y=null,Ce=new Set,se={},Xe=new Set,ee=e=>{Xe.forEach(t=>{try{t(e)}catch(n){console.warn("[miniapp-queue] event listener error",n==null?void 0:n.message)}})},Wt=e=>(Xe.add(e),()=>{Xe.delete(e)}),zt=()=>_.getState().downloads,L=(e,t)=>{let n=!!x(e),r=_.getState().downloads[e],o=t.status==="downloading"&&n?"updating":t.status,s={...r!=null?r:{status:"queued",progress:0},...t,...o?{status:o}:{},has_local:n};_.setState(a=>({downloads:{...a.downloads,[e]:s}})),(r==null?void 0:r.status)!==s.status||(r==null?void 0:r.version)!==s.version||(r==null?void 0:r.has_local)!==s.has_local?ee({type:"status_change",app_id:e,state:s}):r.progress!==s.progress&&ee({type:"progress",app_id:e,progress:s.progress,version:s.version})},ke=(e,t)=>{var n;(n=se[e])==null||n.forEach(r=>r(t)),delete se[e]},Tn=()=>_.getState().pause_reasons.length>0,te=e=>{var p;if(y)return;let t=e?O.indexOf(e):Tn()?-1:O.findIndex(i=>!j.has(i));if(t<0||t>=O.length)return;let[n]=O.splice(t,1),r=_.getState().catalog[n];if(!r){ke(n,x(n)),te();return}let o=Date.now();G[n]=((p=G[n])!=null?p:0)+1,L(n,{status:"downloading",progress:0,version:r.version,error:void 0});let s=0,a=Ge(r,{onProgress:i=>{let u=Math.floor(i*100);u!==s&&(s=u,L(n,{progress:u/100,version:r.version}))}});y={app_id:n,handle:a,forced:!!e},q("start",n,r.version,e?"(forced)":""),a.promise.then(i=>{q("installed",n,r.version,`${Date.now()-o}ms`),L(n,{status:"installed",progress:1,version:r.version}),ke(n,i)}).catch(i=>{var M;if(i instanceof ae){if(Ce.has(n))return;q("paused",n),G[n]-=1,O.unshift(n),L(n,{status:j.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),G[n]<En){L(n,{status:"queued",progress:0,version:r.version,error:u}),setTimeout(()=>{var m;O.includes(n)||(y==null?void 0:y.app_id)===n||(O.push(n),te((m=se[n])!=null&&m.length?n:void 0))},Rn);return}L(n,{status:"failed",progress:0,version:r.version,error:u}),ke(n,x(n))}).finally(()=>{y=null;let i=O.find(u=>{var M;return(M=se[u])==null?void 0:M.length});te(i)})},Le=(e,{front:t=!1}={})=>{if((y==null?void 0:y.app_id)===e)return;let n=O.indexOf(e);if(n>=0){if(!t)return;O.splice(n,1)}t?O.unshift(e):O.push(e)},On=async e=>{let{host_id:t,client_token:n}=R(),r=new AbortController,o=setTimeout(()=>r.abort(),xn);try{let s=`${be}/api/hosts/${encodeURIComponent(t)}/miniapps?channel=${e}`,a=await fetch(s,{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(o)}},Ae=null,Ne=()=>(Ae!=null||(Ae=(async()=>{var t;let e=Date.now();try{let n=await Promise.all(R().channels.map(On)),r={};[...n].reverse().flat().forEach(i=>{r[i.app_id]=i});let o=Object.keys(_.getState().catalog).filter(i=>!r[i]);R().storage.setString(Jt,JSON.stringify(r)),_.setState({catalog:r}),await Promise.all(o.map(i=>Kt(i,{by_user:!1}))),o.forEach(i=>ne.delete(i));let s=Object.keys(r).filter(i=>!ne.has(i)),a=[],p={};for(let i of s.map(u=>r[u])){if(await Qe(i)){L(i.app_id,{status:"installed",progress:1,version:i.version});continue}let u=x(i.app_id);if(qt(i.app_id)&&!De.has(i.app_id)&&u&&await Q(u)){L(i.app_id,{status:"installed",progress:1,version:u.version}),p[i.app_id]={app_id:i.app_id,current_version:u.version,next_version:i.version};continue}a.push(i)}return _.setState({updates:p}),a.forEach(i=>{G[i.app_id]=0,L(i.app_id,{status:j.has(i.app_id)?"paused":"queued",progress:0,version:i.version,error:void 0}),Le(i.app_id)}),q("catalog",s.length,"apps, outdated",a.map(i=>i.app_id),"removed",o,`${Date.now()-e}ms`),ee({type:"sync_complete",app_ids:s,removed:o}),Object.values(p).forEach(i=>ee({type:"update_available",...i})),te(),{ok:!0,app_ids:s,removed:o}}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),ee({type:"sync_failed",error:r}),{ok:!1,error:r}}finally{Ae=null}})()),Ae),Kt=async(e,{by_user:t})=>{var o,s,a,p;if(t&&ne.add(e),Ce.has(e))return;Ce.add(e),j.delete(e);let n=O.indexOf(e);n>=0&&O.splice(n,1),(y==null?void 0:y.app_id)===e&&y.handle.cancel();let r=(p=(a=(o=_.getState().downloads[e])==null?void 0:o.version)!=null?a:(s=x(e))==null?void 0:s.version)!=null?p:"";L(e,{status:"uninstalling",progress:0,version:r}),await Dt(e),Oe(e),_.setState(i=>{let u={...i.downloads};return delete u[e],{downloads:u}}),delete G[e],Ce.delete(e),ke(e,null),q("uninstalled",e,t?"(user)":"(not in list)"),ee({type:"uninstalled",app_id:e})},Yt=e=>Kt(e,{by_user:!0}),Qt=e=>{let t=pe(e);return t?(ne.delete(e),(y==null?void 0:y.app_id)===e||O.includes(e)||(G[e]=0,L(e,{status:j.has(e)?"paused":"queued",progress:0,version:t.version,error:void 0}),Le(e),te(),q("restore",e)),!0):!1},Gt=e=>{if(j.has(e))return;if(j.add(e),q("pause app",e),(y==null?void 0:y.app_id)===e&&!y.forced){y.handle.cancel();return}let t=_.getState().downloads[e];O.includes(e)&&t&&L(e,{status:"paused",progress:0,version:t.version})},Xt=e=>{if(!j.delete(e))return;q("resume app",e);let t=_.getState().downloads[e];(t==null?void 0:t.status)==="paused"&&!O.includes(e)&&pe(e)&&(G[e]=0,Le(e)),O.includes(e)&&t&&L(e,{status:"queued",progress:0,version:t.version}),te()},Zt=e=>{let{pause_reasons:t}=_.getState();t.includes(e)||(_.setState({pause_reasons:[...t,e]}),q("pause",e),t.length===0&&ee({type:"pause_change",paused:!0,reasons:[e]}),y&&!y.forced&&y.handle.cancel())},en=e=>{let{pause_reasons:t}=_.getState();if(!t.includes(e))return;let n=t.filter(r=>r!==e);_.setState({pause_reasons:n}),q("resume",e),n.length===0&&ee({type:"pause_change",paused:!1,reasons:n}),te()},Ze=e=>_.getState().updates[e],tn=async e=>{var n,r;let t=Ze(e);De.add(e);try{let o=await we(e),s=(r=t==null?void 0:t.next_version)!=null?r:(n=pe(e))==null?void 0:n.version;return!o||!s||o.version!==s?!1:(_.setState(a=>{var i;let p={...a.updates};return delete p[e],{updates:p,apply_ticks:{...a.apply_ticks,[e]:((i=a.apply_ticks[e])!=null?i:0)+1}}}),q("updated",e,t==null?void 0:t.current_version,"\u2192",o.version),!0)}finally{De.delete(e)}},nn=()=>Object.values(_.getState().catalog).map(e=>({...e,installed:!!x(e.app_id),removed_by_user:ne.has(e.app_id)})),pe=e=>_.getState().catalog[e],we=async e=>{let t=pe(e);if(!t)return;if(j.delete(e),ne.delete(e),await Qe(t))return x(e);let n=x(e);if(qt(e)&&!De.has(e)&&n&&await Q(n))return n;let r=new Promise(o=>{var s;((s=se[e])!=null?s:se[e]=[]).push(o)});return(y==null?void 0:y.app_id)===e?y.forced=!0:(G[e]=0,Le(e,{front:!0}),y&&!y.forced?y.handle.cancel():te(e)),r};var E=require("react/jsx-runtime"),et=e=>(e!=null?e:"").replace(/\?[^#]*/,""),rn=0,Cn=()=>{let e=new Set;return{emit:t=>e.forEach(n=>n(t)),subscribe:t=>(e.add(t),()=>{e.delete(t)})}},kn=d.default.memo(({instance_key:e,is_active:t,is_front:n,is_dark:r,reload_tick:o,web_at_top:s,splash:a,bridge:p,opaque_background:i,allow_embedded_miniapps:u,onWebLoadEnd:M})=>{var st,at;let m=(0,d.useRef)(null),v=(0,d.useRef)(!1),A=z(F,c=>c.instances[e]),h=A==null?void 0:A.app.app_id,C=A==null?void 0:A.app.manifest_url,T=A==null?void 0:A.context,N=A==null?void 0:A.url_params,[l,k]=(0,d.useState)(()=>h?x(h):null),[le,X]=(0,d.useState)(!1),[Me,g]=(0,d.useState)(0),[S,U]=(0,d.useState)(0),[re,B]=(0,d.useState)(!1),H=(0,d.useRef)(null),nt=c=>{H.current&&clearTimeout(H.current),H.current=setTimeout(()=>{H.current=null,B(!0)},c)};(0,d.useEffect)(()=>()=>{H.current&&clearTimeout(H.current)},[]),(0,d.useEffect)(()=>{if(!h||!t&&l)return;let c=!0;return X(!1),(async()=>{let f=x(h),D=f?await Q(f):!1;if(!c||(k(D?J=>!J||J.version!==f.version||J.permissions.join(",")!==f.permissions.join(",")?f:J:null),__DEV__&&Date.now()-rn>1e4&&(rn=Date.now(),await Ne()),!c))return;let Z=await we(h),ie=Z!==void 0?Z:C?await Nt(h,C):x(h);if(c){if(!ie){X(!0);return}k(J=>J!=null?J:ie)}})(),()=>{c=!1}},[t,h,C,Me]),(0,d.useEffect)(()=>Bt(e,c=>m.current?(m.current.postMessage(c),!0):!1),[e]);let cn=z(_,c=>{let f=h?c.downloads[h]:void 0;return(f==null?void 0:f.status)==="installed"?f.version:void 0});(0,d.useEffect)(()=>{if(t||!h||!l)return;let c=x(h);if(!c||c.version===l.version)return;let f=!0;return Q(c).then(D=>{!f||!D||($(`webview:${e}`,"\u0111\u1ED5i bundle (\u1EA9n)",l.version,"\u2192",c.version),k(c))}),()=>{f=!1}},[t,h,cn,l==null?void 0:l.version]);let rt=z(_,c=>{var f;return h&&(f=c.apply_ticks[h])!=null?f:0});(0,d.useEffect)(()=>{if(!rt||!h)return;let c=x(h);if(!c||c.version===(l==null?void 0:l.version))return;let f=!0;return Q(c).then(D=>{!f||!D||($(`webview:${e}`,"c\u1EADp nh\u1EADt",l==null?void 0:l.version,"\u2192",c.version),B(!1),k(c))}),()=>{f=!1}},[rt]),(0,d.useEffect)(()=>{var D;let c=(D=R().keep_alive)==null?void 0:D.idle_close_ms;if(t||!c||c<=0)return;let f=setTimeout(()=>{Oe(e)},c);return()=>clearTimeout(f)},[t,e]),(0,d.useEffect)(()=>{o>0&&(X(!1),B(!1),U(c=>c+1),g(c=>c+1))},[o]);let it=(0,d.useRef)(t);(0,d.useEffect)(()=>{var c;it.current!==t&&(it.current=t,v.current&&((c=m.current)==null||c.injectJavaScript(_t(t?"resumed":"paused"))))},[t]);let ue=`${(st=l==null?void 0:l.version)!=null?st:"none"}:${(at=l==null?void 0:l.permissions.join(","))!=null?at:""}:${S}`,de=(0,d.useMemo)(()=>JSON.stringify([T!=null?T:{},N!=null?N:{}]),[T,N]),Be=(0,d.useMemo)(()=>{var c;return Tt(N!=null?N:{},(c=l==null?void 0:l.permissions)!=null?c:[])},[de,l==null?void 0:l.permissions]),pn=(0,d.useMemo)(()=>Rt(T!=null?T:{},Be)+bt()+(R().debug?St():""),[Be]),ye=(0,d.useRef)(null),ot=(0,d.useRef)(null);(0,d.useEffect)(()=>{var f,D,Z;if(!l)return;if(ot.current!==ue){ot.current=ue,ye.current=de;return}if(ye.current===de)return;let c=((D=JSON.parse((f=ye.current)!=null?f:"[]")[0])!=null?D:{}).org_id;if(ye.current=de,c===(T==null?void 0:T.org_id)&&v.current){B(!1),nt(1500),(Z=m.current)==null||Z.injectJavaScript(xt(T!=null?T:{},Be));return}B(!1),U(ie=>ie+1)},[de,l,ue]),(0,d.useEffect)(()=>(t||W(e),()=>W(e)),[t,e,ue,o]),(0,d.useEffect)(()=>{let c=b.AppState.addEventListener("change",f=>{f==="background"&&W(e)});return()=>c.remove()},[e]);let ln=(0,d.useCallback)(async c=>{var D,Z,ie,J,$e;let f=wt(c.nativeEvent.data);if(!f){if(h&&(p!=null&&p.onWebEvent))try{Promise.resolve(p.onWebEvent(c.nativeEvent.data,{app_id:h,instance_id:e})).catch(P=>{console.warn("[miniapp] onWebEvent l\u1ED7i",h,P)})}catch(P){console.warn("[miniapp] onWebEvent l\u1ED7i",h,P)}return}if(f.method==="log"){let{level:P,text:I}=f;$(`web:${e}`,P!=null?P:"log",I!=null?I:"");return}if(f.method==="pong"){H.current||B(!0);return}if(f.method==="touchAtTop"){s.emit(!!f.at_top);return}if(f.method==="contextApplied"){H.current&&clearTimeout(H.current),H.current=null,B(!0);return}if(f.method==="ready"){v.current=!0,B(!0);let P=(D=F.getState().instances[e])==null?void 0:D.context;P&&((Z=m.current)==null||Z.injectJavaScript(je(P)));return}try{let P=await Ot(f,{getHostData:()=>{var I,K;return(K=(I=F.getState().instances[e])==null?void 0:I.host_data)!=null?K:{}},getPermissions:()=>{var I,K;return h?(K=(I=x(h))==null?void 0:I.permissions)!=null?K:[]:[]},is_dark:r,close:ce,app_id:h!=null?h:"",instance_id:e,options:p,emit:(I,K)=>{var ct;(ct=m.current)==null||ct.injectJavaScript(vt(I,K))},isActive:()=>F.getState().active_key===e&&b.AppState.currentState!=="background"});f.id&&((ie=m.current)==null||ie.injectJavaScript(Mt(f.id,P)))}catch(P){if(!f.id)return;let I=P==null?void 0:P.code,K=P instanceof w?P:new w(typeof I=="string"?I:"HOST_ERROR",String((J=P==null?void 0:P.message)!=null?J:P));($e=m.current)==null||$e.injectJavaScript(yt(f.id,K))}},[e,r,h,s,p]),un=(0,d.useCallback)(()=>{X(!1),U(c=>c+1),g(c=>c+1)},[]);return(0,E.jsxs)(b.View,{style:[b.StyleSheet.absoluteFill,i&&{backgroundColor:r?"#09090B":"#FFFFFF"},!n&&V.behind],pointerEvents:t?"auto":"none",children:[l?(0,E.jsx)(sn.default,{ref:m,source:{uri:l.entry_uri},originWhitelist:["*"],allowingReadAccessToURL:`file://${u?ze():l.dir}`,allowFileAccess:!0,allowFileAccessFromFileURLs:!0,allowUniversalAccessFromFileURLs:!0,injectedJavaScriptBeforeContentLoaded:pn,onMessage:ln,bounces:!1,overScrollMode:"never",onLoadStart:c=>{W(e),$(`webview:${e}`,"load start",et(c.nativeEvent.url)),v.current=!1,B(!1)},onError:c=>{W(e),$(`webview:${e}`,"load error",et(c.nativeEvent.url),c.nativeEvent.description),X(!0),B(!1)},onLoadEnd:c=>{let f=c.nativeEvent.url;$(`webview:${e}`,"load end",et(f)),h&&(M==null||M({app_id:h,instance_id:e,url:f})),nt(1500)},onContentProcessDidTerminate:()=>{W(e),v.current=!1,B(!1),U(c=>c+1)},onRenderProcessGone:()=>(W(e),v.current=!1,B(!1),U(c=>c+1),!0),style:V.webview},ue):null,A&&(0,E.jsx)(In,{visible:!l||!re,interactive:le,children:(0,E.jsx)(Dn,{splash:a,app:A.app,is_dark:r,error:le,has_bundle:!!l,retry:un})})]})}),Dn=d.default.memo(({splash:e,app:t,is_dark:n,error:r,has_bundle:o,retry:s})=>{let a=e,p=Ie(t.app_id),i=r?"error":!o&&(p==null?void 0:p.status)==="downloading"?"downloading":"loading";return(0,E.jsx)(a,{app:t,is_dark:n,status:i,progress:i==="downloading"?p==null?void 0:p.progress:void 0,retry:s})}),In=({visible:e,interactive:t,children:n})=>{let r=(0,d.useRef)(new b.Animated.Value(e?1:0)).current,[o,s]=(0,d.useState)(e);return(0,d.useEffect)(()=>{if(e){s(!0),r.setValue(1);return}let a=b.Animated.timing(r,{toValue:0,duration:180,useNativeDriver:!0});return a.start(({finished:p})=>{p&&s(!1)}),()=>a.stop()},[e,r]),o?(0,E.jsx)(b.Animated.View,{style:[b.StyleSheet.absoluteFill,{opacity:r}],pointerEvents:t?"auto":"none",children:n}):null},tt=({app:e,is_dark:t,status:n,progress:r,retry:o})=>{let s=t?"#FAFAFA":"#18181B";return(0,E.jsxs)(b.View,{style:[V.splash,{backgroundColor:t?"#09090B":"#FFFFFF"}],children:[(0,E.jsx)(b.View,{style:[V.splash_icon,{backgroundColor:t?"#18181B":"#F4F4F5"}],children:e.icon?(0,E.jsx)(b.Image,{source:{uri:e.icon},style:V.splash_icon_image}):(0,E.jsx)(b.Text,{style:V.splash_letter,children:(e.name||"?").slice(0,1).toUpperCase()})}),(0,E.jsx)(b.Text,{style:[V.splash_name,{color:s}],children:e.name}),n==="error"?(0,E.jsxs)(E.Fragment,{children:[(0,E.jsx)(b.Text,{style:V.splash_hint,children:"Kh\xF4ng t\u1EA3i \u0111\u01B0\u1EE3c mini app"}),(0,E.jsx)(b.TouchableOpacity,{activeOpacity:.7,style:[V.retry_button,{backgroundColor:t?"#27272A":"#F4F4F5"}],onPress:o,children:(0,E.jsx)(b.Text,{style:[V.retry_text,{color:s}],children:"Th\u1EED l\u1EA1i"})})]}):(0,E.jsxs)(E.Fragment,{children:[(0,E.jsx)(b.ActivityIndicator,{style:V.splash_spinner,color:t?"#A1A1AA":"#71717A"}),n==="downloading"&&(0,E.jsxs)(b.Text,{style:V.splash_hint,children:["\u0110ang t\u1EA3i mini app",r?` ${Math.round(r*100)}%`:"\u2026"]})]})]})},on=(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.`))},Ln=({container:e,splash:t=tt,is_dark:n=!1,bridge:r,close_on_back:o=!0,opaque_background:s=!0,allow_embedded_miniapps:a=!1,onWebLoadEnd:p})=>{on("container",e),on("splash",t);let i=e,u=z(F,l=>l.active_key),M=(0,d.useRef)(u);u&&(M.current=u);let m=z(F,l=>Object.keys(l.instances).join("|")),v=z(F,l=>{var k;return l.active_key?(k=l.instances[l.active_key])==null?void 0:k.app.name:void 0}),A=(0,d.useMemo)(()=>m?m.split("|"):[],[m]),[h,C]=(0,d.useState)({}),T=(0,d.useRef)(Cn()).current;(0,d.useEffect)(()=>{if(!u||!o)return;let l=b.BackHandler.addEventListener("hardwareBackPress",()=>(ce(),!0));return()=>l.remove()},[u,o]);let N=(0,d.useCallback)(()=>{let l=F.getState().active_key;l&&C(k=>({...k,[l]:(k[l]||0)+1}))},[]);return A.length?(0,E.jsx)(i,{visible:!!u,title:v!=null?v:"",is_dark:n,close:ce,reload:N,subscribeWebAtTop:T.subscribe,children:A.map(l=>(0,E.jsx)(kn,{instance_key:l,is_active:u===l,is_front:(u!=null?u:M.current)===l,is_dark:n,reload_tick:h[l]||0,web_at_top:T,splash:t,bridge:r,opaque_background:s,allow_embedded_miniapps:a,onWebLoadEnd:p},l))}):null},V=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"}}),an=d.default.memo(Ln);0&&(module.exports={DefaultMiniAppSplash,MINIAPP_PLATFORM_URL,MiniAppHost,MiniAppHostError,closeMiniApp,configureMiniApp,createMmkvStorage,createReactNativeBiometrics,createRnfsFileSystem,ensureMiniApp,getLocalMiniApp,getMiniAppCatalog,getMiniAppCatalogEntry,getMiniAppStatuses,getMiniAppUpdate,installBundledMiniApp,onMiniAppEvent,openMiniApp,pauseMiniApp,pauseMiniAppDownloads,preloadMiniApp,releaseSpeechFor,restoreMiniApp,resumeMiniApp,resumeMiniAppDownloads,sendEventToWeb,syncMiniAppCatalog,uninstallMiniApp,updateMiniApp,useMiniAppDownload,useMiniAppDownloadsPaused});
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- var Ie="https://retion-miniapp-platform.vercel.app",ne=null,st=new Set,Ht=e=>{ne=e,st.forEach(t=>t())},b=()=>{if(!ne)throw new Error("[miniapp] Ch\u01B0a g\u1ECDi configureMiniApp()");return ne},at=e=>{st.add(e),ne&&e()},L=(...e)=>{ne!=null&&ne.debug&&console.log("[miniapp]",...e)};var Wt=(e,t)=>({document_dir:e.DocumentDirectoryPath,cache_dir:e.CachesDirectoryPath,exists:n=>e.exists(n),mkdir:n=>e.mkdir(n),remove:n=>e.unlink(n).catch(()=>{}),listDir:n=>e.readDir(n).then(r=>r.map(s=>s.name)).catch(()=>[]),sha256:n=>e.hash(n,"sha256"),unzip:async(n,r)=>{await t(n,r)},download:({url:n,to_file:r,onProgress:s})=>{let{jobId:o,promise:a}=e.downloadFile({fromUrl:n,toFile:r,progressInterval:250,begin:()=>{},progress:({bytesWritten:u,contentLength:i})=>s==null?void 0:s(u,i)});return{promise:a.then(({statusCode:u})=>({status:u})),cancel:()=>e.stopDownload(o)}}}),jt=e=>({getString:t=>e.getString(t),setString:(t,n)=>e.set(t,n)});import Xe,{useCallback as Qe,useEffect as V,useMemo as ke,useRef as H,useState as ie}from"react";import{ActivityIndicator as Sn,Animated as ze,BackHandler as bn,Image as xn,StyleSheet as Ze,Text as fe,TouchableOpacity as En,View as Ge}from"react-native";import Pn from"react-native-webview";import{Linking as pt,Platform as qt}from"react-native";var ct=e=>({getAvailability:()=>e.isSensorAvailable(),authenticate:({reason:t,cancelButtonText:n})=>e.simplePrompt({promptMessage:t,cancelButtonText:n,fallbackPromptMessage:""})}),Me,De=()=>(Me||(Me=import("react-native-biometrics").then(({default:e})=>ct(new e({allowDeviceCredentials:!1}))).catch(e=>{throw Me=void 0,new w("NOT_SUPPORTED",`Biometric native module unavailable: ${e instanceof Error?e.message:String(e)}`)})),Me);var we=1,w=class extends Error{constructor(n,r){super(r);this.code=n}},lt=e=>{try{let t=JSON.parse(e);return(t==null?void 0:t.__retion)===we&&typeof t.method=="string"?t:null}catch{return null}},ve=e=>`window.__RETION_MINIAPP__ && window.__RETION_MINIAPP__.receive(${JSON.stringify(e)}); true;`,ut=(e,t)=>ve({id:e,result:t}),dt=(e,t)=>ve({id:e,error:{code:t.code,message:t.message}}),Ne=e=>ve({event:"context",data:e});var gt=()=>`(function () {
1
+ var Ne="https://retion-miniapp-platform.vercel.app",oe=null,ut=new Set,Gt=e=>{oe=e,ut.forEach(t=>t())},_=()=>{if(!oe)throw new Error("[miniapp] Ch\u01B0a g\u1ECDi configureMiniApp()");return oe},dt=e=>{ut.add(e),oe&&e()},B=(...e)=>{oe!=null&&oe.debug&&console.log("[miniapp]",...e)};var Xt=(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(o=>o.name)).catch(()=>[]),sha256:n=>e.hash(n,"sha256"),unzip:async(n,r)=>{await t(n,r)},download:({url:n,to_file:r,onProgress:o})=>{let{jobId:s,promise:a}=e.downloadFile({fromUrl:n,toFile:r,progressInterval:250,begin:()=>{},progress:({bytesWritten:p,contentLength:i})=>o==null?void 0:o(p,i)});return{promise:a.then(({statusCode:p})=>({status:p})),cancel:()=>e.stopDownload(s)}}}),Zt=e=>({getString:t=>e.getString(t),setString:(t,n)=>e.set(t,n)});import nt,{useCallback as et,useEffect as I,useMemo as De,useRef as j,useState as ae}from"react";import{AppState as Jt,ActivityIndicator as kn,Animated as Xe,BackHandler as Dn,Image as In,StyleSheet as rt,Text as we,TouchableOpacity as Ln,View as tt}from"react-native";import Nn from"react-native-webview";import{Linking as mt,Platform as tn}from"react-native";var gt=e=>({getAvailability:()=>e.isSensorAvailable(),authenticate:({reason:t,cancelButtonText:n})=>e.simplePrompt({promptMessage:t,cancelButtonText:n,fallbackPromptMessage:""})}),Se,Be=()=>(Se||(Se=import("react-native-biometrics").then(({default:e})=>gt(new e({allowDeviceCredentials:!1}))).catch(e=>{throw Se=void 0,new A("NOT_SUPPORTED",`Biometric native module unavailable: ${e instanceof Error?e.message:String(e)}`)})),Se);import{Platform as en}from"react-native";var K,$e=e=>{var t;if(K===e&&(K=void 0,e.subscriptions.forEach(n=>n.remove()),e.started&&en.OS==="ios"))try{(t=e.native)==null||t.setAudioSessionActiveIOS(!1,{notifyOthersOnDeactivation:!0})}catch{}},ft=async(e,t,n,r=()=>!0)=>{var s,a,p,i,u;if(K)throw new A("BUSY","Micro \u0111ang \u0111\u01B0\u1EE3c mini app kh\xE1c s\u1EED d\u1EE5ng");if(!r())throw new A("CANCELLED","Mini app kh\xF4ng c\xF2n ho\u1EA1t \u0111\u1ED9ng");let o={owner:e,emit:n,cancelled:!1,started:!1,subscriptions:[]};K=o;try{let w;try{w=await import("expo-speech-recognition")}catch{throw new A("NOT_SUPPORTED","Ch\u01B0a c\xF3 module nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i trong b\u1EA3n native")}let h=w.ExpoSpeechRecognitionModule;if(o.native=h,o.cancelled||!r())throw new A("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");let y=await h.requestPermissionsAsync();if(o.cancelled||!r())throw new A("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");if(!y.granted)throw new A("PERMISSION_DENIED","Ch\u01B0a c\u1EA5p quy\u1EC1n micro / nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i");if(await h.getStateAsync()!=="inactive")throw new A("BUSY","Nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i \u0111ang \u0111\u01B0\u1EE3c t\xEDnh n\u0103ng kh\xE1c s\u1EED d\u1EE5ng");if(o.cancelled||!r())throw new A("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");o.subscriptions.push(w.addSpeechRecognitionListener("result",m=>{var f,T;K!==o||o.cancelled||n(m.isFinal?"speech.final":"speech.partial",{...m,text:(T=(f=m.results[0])==null?void 0:f.transcript)!=null?T:""})}),w.addSpeechRecognitionListener("error",m=>{K===o&&!o.cancelled&&n("speech.error",{...m,code:m.error})}),w.addSpeechRecognitionListener("end",()=>{K===o&&($e(o),n("speech.end"))})),o.started=!0,h.start({lang:(s=t.lang)!=null?s:"vi-VN",continuous:(a=t.continuous)!=null?a:!0,interimResults:(p=t.interimResults)!=null?p:!0,addsPunctuation:(i=t.addsPunctuation)!=null?i:!0,requiresOnDeviceRecognition:(u=t.requiresOnDeviceRecognition)!=null?u:!1,iosCategory:{category:w.AVAudioSessionCategory.playAndRecord,categoryOptions:[w.AVAudioSessionCategoryOptions.defaultToSpeaker,w.AVAudioSessionCategoryOptions.allowBluetooth],mode:w.AVAudioSessionMode.measurement}})}catch(w){throw $e(o),w}},ht=e=>{let t=K;if(!(!t||t.owner!==e)){if(!t.started){t.cancelled=!0;return}t.native.stop()}},Y=e=>{let t=K;if(!(!t||t.owner!==e||t.cancelled)&&(t.cancelled=!0,t.started))try{t.native.abort()}catch{$e(t)}};var _e=1,A=class extends Error{constructor(n,r){super(r);this.code=n}},At=e=>{try{let t=JSON.parse(e);return(t==null?void 0:t.__retion)===_e&&typeof t.method=="string"?t:null}catch{return null}},de=e=>`window.__RETION_MINIAPP__ && window.__RETION_MINIAPP__.receive(${JSON.stringify(e)}); true;`,wt=(e,t)=>de({id:e,result:t}),Mt=(e,t)=>de({id:e,error:{code:t.code,message:t.message}}),yt=(e,t)=>de({event:e,data:t}),Ue=e=>de({event:"context",data:e});var vt=()=>`(function () {
2
2
  var post = function (level, args) {
3
3
  try {
4
4
  var parts = [];
@@ -8,7 +8,7 @@ var Ie="https://retion-miniapp-platform.vercel.app",ne=null,st=new Set,Ht=e=>{ne
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: ${we}, method: 'log', level: level, text: parts.join(' ') }));
11
+ window.ReactNativeWebView && window.ReactNativeWebView.postMessage(JSON.stringify({ __retion: ${_e}, 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 Ie="https://retion-miniapp-platform.vercel.app",ne=null,st=new Set,Ht=e=>{ne
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;`,ft=()=>`(function () {
22
+ })(); true;`,St=()=>`(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 Ie="https://retion-miniapp-platform.vercel.app",ne=null,st=new Set,Ht=e=>{ne
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: ${we}, method: 'touchAtTop', at_top: at_top }));
33
+ window.ReactNativeWebView && window.ReactNativeWebView.postMessage(JSON.stringify({ __retion: ${_e}, 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 Ie="https://retion-miniapp-platform.vercel.app",ne=null,st=new Set,Ht=e=>{ne
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;`,ht=e=>ve({event:e}),mt=(e,t)=>{let n=At(t);return`try { history.replaceState(history.state, '', location.pathname + ${JSON.stringify(n?`?${n}`:"")} + location.hash); } catch (e) {}
42
- ${Ne(e)}`},At=e=>Object.entries(e).filter(([,t])=>t!=null&&t!=="").map(([t,n])=>`${encodeURIComponent(t)}=${encodeURIComponent(String(n))}`).join("&"),Mt=(e,t={})=>{let n=At(t);return`window.__RETION_MINIAPP_HOST__ = { protocol: ${we} };
41
+ })(); true;`,bt=e=>de({event:e}),_t=(e,t)=>{let n=xt(t);return`try { history.replaceState(history.state, '', location.pathname + ${JSON.stringify(n?`?${n}`:"")} + location.hash); } catch (e) {}
42
+ ${Ue(e)}`},xt=e=>Object.entries(e).filter(([,t])=>t!=null&&t!=="").map(([t,n])=>`${encodeURIComponent(t)}=${encodeURIComponent(String(n))}`).join("&"),Et=(e,t={})=>{let n=xt(t);return`window.__RETION_MINIAPP_HOST__ = { protocol: ${_e} };
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;`},yt={partner:"partner_token",chatbox:"chatbox_token"},wt=(e,t)=>{let n={...e};for(let r of Object.values(yt))t.includes(r)||delete n[r];return n},Le=new Set,Be=async(e,t)=>{if(Le.has(e))throw new w("BUSY",`${e} \u0111ang ch\u1EA1y \u2014 ch\u1EDD l\u01B0\u1EE3t tr\u01B0\u1EDBc xong`);Le.add(e);try{return await t()}finally{Le.delete(e)}},Kt=new Set(["selection","impactLight","impactMedium","impactHeavy","rigid","soft","notificationSuccess","notificationWarning","notificationError"]),ye=(e,t)=>{if(typeof e!="string"||!e)throw new w("INVALID_PARAMS",`Thi\u1EBFu ${t}`);return e},vt=async({method:e,params:t},{getHostData:n,getPermissions:r,is_dark:s,close:o,app_id:a,instance_id:u,options:i})=>{var y,m,f,N,E,O,l,T,se;let p=i==null?void 0:i.handlers,A={app_id:a,instance_id:u,close:o},M=()=>new w("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF \u1EE9ng d\u1EE5ng n\xE0y`);switch(e){case"getBiometricAvailability":return((y=i==null?void 0:i.biometrics)!=null?y:await De()).getAvailability();case"authenticateBiometric":{let d=ye(t==null?void 0:t.reason,"reason").trim();if(!d||d.length>200)throw new w("INVALID_PARAMS","reason must contain 1\u2013200 characters");let S=t==null?void 0:t.cancelButtonText;if(S!==void 0&&(typeof S!="string"||!S.trim()||S.length>80))throw new w("INVALID_PARAMS","Invalid cancelButtonText");return Be(e,async()=>{var Z;return((Z=i==null?void 0:i.biometrics)!=null?Z:await De()).authenticate({reason:d,cancelButtonText:S})})}case"requestPayment":{let d=p==null?void 0:p.requestPayment;if(!d)throw M();let S=t==null?void 0:t.amount;if(typeof S!="number"||!Number.isFinite(S)||S<=0)throw new w("INVALID_PARAMS","amount ph\u1EA3i l\xE0 s\u1ED1 > 0");let z={...t,amount:S,currency:ye(t==null?void 0:t.currency,"currency")};return Be(e,()=>d(z,A))}case"printImage":{let d=p==null?void 0:p.printImage;if(!d)throw M();let S=ye(t==null?void 0:t.image,"image");await Be(e,()=>d({image:S},A));return}case"openScreen":if(!(p!=null&&p.openScreen))throw M();await p.openScreen({screen:ye(t==null?void 0:t.screen,"screen"),params:t==null?void 0:t.params},A);return;case"closeApp":o();return;case"openWebview":{let d=String((m=t==null?void 0:t.url)!=null?m:"");if(!/^https?:\/\//i.test(d))throw new w("INVALID_PARAMS","url ph\u1EA3i l\xE0 http(s)");await(i!=null&&i.openUrl?i.openUrl(d):pt.openURL(d));return}case"openLink":{let d=String((f=t==null?void 0:t.url)!=null?f:"").trim();if(!/^[a-z][a-z0-9+.-]*:/i.test(d)||/^(javascript|file|data|about|blob):/i.test(d))throw new w("INVALID_PARAMS","url kh\xF4ng h\u1EE3p l\u1EC7");try{await(i!=null&&i.openUrl?i.openUrl(d):pt.openURL(d))}catch(S){throw new w("NOT_SUPPORTED",String((E=(N=S==null?void 0:S.message)!=null?N:S)!=null?E:"Kh\xF4ng m\u1EDF \u0111\u01B0\u1EE3c link"))}return}case"showToast":(l=i==null?void 0:i.showToast)==null||l.call(i,String((O=t==null?void 0:t.message)!=null?O:""));return;case"haptic":{let d=Kt.has(t==null?void 0:t.type)?t.type:"selection";(T=i==null?void 0:i.haptic)==null||T.call(i,d);return}case"getSystemInfo":return{platform:qt.OS==="ios"?"ios":"android",appVersion:(se=i==null?void 0:i.app_version)!=null?se:"",theme:s?"dark":"light"};case"getAccessToken":{let d=n().access_token;if(!d)throw new w("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 Z=n().access_token;if(!Z)throw new w("HOST_ERROR","Mini app ch\u01B0a c\xF3 token cho page n\xE0y");return Z}if(d!=="partner"&&d!=="chatbox")throw new w("HOST_ERROR",`Lo\u1EA1i token kh\xF4ng h\u1EE3p l\u1EC7: ${String(d)}`);let S=yt[d];if(!r().includes(S))throw new w("PERMISSION_DENIED",`Mini app ch\u01B0a \u0111\u01B0\u1EE3c c\u1EA5p quy\u1EC1n ${S} (Console \u2192 Quy\u1EC1n l\u1EA5y token)`);let z=d==="partner"?n().partner_token:n().chatbox_token;if(!z)throw new w("HOST_ERROR",`Kh\xF4ng c\xF3 ${S}`);return z}case"getUserInfo":{let d=n().user;if(!d)throw new w("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 w("HOST_ERROR","Kh\xF4ng l\u1EA5y \u0111\u01B0\u1EE3c th\xF4ng tin page");return d}case"sendMessage":case"insertText":throw new w("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF phi\xEAn b\u1EA3n app n\xE0y`);default:throw new w("NOT_SUPPORTED",`API kh\xF4ng t\u1ED3n t\u1EA1i: ${e}`)}};var Fe=e=>`bundle:${e}`,Ue=()=>`${b().file_system.document_dir}/miniapps`,Je=Ue,Ve=(e,t,n="index.html",r=!1,s=[])=>{let o=`${Je()}/${e}/${t}`;return{app_id:e,version:t,dir:o,entry_uri:`file://${o}/${n}`,context_update:r,permissions:s}},$e=e=>{var t;b().storage.setString(Fe(e.app_id),JSON.stringify({version:e.version,entry:e.entry,context_update:!!e.context_update,permissions:(t=e.permissions)!=null?t:[]}))},zt=(e,t)=>/^https?:\/\//.test(t)?t:`${e.replace(/[^/]*$/,"")}${t}`,_=e=>{let t=b().storage.getString(Fe(e));if(!t)return null;try{let{version:n,entry:r,context_update:s,permissions:o}=JSON.parse(t);return Ve(e,n,r,!!s,Array.isArray(o)?o:[])}catch{return null}},q=e=>b().file_system.exists(e.entry_uri.replace("file://","")),He=async e=>{let t=_(e.app_id);return(t==null?void 0:t.version)===e.version&&await q(t)},St=async(e,t)=>{let n=b().file_system,r=`${Je()}/${e}`,s=await n.listDir(r).catch(()=>[]);await Promise.all(s.filter(o=>!t.includes(o)).map(o=>n.remove(`${r}/${o}`).catch(()=>{})))},bt=async e=>{var t;await((t=le[e])==null?void 0:t.catch(()=>{})),b().storage.setString(Fe(e),""),await b().file_system.remove(`${Je()}/${e}`).catch(()=>{})},oe=class extends Error{constructor(){super("cancelled"),this.name="MiniAppInstallCancelled"}},le={},xt=(e,t)=>{var o;let r=((o=le[e])!=null?o:Promise.resolve()).catch(()=>{}).then(t),s=r.catch(()=>{});return le[e]=s,s.then(()=>{le[e]===s&&delete le[e]}),r},Yt=(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},Qt=({manifest:e,zip_path:t})=>xt(e.app_id,async()=>{var o;let n=b().file_system,r=_(e.app_id);if(r&&Yt(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=Ve(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),$e(e),L("\u0111\xE3 c\xE0i b\u1EA3n \u0111\xF3ng s\u1EB5n",e.app_id,e.version),St(e.app_id,[e.version,r==null?void 0:r.version].filter(Boolean)),s}),We=(e,{base_url:t,onProgress:n}={})=>{let r=b().file_system,s=null,o=!1,a=`${r.cache_dir}/${e.app_id}-${e.version}.zip`,u=()=>{if(o)throw new oe},i=async()=>{var M;u();let p=_(e.app_id);if((p==null?void 0:p.version)===e.version&&await r.exists(p.dir))return $e(e),_(e.app_id);u();let A=r.download({url:t?zt(t,e.bundle_url):e.bundle_url,to_file:a,onProgress:(y,m)=>{var N;let f=m>0?m:(N=e.size)!=null?N:0;f>0&&(n==null||n(Math.min(1,y/f)))}});s=A;try{let{status:y}=await A.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 m=Ve(e.app_id,e.version,e.entry,!!e.context_update,(M=e.permissions)!=null?M:[]);return await r.remove(m.dir).catch(()=>{}),await r.mkdir(m.dir),await r.unzip(a,m.dir),$e(e),St(e.app_id,[e.version,p==null?void 0:p.version].filter(Boolean)),m}catch(y){throw o?new oe:y}finally{s=null,r.remove(a).catch(()=>{})}};return{promise:xt(e.app_id,i),cancel:()=>{o=!0,s==null||s.cancel()}}},pe={},Gt=__DEV__?0:60*1e3,_t={},Et=(e,t)=>{var r,s;let n=_(e);return n&&Date.now()-((r=_t[t])!=null?r:0)<Gt?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 We(a,{base_url:t}).promise;return _t[t]=Date.now(),u})().catch(o=>(console.warn("[miniapp] sync failed",e,o==null?void 0:o.message),_(e))).finally(()=>{pe[e]=void 0})),pe[e])};var _e=new Map,Pt=(e,t)=>(_e.set(e,t),()=>{_e.get(e)===t&&_e.delete(e)}),Xt=(e,t)=>{let n=_e.get(e);return n?n(t):!1};import{useRef as Zt,useSyncExternalStore as en}from"react";var Se=e=>{let t=e,n=new Set;return{getState:()=>t,setState:r=>{let s=typeof r=="function"?r(t):r;t={...t,...s},n.forEach(o=>o())},subscribe:r=>(n.add(r),()=>{n.delete(r)})}},j=(e,t,n=Object.is)=>{let r=Zt(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 en(e.subscribe,s)};var F=Se({active_key:null,instances:{}}),Rt=({app:e,instance_id:t,context:n={},url_params:r={},host_data:s={}},o)=>{var u;let a=(u=b().keep_alive)==null?void 0:u.max_webviews;F.setState(i=>{let p=t!=null?t:e.app_id,A={...i.instances,[p]:{key:p,app:e,context:n,url_params:r,host_data:s,last_used_at:Date.now()}},M=Object.keys(A);return a&&a>0&&M.length>a&&M.filter(y=>y!==p).sort((y,m)=>A[y].last_used_at-A[m].last_used_at).slice(0,M.length-a).forEach(y=>{delete A[y]}),o?{active_key:p,instances:A}:{instances:A}})},tn=e=>Rt(e,!0),nn=e=>Rt(e,!1),ue=()=>F.setState({active_key:null}),be=e=>{F.setState(t=>{if(t.active_key===e||!t.instances[e])return{};let n={...t.instances};return delete n[e],{instances:n}})};var Tt="catalog",rn="paused_apps",on="removed_apps",sn=10*1e3,an=2,cn=3e3,pn=()=>{var e;try{return JSON.parse((e=b().storage.getString(Tt))!=null?e:"{}")}catch{return{}}},v=Se({catalog:{},downloads:{},pause_reasons:[],updates:{},apply_ticks:{}}),kt=e=>{var t;return!!((t=b().manual_update)!=null&&t.includes(e))},Pe=new Set,Ct=e=>{let t=new Set,n=()=>b().storage.setString(e,JSON.stringify([...t]));return{has:r=>t.has(r),values:()=>[...t],add:r=>t.has(r)?!1:(t.add(r),n(),!0),delete:r=>t.delete(r)?(n(),!0):!1,load:()=>{var r;t.clear();try{let s=JSON.parse((r=b().storage.getString(e))!=null?r:"[]");Array.isArray(s)&&s.forEach(o=>{typeof o=="string"&&t.add(o)})}catch{}}}},J=Ct(rn),X=Ct(on);at(()=>{J.load(),X.load();let e=pn(),t={};Object.keys(e).filter(n=>!X.has(n)).forEach(n=>{let r=_(n);r?t[n]={status:"installed",progress:1,version:r.version,has_local:!0}:J.has(n)&&(t[n]={status:"paused",progress:0,version:e[n].version,has_local:!1})}),v.setState({catalog:e,downloads:t})});var qe=e=>j(v,t=>e?t.downloads[e]:void 0),ln=()=>j(v,e=>e.pause_reasons.length>0),U=(...e)=>L("queue",...e),P=[],K={},h=null,xe=new Set,re={},je=new Set,Q=e=>{je.forEach(t=>{try{t(e)}catch(n){console.warn("[miniapp-queue] event listener error",n==null?void 0:n.message)}})},un=e=>(je.add(e),()=>{je.delete(e)}),dn=()=>v.getState().downloads,C=(e,t)=>{let n=!!_(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?Q({type:"status_change",app_id:e,state:o}):r.progress!==o.progress&&Q({type:"progress",app_id:e,progress:o.progress,version:o.version})},Ee=(e,t)=>{var n;(n=re[e])==null||n.forEach(r=>r(t)),delete re[e]},gn=()=>v.getState().pause_reasons.length>0,G=e=>{var u;if(h)return;let t=e?P.indexOf(e):gn()?-1:P.findIndex(i=>!J.has(i));if(t<0||t>=P.length)return;let[n]=P.splice(t,1),r=v.getState().catalog[n];if(!r){Ee(n,_(n)),G();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=We(r,{onProgress:i=>{let p=Math.floor(i*100);p!==o&&(o=p,C(n,{progress:p/100,version:r.version}))}});h={app_id:n,handle:a,forced:!!e},U("start",n,r.version,e?"(forced)":""),a.promise.then(i=>{U("installed",n,r.version,`${Date.now()-s}ms`),C(n,{status:"installed",progress:1,version:r.version}),Ee(n,i)}).catch(i=>{var A;if(i instanceof oe){if(xe.has(n))return;U("paused",n),K[n]-=1,P.unshift(n),C(n,{status:J.has(n)?"paused":"queued",progress:0,version:r.version});return}let p=String((A=i==null?void 0:i.message)!=null?A:i);if(console.warn("[miniapp-queue] failed",n,p),K[n]<an){C(n,{status:"queued",progress:0,version:r.version,error:p}),setTimeout(()=>{var M;P.includes(n)||(h==null?void 0:h.app_id)===n||(P.push(n),G((M=re[n])!=null&&M.length?n:void 0))},cn);return}C(n,{status:"failed",progress:0,version:r.version,error:p}),Ee(n,_(n))}).finally(()=>{h=null;let i=P.find(p=>{var A;return(A=re[p])==null?void 0:A.length});G(i)})},Re=(e,{front:t=!1}={})=>{if((h==null?void 0:h.app_id)===e)return;let n=P.indexOf(e);if(n>=0){if(!t)return;P.splice(n,1)}t?P.unshift(e):P.push(e)},fn=async e=>{let{host_id:t,client_token:n}=b(),r=new AbortController,s=setTimeout(()=>r.abort(),sn);try{let o=`${Ie}/api/hosts/${encodeURIComponent(t)}/miniapps?channel=${e}`,a=await fetch(o,{headers:{Authorization:`Bearer ${n}`,"Cache-Control":"no-cache"},signal:r.signal});if(!a.ok)throw new Error(`host list ${e} ${a.status}`);return(await a.json()).apps.map(i=>({...i,channel:e}))}finally{clearTimeout(s)}},de=null,Ke=()=>(de!=null||(de=(async()=>{var t;let e=Date.now();try{let n=await Promise.all(b().channels.map(fn)),r={};[...n].reverse().flat().forEach(i=>{r[i.app_id]=i});let s=Object.keys(v.getState().catalog).filter(i=>!r[i]);b().storage.setString(Tt,JSON.stringify(r)),v.setState({catalog:r}),await Promise.all(s.map(i=>Ot(i,{by_user:!1}))),s.forEach(i=>X.delete(i));let o=Object.keys(r).filter(i=>!X.has(i)),a=[],u={};for(let i of o.map(p=>r[p])){if(await He(i)){C(i.app_id,{status:"installed",progress:1,version:i.version});continue}let p=_(i.app_id);if(kt(i.app_id)&&!Pe.has(i.app_id)&&p&&await q(p)){C(i.app_id,{status:"installed",progress:1,version:p.version}),u[i.app_id]={app_id:i.app_id,current_version:p.version,next_version:i.version};continue}a.push(i)}return v.setState({updates:u}),a.forEach(i=>{K[i.app_id]=0,C(i.app_id,{status:J.has(i.app_id)?"paused":"queued",progress:0,version:i.version,error:void 0}),Re(i.app_id)}),U("catalog",o.length,"apps, outdated",a.map(i=>i.app_id),"removed",s,`${Date.now()-e}ms`),Q({type:"sync_complete",app_ids:o,removed:s}),Object.values(u).forEach(i=>Q({type:"update_available",...i})),G(),{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),Q({type:"sync_failed",error:r}),{ok:!1,error:r}}finally{de=null}})()),de),Ot=async(e,{by_user:t})=>{var s,o,a,u;if(t&&X.add(e),xe.has(e))return;xe.add(e),J.delete(e);let n=P.indexOf(e);n>=0&&P.splice(n,1),(h==null?void 0:h.app_id)===e&&h.handle.cancel();let r=(u=(a=(s=v.getState().downloads[e])==null?void 0:s.version)!=null?a:(o=_(e))==null?void 0:o.version)!=null?u:"";C(e,{status:"uninstalling",progress:0,version:r}),await bt(e),be(e),v.setState(i=>{let p={...i.downloads};return delete p[e],{downloads:p}}),delete K[e],xe.delete(e),Ee(e,null),U("uninstalled",e,t?"(user)":"(not in list)"),Q({type:"uninstalled",app_id:e})},hn=e=>Ot(e,{by_user:!0}),mn=e=>{let t=ge(e);return t?(X.delete(e),(h==null?void 0:h.app_id)===e||P.includes(e)||(K[e]=0,C(e,{status:J.has(e)?"paused":"queued",progress:0,version:t.version,error:void 0}),Re(e),G(),U("restore",e)),!0):!1},An=e=>{if(J.has(e))return;if(J.add(e),U("pause app",e),(h==null?void 0:h.app_id)===e&&!h.forced){h.handle.cancel();return}let t=v.getState().downloads[e];P.includes(e)&&t&&C(e,{status:"paused",progress:0,version:t.version})},Mn=e=>{if(!J.delete(e))return;U("resume app",e);let t=v.getState().downloads[e];(t==null?void 0:t.status)==="paused"&&!P.includes(e)&&ge(e)&&(K[e]=0,Re(e)),P.includes(e)&&t&&C(e,{status:"queued",progress:0,version:t.version}),G()},yn=e=>{let{pause_reasons:t}=v.getState();t.includes(e)||(v.setState({pause_reasons:[...t,e]}),U("pause",e),t.length===0&&Q({type:"pause_change",paused:!0,reasons:[e]}),h&&!h.forced&&h.handle.cancel())},wn=e=>{let{pause_reasons:t}=v.getState();if(!t.includes(e))return;let n=t.filter(r=>r!==e);v.setState({pause_reasons:n}),U("resume",e),n.length===0&&Q({type:"pause_change",paused:!1,reasons:n}),G()},It=e=>v.getState().updates[e],vn=async e=>{var n,r;let t=It(e);Pe.add(e);try{let s=await Te(e),o=(r=t==null?void 0:t.next_version)!=null?r:(n=ge(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}}}),U("updated",e,t==null?void 0:t.current_version,"\u2192",s.version),!0)}finally{Pe.delete(e)}},_n=()=>Object.values(v.getState().catalog).map(e=>({...e,installed:!!_(e.app_id),removed_by_user:X.has(e.app_id)})),ge=e=>v.getState().catalog[e],Te=async e=>{let t=ge(e);if(!t)return;if(J.delete(e),X.delete(e),await He(t))return _(e);let n=_(e);if(kt(e)&&!Pe.has(e)&&n&&await q(n))return n;let r=new Promise(s=>{var o;((o=re[e])!=null?o:re[e]=[]).push(s)});return(h==null?void 0:h.app_id)===e?h.forced=!0:(K[e]=0,Re(e,{front:!0}),h&&!h.forced?h.handle.cancel():G(e)),r};import{Fragment as Bt,jsx as R,jsxs as he}from"react/jsx-runtime";var Ye=e=>(e!=null?e:"").replace(/\?[^#]*/,""),Dt=0,Rn=()=>{let e=new Set;return{emit:t=>e.forEach(n=>n(t)),subscribe:t=>(e.add(t),()=>{e.delete(t)})}},Tn=Xe.memo(({instance_key:e,is_active:t,is_front:n,is_dark:r,reload_tick:s,web_at_top:o,splash:a,bridge:u,opaque_background:i,allow_embedded_miniapps:p,onWebLoadEnd:A})=>{var it,ot;let M=H(null),y=H(!1),m=j(F,c=>c.instances[e]),f=m==null?void 0:m.app.app_id,N=m==null?void 0:m.app.manifest_url,E=m==null?void 0:m.context,O=m==null?void 0:m.url_params,[l,T]=ie(()=>f?_(f):null),[se,d]=ie(!1),[S,z]=ie(0),[Z,ae]=ie(0),[$t,I]=ie(!1),W=H(null),et=c=>{W.current&&clearTimeout(W.current),W.current=setTimeout(()=>{W.current=null,I(!0)},c)};V(()=>()=>{W.current&&clearTimeout(W.current)},[]),V(()=>{if(!f||!t&&l)return;let c=!0;return d(!1),(async()=>{let g=_(f),k=g?await q(g):!1;if(!c||(T(k?$=>!$||$.version!==g.version||$.permissions.join(",")!==g.permissions.join(",")?g:$:null),__DEV__&&Date.now()-Dt>1e4&&(Dt=Date.now(),await Ke()),!c))return;let Y=await Te(f),ee=Y!==void 0?Y:N?await Et(f,N):_(f);if(c){if(!ee){d(!0);return}T($=>$!=null?$:ee)}})(),()=>{c=!1}},[t,f,N,S]),V(()=>Pt(e,c=>M.current?(M.current.postMessage(c),!0):!1),[e]);let Ft=j(v,c=>{let g=f?c.downloads[f]:void 0;return(g==null?void 0:g.status)==="installed"?g.version:void 0});V(()=>{if(t||!f||!l)return;let c=_(f);if(!c||c.version===l.version)return;let g=!0;return q(c).then(k=>{!g||!k||(L(`webview:${e}`,"\u0111\u1ED5i bundle (\u1EA9n)",l.version,"\u2192",c.version),T(c))}),()=>{g=!1}},[t,f,Ft,l==null?void 0:l.version]);let tt=j(v,c=>{var g;return f&&(g=c.apply_ticks[f])!=null?g:0});V(()=>{if(!tt||!f)return;let c=_(f);if(!c||c.version===(l==null?void 0:l.version))return;let g=!0;return q(c).then(k=>{!g||!k||(L(`webview:${e}`,"c\u1EADp nh\u1EADt",l==null?void 0:l.version,"\u2192",c.version),I(!1),T(c))}),()=>{g=!1}},[tt]),V(()=>{var k;let c=(k=b().keep_alive)==null?void 0:k.idle_close_ms;if(t||!c||c<=0)return;let g=setTimeout(()=>{be(e)},c);return()=>clearTimeout(g)},[t,e]),V(()=>{s>0&&(d(!1),I(!1),ae(c=>c+1),z(c=>c+1))},[s]);let nt=H(t);V(()=>{var c;nt.current!==t&&(nt.current=t,y.current&&((c=M.current)==null||c.injectJavaScript(ht(t?"resumed":"paused"))))},[t]);let me=`${(it=l==null?void 0:l.version)!=null?it:"none"}:${(ot=l==null?void 0:l.permissions.join(","))!=null?ot:""}:${Z}`,ce=ke(()=>JSON.stringify([E!=null?E:{},O!=null?O:{}]),[E,O]),Ce=ke(()=>{var c;return wt(O!=null?O:{},(c=l==null?void 0:l.permissions)!=null?c:[])},[ce,l==null?void 0:l.permissions]),Ut=ke(()=>Mt(E!=null?E:{},Ce)+ft()+(b().debug?gt():""),[Ce]),Ae=H(null),rt=H(null);V(()=>{var g,k,Y;if(!l)return;if(rt.current!==me){rt.current=me,Ae.current=ce;return}if(Ae.current===ce)return;let c=((k=JSON.parse((g=Ae.current)!=null?g:"[]")[0])!=null?k:{}).org_id;if(Ae.current=ce,c===(E==null?void 0:E.org_id)&&y.current){I(!1),et(1500),(Y=M.current)==null||Y.injectJavaScript(mt(E!=null?E:{},Ce));return}I(!1),ae(ee=>ee+1)},[ce,l,me]);let Jt=Qe(async c=>{var k,Y,ee,$,Oe;let g=lt(c.nativeEvent.data);if(!g){if(f&&(u!=null&&u.onWebEvent))try{Promise.resolve(u.onWebEvent(c.nativeEvent.data,{app_id:f,instance_id:e})).catch(x=>{console.warn("[miniapp] onWebEvent l\u1ED7i",f,x)})}catch(x){console.warn("[miniapp] onWebEvent l\u1ED7i",f,x)}return}if(g.method==="log"){let{level:x,text:D}=g;L(`web:${e}`,x!=null?x:"log",D!=null?D:"");return}if(g.method==="pong"){W.current||I(!0);return}if(g.method==="touchAtTop"){o.emit(!!g.at_top);return}if(g.method==="contextApplied"){W.current&&clearTimeout(W.current),W.current=null,I(!0);return}if(g.method==="ready"){y.current=!0,I(!0);let x=(k=F.getState().instances[e])==null?void 0:k.context;x&&((Y=M.current)==null||Y.injectJavaScript(Ne(x)));return}try{let x=await vt(g,{getHostData:()=>{var D,te;return(te=(D=F.getState().instances[e])==null?void 0:D.host_data)!=null?te:{}},getPermissions:()=>{var D,te;return f?(te=(D=_(f))==null?void 0:D.permissions)!=null?te:[]:[]},is_dark:r,close:ue,app_id:f!=null?f:"",instance_id:e,options:u});g.id&&((ee=M.current)==null||ee.injectJavaScript(ut(g.id,x)))}catch(x){if(!g.id)return;let D=x==null?void 0:x.code,te=x instanceof w?x:new w(typeof D=="string"?D:"HOST_ERROR",String(($=x==null?void 0:x.message)!=null?$:x));(Oe=M.current)==null||Oe.injectJavaScript(dt(g.id,te))}},[e,r,f,o,u]),Vt=Qe(()=>{d(!1),ae(c=>c+1),z(c=>c+1)},[]);return he(Ge,{style:[Ze.absoluteFill,i&&{backgroundColor:r?"#09090B":"#FFFFFF"},!n&&B.behind],pointerEvents:t?"auto":"none",children:[l?R(Pn,{ref:M,source:{uri:l.entry_uri},originWhitelist:["*"],allowingReadAccessToURL:`file://${p?Ue():l.dir}`,allowFileAccess:!0,allowFileAccessFromFileURLs:!0,allowUniversalAccessFromFileURLs:!0,injectedJavaScriptBeforeContentLoaded:Ut,onMessage:Jt,bounces:!1,overScrollMode:"never",onLoadStart:c=>{L(`webview:${e}`,"load start",Ye(c.nativeEvent.url)),y.current=!1,I(!1)},onError:c=>{L(`webview:${e}`,"load error",Ye(c.nativeEvent.url),c.nativeEvent.description),d(!0),I(!1)},onLoadEnd:c=>{let g=c.nativeEvent.url;L(`webview:${e}`,"load end",Ye(g)),f&&(A==null||A({app_id:f,instance_id:e,url:g})),et(1500)},onContentProcessDidTerminate:()=>{y.current=!1,I(!1),ae(c=>c+1)},onRenderProcessGone:()=>(y.current=!1,I(!1),ae(c=>c+1),!0),style:B.webview},me):null,m&&R(Cn,{visible:!l||!$t,interactive:se,children:R(kn,{splash:a,app:m.app,is_dark:r,error:se,has_bundle:!!l,retry:Vt})})]})}),kn=Xe.memo(({splash:e,app:t,is_dark:n,error:r,has_bundle:s,retry:o})=>{let a=e,u=qe(t.app_id),i=r?"error":!s&&(u==null?void 0:u.status)==="downloading"?"downloading":"loading";return R(a,{app:t,is_dark:n,status:i,progress:i==="downloading"?u==null?void 0:u.progress:void 0,retry:o})}),Cn=({visible:e,interactive:t,children:n})=>{let r=H(new ze.Value(e?1:0)).current,[s,o]=ie(e);return V(()=>{if(e){o(!0),r.setValue(1);return}let a=ze.timing(r,{toValue:0,duration:180,useNativeDriver:!0});return a.start(({finished:u})=>{u&&o(!1)}),()=>a.stop()},[e,r]),s?R(ze.View,{style:[Ze.absoluteFill,{opacity:r}],pointerEvents:t?"auto":"none",children:n}):null},Nt=({app:e,is_dark:t,status:n,progress:r,retry:s})=>{let o=t?"#FAFAFA":"#18181B";return he(Ge,{style:[B.splash,{backgroundColor:t?"#09090B":"#FFFFFF"}],children:[R(Ge,{style:[B.splash_icon,{backgroundColor:t?"#18181B":"#F4F4F5"}],children:e.icon?R(xn,{source:{uri:e.icon},style:B.splash_icon_image}):R(fe,{style:B.splash_letter,children:(e.name||"?").slice(0,1).toUpperCase()})}),R(fe,{style:[B.splash_name,{color:o}],children:e.name}),n==="error"?he(Bt,{children:[R(fe,{style:B.splash_hint,children:"Kh\xF4ng t\u1EA3i \u0111\u01B0\u1EE3c mini app"}),R(En,{activeOpacity:.7,style:[B.retry_button,{backgroundColor:t?"#27272A":"#F4F4F5"}],onPress:s,children:R(fe,{style:[B.retry_text,{color:o}],children:"Th\u1EED l\u1EA1i"})})]}):he(Bt,{children:[R(Sn,{style:B.splash_spinner,color:t?"#A1A1AA":"#71717A"}),n==="downloading"&&he(fe,{style:B.splash_hint,children:["\u0110ang t\u1EA3i mini app",r?` ${Math.round(r*100)}%`:"\u2026"]})]})]})},Lt=(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.`))},On=({container:e,splash:t=Nt,is_dark:n=!1,bridge:r,close_on_back:s=!0,opaque_background:o=!0,allow_embedded_miniapps:a=!1,onWebLoadEnd:u})=>{Lt("container",e),Lt("splash",t);let i=e,p=j(F,l=>l.active_key),A=H(p);p&&(A.current=p);let M=j(F,l=>Object.keys(l.instances).join("|")),y=j(F,l=>{var T;return l.active_key?(T=l.instances[l.active_key])==null?void 0:T.app.name:void 0}),m=ke(()=>M?M.split("|"):[],[M]),[f,N]=ie({}),E=H(Rn()).current;V(()=>{if(!p||!s)return;let l=bn.addEventListener("hardwareBackPress",()=>(ue(),!0));return()=>l.remove()},[p,s]);let O=Qe(()=>{let l=F.getState().active_key;l&&N(T=>({...T,[l]:(T[l]||0)+1}))},[]);return m.length?R(i,{visible:!!p,title:y!=null?y:"",is_dark:n,close:ue,reload:O,subscribeWebAtTop:E.subscribe,children:m.map(l=>R(Tn,{instance_key:l,is_active:p===l,is_front:(p!=null?p:A.current)===l,is_dark:n,reload_tick:f[l]||0,web_at_top:E,splash:t,bridge:r,opaque_background:o,allow_embedded_miniapps:a,onWebLoadEnd:u},l))}):null},B=Ze.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"}}),In=Xe.memo(On);export{Nt as DefaultMiniAppSplash,Ie as MINIAPP_PLATFORM_URL,In as MiniAppHost,w as MiniAppHostError,ue as closeMiniApp,Ht as configureMiniApp,jt as createMmkvStorage,ct as createReactNativeBiometrics,Wt as createRnfsFileSystem,Te as ensureMiniApp,_ as getLocalMiniApp,_n as getMiniAppCatalog,ge as getMiniAppCatalogEntry,dn as getMiniAppStatuses,It as getMiniAppUpdate,Qt as installBundledMiniApp,un as onMiniAppEvent,tn as openMiniApp,An as pauseMiniApp,yn as pauseMiniAppDownloads,nn as preloadMiniApp,mn as restoreMiniApp,Mn as resumeMiniApp,wn as resumeMiniAppDownloads,Xt as sendEventToWeb,Ke as syncMiniAppCatalog,hn as uninstallMiniApp,vn as updateMiniApp,qe as useMiniAppDownload,ln as useMiniAppDownloadsPaused};
45
+ true;`},Rt={partner:"partner_token",chatbox:"chatbox_token"},Pt=(e,t)=>{let n={...e};for(let r of Object.values(Rt))t.includes(r)||delete n[r];return n},Fe=new Set,Ve=async(e,t)=>{if(Fe.has(e))throw new A("BUSY",`${e} \u0111ang ch\u1EA1y \u2014 ch\u1EDD l\u01B0\u1EE3t tr\u01B0\u1EDBc xong`);Fe.add(e);try{return await t()}finally{Fe.delete(e)}},nn=new Set(["selection","impactLight","impactMedium","impactHeavy","rigid","soft","notificationSuccess","notificationWarning","notificationError"]),be=(e,t)=>{if(typeof e!="string"||!e)throw new A("INVALID_PARAMS",`Thi\u1EBFu ${t}`);return e},Tt=async({method:e,params:t},{getHostData:n,getPermissions:r,is_dark:o,close:s,app_id:a,instance_id:p,options:i,emit:u,isActive:w})=>{var f,T,E,L,l,O,pe,X,ye;let h=i==null?void 0:i.handlers,y={app_id:a,instance_id:p,close:s},m=()=>new A("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF \u1EE9ng d\u1EE5ng n\xE0y`);switch(e){case"speech.start":{if(!u)throw m();let d={};if((t==null?void 0:t.lang)!==void 0){if(typeof t.lang!="string"||!/^[a-zA-Z]{2,8}(-[a-zA-Z0-9]{1,8})*$/.test(t.lang))throw new A("INVALID_PARAMS","lang ph\u1EA3i l\xE0 m\xE3 ng\xF4n ng\u1EEF nh\u01B0 vi-VN");d.lang=t.lang}for(let v of["continuous","interimResults","addsPunctuation","requiresOnDeviceRecognition"])if((t==null?void 0:t[v])!==void 0){if(typeof t[v]!="boolean")throw new A("INVALID_PARAMS",`${v} ph\u1EA3i l\xE0 boolean`);d[v]=t[v]}return ft(p,d,u,w)}case"speech.stop":return ht(p);case"getBiometricAvailability":return((f=i==null?void 0:i.biometrics)!=null?f:await Be()).getAvailability();case"authenticateBiometric":{let d=be(t==null?void 0:t.reason,"reason").trim();if(!d||d.length>200)throw new A("INVALID_PARAMS","reason must contain 1\u2013200 characters");let v=t==null?void 0:t.cancelButtonText;if(v!==void 0&&(typeof v!="string"||!v.trim()||v.length>80))throw new A("INVALID_PARAMS","Invalid cancelButtonText");return Ve(e,async()=>{var re;return((re=i==null?void 0:i.biometrics)!=null?re:await Be()).authenticate({reason:d,cancelButtonText:v})})}case"requestPayment":{let d=h==null?void 0:h.requestPayment;if(!d)throw m();let v=t==null?void 0:t.amount;if(typeof v!="number"||!Number.isFinite(v)||v<=0)throw new A("INVALID_PARAMS","amount ph\u1EA3i l\xE0 s\u1ED1 > 0");let V={...t,amount:v,currency:be(t==null?void 0:t.currency,"currency")};return Ve(e,()=>d(V,y))}case"printImage":{let d=h==null?void 0:h.printImage;if(!d)throw m();let v=be(t==null?void 0:t.image,"image");await Ve(e,()=>d({image:v},y));return}case"openScreen":if(!(h!=null&&h.openScreen))throw m();await h.openScreen({screen:be(t==null?void 0:t.screen,"screen"),params:t==null?void 0:t.params},y);return;case"closeApp":s();return;case"openWebview":{let d=String((T=t==null?void 0:t.url)!=null?T:"");if(!/^https?:\/\//i.test(d))throw new A("INVALID_PARAMS","url ph\u1EA3i l\xE0 http(s)");await(i!=null&&i.openUrl?i.openUrl(d):mt.openURL(d));return}case"openLink":{let d=String((E=t==null?void 0:t.url)!=null?E:"").trim();if(!/^[a-z][a-z0-9+.-]*:/i.test(d)||/^(javascript|file|data|about|blob):/i.test(d))throw new A("INVALID_PARAMS","url kh\xF4ng h\u1EE3p l\u1EC7");try{await(i!=null&&i.openUrl?i.openUrl(d):mt.openURL(d))}catch(v){throw new A("NOT_SUPPORTED",String((l=(L=v==null?void 0:v.message)!=null?L:v)!=null?l:"Kh\xF4ng m\u1EDF \u0111\u01B0\u1EE3c link"))}return}case"showToast":(pe=i==null?void 0:i.showToast)==null||pe.call(i,String((O=t==null?void 0:t.message)!=null?O:""));return;case"haptic":{let d=nn.has(t==null?void 0:t.type)?t.type:"selection";(X=i==null?void 0:i.haptic)==null||X.call(i,d);return}case"getSystemInfo":return{platform:tn.OS==="ios"?"ios":"android",appVersion:(ye=i==null?void 0:i.app_version)!=null?ye:"",theme:o?"dark":"light"};case"getAccessToken":{let d=n().access_token;if(!d)throw new A("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 A("HOST_ERROR","Mini app ch\u01B0a c\xF3 token cho page n\xE0y");return re}if(d!=="partner"&&d!=="chatbox")throw new A("HOST_ERROR",`Lo\u1EA1i token kh\xF4ng h\u1EE3p l\u1EC7: ${String(d)}`);let v=Rt[d];if(!r().includes(v))throw new A("PERMISSION_DENIED",`Mini app ch\u01B0a \u0111\u01B0\u1EE3c c\u1EA5p quy\u1EC1n ${v} (Console \u2192 Quy\u1EC1n l\u1EA5y token)`);let V=d==="partner"?n().partner_token:n().chatbox_token;if(!V)throw new A("HOST_ERROR",`Kh\xF4ng c\xF3 ${v}`);return V}case"getUserInfo":{let d=n().user;if(!d)throw new A("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 A("HOST_ERROR","Kh\xF4ng l\u1EA5y \u0111\u01B0\u1EE3c th\xF4ng tin page");return d}case"sendMessage":case"insertText":throw new A("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF phi\xEAn b\u1EA3n app n\xE0y`);default:throw new A("NOT_SUPPORTED",`API kh\xF4ng t\u1ED3n t\u1EA1i: ${e}`)}};var qe=e=>`bundle:${e}`,je=()=>`${_().file_system.document_dir}/miniapps`,He=je,We=(e,t,n="index.html",r=!1,o=[])=>{let s=`${He()}/${e}/${t}`;return{app_id:e,version:t,dir:s,entry_uri:`file://${s}/${n}`,context_update:r,permissions:o}},Je=e=>{var t;_().storage.setString(qe(e.app_id),JSON.stringify({version:e.version,entry:e.entry,context_update:!!e.context_update,permissions:(t=e.permissions)!=null?t:[]}))},rn=(e,t)=>/^https?:\/\//.test(t)?t:`${e.replace(/[^/]*$/,"")}${t}`,b=e=>{let t=_().storage.getString(qe(e));if(!t)return null;try{let{version:n,entry:r,context_update:o,permissions:s}=JSON.parse(t);return We(e,n,r,!!o,Array.isArray(s)?s:[])}catch{return null}},Q=e=>_().file_system.exists(e.entry_uri.replace("file://","")),ze=async e=>{let t=b(e.app_id);return(t==null?void 0:t.version)===e.version&&await Q(t)},Ct=async(e,t)=>{let n=_().file_system,r=`${He()}/${e}`,o=await n.listDir(r).catch(()=>[]);await Promise.all(o.filter(s=>!t.includes(s)).map(s=>n.remove(`${r}/${s}`).catch(()=>{})))},kt=async e=>{var t;await((t=fe[e])==null?void 0:t.catch(()=>{})),_().storage.setString(qe(e),""),await _().file_system.remove(`${He()}/${e}`).catch(()=>{})},ce=class extends Error{constructor(){super("cancelled"),this.name="MiniAppInstallCancelled"}},fe={},Dt=(e,t)=>{var s;let r=((s=fe[e])!=null?s:Promise.resolve()).catch(()=>{}).then(t),o=r.catch(()=>{});return fe[e]=o,o.then(()=>{fe[e]===o&&delete fe[e]}),r},on=(e,t)=>{var o,s;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 p=((o=n[a])!=null?o:0)-((s=r[a])!=null?s:0);if(p)return p}return 0},sn=({manifest:e,zip_path:t})=>Dt(e.app_id,async()=>{var s;let n=_().file_system,r=b(e.app_id);if(r&&on(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 o=We(e.app_id,e.version,e.entry,!!e.context_update,(s=e.permissions)!=null?s:[]);return await n.remove(o.dir).catch(()=>{}),await n.mkdir(o.dir),await n.unzip(t,o.dir),Je(e),B("\u0111\xE3 c\xE0i b\u1EA3n \u0111\xF3ng s\u1EB5n",e.app_id,e.version),Ct(e.app_id,[e.version,r==null?void 0:r.version].filter(Boolean)),o}),Ke=(e,{base_url:t,onProgress:n}={})=>{let r=_().file_system,o=null,s=!1,a=`${r.cache_dir}/${e.app_id}-${e.version}.zip`,p=()=>{if(s)throw new ce},i=async()=>{var h;p();let u=b(e.app_id);if((u==null?void 0:u.version)===e.version&&await r.exists(u.dir))return Je(e),b(e.app_id);p();let w=r.download({url:t?rn(t,e.bundle_url):e.bundle_url,to_file:a,onProgress:(y,m)=>{var T;let f=m>0?m:(T=e.size)!=null?T:0;f>0&&(n==null||n(Math.min(1,y/f)))}});o=w;try{let{status:y}=await w.promise;if(p(),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 B("b\u1ECF qua ki\u1EC3m tra sha256 (file_system kh\xF4ng c\xF3 sha256)",e.app_id);p();let m=We(e.app_id,e.version,e.entry,!!e.context_update,(h=e.permissions)!=null?h:[]);return await r.remove(m.dir).catch(()=>{}),await r.mkdir(m.dir),await r.unzip(a,m.dir),Je(e),Ct(e.app_id,[e.version,u==null?void 0:u.version].filter(Boolean)),m}catch(y){throw s?new ce:y}finally{o=null,r.remove(a).catch(()=>{})}};return{promise:Dt(e.app_id,i),cancel:()=>{s=!0,o==null||o.cancel()}}},ge={},an=__DEV__?0:60*1e3,Ot={},It=(e,t)=>{var r,o;let n=b(e);return n&&Date.now()-((r=Ot[t])!=null?r:0)<an?Promise.resolve(n):((o=ge[e])!=null||(ge[e]=(async()=>{let s=await fetch(t,{headers:{"Cache-Control":"no-cache"}});if(!s.ok)throw new Error(`manifest ${s.status}`);let a=await s.json(),p=await Ke(a,{base_url:t}).promise;return Ot[t]=Date.now(),p})().catch(s=>(console.warn("[miniapp] sync failed",e,s==null?void 0:s.message),b(e))).finally(()=>{ge[e]=void 0})),ge[e])};var xe=new Map,Lt=(e,t)=>(xe.set(e,t),()=>{xe.get(e)===t&&xe.delete(e)}),cn=(e,t)=>{let n=xe.get(e);return n?n(t):!1};import{useRef as pn,useSyncExternalStore as ln}from"react";var Ee=e=>{let t=e,n=new Set;return{getState:()=>t,setState:r=>{let o=typeof r=="function"?r(t):r;t={...t,...o},n.forEach(s=>s())},subscribe:r=>(n.add(r),()=>{n.delete(r)})}},W=(e,t,n=Object.is)=>{let r=pn(null),o=()=>{let s=e.getState(),a=r.current;if(a&&a.state===s&&a.selector===t)return a.value;let p=t(s),i=a&&n(a.value,p)?a.value:p;return r.current={state:s,selector:t,value:i},i};return ln(e.subscribe,o)};var $=Ee({active_key:null,instances:{}}),Nt=({app:e,instance_id:t,context:n={},url_params:r={},host_data:o={}},s)=>{var p;let a=(p=_().keep_alive)==null?void 0:p.max_webviews;$.setState(i=>{let u=t!=null?t:e.app_id,w={...i.instances,[u]:{key:u,app:e,context:n,url_params:r,host_data:o,last_used_at:Date.now()}},h=Object.keys(w);return a&&a>0&&h.length>a&&h.filter(y=>y!==u).sort((y,m)=>w[y].last_used_at-w[m].last_used_at).slice(0,h.length-a).forEach(y=>{delete w[y]}),s?{active_key:u,instances:w}:{instances:w}})},un=e=>Nt(e,!0),dn=e=>Nt(e,!1),he=()=>$.setState({active_key:null}),Re=e=>{$.setState(t=>{if(t.active_key===e||!t.instances[e])return{};let n={...t.instances};return delete n[e],{instances:n}})};var Bt="catalog",gn="paused_apps",fn="removed_apps",hn=10*1e3,mn=2,An=3e3,wn=()=>{var e;try{return JSON.parse((e=_().storage.getString(Bt))!=null?e:"{}")}catch{return{}}},S=Ee({catalog:{},downloads:{},pause_reasons:[],updates:{},apply_ticks:{}}),$t=e=>{var t;return!!((t=_().manual_update)!=null&&t.includes(e))},Oe=new Set,Ft=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 o=JSON.parse((r=_().storage.getString(e))!=null?r:"[]");Array.isArray(o)&&o.forEach(s=>{typeof s=="string"&&t.add(s)})}catch{}}}},q=Ft(gn),ne=Ft(fn);dt(()=>{q.load(),ne.load();let e=wn(),t={};Object.keys(e).filter(n=>!ne.has(n)).forEach(n=>{let r=b(n);r?t[n]={status:"installed",progress:1,version:r.version,has_local:!0}:q.has(n)&&(t[n]={status:"paused",progress:0,version:e[n].version,has_local:!1})}),S.setState({catalog:e,downloads:t})});var Qe=e=>W(S,t=>e?t.downloads[e]:void 0),Mn=()=>W(S,e=>e.pause_reasons.length>0),J=(...e)=>B("queue",...e),R=[],G={},M=null,Pe=new Set,se={},Ye=new Set,ee=e=>{Ye.forEach(t=>{try{t(e)}catch(n){console.warn("[miniapp-queue] event listener error",n==null?void 0:n.message)}})},yn=e=>(Ye.add(e),()=>{Ye.delete(e)}),vn=()=>S.getState().downloads,D=(e,t)=>{let n=!!b(e),r=S.getState().downloads[e],o=t.status==="downloading"&&n?"updating":t.status,s={...r!=null?r:{status:"queued",progress:0},...t,...o?{status:o}:{},has_local:n};S.setState(a=>({downloads:{...a.downloads,[e]:s}})),(r==null?void 0:r.status)!==s.status||(r==null?void 0:r.version)!==s.version||(r==null?void 0:r.has_local)!==s.has_local?ee({type:"status_change",app_id:e,state:s}):r.progress!==s.progress&&ee({type:"progress",app_id:e,progress:s.progress,version:s.version})},Te=(e,t)=>{var n;(n=se[e])==null||n.forEach(r=>r(t)),delete se[e]},Sn=()=>S.getState().pause_reasons.length>0,te=e=>{var p;if(M)return;let t=e?R.indexOf(e):Sn()?-1:R.findIndex(i=>!q.has(i));if(t<0||t>=R.length)return;let[n]=R.splice(t,1),r=S.getState().catalog[n];if(!r){Te(n,b(n)),te();return}let o=Date.now();G[n]=((p=G[n])!=null?p:0)+1,D(n,{status:"downloading",progress:0,version:r.version,error:void 0});let s=0,a=Ke(r,{onProgress:i=>{let u=Math.floor(i*100);u!==s&&(s=u,D(n,{progress:u/100,version:r.version}))}});M={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()-o}ms`),D(n,{status:"installed",progress:1,version:r.version}),Te(n,i)}).catch(i=>{var w;if(i instanceof ce){if(Pe.has(n))return;J("paused",n),G[n]-=1,R.unshift(n),D(n,{status:q.has(n)?"paused":"queued",progress:0,version:r.version});return}let u=String((w=i==null?void 0:i.message)!=null?w:i);if(console.warn("[miniapp-queue] failed",n,u),G[n]<mn){D(n,{status:"queued",progress:0,version:r.version,error:u}),setTimeout(()=>{var h;R.includes(n)||(M==null?void 0:M.app_id)===n||(R.push(n),te((h=se[n])!=null&&h.length?n:void 0))},An);return}D(n,{status:"failed",progress:0,version:r.version,error:u}),Te(n,b(n))}).finally(()=>{M=null;let i=R.find(u=>{var w;return(w=se[u])==null?void 0:w.length});te(i)})},Ce=(e,{front:t=!1}={})=>{if((M==null?void 0:M.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)},bn=async e=>{let{host_id:t,client_token:n}=_(),r=new AbortController,o=setTimeout(()=>r.abort(),hn);try{let s=`${Ne}/api/hosts/${encodeURIComponent(t)}/miniapps?channel=${e}`,a=await fetch(s,{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(o)}},me=null,Ge=()=>(me!=null||(me=(async()=>{var t;let e=Date.now();try{let n=await Promise.all(_().channels.map(bn)),r={};[...n].reverse().flat().forEach(i=>{r[i.app_id]=i});let o=Object.keys(S.getState().catalog).filter(i=>!r[i]);_().storage.setString(Bt,JSON.stringify(r)),S.setState({catalog:r}),await Promise.all(o.map(i=>Vt(i,{by_user:!1}))),o.forEach(i=>ne.delete(i));let s=Object.keys(r).filter(i=>!ne.has(i)),a=[],p={};for(let i of s.map(u=>r[u])){if(await ze(i)){D(i.app_id,{status:"installed",progress:1,version:i.version});continue}let u=b(i.app_id);if($t(i.app_id)&&!Oe.has(i.app_id)&&u&&await Q(u)){D(i.app_id,{status:"installed",progress:1,version:u.version}),p[i.app_id]={app_id:i.app_id,current_version:u.version,next_version:i.version};continue}a.push(i)}return S.setState({updates:p}),a.forEach(i=>{G[i.app_id]=0,D(i.app_id,{status:q.has(i.app_id)?"paused":"queued",progress:0,version:i.version,error:void 0}),Ce(i.app_id)}),J("catalog",s.length,"apps, outdated",a.map(i=>i.app_id),"removed",o,`${Date.now()-e}ms`),ee({type:"sync_complete",app_ids:s,removed:o}),Object.values(p).forEach(i=>ee({type:"update_available",...i})),te(),{ok:!0,app_ids:s,removed:o}}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),ee({type:"sync_failed",error:r}),{ok:!1,error:r}}finally{me=null}})()),me),Vt=async(e,{by_user:t})=>{var o,s,a,p;if(t&&ne.add(e),Pe.has(e))return;Pe.add(e),q.delete(e);let n=R.indexOf(e);n>=0&&R.splice(n,1),(M==null?void 0:M.app_id)===e&&M.handle.cancel();let r=(p=(a=(o=S.getState().downloads[e])==null?void 0:o.version)!=null?a:(s=b(e))==null?void 0:s.version)!=null?p:"";D(e,{status:"uninstalling",progress:0,version:r}),await kt(e),Re(e),S.setState(i=>{let u={...i.downloads};return delete u[e],{downloads:u}}),delete G[e],Pe.delete(e),Te(e,null),J("uninstalled",e,t?"(user)":"(not in list)"),ee({type:"uninstalled",app_id:e})},_n=e=>Vt(e,{by_user:!0}),xn=e=>{let t=Ae(e);return t?(ne.delete(e),(M==null?void 0:M.app_id)===e||R.includes(e)||(G[e]=0,D(e,{status:q.has(e)?"paused":"queued",progress:0,version:t.version,error:void 0}),Ce(e),te(),J("restore",e)),!0):!1},En=e=>{if(q.has(e))return;if(q.add(e),J("pause app",e),(M==null?void 0:M.app_id)===e&&!M.forced){M.handle.cancel();return}let t=S.getState().downloads[e];R.includes(e)&&t&&D(e,{status:"paused",progress:0,version:t.version})},Rn=e=>{if(!q.delete(e))return;J("resume app",e);let t=S.getState().downloads[e];(t==null?void 0:t.status)==="paused"&&!R.includes(e)&&Ae(e)&&(G[e]=0,Ce(e)),R.includes(e)&&t&&D(e,{status:"queued",progress:0,version:t.version}),te()},Pn=e=>{let{pause_reasons:t}=S.getState();t.includes(e)||(S.setState({pause_reasons:[...t,e]}),J("pause",e),t.length===0&&ee({type:"pause_change",paused:!0,reasons:[e]}),M&&!M.forced&&M.handle.cancel())},Tn=e=>{let{pause_reasons:t}=S.getState();if(!t.includes(e))return;let n=t.filter(r=>r!==e);S.setState({pause_reasons:n}),J("resume",e),n.length===0&&ee({type:"pause_change",paused:!1,reasons:n}),te()},Ut=e=>S.getState().updates[e],On=async e=>{var n,r;let t=Ut(e);Oe.add(e);try{let o=await ke(e),s=(r=t==null?void 0:t.next_version)!=null?r:(n=Ae(e))==null?void 0:n.version;return!o||!s||o.version!==s?!1:(S.setState(a=>{var i;let p={...a.updates};return delete p[e],{updates:p,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",o.version),!0)}finally{Oe.delete(e)}},Cn=()=>Object.values(S.getState().catalog).map(e=>({...e,installed:!!b(e.app_id),removed_by_user:ne.has(e.app_id)})),Ae=e=>S.getState().catalog[e],ke=async e=>{let t=Ae(e);if(!t)return;if(q.delete(e),ne.delete(e),await ze(t))return b(e);let n=b(e);if($t(e)&&!Oe.has(e)&&n&&await Q(n))return n;let r=new Promise(o=>{var s;((s=se[e])!=null?s:se[e]=[]).push(o)});return(M==null?void 0:M.app_id)===e?M.forced=!0:(G[e]=0,Ce(e,{front:!0}),M&&!M.forced?M.handle.cancel():te(e)),r};import{Fragment as Ht,jsx as P,jsxs as Me}from"react/jsx-runtime";var Ze=e=>(e!=null?e:"").replace(/\?[^#]*/,""),qt=0,Bn=()=>{let e=new Set;return{emit:t=>e.forEach(n=>n(t)),subscribe:t=>(e.add(t),()=>{e.delete(t)})}},$n=nt.memo(({instance_key:e,is_active:t,is_front:n,is_dark:r,reload_tick:o,web_at_top:s,splash:a,bridge:p,opaque_background:i,allow_embedded_miniapps:u,onWebLoadEnd:w})=>{var ct,pt;let h=j(null),y=j(!1),m=W($,c=>c.instances[e]),f=m==null?void 0:m.app.app_id,T=m==null?void 0:m.app.manifest_url,E=m==null?void 0:m.context,L=m==null?void 0:m.url_params,[l,O]=ae(()=>f?b(f):null),[pe,X]=ae(!1),[ye,d]=ae(0),[v,V]=ae(0),[re,N]=ae(!1),H=j(null),it=c=>{H.current&&clearTimeout(H.current),H.current=setTimeout(()=>{H.current=null,N(!0)},c)};I(()=>()=>{H.current&&clearTimeout(H.current)},[]),I(()=>{if(!f||!t&&l)return;let c=!0;return X(!1),(async()=>{let g=b(f),C=g?await Q(g):!1;if(!c||(O(C?U=>!U||U.version!==g.version||U.permissions.join(",")!==g.permissions.join(",")?g:U:null),__DEV__&&Date.now()-qt>1e4&&(qt=Date.now(),await Ge()),!c))return;let Z=await ke(f),ie=Z!==void 0?Z:T?await It(f,T):b(f);if(c){if(!ie){X(!0);return}O(U=>U!=null?U:ie)}})(),()=>{c=!1}},[t,f,T,ye]),I(()=>Lt(e,c=>h.current?(h.current.postMessage(c),!0):!1),[e]);let zt=W(S,c=>{let g=f?c.downloads[f]:void 0;return(g==null?void 0:g.status)==="installed"?g.version:void 0});I(()=>{if(t||!f||!l)return;let c=b(f);if(!c||c.version===l.version)return;let g=!0;return Q(c).then(C=>{!g||!C||(B(`webview:${e}`,"\u0111\u1ED5i bundle (\u1EA9n)",l.version,"\u2192",c.version),O(c))}),()=>{g=!1}},[t,f,zt,l==null?void 0:l.version]);let ot=W(S,c=>{var g;return f&&(g=c.apply_ticks[f])!=null?g:0});I(()=>{if(!ot||!f)return;let c=b(f);if(!c||c.version===(l==null?void 0:l.version))return;let g=!0;return Q(c).then(C=>{!g||!C||(B(`webview:${e}`,"c\u1EADp nh\u1EADt",l==null?void 0:l.version,"\u2192",c.version),N(!1),O(c))}),()=>{g=!1}},[ot]),I(()=>{var C;let c=(C=_().keep_alive)==null?void 0:C.idle_close_ms;if(t||!c||c<=0)return;let g=setTimeout(()=>{Re(e)},c);return()=>clearTimeout(g)},[t,e]),I(()=>{o>0&&(X(!1),N(!1),V(c=>c+1),d(c=>c+1))},[o]);let st=j(t);I(()=>{var c;st.current!==t&&(st.current=t,y.current&&((c=h.current)==null||c.injectJavaScript(bt(t?"resumed":"paused"))))},[t]);let le=`${(ct=l==null?void 0:l.version)!=null?ct:"none"}:${(pt=l==null?void 0:l.permissions.join(","))!=null?pt:""}:${v}`,ue=De(()=>JSON.stringify([E!=null?E:{},L!=null?L:{}]),[E,L]),Ie=De(()=>{var c;return Pt(L!=null?L:{},(c=l==null?void 0:l.permissions)!=null?c:[])},[ue,l==null?void 0:l.permissions]),Kt=De(()=>Et(E!=null?E:{},Ie)+St()+(_().debug?vt():""),[Ie]),ve=j(null),at=j(null);I(()=>{var g,C,Z;if(!l)return;if(at.current!==le){at.current=le,ve.current=ue;return}if(ve.current===ue)return;let c=((C=JSON.parse((g=ve.current)!=null?g:"[]")[0])!=null?C:{}).org_id;if(ve.current=ue,c===(E==null?void 0:E.org_id)&&y.current){N(!1),it(1500),(Z=h.current)==null||Z.injectJavaScript(_t(E!=null?E:{},Ie));return}N(!1),V(ie=>ie+1)},[ue,l,le]),I(()=>(t||Y(e),()=>Y(e)),[t,e,le,o]),I(()=>{let c=Jt.addEventListener("change",g=>{g==="background"&&Y(e)});return()=>c.remove()},[e]);let Yt=et(async c=>{var C,Z,ie,U,Le;let g=At(c.nativeEvent.data);if(!g){if(f&&(p!=null&&p.onWebEvent))try{Promise.resolve(p.onWebEvent(c.nativeEvent.data,{app_id:f,instance_id:e})).catch(x=>{console.warn("[miniapp] onWebEvent l\u1ED7i",f,x)})}catch(x){console.warn("[miniapp] onWebEvent l\u1ED7i",f,x)}return}if(g.method==="log"){let{level:x,text:k}=g;B(`web:${e}`,x!=null?x:"log",k!=null?k:"");return}if(g.method==="pong"){H.current||N(!0);return}if(g.method==="touchAtTop"){s.emit(!!g.at_top);return}if(g.method==="contextApplied"){H.current&&clearTimeout(H.current),H.current=null,N(!0);return}if(g.method==="ready"){y.current=!0,N(!0);let x=(C=$.getState().instances[e])==null?void 0:C.context;x&&((Z=h.current)==null||Z.injectJavaScript(Ue(x)));return}try{let x=await Tt(g,{getHostData:()=>{var k,z;return(z=(k=$.getState().instances[e])==null?void 0:k.host_data)!=null?z:{}},getPermissions:()=>{var k,z;return f?(z=(k=b(f))==null?void 0:k.permissions)!=null?z:[]:[]},is_dark:r,close:he,app_id:f!=null?f:"",instance_id:e,options:p,emit:(k,z)=>{var lt;(lt=h.current)==null||lt.injectJavaScript(yt(k,z))},isActive:()=>$.getState().active_key===e&&Jt.currentState!=="background"});g.id&&((ie=h.current)==null||ie.injectJavaScript(wt(g.id,x)))}catch(x){if(!g.id)return;let k=x==null?void 0:x.code,z=x instanceof A?x:new A(typeof k=="string"?k:"HOST_ERROR",String((U=x==null?void 0:x.message)!=null?U:x));(Le=h.current)==null||Le.injectJavaScript(Mt(g.id,z))}},[e,r,f,s,p]),Qt=et(()=>{X(!1),V(c=>c+1),d(c=>c+1)},[]);return Me(tt,{style:[rt.absoluteFill,i&&{backgroundColor:r?"#09090B":"#FFFFFF"},!n&&F.behind],pointerEvents:t?"auto":"none",children:[l?P(Nn,{ref:h,source:{uri:l.entry_uri},originWhitelist:["*"],allowingReadAccessToURL:`file://${u?je():l.dir}`,allowFileAccess:!0,allowFileAccessFromFileURLs:!0,allowUniversalAccessFromFileURLs:!0,injectedJavaScriptBeforeContentLoaded:Kt,onMessage:Yt,bounces:!1,overScrollMode:"never",onLoadStart:c=>{Y(e),B(`webview:${e}`,"load start",Ze(c.nativeEvent.url)),y.current=!1,N(!1)},onError:c=>{Y(e),B(`webview:${e}`,"load error",Ze(c.nativeEvent.url),c.nativeEvent.description),X(!0),N(!1)},onLoadEnd:c=>{let g=c.nativeEvent.url;B(`webview:${e}`,"load end",Ze(g)),f&&(w==null||w({app_id:f,instance_id:e,url:g})),it(1500)},onContentProcessDidTerminate:()=>{Y(e),y.current=!1,N(!1),V(c=>c+1)},onRenderProcessGone:()=>(Y(e),y.current=!1,N(!1),V(c=>c+1),!0),style:F.webview},le):null,m&&P(Vn,{visible:!l||!re,interactive:pe,children:P(Fn,{splash:a,app:m.app,is_dark:r,error:pe,has_bundle:!!l,retry:Qt})})]})}),Fn=nt.memo(({splash:e,app:t,is_dark:n,error:r,has_bundle:o,retry:s})=>{let a=e,p=Qe(t.app_id),i=r?"error":!o&&(p==null?void 0:p.status)==="downloading"?"downloading":"loading";return P(a,{app:t,is_dark:n,status:i,progress:i==="downloading"?p==null?void 0:p.progress:void 0,retry:s})}),Vn=({visible:e,interactive:t,children:n})=>{let r=j(new Xe.Value(e?1:0)).current,[o,s]=ae(e);return I(()=>{if(e){s(!0),r.setValue(1);return}let a=Xe.timing(r,{toValue:0,duration:180,useNativeDriver:!0});return a.start(({finished:p})=>{p&&s(!1)}),()=>a.stop()},[e,r]),o?P(Xe.View,{style:[rt.absoluteFill,{opacity:r}],pointerEvents:t?"auto":"none",children:n}):null},Wt=({app:e,is_dark:t,status:n,progress:r,retry:o})=>{let s=t?"#FAFAFA":"#18181B";return Me(tt,{style:[F.splash,{backgroundColor:t?"#09090B":"#FFFFFF"}],children:[P(tt,{style:[F.splash_icon,{backgroundColor:t?"#18181B":"#F4F4F5"}],children:e.icon?P(In,{source:{uri:e.icon},style:F.splash_icon_image}):P(we,{style:F.splash_letter,children:(e.name||"?").slice(0,1).toUpperCase()})}),P(we,{style:[F.splash_name,{color:s}],children:e.name}),n==="error"?Me(Ht,{children:[P(we,{style:F.splash_hint,children:"Kh\xF4ng t\u1EA3i \u0111\u01B0\u1EE3c mini app"}),P(Ln,{activeOpacity:.7,style:[F.retry_button,{backgroundColor:t?"#27272A":"#F4F4F5"}],onPress:o,children:P(we,{style:[F.retry_text,{color:s}],children:"Th\u1EED l\u1EA1i"})})]}):Me(Ht,{children:[P(kn,{style:F.splash_spinner,color:t?"#A1A1AA":"#71717A"}),n==="downloading"&&Me(we,{style:F.splash_hint,children:["\u0110ang t\u1EA3i mini app",r?` ${Math.round(r*100)}%`:"\u2026"]})]})]})},jt=(e,t)=>{let n=j(t),r=j(!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.`))},Un=({container:e,splash:t=Wt,is_dark:n=!1,bridge:r,close_on_back:o=!0,opaque_background:s=!0,allow_embedded_miniapps:a=!1,onWebLoadEnd:p})=>{jt("container",e),jt("splash",t);let i=e,u=W($,l=>l.active_key),w=j(u);u&&(w.current=u);let h=W($,l=>Object.keys(l.instances).join("|")),y=W($,l=>{var O;return l.active_key?(O=l.instances[l.active_key])==null?void 0:O.app.name:void 0}),m=De(()=>h?h.split("|"):[],[h]),[f,T]=ae({}),E=j(Bn()).current;I(()=>{if(!u||!o)return;let l=Dn.addEventListener("hardwareBackPress",()=>(he(),!0));return()=>l.remove()},[u,o]);let L=et(()=>{let l=$.getState().active_key;l&&T(O=>({...O,[l]:(O[l]||0)+1}))},[]);return m.length?P(i,{visible:!!u,title:y!=null?y:"",is_dark:n,close:he,reload:L,subscribeWebAtTop:E.subscribe,children:m.map(l=>P($n,{instance_key:l,is_active:u===l,is_front:(u!=null?u:w.current)===l,is_dark:n,reload_tick:f[l]||0,web_at_top:E,splash:t,bridge:r,opaque_background:s,allow_embedded_miniapps:a,onWebLoadEnd:p},l))}):null},F=rt.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"}}),Jn=nt.memo(Un);export{Wt as DefaultMiniAppSplash,Ne as MINIAPP_PLATFORM_URL,Jn as MiniAppHost,A as MiniAppHostError,he as closeMiniApp,Gt as configureMiniApp,Zt as createMmkvStorage,gt as createReactNativeBiometrics,Xt as createRnfsFileSystem,ke as ensureMiniApp,b as getLocalMiniApp,Cn as getMiniAppCatalog,Ae as getMiniAppCatalogEntry,vn as getMiniAppStatuses,Ut as getMiniAppUpdate,sn as installBundledMiniApp,yn as onMiniAppEvent,un as openMiniApp,En as pauseMiniApp,Pn as pauseMiniAppDownloads,dn as preloadMiniApp,Y as releaseSpeechFor,xn as restoreMiniApp,Rn as resumeMiniApp,Tn as resumeMiniAppDownloads,cn as sendEventToWeb,Ge as syncMiniAppCatalog,_n as uninstallMiniApp,On as updateMiniApp,Qe as useMiniAppDownload,Mn as useMiniAppDownloadsPaused};
@@ -33,6 +33,10 @@ Chạy **Retion Mini App** (web app đóng gói sẵn, tải về máy, chạy o
33
33
 
34
34
  ---
35
35
 
36
+ ## Nhận dạng giọng nói
37
+
38
+ Từ **0.8.0**, package tích hợp speech-to-text qua bridge chung. Xem [quyền native, API web và chuyển từ Chat SDK](SPEECH.md). App chủ cần Expo Modules và cấu hình quyền một lần, không gắn handler speech.
39
+
36
40
  ## Yêu cầu
37
41
 
38
42
  - React ≥ 18, React Native ≥ 0.72 (Expo dev build / bare đều được).
package/docs/SPEECH.md ADDED
@@ -0,0 +1,118 @@
1
+ # Nhận dạng giọng nói cho mini app
2
+
3
+ Từ **0.8.0**, speech-to-text thuộc `@retion-miniapp/react-native`, không phụ thuộc Chat SDK hoặc kênh `chat_sdk`. Package cài trực tiếp `expo-speech-recognition@1.1.1`, tự xin quyền khi web bắt đầu nghe, quản lý phiên micro và gửi kết quả qua bridge chung. App chủ không gắn handler speech hoặc `onWebEvent` để dùng tính năng này.
4
+
5
+ ## Cấu hình app chủ
6
+
7
+ ### Expo
8
+
9
+ App cần Expo **52+** và bộ native tương thích với `expo-speech-recognition@1.1.1`. Thêm plugin Mini App vào cấu hình, giữ các plugin khác:
10
+
11
+ ```json
12
+ {
13
+ "expo": {
14
+ "plugins": [["@retion-miniapp/react-native", {
15
+ "faceIDPermission": "Cho phép ứng dụng dùng Face ID để xác thực danh tính",
16
+ "microphonePermission": "Cho phép ứng dụng dùng micro để chuyển lời nói thành văn bản",
17
+ "speechRecognitionPermission": "Cho phép ứng dụng nhận dạng giọng nói"
18
+ }]]
19
+ }
20
+ }
21
+ ```
22
+
23
+ Plugin Mini App gọi plugin của thư viện speech để khai báo quyền iOS/Android và dịch vụ nhận dạng Android. Không cần thêm plugin speech lần nữa chỉ để phục vụ mini app. Nếu app đã có plugin speech cho tính năng khác, thống nhất nội dung quyền, tránh cấu hình trùng trái ngược nhau.
24
+
25
+ Áp dụng cấu hình bằng quy trình prebuild của dự án rồi build development client hoặc bản phát hành. Expo Go không chứa module này. OTA/reload không bổ sung được module hoặc quyền vào binary cũ.
26
+
27
+ ### React Native thuần / dự án giữ thư mục native
28
+
29
+ Cần tích hợp Expo Modules vào app trước khi dùng thư viện speech. Cài package Mini App, chạy quy trình liên kết Expo Modules, Pods và build native của dự án. Không cần viết handler speech riêng.
30
+
31
+ iOS: khai báo hai khóa trong `Info.plist` của đúng target app:
32
+
33
+ ```xml
34
+ <key>NSMicrophoneUsageDescription</key>
35
+ <string>Cho phép ứng dụng dùng micro để chuyển lời nói thành văn bản</string>
36
+ <key>NSSpeechRecognitionUsageDescription</key>
37
+ <string>Cho phép ứng dụng nhận dạng giọng nói</string>
38
+ ```
39
+
40
+ Android: kiểm tra manifest sau khi hợp nhất có `android.permission.RECORD_AUDIO` và cấu hình truy vấn dịch vụ nhận dạng tương đương plugin của thư viện:
41
+
42
+ ```xml
43
+ <uses-permission android:name="android.permission.RECORD_AUDIO" />
44
+ <queries>
45
+ <package android:name="com.google.android.googlequicksearchbox" />
46
+ <intent>
47
+ <action android:name="android.speech.RecognitionService" />
48
+ </intent>
49
+ </queries>
50
+ ```
51
+
52
+ Package tự gọi xin quyền runtime khi bắt đầu; app chủ không phải xin quyền trước. Nếu người dùng đã từ chối và không thể hỏi lại, hướng dẫn mở Cài đặt của thiết bị.
53
+
54
+ **Tương thích Expo 57:** Retion đang có patch cho `expo-speech-recognition@1.1.1` để tương thích kiểu resolver của Expo 57. Giữ patch hiện có khi nâng package. Chuyển code JavaScript sang Mini App SDK không tự sửa mã Swift của thư viện; app mới dùng cùng bộ phiên bản cần áp dụng bản vá tương thích trước khi build. Chưa xác minh native build trên các bộ phiên bản Expo khác.
55
+
56
+ ## API phía web
57
+
58
+ Cài `@retion-miniapp/sdk@0.8.0` và đăng ký event **trước** khi bắt đầu nghe:
59
+
60
+ ```ts
61
+ import { startSpeech, stopSpeech, onSpeech } from '@retion-miniapp/sdk';
62
+
63
+ const offPartial = onSpeech('speech.partial', result => {
64
+ console.log('Tạm thời:', result.text, result.results);
65
+ });
66
+ const offFinal = onSpeech('speech.final', result => {
67
+ console.log('Câu cuối:', result.text, result.results);
68
+ });
69
+ const offError = onSpeech('speech.error', error => {
70
+ console.log(error.code, error.message);
71
+ });
72
+ const offEnd = onSpeech('speech.end', () => {
73
+ console.log('Đã kết thúc phiên nghe');
74
+ });
75
+
76
+ await startSpeech({ lang: 'vi-VN' });
77
+ // Khi người dùng bấm dừng:
78
+ await stopSpeech();
79
+ // Vẫn chờ speech.final / speech.end; stopSpeech resolve chưa có nghĩa đã nhận câu cuối.
80
+
81
+ // Khi huỷ component phía web:
82
+ offPartial(); offFinal(); offError(); offEnd();
83
+ ```
84
+
85
+ `startSpeech()` resolve sau khi xin quyền và gửi lệnh bắt đầu cho native, không phải sau khi có văn bản. Thời gian chờ xin quyền tối đa 2 phút phía web; hết thời gian chờ không tự đóng hộp quyền hệ điều hành.
86
+
87
+ | Tuỳ chọn | Mặc định | Ý nghĩa |
88
+ | --- | --- | --- |
89
+ | `lang` | `vi-VN` | Mã ngôn ngữ nhận dạng, ví dụ `en-US` |
90
+ | `continuous` | `true` | Yêu cầu nghe liên tục nếu dịch vụ hỗ trợ |
91
+ | `interimResults` | `true` | Nhận văn bản tạm thời |
92
+ | `addsPunctuation` | `true` | Yêu cầu thêm dấu câu |
93
+ | `requiresOnDeviceRecognition` | `false` | Khi bật, yêu cầu nhận dạng trên thiết bị; phụ thuộc dịch vụ và mô hình đã cài |
94
+
95
+ Kết quả `speech.partial` / `speech.final` giữ trường native (`isFinal`, `results`) và bổ sung `text` lấy từ kết quả đầu tiên. `speech.error` giữ các trường native (`error`, `message`, …), bổ sung `code` bằng giá trị `error`. Event chỉ gửi về đúng instance đã bắt đầu nghe.
96
+
97
+ ## Quản lý phiên và lỗi
98
+
99
+ - Mỗi lúc chỉ một mini app được giữ phiên, kể cả thời gian đang xin quyền. Yêu cầu mới trả `BUSY`, không tự ngắt phiên cũ.
100
+ - Nếu bộ nhận dạng đang được tính năng khác của app sử dụng, trả `BUSY` thay vì bắt đầu phiên mới. App chủ cũng cần tránh tự mở bộ nhận dạng khác khi mini app đang nghe.
101
+ - Chỉ chủ phiên được dừng. `stopSpeech()` yêu cầu native kết thúc và trả kết quả cuối; phiên được giải phóng ở `speech.end`.
102
+ - Đóng/ẩn mini app, reload, WebView bị huỷ hoặc app xuống nền sẽ huỷ phiên. Nếu đang chờ quyền, không mở micro sau khi mini app đã đóng.
103
+ - Sau khi huỷ phiên đã chạy, chờ native `end` rồi mới cho mở phiên tiếp theo, tránh kết quả muộn từ phiên cũ lẫn sang phiên mới. iOS trả lại audio session khi phiên kết thúc.
104
+ - `PERMISSION_DENIED`: thiếu quyền; `NOT_SUPPORTED`: chưa có module native; `INVALID_PARAMS`: tuỳ chọn sai; `CANCELLED`: mini app không còn hoạt động; lỗi nhận dạng sau khi bắt đầu được gửi qua `speech.error`.
105
+ - Không đảm bảo nhận dạng ngoại tuyến khi `requiresOnDeviceRecognition: false`; khả năng nhận dạng và ngôn ngữ phụ thuộc hệ điều hành/dịch vụ trên thiết bị.
106
+
107
+ ## Chuyển từ speech của Chat SDK
108
+
109
+ 1. Nâng host Mini App React Native và Web SDK lên **0.8.0**.
110
+ 2. Phía web thay file cầu nối `chatSpeech.js` tự viết bằng import `startSpeech`, `stopSpeech`, `onSpeech` từ Web SDK. Đổi `startSpeech('vi-VN')` thành `startSpeech({ lang: 'vi-VN' })`.
111
+ 3. Không gửi `{ chat_sdk: 1, method: 'speech.start' }` nữa. Kênh speech cũ của Chat SDK trả `NOT_SUPPORTED` để hướng dẫn nâng web.
112
+ 4. Không bỏ `onWebEvent` của Chat SDK nếu app vẫn dùng event riêng cho ghi chú hoặc các tính năng chat khác.
113
+ 5. Mini App SDK không đọc cài đặt ngôn ngữ trong Chat SDK. Web truyền `lang` khi muốn dùng ngôn ngữ riêng.
114
+ 6. Không xoá dependency speech của app nếu ô nhập chat vẫn dùng nó. Đồng bộ phiên bản để không có hai bản native khác nhau.
115
+
116
+ ## Kiểm tra trên thiết bị
117
+
118
+ Thử cấp/từ chối quyền, nói và nhận văn bản tạm thời/cuối cùng, dừng rồi nghe lại, đóng mini app lúc xin quyền, đóng khi đang nghe, chuyển nền, mở mini app khác khi micro đang dùng và phát lại nhạc sau khi kết thúc. Kiểm tra trên cả iOS và Android; kiểm tra JavaScript không thay thế được xác minh native trên thiết bị.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@retion-miniapp/react-native",
3
- "version": "0.7.8",
3
+ "version": "0.8.0",
4
4
  "description": "React Native host for Retion Mini Apps with built-in biometric authentication",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -43,7 +43,8 @@
43
43
  "dist",
44
44
  "app.plugin.js",
45
45
  "docs/BIOMETRICS.md",
46
- "docs/MINIAPP_README.md"
46
+ "docs/MINIAPP_README.md",
47
+ "docs/SPEECH.md"
47
48
  ],
48
49
  "sideEffects": false,
49
50
  "scripts": {
@@ -59,7 +60,8 @@
59
60
  "react-native-fs": ">=2.20",
60
61
  "react-native-mmkv": ">=3",
61
62
  "react-native-webview": ">=13",
62
- "react-native-zip-archive": ">=6"
63
+ "react-native-zip-archive": ">=6",
64
+ "expo": ">=52"
63
65
  },
64
66
  "peerDependenciesMeta": {
65
67
  "react-native-fs": {
@@ -85,6 +87,7 @@
85
87
  "access": "public"
86
88
  },
87
89
  "dependencies": {
90
+ "expo-speech-recognition": "1.1.1",
88
91
  "react-native-biometrics": "3.0.1"
89
92
  }
90
93
  }