@retion-miniapp/react-native 0.16.0 → 0.17.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/dist/index.d.mts CHANGED
@@ -4,6 +4,17 @@ type MiniAppChannel = 'production' | 'testing';
4
4
  /** Quyền lấy token nhạy cảm — admin bật trên Console, Platform trả trong manifest. */
5
5
  type MiniAppPermission = 'partner_token' | 'chatbox_token';
6
6
  /** Manifest Platform trả (API list ứng dụng hoặc manifest lẻ). */
7
+ /** Changelog 1 version (Console / CHANGELOG.md): Mới · Sửa lỗi · Cải thiện. */
8
+ interface MiniAppChangelog {
9
+ new: string[];
10
+ fix: string[];
11
+ improve: string[];
12
+ }
13
+ interface MiniAppChangelogVersion {
14
+ version: string;
15
+ changelog: MiniAppChangelog;
16
+ created_at: string;
17
+ }
7
18
  interface MiniAppManifest {
8
19
  app_id: string;
9
20
  name?: string;
@@ -15,6 +26,8 @@ interface MiniAppManifest {
15
26
  /** true: đổi conversation → đẩy context; false: reload với context mới. */
16
27
  context_update?: boolean;
17
28
  permissions?: MiniAppPermission[];
29
+ /** Changelog version này (null: bản deploy trước khi có changelog). */
30
+ changelog?: MiniAppChangelog | null;
18
31
  }
19
32
  /** Bundle đã giải nén trong máy. */
20
33
  interface MiniAppLocalBundle {
@@ -640,6 +653,40 @@ declare const installBundledMiniApp: ({ manifest, zip_path }: {
640
653
  zip_path: string;
641
654
  }) => Promise<MiniAppLocalBundle>;
642
655
 
656
+ interface MiniAppPendingChangelog {
657
+ app_id: string;
658
+ /** Version đã xem changelog lần trước (loại trừ). */
659
+ from: string;
660
+ /** Version đang có trong máy (bao gồm). */
661
+ to: string;
662
+ }
663
+ declare const getMiniAppChangelogSeen: (app_id: string) => string | null;
664
+ /** Đã xem changelog tới version này (mặc định: bản đang có trong máy). */
665
+ declare const markMiniAppChangelogSeen: (app_id: string, version?: string | undefined) => void;
666
+ /** Gọi khi người dùng bấm mở mini app: có bản mới chưa xem changelog → { from, to }, không thì null. */
667
+ declare const getPendingChangelog: (app_id: string) => MiniAppPendingChangelog | null;
668
+ /**
669
+ * Changelog từ Platform, mới nhất trước. from: loại trừ, to: bao gồm; bỏ trống cả 2 → toàn bộ lịch sử.
670
+ * Reject khi lỗi mạng / API.
671
+ */
672
+ declare const fetchMiniAppChangelog: (app_id: string, { from, to, channel }?: {
673
+ from?: string;
674
+ to?: string;
675
+ channel?: MiniAppChannel;
676
+ }) => Promise<MiniAppChangelogVersion[]>;
677
+ interface MiniAppChangelogState {
678
+ versions: MiniAppChangelogVersion[];
679
+ loading: boolean;
680
+ error?: string;
681
+ reload: () => void;
682
+ }
683
+ /** Hook lấy changelog (modal "Có gì mới": truyền from/to; màn "Xem tất cả": bỏ trống). enabled=false → không gọi. */
684
+ declare const useMiniAppChangelog: (app_id: string | undefined, { from, to, enabled }?: {
685
+ from?: string;
686
+ to?: string;
687
+ enabled?: boolean;
688
+ }) => MiniAppChangelogState;
689
+
643
690
  /**
644
691
  * App → web: gửi event xuống web của mini app — web nhận y như `WebView.postMessage` (sự kiện `message`).
645
692
  * `instance_id`: instance_id lúc openMiniApp; không dùng instance_id thì truyền app_id.
@@ -811,4 +858,4 @@ interface UploadCapabilities {
811
858
  /** XHR (không phải fetch) để có tiến trình upload; RN đọc file từ uri (cả content://), không nạp vào JS. */
812
859
  declare const uploadToUrl: MiniAppUploader;
813
860
 
814
- export { CodeType, DefaultMiniAppSplash, type LocationOptions, type LocationResult, 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 MiniAppPickedFile, type MiniAppSpeechProvider, type MiniAppSpeechStartContext, type MiniAppSplashProps, type MiniAppStorage, type MiniAppSyncResult, type MiniAppUpdate, type MiniAppUploadCaller, type MiniAppUploadOptions, type MiniAppUploadProcessOptions, type MiniAppUploadProcessor, type MiniAppUploadRequest, type MiniAppUploadSource, type MiniAppUploadSourceRequest, type MiniAppUploadTarget, type MiniAppUploader, type MiniAppUrlUploadTarget, type OpenMiniAppArgs, type ReactNativeBiometricsLike, ScannerEndReason, ScannerEvent, ScannerLayout, ScannerMethod, type ScannerOptions, type ScannerResult, type SpeechOptions, ToastType, type UploadCapabilities, type UploadFileType, type UploadFilesResult, type UploadedFile, 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, uploadToUrl, useMiniAppDownload, useMiniAppDownloadsPaused };
861
+ export { CodeType, DefaultMiniAppSplash, type LocationOptions, type LocationResult, MINIAPP_PLATFORM_URL, type MiniAppBiometricAvailability, type MiniAppBiometricRequest, type MiniAppBiometricResult, type MiniAppBiometrics, type MiniAppBiometryType, type MiniAppBridgeOptions, type MiniAppCatalogEntry, type MiniAppCatalogItem, type MiniAppChangelog, type MiniAppChangelogState, type MiniAppChangelogVersion, 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 MiniAppPendingChangelog, type MiniAppPermission, type MiniAppPickedFile, type MiniAppSpeechProvider, type MiniAppSpeechStartContext, type MiniAppSplashProps, type MiniAppStorage, type MiniAppSyncResult, type MiniAppUpdate, type MiniAppUploadCaller, type MiniAppUploadOptions, type MiniAppUploadProcessOptions, type MiniAppUploadProcessor, type MiniAppUploadRequest, type MiniAppUploadSource, type MiniAppUploadSourceRequest, type MiniAppUploadTarget, type MiniAppUploader, type MiniAppUrlUploadTarget, type OpenMiniAppArgs, type ReactNativeBiometricsLike, ScannerEndReason, ScannerEvent, ScannerLayout, ScannerMethod, type ScannerOptions, type ScannerResult, type SpeechOptions, ToastType, type UploadCapabilities, type UploadFileType, type UploadFilesResult, type UploadedFile, closeMiniApp, configureMiniApp, createMmkvStorage, createReactNativeBiometrics, createRnfsFileSystem, ensureMiniApp, fetchMiniAppChangelog, getLocalMiniApp, getMiniAppCatalog, getMiniAppCatalogEntry, getMiniAppChangelogSeen, getMiniAppStatuses, getMiniAppUpdate, getPendingChangelog, installBundledMiniApp, markMiniAppChangelogSeen, onMiniAppEvent, openMiniApp, pauseMiniApp, pauseMiniAppDownloads, preloadMiniApp, releaseSpeechFor, restoreMiniApp, resumeMiniApp, resumeMiniAppDownloads, sendEventToWeb, syncMiniAppCatalog, uninstallMiniApp, updateMiniApp, uploadToUrl, useMiniAppChangelog, useMiniAppDownload, useMiniAppDownloadsPaused };
package/dist/index.d.ts CHANGED
@@ -4,6 +4,17 @@ type MiniAppChannel = 'production' | 'testing';
4
4
  /** Quyền lấy token nhạy cảm — admin bật trên Console, Platform trả trong manifest. */
5
5
  type MiniAppPermission = 'partner_token' | 'chatbox_token';
6
6
  /** Manifest Platform trả (API list ứng dụng hoặc manifest lẻ). */
7
+ /** Changelog 1 version (Console / CHANGELOG.md): Mới · Sửa lỗi · Cải thiện. */
8
+ interface MiniAppChangelog {
9
+ new: string[];
10
+ fix: string[];
11
+ improve: string[];
12
+ }
13
+ interface MiniAppChangelogVersion {
14
+ version: string;
15
+ changelog: MiniAppChangelog;
16
+ created_at: string;
17
+ }
7
18
  interface MiniAppManifest {
8
19
  app_id: string;
9
20
  name?: string;
@@ -15,6 +26,8 @@ interface MiniAppManifest {
15
26
  /** true: đổi conversation → đẩy context; false: reload với context mới. */
16
27
  context_update?: boolean;
17
28
  permissions?: MiniAppPermission[];
29
+ /** Changelog version này (null: bản deploy trước khi có changelog). */
30
+ changelog?: MiniAppChangelog | null;
18
31
  }
19
32
  /** Bundle đã giải nén trong máy. */
20
33
  interface MiniAppLocalBundle {
@@ -640,6 +653,40 @@ declare const installBundledMiniApp: ({ manifest, zip_path }: {
640
653
  zip_path: string;
641
654
  }) => Promise<MiniAppLocalBundle>;
642
655
 
656
+ interface MiniAppPendingChangelog {
657
+ app_id: string;
658
+ /** Version đã xem changelog lần trước (loại trừ). */
659
+ from: string;
660
+ /** Version đang có trong máy (bao gồm). */
661
+ to: string;
662
+ }
663
+ declare const getMiniAppChangelogSeen: (app_id: string) => string | null;
664
+ /** Đã xem changelog tới version này (mặc định: bản đang có trong máy). */
665
+ declare const markMiniAppChangelogSeen: (app_id: string, version?: string | undefined) => void;
666
+ /** Gọi khi người dùng bấm mở mini app: có bản mới chưa xem changelog → { from, to }, không thì null. */
667
+ declare const getPendingChangelog: (app_id: string) => MiniAppPendingChangelog | null;
668
+ /**
669
+ * Changelog từ Platform, mới nhất trước. from: loại trừ, to: bao gồm; bỏ trống cả 2 → toàn bộ lịch sử.
670
+ * Reject khi lỗi mạng / API.
671
+ */
672
+ declare const fetchMiniAppChangelog: (app_id: string, { from, to, channel }?: {
673
+ from?: string;
674
+ to?: string;
675
+ channel?: MiniAppChannel;
676
+ }) => Promise<MiniAppChangelogVersion[]>;
677
+ interface MiniAppChangelogState {
678
+ versions: MiniAppChangelogVersion[];
679
+ loading: boolean;
680
+ error?: string;
681
+ reload: () => void;
682
+ }
683
+ /** Hook lấy changelog (modal "Có gì mới": truyền from/to; màn "Xem tất cả": bỏ trống). enabled=false → không gọi. */
684
+ declare const useMiniAppChangelog: (app_id: string | undefined, { from, to, enabled }?: {
685
+ from?: string;
686
+ to?: string;
687
+ enabled?: boolean;
688
+ }) => MiniAppChangelogState;
689
+
643
690
  /**
644
691
  * App → web: gửi event xuống web của mini app — web nhận y như `WebView.postMessage` (sự kiện `message`).
645
692
  * `instance_id`: instance_id lúc openMiniApp; không dùng instance_id thì truyền app_id.
@@ -811,4 +858,4 @@ interface UploadCapabilities {
811
858
  /** XHR (không phải fetch) để có tiến trình upload; RN đọc file từ uri (cả content://), không nạp vào JS. */
812
859
  declare const uploadToUrl: MiniAppUploader;
813
860
 
814
- export { CodeType, DefaultMiniAppSplash, type LocationOptions, type LocationResult, 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 MiniAppPickedFile, type MiniAppSpeechProvider, type MiniAppSpeechStartContext, type MiniAppSplashProps, type MiniAppStorage, type MiniAppSyncResult, type MiniAppUpdate, type MiniAppUploadCaller, type MiniAppUploadOptions, type MiniAppUploadProcessOptions, type MiniAppUploadProcessor, type MiniAppUploadRequest, type MiniAppUploadSource, type MiniAppUploadSourceRequest, type MiniAppUploadTarget, type MiniAppUploader, type MiniAppUrlUploadTarget, type OpenMiniAppArgs, type ReactNativeBiometricsLike, ScannerEndReason, ScannerEvent, ScannerLayout, ScannerMethod, type ScannerOptions, type ScannerResult, type SpeechOptions, ToastType, type UploadCapabilities, type UploadFileType, type UploadFilesResult, type UploadedFile, 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, uploadToUrl, useMiniAppDownload, useMiniAppDownloadsPaused };
861
+ export { CodeType, DefaultMiniAppSplash, type LocationOptions, type LocationResult, MINIAPP_PLATFORM_URL, type MiniAppBiometricAvailability, type MiniAppBiometricRequest, type MiniAppBiometricResult, type MiniAppBiometrics, type MiniAppBiometryType, type MiniAppBridgeOptions, type MiniAppCatalogEntry, type MiniAppCatalogItem, type MiniAppChangelog, type MiniAppChangelogState, type MiniAppChangelogVersion, 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 MiniAppPendingChangelog, type MiniAppPermission, type MiniAppPickedFile, type MiniAppSpeechProvider, type MiniAppSpeechStartContext, type MiniAppSplashProps, type MiniAppStorage, type MiniAppSyncResult, type MiniAppUpdate, type MiniAppUploadCaller, type MiniAppUploadOptions, type MiniAppUploadProcessOptions, type MiniAppUploadProcessor, type MiniAppUploadRequest, type MiniAppUploadSource, type MiniAppUploadSourceRequest, type MiniAppUploadTarget, type MiniAppUploader, type MiniAppUrlUploadTarget, type OpenMiniAppArgs, type ReactNativeBiometricsLike, ScannerEndReason, ScannerEvent, ScannerLayout, ScannerMethod, type ScannerOptions, type ScannerResult, type SpeechOptions, ToastType, type UploadCapabilities, type UploadFileType, type UploadFilesResult, type UploadedFile, closeMiniApp, configureMiniApp, createMmkvStorage, createReactNativeBiometrics, createRnfsFileSystem, ensureMiniApp, fetchMiniAppChangelog, getLocalMiniApp, getMiniAppCatalog, getMiniAppCatalogEntry, getMiniAppChangelogSeen, getMiniAppStatuses, getMiniAppUpdate, getPendingChangelog, installBundledMiniApp, markMiniAppChangelogSeen, onMiniAppEvent, openMiniApp, pauseMiniApp, pauseMiniAppDownloads, preloadMiniApp, releaseSpeechFor, restoreMiniApp, resumeMiniApp, resumeMiniAppDownloads, sendEventToWeb, syncMiniAppCatalog, uninstallMiniApp, updateMiniApp, uploadToUrl, useMiniAppChangelog, useMiniAppDownload, useMiniAppDownloadsPaused };
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var gr=Object.create;var yt=Object.defineProperty;var mr=Object.getOwnPropertyDescriptor;var hr=Object.getOwnPropertyNames;var fr=Object.getPrototypeOf,yr=Object.prototype.hasOwnProperty;var wr=(e,t)=>{for(var n in t)yt(e,n,{get:t[n],enumerable:!0})},vn=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of hr(t))!yr.call(e,r)&&r!==n&&yt(e,r,{get:()=>t[r],enumerable:!(o=mr(t,r))||o.enumerable});return e};var le=(e,t,n)=>(n=e!=null?gr(fr(e)):{},vn(t||!e||!e.__esModule?yt(n,"default",{value:e,enumerable:!0}):n,e)),br=e=>vn(yt({},"__esModule",{value:!0}),e);var bi={};wr(bi,{CodeType:()=>te,DefaultMiniAppSplash:()=>_n,MINIAPP_PLATFORM_URL:()=>wt,MiniAppHost:()=>dr,MiniAppHostError:()=>g,ScannerEndReason:()=>ze,ScannerEvent:()=>xt,ScannerLayout:()=>pe,ScannerMethod:()=>Je,ToastType:()=>he,closeMiniApp:()=>Ye,configureMiniApp:()=>xn,createMmkvStorage:()=>Pn,createReactNativeBiometrics:()=>Wt,createRnfsFileSystem:()=>Rn,ensureMiniApp:()=>mt,getLocalMiniApp:()=>$,getMiniAppCatalog:()=>cr,getMiniAppCatalogEntry:()=>Xe,getMiniAppStatuses:()=>Qo,getMiniAppUpdate:()=>wn,installBundledMiniApp:()=>Fo,onMiniAppEvent:()=>Zo,openMiniApp:()=>Ho,pauseMiniApp:()=>or,pauseMiniAppDownloads:()=>ir,preloadMiniApp:()=>Jo,releaseSpeechFor:()=>Re,restoreMiniApp:()=>nr,resumeMiniApp:()=>rr,resumeMiniAppDownloads:()=>sr,sendEventToWeb:()=>Uo,syncMiniAppCatalog:()=>Bt,uninstallMiniApp:()=>tr,updateMiniApp:()=>ar,uploadToUrl:()=>Gt,useMiniAppDownload:()=>Ut,useMiniAppDownloadsPaused:()=>Xo});module.exports=br(bi);var wt="https://retion-miniapp-platform.vercel.app",Be=null,Mn=new Set,xn=e=>{Be=e,Mn.forEach(t=>t())},z=()=>{if(!Be)throw new Error("[miniapp] Ch\u01B0a g\u1ECDi configureMiniApp()");return Be},En=e=>{Mn.add(e),Be&&e()},me=(...e)=>{Be!=null&&Be.debug&&console.log("[miniapp]",...e)};var Rn=(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(o=>o.map(r=>r.name)).catch(()=>[]),sha256:n=>e.hash(n,"sha256"),unzip:async(n,o)=>{await t(n,o)},download:({url:n,to_file:o,onProgress:r})=>{let{jobId:i,promise:a}=e.downloadFile({fromUrl:n,toFile:o,progressInterval:250,begin:()=>{},progress:({bytesWritten:c,contentLength:l})=>r==null?void 0:r(c,l)});return{promise:a.then(({statusCode:c})=>({status:c})),cancel:()=>e.stopDownload(i)}}}),Pn=e=>({getString:t=>e.getString(t),setString:(t,n)=>e.set(t,n)});var S=le(require("react")),k=require("react-native"),ur=le(require("react-native-webview"));var at=require("react-native");var Wt=e=>({getAvailability:()=>e.isSensorAvailable(),authenticate:({reason:t,cancelButtonText:n})=>e.simplePrompt({promptMessage:t,cancelButtonText:n,fallbackPromptMessage:""})}),bt,jt=()=>(bt||(bt=import("react-native-biometrics").then(({default:e})=>Wt(new e({allowDeviceCredentials:!1}))).catch(e=>{throw bt=void 0,new g("NOT_SUPPORTED",`Biometric native module unavailable: ${e instanceof Error?e.message:String(e)}`)})),bt);var Ee=require("react-native");var Tn=e=>{var n,o,r;if(e!==void 0&&(e===null||typeof e!="object"||Array.isArray(e)))throw new g("INVALID_PARAMS","Tu\u1EF3 ch\u1ECDn v\u1ECB tr\xED ph\u1EA3i l\xE0 object");let t=e!=null?e:{};if(t.enableHighAccuracy!==void 0&&typeof t.enableHighAccuracy!="boolean")throw new g("INVALID_PARAMS","enableHighAccuracy ph\u1EA3i l\xE0 boolean");for(let[i,a,c]of[["timeout",1,6e4],["maximumAge",0,864e5]]){let l=t[i];if(l!==void 0&&(typeof l!="number"||!Number.isFinite(l)||l<a||l>c))throw new g("INVALID_PARAMS",`${i} ph\u1EA3i n\u1EB1m trong kho\u1EA3ng ${a}\u2013${c} ms`)}return{enableHighAccuracy:(n=t.enableHighAccuracy)!=null?n:!1,timeout:(o=t.timeout)!=null?o:15e3,maximumAge:(r=t.maximumAge)!=null?r:0}},Cn=(e,t=()=>!0)=>new Promise((n,o)=>{let r=!1,i=(l,s)=>{r||(r=!0,clearTimeout(a),l?o(l):n(s))},a=setTimeout(()=>i(new g("TIMEOUT","H\u1EBFt th\u1EDDi gian ch\u1EDD c\u1EA5p quy\u1EC1n/l\u1EA5y v\u1ECB tr\xED")),12e4+e.timeout),c=()=>r?!1:t()?!0:(i(new g("CANCELLED","Mini app kh\xF4ng c\xF2n ho\u1EA1t \u0111\u1ED9ng")),!1);(async()=>{if(!c())return;let l;try{l=(await import("@react-native-community/geolocation")).default}catch{throw new g("NOT_SUPPORTED","Ch\u01B0a c\xF3 module v\u1ECB tr\xED trong b\u1EA3n native")}if(c()){if(Ee.Platform.OS==="android"){let s=Ee.PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,d=Ee.PermissionsAndroid.PERMISSIONS.ACCESS_COARSE_LOCATION,u=await Ee.PermissionsAndroid.check(s);if(!c())return;let y=u||await Ee.PermissionsAndroid.check(d);if(!c())return;if(!u&&!y){let p=await Ee.PermissionsAndroid.requestMultiple([s,d]);if(!c())return;if(p[s]!==Ee.PermissionsAndroid.RESULTS.GRANTED&&p[d]!==Ee.PermissionsAndroid.RESULTS.GRANTED)throw new g("PERMISSION_DENIED","Ch\u01B0a c\u1EA5p quy\u1EC1n truy c\u1EADp v\u1ECB tr\xED")}}c()&&l.getCurrentPosition(s=>{c()&&i(void 0,s)},s=>{var u;if(!c())return;let d=(u={1:"PERMISSION_DENIED",2:"POSITION_UNAVAILABLE",3:"TIMEOUT"}[s.code])!=null?u:"LOCATION_ERROR";i(new g(d,s.message))},e)}})().catch(l=>i(l))});var Jt=require("react-native");var Ht=20,On=20,Nn=/^[a-z][a-z0-9_-]{0,31}$/,_r=/^(\.[\w-]{1,16}|[\w.+-]+\/(\*|[\w.+-]+))$/,Sr=["low","medium","high"],ke=e=>!!e&&typeof e=="object"&&!Array.isArray(e),X=e=>new g("INVALID_PARAMS",e),rt=(e,t,n)=>typeof e=="number"&&Number.isInteger(e)&&e>=t&&e<=n,kn=(e,t)=>{if(e===void 0)return{};if(!ke(e)||Object.keys(e).length>On||Object.values(e).some(n=>typeof n!="string"))throw X(`${t} ph\u1EA3i l\xE0 object chu\u1ED7i (t\u1ED1i \u0111a ${On} key)`);return e},Un=e=>{var n,o,r,i;if(e!==void 0&&!ke(e))throw X("Tu\u1EF3 ch\u1ECDn upload ph\u1EA3i l\xE0 object");let t=e!=null?e:{};if(t.source!==void 0&&(typeof t.source!="string"||!Nn.test(t.source)))throw X("source ph\u1EA3i l\xE0 t\xEAn ngu\u1ED3n, vd library | camera | document");if(t.accept!==void 0&&(!Array.isArray(t.accept)||t.accept.length>50||t.accept.some(a=>typeof a!="string"||!_r.test(a))))throw X("accept ph\u1EA3i l\xE0 m\u1EA3ng mime (image/*, application/pdf) ho\u1EB7c \u0111u\xF4i (.docx)");if(t.max_count!==void 0&&!rt(t.max_count,1,Ht))throw X(`max_count ph\u1EA3i l\xE0 s\u1ED1 nguy\xEAn 1\u2013${Ht}`);if(t.max_size!==void 0&&!rt(t.max_size,1,Number.MAX_SAFE_INTEGER))throw X("max_size ph\u1EA3i l\xE0 s\u1ED1 byte > 0");if(t.concurrency!==void 0&&!rt(t.concurrency,1,5))throw X("concurrency ph\u1EA3i l\xE0 s\u1ED1 nguy\xEAn 1\u20135");return{source:(n=t.source)!=null?n:"library",accept:((o=t.accept)!=null?o:[]).map(a=>a.toLowerCase()),max_count:(r=t.max_count)!=null?r:1,max_size:t.max_size,process:Ar(t.process),target:vr(t.upload),concurrency:(i=t.concurrency)!=null?i:3}},Ar=e=>{if(e===void 0)return{};if(!ke(e))throw X("process ph\u1EA3i l\xE0 object");let t={};if(e.image!==void 0){let n=e.image;if(!ke(n))throw X("process.image ph\u1EA3i l\xE0 object");for(let o of["max_width","max_height"])if(n[o]!==void 0&&!rt(n[o],1,1e4))throw X(`process.image.${o} ph\u1EA3i l\xE0 s\u1ED1 nguy\xEAn 1\u201310000`);if(n.quality!==void 0&&(typeof n.quality!="number"||n.quality<=0||n.quality>1))throw X("process.image.quality ph\u1EA3i trong kho\u1EA3ng (0, 1]");t.image={max_width:n.max_width,max_height:n.max_height,quality:n.quality}}if(e.video!==void 0){let n=e.video;if(!ke(n))throw X("process.video ph\u1EA3i l\xE0 object");if(n.max_duration!==void 0&&!rt(n.max_duration,1,3600))throw X("process.video.max_duration ph\u1EA3i l\xE0 s\u1ED1 gi\xE2y 1\u20133600");if(n.quality!==void 0&&!Sr.includes(n.quality))throw X("process.video.quality ph\u1EA3i l\xE0 low | medium | high");t.video={max_duration:n.max_duration,quality:n.quality}}return t},vr=e=>{var n,o,r,i;if(e===void 0)return{target:"host",params:{}};if(!ke(e))throw X("upload ph\u1EA3i l\xE0 object");let t=(n=e.target)!=null?n:"host";if(typeof t!="string"||!Nn.test(t))throw X("upload.target ph\u1EA3i l\xE0 t\xEAn \u0111\xEDch, vd host | url");if(t!=="url"){if(e.params!==void 0&&!ke(e.params))throw X("upload.params ph\u1EA3i l\xE0 object");return{target:t,params:(o=e.params)!=null?o:{}}}if(typeof e.url!="string"||!/^https:\/\//i.test(e.url))throw X("upload.url ph\u1EA3i l\xE0 https");for(let a of["field_name","url_field"])if(e[a]!==void 0&&(typeof e[a]!="string"||!e[a]))throw X(`upload.${a} ph\u1EA3i l\xE0 chu\u1ED7i`);return{target:"url",url:e.url,headers:kn(e.headers,"upload.headers"),form_data:kn(e.form_data,"upload.form_data"),field_name:(r=e.field_name)!=null?r:"file",url_field:(i=e.url_field)!=null?i:"url"}},Vn=e=>{let t=e.lastIndexOf(".");return t>0?e.slice(t).toLowerCase():""},Mr=(e,t)=>{if(!t.length)return!0;let n=e.mime_type.toLowerCase(),o=Vn(e.name);return t.some(r=>r==="*/*"?!0:r.startsWith(".")?r===o:r.endsWith("/*")?n.startsWith(r.slice(0,-1)):n===r)},xr=e=>{let t=e.length>0&&e.every(o=>o.startsWith("image/")),n=e.length>0&&e.every(o=>o.startsWith("video/"));return t?"image":n?"video":"mixed"},tt,Er=()=>(tt!=null||(tt=import("react-native-image-picker").catch(e=>{throw tt=void 0,new g("NOT_SUPPORTED",`Ch\u01B0a c\xF3 module ch\u1ECDn \u1EA3nh trong b\u1EA3n native: ${e instanceof Error?e.message:String(e)}`)})),tt),In=e=>async({accept:t,max_count:n,process:o})=>{var l,s,d,u,y,p,w,F,T;let r=await Er(),i=xr(t),a={mediaType:i==="image"?"photo":i,maxWidth:(l=o.image)==null?void 0:l.max_width,maxHeight:(s=o.image)==null?void 0:s.max_height,quality:(u=(d=o.image)==null?void 0:d.quality)!=null?u:.8,videoQuality:(p=(y=o.video)==null?void 0:y.quality)!=null?p:"medium",durationLimit:(w=o.video)==null?void 0:w.max_duration,assetRepresentationMode:"compatible"},c=e==="camera"?await r.launchCamera({...a,saveToPhotos:!1}):await r.launchImageLibrary({...a,selectionLimit:n});if(c.didCancel)return[];if(c.errorCode){let R=c.errorCode==="permission"?"PERMISSION_DENIED":c.errorCode==="camera_unavailable"?"NOT_SUPPORTED":"HOST_ERROR";throw new g(R,(F=c.errorMessage)!=null?F:c.errorCode)}return((T=c.assets)!=null?T:[]).filter(R=>R.uri).map((R,M)=>{var V,W,oe;return{uri:R.uri,name:(V=R.fileName)!=null?V:`file_${M+1}`,mime_type:(W=R.type)!=null?W:"application/octet-stream",size:R.fileSize,width:R.width,height:R.height,duration:R.duration,processed:!((oe=R.type)!=null&&oe.startsWith("video/"))||Jt.Platform.OS==="ios"}})},Rr={"image/*":"images","video/*":"video","audio/*":"audio","text/plain":"plainText","text/csv":"csv","application/pdf":"pdf","application/json":"json","application/zip":"zip","application/msword":"doc","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"docx","application/vnd.ms-excel":"xls","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"xlsx","application/vnd.ms-powerpoint":"ppt","application/vnd.openxmlformats-officedocument.presentationml.presentation":"pptx"},Pr={".pdf":"pdf",".txt":"plainText",".csv":"csv",".json":"json",".zip":"zip",".doc":"doc",".docx":"docx",".xls":"xls",".xlsx":"xlsx",".ppt":"ppt",".pptx":"pptx"},Tr=e=>async({accept:t,max_count:n})=>{var i,a,c,l;let o=t.map(s=>{var d;return(d=Rr[s])!=null?d:Pr[s]}),r=!t.length||o.some(s=>!s||!e.types[s])?e.types.allFiles:[...new Set(o)].flatMap(s=>e.types[s]);try{let d=(await e.pick({type:r,allowMultiSelection:n>1,mode:"import"})).filter(p=>p.uri&&!p.error).map((p,w)=>{var F,T,R;return{uri:p.uri,name:(F=p.name)!=null?F:`file_${w+1}`,mime_type:(T=p.type)!=null?T:"application/octet-stream",size:(R=p.size)!=null?R:void 0}});if(Jt.Platform.OS!=="android"||!e.keepLocalCopy||!d.some(p=>p.uri.startsWith("content://")))return d;let u=await e.keepLocalCopy({files:d.map(p=>({uri:p.uri,fileName:p.name})),destination:"cachesDirectory"}),y=new Map(u.map(p=>[p.sourceUri,p.status==="success"?p.localUri:void 0]));return d.map(p=>{var w;return{...p,uri:(w=y.get(p.uri))!=null?w:p.uri}})}catch(s){let d=s==null?void 0:s.code;if(d===((a=(i=e.errorCodes)==null?void 0:i.OPERATION_CANCELED)!=null?a:"OPERATION_CANCELED"))return[];throw d===((l=(c=e.errorCodes)==null?void 0:c.IN_PROGRESS)!=null?l:"ASYNC_OP_IN_PROGRESS")?new g("BUSY","\u0110ang m\u1EDF tr\xECnh ch\u1ECDn file kh\xE1c"):s}},nt,Cr=async e=>(nt!=null||(nt=import("@react-native-documents/picker").then(t=>Tr(t)).catch(t=>{throw nt=void 0,new g("NOT_SUPPORTED",`Ch\u01B0a c\xF3 module ch\u1ECDn file trong b\u1EA3n native: ${t instanceof Error?t.message:String(t)}`)})),(await nt)(e)),Bn={library:In("library"),camera:In("camera"),document:Cr},Ln={type:"image",label:"\u1EA2nh",accept:["image/*"]},Fn={type:"video",label:"Video",accept:["video/*"]},Dn={library:[Ln,Fn],camera:[Ln,Fn],document:[{type:"any",label:"M\u1ECDi file",accept:[]},{type:"pdf",label:"PDF",accept:["application/pdf"]},{type:"word",label:"Word",accept:[".doc",".docx"]},{type:"excel",label:"Excel",accept:[".xls",".xlsx"]},{type:"powerpoint",label:"PowerPoint",accept:[".ppt",".pptx"]}]},ot,qn=()=>(ot!=null||(ot=import("react-native-compressor").catch(()=>(ot=void 0,null))),ot),$n=async(e,t,n)=>{try{return Number(await e.getFileSize(t))||n}catch{return n}},Or=new Set(["image/jpeg","image/jpg","image/heic","image/heif","image/webp"]),kr={low:640,medium:1280,high:1920},Ir=async(e,{image:t})=>{var o;if(!t||!Or.has(e.mime_type.toLowerCase()))return e;let n=await qn();if(!n)return e;try{let r=await n.Image.compress(e.uri,{compressionMethod:"manual",maxWidth:t.max_width,maxHeight:t.max_height,quality:(o=t.quality)!=null?o:.8,output:"jpg"});return{...e,uri:r,mime_type:"image/jpeg",name:e.name.replace(/\.[^.]+$/,"")+".jpg",size:await $n(n,r,e.size),processed:!0}}catch{return e}},Lr=async(e,{video:t})=>{var o;let n=await qn();if(!n)return e;try{let r=await n.Video.compress(e.uri,{compressionMethod:"auto",maxSize:kr[(o=t==null?void 0:t.quality)!=null?o:"medium"],minimumFileSizeForCompress:2});return{...e,uri:r,mime_type:"video/mp4",size:await $n(n,r,e.size),processed:!0}}catch{return e}},Fr={image:Ir,video:Lr},Dr=(e,t)=>t.split(".").reduce((n,o)=>ke(n)?n[o]:void 0,e),Gt=({file:e,target:t,onProgress:n,signal:o})=>new Promise((r,i)=>{if(t.target!=="url"||!("url"in t)){i(new g("INVALID_PARAMS","Thi\u1EBFu upload.url"));return}let a=t;if(o.aborted){i(new g("CANCELLED","\u0110\xE3 hu\u1EF7 upload"));return}let c=new XMLHttpRequest,l=new FormData;Object.entries(a.form_data).forEach(([u,y])=>l.append(u,y)),l.append(a.field_name,{uri:e.uri,name:e.name,type:e.mime_type});let s=()=>c.abort();o.addEventListener("abort",s);let d=u=>{o.removeEventListener("abort",s),u()};c.open("POST",a.url),Object.entries(a.headers).forEach(([u,y])=>c.setRequestHeader(u,y)),c.upload.onprogress=u=>n(u.loaded,u.total||e.size||0),c.onload=()=>d(()=>{let u=c.responseText;try{u=JSON.parse(c.responseText)}catch{}if(c.status<200||c.status>=300){i(new g("UPLOAD_FAILED",`HTTP ${c.status}`));return}let y=Dr(u,a.url_field);if(typeof y!="string"||!y){i(new g("UPLOAD_FAILED",`Response kh\xF4ng c\xF3 "${a.url_field}"`));return}r({url:y,response:u})}),c.onerror=()=>d(()=>i(new g("UPLOAD_FAILED","L\u1ED7i m\u1EA1ng khi upload"))),c.onabort=()=>d(()=>i(new g("CANCELLED","\u0110\xE3 hu\u1EF7 upload"))),c.send(l)}),zn=e=>{var o,r;let t={...Bn};for(let[i,a]of Object.entries((o=e==null?void 0:e.sources)!=null?o:{}))a?t[i]=a:delete t[i];let n={url:Gt};for(let[i,a]of Object.entries((r=e==null?void 0:e.targets)!=null?r:{}))i!=="url"&&a&&(n[i]=a);return{sources:t,targets:n}},Wn=e=>{let{sources:t,targets:n}=zn(e),o=Object.keys(t),r=Object.fromEntries(o.filter(i=>t[i]===Bn[i]&&Dn[i]).map(i=>[i,Dn[i]]));return{sources:o,file_types:r,targets:Object.keys(n),max_count:Ht}},St=new Map,jn=(e,t)=>`${e}:${t}`,Nr=0,Hn=(e,t)=>{var n;typeof t=="string"&&((n=St.get(jn(e,t)))==null||n.abort())},qe=e=>{for(let[t,n]of St)t.startsWith(`${e}:`)&&n.abort()},_t=()=>new g("CANCELLED","\u0110\xE3 hu\u1EF7 upload"),Ur=(e,t)=>{var n;return{name:e,code:typeof(t==null?void 0:t.code)=="string"?t.code:"UPLOAD_FAILED",message:String((n=t==null?void 0:t.message)!=null?n:t)}},Jn=async(e,t)=>{var l;let{sources:n,targets:o}=zn(t.config),r=n[e.source];if(!r)throw new g("NOT_SUPPORTED",`\u1EE8ng d\u1EE5ng ch\u01B0a h\u1ED7 tr\u1EE3 ngu\u1ED3n "${e.source}"`);let i=o[e.target.target];if(!i)throw new g("NOT_SUPPORTED",`\u1EE8ng d\u1EE5ng ch\u01B0a h\u1ED7 tr\u1EE3 \u0111\xEDch upload "${e.target.target}"`);let a=new AbortController,c=jn(t.instance_id,(l=t.task_id)!=null?l:`auto-${++Nr}`);St.set(c,a);try{return await Vr(e,t,r,i,a.signal)}finally{St.delete(c)}},Vr=async(e,{instance_id:t,app_id:n,getContext:o,task_id:r,config:i,emit:a,exclusivePick:c=u=>u()},l,s,d)=>{var E,h,C;let u={app_id:n!=null?n:"",instance_id:t,context:{...(E=o==null?void 0:o())!=null?E:{}}},y=(await c(()=>l({accept:e.accept,max_count:e.max_count,process:e.process,caller:u}))).slice(0,e.max_count);if(d.aborted)throw _t();if(!y.length)throw new g("CANCELLED","Ng\u01B0\u1EDDi d\xF9ng kh\xF4ng ch\u1ECDn file");let p=[],w=y.filter(x=>Mr(x,e.accept)?!0:(p.push({name:x.name,code:"INVALID_FILE",message:`Kh\xF4ng cho ph\xE9p \u0111\u1ECBnh d\u1EA1ng ${x.mime_type||Vn(x.name)}`}),!1)),F=w.map(()=>0),T=w.map(x=>{var D;return(D=x.size)!=null?D:0}),R=0,M=0,V=(x=!1)=>{if(!a||!r)return;let D=Date.now();if(!x&&D-M<200)return;M=D;let _e=T.reduce((I,re)=>I+re,0),Y=F.reduce((I,re)=>I+re,0);a("upload.progress",{task_id:r,loaded:Y,total:_e,percent:_e?Math.min(100,Math.round(Y/_e*100)):0,done_count:R,count:w.length})},W=[],oe=0,Pe=async()=>{var x,D,_e;for(;oe<w.length;){let Y=oe++,I=w[Y];try{if(d.aborted)throw _t();let re=I.mime_type.startsWith("image/")?"image":I.mime_type.startsWith("video/")?"video":void 0,G=re&&!I.processed?(D=(x=i==null?void 0:i.processors)==null?void 0:x[re])!=null?D:Fr[re]:void 0;if(G&&(I=await G(I,e.process),T[Y]=(_e=I.size)!=null?_e:T[Y],d.aborted))throw _t();if(e.max_size&&I.size&&I.size>e.max_size)throw new g("FILE_TOO_LARGE",`File ${I.size} byte v\u01B0\u1EE3t gi\u1EDBi h\u1EA1n ${e.max_size}`);let ee=(je,xe)=>{F[Y]=je,xe&&(T[Y]=xe),V()},ie=await s({file:I,target:e.target,onProgress:ee,signal:d,caller:u});if(typeof(ie==null?void 0:ie.url)!="string"||!ie.url)throw new g("UPLOAD_FAILED","Upload kh\xF4ng tr\u1EA3 url");let{url:ve,...Me}=ie;W[Y]={url:ve,name:I.name,mime_type:I.mime_type,size:I.size,width:I.width,height:I.height,duration:I.duration,...Object.keys(Me).length?{response:"response"in Me?Me.response:Me}:{}},F[Y]=T[Y]}catch(re){p.push(Ur(w[Y].name,re))}finally{R++,V(!0)}}};if(await Promise.all(Array.from({length:Math.min(e.concurrency,w.length)},Pe)),d.aborted)throw _t();let ce=W.filter(x=>!!x);if(!ce.length){let x=p[0];throw new g((h=x==null?void 0:x.code)!=null?h:"UPLOAD_FAILED",(C=x==null?void 0:x.message)!=null?C:"Kh\xF4ng upload \u0111\u01B0\u1EE3c file n\xE0o")}return{files:ce,failed:p}};var At=require("react"),Ie=e=>{let t=e,n=new Set;return{getState:()=>t,setState:o=>{let r=typeof o=="function"?o(t):o;t={...t,...r},n.forEach(i=>i())},subscribe:o=>(n.add(o),()=>{n.delete(o)})}},H=(e,t,n=Object.is)=>{let o=(0,At.useRef)(null),r=()=>{let i=e.getState(),a=o.current;if(a&&a.state===i&&a.selector===t)return a.value;let c=t(i),l=a&&n(a.value,c)?a.value:c;return o.current={state:i,selector:t,value:l},l};return(0,At.useSyncExternalStore)(e.subscribe,r)};var he={info:"info",success:"success",error:"error"},Br=200,Gn={info:2e3,success:2e3,error:3e3},it=Ie({message:"",type:he.info,tick:0}),Kn=e=>{let{message:t,type:n}=e!=null?e:{},o=String(t!=null?t:"").trim().slice(0,Br);return o?{message:o,type:Object.values(he).includes(n)?n:he.info}:null},Yn=(e,t=he.info)=>{it.setState(n=>({message:e,type:t,tick:n.tick+1}))};var ye=require("react-native");var $e=require("react-native");var fe,He=new Map,Xn=(e,t)=>{var o;let n=(o=He.get(e))!=null?o:new Set;n.add(t),He.set(e,n)},Zn=(e,t)=>{let n=He.get(e);n&&(t?n.delete(t):n.clear(),n.size===0&&He.delete(e))},Yt=new Map,Qn=(e,t)=>{Yt.set(e,t)},eo=e=>Yt.get(e),to=()=>$e.Platform.OS==="android"&&!!(fe!=null&&fe.requesting_permission),qr=1500,vt=()=>new Promise(e=>{if($e.Platform.OS!=="android"||$e.AppState.currentState==="active"){e();return}let t=()=>{clearTimeout(n),o.remove(),e()},n=setTimeout(t,qr),o=$e.AppState.addEventListener("change",r=>{r==="active"&&t()})}),Kt=e=>{var t;if(fe===e&&(fe=void 0,e.subscriptions.forEach(n=>n.remove()),e.started&&$e.Platform.OS==="ios"))try{(t=e.native)==null||t.setAudioSessionActiveIOS(!1,{notifyOthersOnDeactivation:!0})}catch{}},no=async(e,t,n,o=()=>!0)=>{var i,a,c,l,s;if(fe)throw new g("BUSY","Micro \u0111ang \u0111\u01B0\u1EE3c mini app kh\xE1c s\u1EED d\u1EE5ng");if(!o())throw new g("CANCELLED","Mini app kh\xF4ng c\xF2n ho\u1EA1t \u0111\u1ED9ng");let r={owner:e,emit:n,cancelled:!1,started:!1,subscriptions:[]};fe=r;try{let d;try{d=await import("expo-speech-recognition")}catch{throw new g("NOT_SUPPORTED","Ch\u01B0a c\xF3 module nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i trong b\u1EA3n native")}let u=d.ExpoSpeechRecognitionModule;if(r.native=u,r.cancelled||!o())throw new g("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");r.requesting_permission=!0;let y;try{y=await u.requestPermissionsAsync()}finally{r.requesting_permission=!1}if(await vt(),r.cancelled||!o())throw new g("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");if(!y.granted)throw new g("PERMISSION_DENIED","Ch\u01B0a c\u1EA5p quy\u1EC1n micro / nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i");if(await u.getStateAsync()!=="inactive")throw new g("BUSY","Nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i \u0111ang \u0111\u01B0\u1EE3c t\xEDnh n\u0103ng kh\xE1c s\u1EED d\u1EE5ng");if(r.cancelled||!o())throw new g("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");r.subscriptions.push(u.addListener("result",p=>{var w,F;fe!==r||r.cancelled||n(p.isFinal?"speech.final":"speech.partial",{...p,text:(F=(w=p.results[0])==null?void 0:w.transcript)!=null?F:""})}),u.addListener("error",p=>{fe===r&&!r.cancelled&&n("speech.error",{...p,code:p.error})}),u.addListener("end",()=>{fe===r&&(Kt(r),n("speech.end"))})),r.started=!0,u.start({lang:(i=t.lang)!=null?i:"vi-VN",continuous:(a=t.continuous)!=null?a:!0,interimResults:(c=t.interimResults)!=null?c:!0,addsPunctuation:(l=t.addsPunctuation)!=null?l:!0,requiresOnDeviceRecognition:(s=t.requiresOnDeviceRecognition)!=null?s:!1,iosCategory:{category:d.AVAudioSessionCategory.playAndRecord,categoryOptions:[d.AVAudioSessionCategoryOptions.defaultToSpeaker,d.AVAudioSessionCategoryOptions.allowBluetooth],mode:d.AVAudioSessionMode.measurement}})}catch(d){throw Kt(r),d}},oo=e=>{let t=fe;if(!(!t||t.owner!==e)){if(!t.started){t.cancelled=!0;return}t.native.stop()}},Re=e=>{Yt.delete(e);let t=He.get(e);He.delete(e),t==null||t.forEach(o=>{var r;try{(r=o.release)==null||r.call(o,e)}catch{}});let n=fe;if(!(!n||n.owner!==e||n.cancelled)&&(n.cancelled=!0,n.started))try{n.native.abort()}catch{Kt(n)}};var ro={qr:"qr",ean13:"ean-13",ean8:"ean-8",upcA:"upc-a",upcE:"upc-e",code128:"code-128",code39:"code-39",code93:"code-93",codabar:"codabar",itf:"itf",pdf417:"pdf-417",aztec:"aztec",dataMatrix:"data-matrix"},te={...ro,all:Object.values(ro)},Je={scan:"scanner.scan",start:"scanner.start",stop:"scanner.stop"},xt={result:"scanner.result",end:"scanner.end"},ze={user:"user",web:"web",closed:"closed",error:"error"},pe={top:"top",full:"full"},Le={once:"once",continuous:"continuous"},$r=1500,io=6e4,q,Z=Ie({active:null,last_value:null,hit_tick:0,scan_count:0,notice:null,is_picking:!1}),ao=()=>ye.Platform.OS==="android"&&!!(q!=null&&q.requesting_permission),Zt=e=>{let{types:t,cooldown_ms:n,hint:o,layout:r,absolute:i}=e!=null?e:{},a={};if(t!==void 0){if(!Array.isArray(t)||!t.length||!t.every(c=>te.all.includes(c)))throw new g("INVALID_PARAMS","types ph\u1EA3i l\xE0 m\u1EA3ng CodeType");a.types=t}if(n!==void 0){if(typeof n!="number"||!Number.isFinite(n)||n<0||n>io)throw new g("INVALID_PARAMS",`cooldown_ms ph\u1EA3i t\u1EEB 0 \u0111\u1EBFn ${io}`);a.cooldown_ms=n}if(o!==void 0){if(typeof o!="string"||!o.trim()||o.length>80)throw new g("INVALID_PARAMS","hint ph\u1EA3i c\xF3 1\u201380 k\xFD t\u1EF1");a.hint=o}if(r!==void 0){if(!Object.values(pe).includes(r))throw new g("INVALID_PARAMS","layout ph\u1EA3i l\xE0 ScannerLayout");a.layout=r}if(i!==void 0){if(typeof i!="boolean")throw new g("INVALID_PARAMS","absolute ph\u1EA3i l\xE0 boolean");a.absolute=i}return a},Qt=e=>q!==e?!1:(q=void 0,Z.setState({active:null,last_value:null,scan_count:0,notice:null,is_picking:!1}),!0),zr=()=>ye.Alert.alert("Ch\u01B0a c\u1EA5p quy\u1EC1n camera","H\xE3y b\u1EADt quy\u1EC1n camera trong C\xE0i \u0111\u1EB7t \u0111\u1EC3 qu\xE9t m\xE3.",[{text:"Hu\u1EF7",style:"cancel"},{text:"M\u1EDF C\xE0i \u0111\u1EB7t",onPress:()=>{ye.Linking.openSettings().catch(()=>{})}}]),co=async(e,t)=>{if(q)throw new g("BUSY","Camera qu\xE9t m\xE3 \u0111ang \u0111\u01B0\u1EE3c s\u1EED d\u1EE5ng");if(!t())throw new g("CANCELLED","Mini app kh\xF4ng c\xF2n ho\u1EA1t \u0111\u1ED9ng");q=e;let n=()=>{if(e.cancelled||!t())throw new g("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng")};try{let o;try{o=await import("react-native-vision-camera")}catch{throw new g("NOT_SUPPORTED","Ch\u01B0a c\xF3 module camera trong b\u1EA3n native")}n();let r=o.Camera.getCameraPermissionStatus();if(r!=="granted"){let a=ye.Platform.OS==="ios"&&r==="denied";e.requesting_permission=!0;let c;try{c=await o.Camera.requestCameraPermission()}finally{e.requesting_permission=!1}if(await vt(),n(),c!=="granted")throw a&&zr(),new g("PERMISSION_DENIED","Ch\u01B0a c\u1EA5p quy\u1EC1n camera")}if(!o.Camera.getAvailableCameraDevices().some(a=>a.position==="back"))throw new g("NOT_SUPPORTED","Thi\u1EBFt b\u1ECB kh\xF4ng c\xF3 camera sau");let i=await en();n(),Z.setState({active:{owner:e.owner,mode:e.mode,types:e.types,layout:e.layout,absolute:e.absolute,hint:e.hint,vision:o,glass_view:i},last_value:null,scan_count:0,notice:null})}catch(o){throw Qt(e),o}},Mt;import("react-native-safe-area-context").then(({initialWindowMetrics:e})=>{Mt=e==null?void 0:e.insets}).catch(()=>{});var Et=()=>{var e;return Mt!=null?Mt:{top:ye.Platform.OS==="ios"?54:(e=ye.StatusBar.currentHeight)!=null?e:0,bottom:ye.Platform.OS==="ios"?34:48}},en=async()=>{if(ye.Platform.OS==="ios")try{let e=await import("expo-glass-effect");return e.isLiquidGlassAvailable()?e.GlassView:void 0}catch{return}},lo=(e,t,n)=>{var o,r,i,a;return{owner:e,mode:t,types:(o=n.types)!=null?o:te.all,cooldown_ms:(r=n.cooldown_ms)!=null?r:$r,hint:n.hint,layout:t===Le.once?pe.full:(i=n.layout)!=null?i:pe.top,absolute:t!==Le.once&&((a=n.layout)!=null?a:pe.top)===pe.top&&n.absolute===!0,cancelled:!1,requesting_permission:!1,last_seen:new Map}},po=(e,t,n=()=>!0,o)=>new Promise((r,i)=>{let a=lo(e,Le.once,t);a.onHit=o,a.resolve=r,a.reject=i,co(a,n).catch(i)}),uo=(e,t,n,o=()=>!0,r)=>{let i=lo(e,Le.continuous,t);return i.emit=n,i.onHit=r,co(i,o)},Rt=(e,t,n)=>{var o,r;if(!Z.getState().active){e.cancelled=!0;return}if(Qt(e)){if(e.mode===Le.once){(o=e.reject)==null||o.call(e,t===ze.error?new g("HOST_ERROR",n!=null?n:"L\u1ED7i camera"):new g("CANCELLED","\u0110\xE3 \u0111\xF3ng camera qu\xE9t m\xE3"));return}(r=e.emit)==null||r.call(e,xt.end,n?{reason:t,message:n}:{reason:t})}},go=e=>{(q==null?void 0:q.owner)===e&&Rt(q,ze.web)},Fe=e=>{(q==null?void 0:q.owner)===e&&Rt(q,ze.closed)},tn=()=>{q&&Rt(q,ze.user)},mo=e=>{q&&Rt(q,ze.error,e)},nn=(e,t=Date.now(),n=!1)=>{var r,i,a;let o=q;if(!(!o||!Z.getState().active))for(let{value:c,type:l}of e){if(!c)continue;let s=o.last_seen.get(c);if(o.last_seen.set(c,t),!(!n&&s!==void 0&&t-s<o.cooldown_ms)){if((r=o.onHit)==null||r.call(o),o.mode===Le.once){Qt(o),(i=o.resolve)==null||i.call(o,{value:c,type:l});return}Z.setState(d=>({last_value:c,hit_tick:d.hit_tick+1,scan_count:d.scan_count+1,notice:null})),(a=o.emit)==null||a.call(o,xt.result,{value:c,type:l})}}},Wr={1:te.code128,2:te.code39,4:te.code93,8:te.codabar,16:te.dataMatrix,32:te.ean13,64:te.ean8,128:te.itf,256:te.qr,512:te.upcA,1024:te.upcE,2048:te.pdf417,4096:te.aztec},jr=2500,so=2e3,Xt=e=>{Z.setState({notice:e}),setTimeout(()=>{Z.getState().notice===e&&Z.setState({notice:null})},jr)},ho=async()=>{var t,n;let e=q;if(!(!e||Z.getState().is_picking)){e.requesting_permission=!0,Z.setState({is_picking:!0,notice:null});try{let{launchImageLibrary:o}=await import("react-native-image-picker"),r=await o({mediaType:"photo",selectionLimit:1,maxWidth:so,maxHeight:so}),i=(n=(t=r.assets)==null?void 0:t[0])==null?void 0:n.uri;if(r.didCancel||q!==e)return;if(r.errorCode||!i){Xt("Kh\xF4ng m\u1EDF \u0111\u01B0\u1EE3c \u1EA3nh");return}let{default:a}=await import("@react-native-ml-kit/barcode-scanning"),c=await a.scan(i);if(q!==e)return;let l=c.map(({value:s,format:d})=>({value:s,code_type:Wr[d]})).filter(({code_type:s})=>!s||e.types.includes(s)).map(({value:s,code_type:d})=>({value:s,type:d!=null?d:"unknown"}));if(!l.length){Xt("Kh\xF4ng t\xECm th\u1EA5y m\xE3 trong \u1EA3nh");return}nn(l,Date.now(),!0)}catch{q===e&&Xt("Kh\xF4ng \u0111\u1ECDc \u0111\u01B0\u1EE3c m\xE3 t\u1EEB \u1EA3nh")}finally{await vt(),e.requesting_permission=!1,q===e&&Z.setState({is_picking:!1})}}};var Tt=1,g=class extends Error{constructor(n,o){super(o);this.code=n}},fo=e=>{try{let t=JSON.parse(e);return(t==null?void 0:t.__retion)===Tt&&typeof t.method=="string"?t:null}catch{return null}},ct=e=>`window.__RETION_MINIAPP__ && window.__RETION_MINIAPP__.receive(${JSON.stringify(e)}); true;`,yo=(e,t)=>ct({id:e,result:t}),wo=(e,t)=>ct({id:e,error:{code:t.code,message:t.message}}),bo=(e,t)=>ct({event:e,data:t}),rn=e=>ct({event:"context",data:e});var _o=()=>`(function () {
1
+ "use strict";var Sr=Object.create;var bt=Object.defineProperty;var _r=Object.getOwnPropertyDescriptor;var vr=Object.getOwnPropertyNames;var Mr=Object.getPrototypeOf,xr=Object.prototype.hasOwnProperty;var Er=(e,t)=>{for(var n in t)bt(e,n,{get:t[n],enumerable:!0})},Pn=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of vr(t))!xr.call(e,r)&&r!==n&&bt(e,r,{get:()=>t[r],enumerable:!(o=_r(t,r))||o.enumerable});return e};var le=(e,t,n)=>(n=e!=null?Sr(Mr(e)):{},Pn(t||!e||!e.__esModule?bt(n,"default",{value:e,enumerable:!0}):n,e)),Cr=e=>Pn(bt({},"__esModule",{value:!0}),e);var Pi={};Er(Pi,{CodeType:()=>te,DefaultMiniAppSplash:()=>_n,MINIAPP_PLATFORM_URL:()=>Je,MiniAppHost:()=>yr,MiniAppHostError:()=>g,ScannerEndReason:()=>We,ScannerEvent:()=>Et,ScannerLayout:()=>pe,ScannerMethod:()=>Ke,ToastType:()=>me,closeMiniApp:()=>Qe,configureMiniApp:()=>Tn,createMmkvStorage:()=>In,createReactNativeBiometrics:()=>jt,createRnfsFileSystem:()=>kn,ensureMiniApp:()=>ft,fetchMiniAppChangelog:()=>xn,getLocalMiniApp:()=>N,getMiniAppCatalog:()=>gr,getMiniAppCatalogEntry:()=>Ze,getMiniAppChangelogSeen:()=>vn,getMiniAppStatuses:()=>rr,getMiniAppUpdate:()=>An,getPendingChangelog:()=>br,installBundledMiniApp:()=>Bo,markMiniAppChangelogSeen:()=>Mn,onMiniAppEvent:()=>or,openMiniApp:()=>Xo,pauseMiniApp:()=>cr,pauseMiniAppDownloads:()=>pr,preloadMiniApp:()=>Qo,releaseSpeechFor:()=>Ce,restoreMiniApp:()=>ar,resumeMiniApp:()=>lr,resumeMiniAppDownloads:()=>ur,sendEventToWeb:()=>zo,syncMiniAppCatalog:()=>qt,uninstallMiniApp:()=>sr,updateMiniApp:()=>dr,uploadToUrl:()=>Kt,useMiniAppChangelog:()=>Ar,useMiniAppDownload:()=>Vt,useMiniAppDownloadsPaused:()=>nr});module.exports=Cr(Pi);var Je="https://retion-miniapp-platform.vercel.app",qe=null,Rn=new Set,Tn=e=>{qe=e,Rn.forEach(t=>t())},D=()=>{if(!qe)throw new Error("[miniapp] Ch\u01B0a g\u1ECDi configureMiniApp()");return qe},On=e=>{Rn.add(e),qe&&e()},he=(...e)=>{qe!=null&&qe.debug&&console.log("[miniapp]",...e)};var kn=(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(o=>o.map(r=>r.name)).catch(()=>[]),sha256:n=>e.hash(n,"sha256"),unzip:async(n,o)=>{await t(n,o)},download:({url:n,to_file:o,onProgress:r})=>{let{jobId:i,promise:a}=e.downloadFile({fromUrl:n,toFile:o,progressInterval:250,begin:()=>{},progress:({bytesWritten:c,contentLength:l})=>r==null?void 0:r(c,l)});return{promise:a.then(({statusCode:c})=>({status:c})),cancel:()=>e.stopDownload(i)}}}),In=e=>({getString:t=>e.getString(t),setString:(t,n)=>e.set(t,n)});var S=le(require("react")),I=require("react-native"),fr=le(require("react-native-webview"));var lt=require("react-native");var jt=e=>({getAvailability:()=>e.isSensorAvailable(),authenticate:({reason:t,cancelButtonText:n})=>e.simplePrompt({promptMessage:t,cancelButtonText:n,fallbackPromptMessage:""})}),At,Ht=()=>(At||(At=import("react-native-biometrics").then(({default:e})=>jt(new e({allowDeviceCredentials:!1}))).catch(e=>{throw At=void 0,new g("NOT_SUPPORTED",`Biometric native module unavailable: ${e instanceof Error?e.message:String(e)}`)})),At);var Ee=require("react-native");var Ln=e=>{var n,o,r;if(e!==void 0&&(e===null||typeof e!="object"||Array.isArray(e)))throw new g("INVALID_PARAMS","Tu\u1EF3 ch\u1ECDn v\u1ECB tr\xED ph\u1EA3i l\xE0 object");let t=e!=null?e:{};if(t.enableHighAccuracy!==void 0&&typeof t.enableHighAccuracy!="boolean")throw new g("INVALID_PARAMS","enableHighAccuracy ph\u1EA3i l\xE0 boolean");for(let[i,a,c]of[["timeout",1,6e4],["maximumAge",0,864e5]]){let l=t[i];if(l!==void 0&&(typeof l!="number"||!Number.isFinite(l)||l<a||l>c))throw new g("INVALID_PARAMS",`${i} ph\u1EA3i n\u1EB1m trong kho\u1EA3ng ${a}\u2013${c} ms`)}return{enableHighAccuracy:(n=t.enableHighAccuracy)!=null?n:!1,timeout:(o=t.timeout)!=null?o:15e3,maximumAge:(r=t.maximumAge)!=null?r:0}},Fn=(e,t=()=>!0)=>new Promise((n,o)=>{let r=!1,i=(l,s)=>{r||(r=!0,clearTimeout(a),l?o(l):n(s))},a=setTimeout(()=>i(new g("TIMEOUT","H\u1EBFt th\u1EDDi gian ch\u1EDD c\u1EA5p quy\u1EC1n/l\u1EA5y v\u1ECB tr\xED")),12e4+e.timeout),c=()=>r?!1:t()?!0:(i(new g("CANCELLED","Mini app kh\xF4ng c\xF2n ho\u1EA1t \u0111\u1ED9ng")),!1);(async()=>{if(!c())return;let l;try{l=(await import("@react-native-community/geolocation")).default}catch{throw new g("NOT_SUPPORTED","Ch\u01B0a c\xF3 module v\u1ECB tr\xED trong b\u1EA3n native")}if(c()){if(Ee.Platform.OS==="android"){let s=Ee.PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,d=Ee.PermissionsAndroid.PERMISSIONS.ACCESS_COARSE_LOCATION,u=await Ee.PermissionsAndroid.check(s);if(!c())return;let y=u||await Ee.PermissionsAndroid.check(d);if(!c())return;if(!u&&!y){let p=await Ee.PermissionsAndroid.requestMultiple([s,d]);if(!c())return;if(p[s]!==Ee.PermissionsAndroid.RESULTS.GRANTED&&p[d]!==Ee.PermissionsAndroid.RESULTS.GRANTED)throw new g("PERMISSION_DENIED","Ch\u01B0a c\u1EA5p quy\u1EC1n truy c\u1EADp v\u1ECB tr\xED")}}c()&&l.getCurrentPosition(s=>{c()&&i(void 0,s)},s=>{var u;if(!c())return;let d=(u={1:"PERMISSION_DENIED",2:"POSITION_UNAVAILABLE",3:"TIMEOUT"}[s.code])!=null?u:"LOCATION_ERROR";i(new g(d,s.message))},e)}})().catch(l=>i(l))});var Gt=require("react-native");var Jt=20,Dn=20,$n=/^[a-z][a-z0-9_-]{0,31}$/,Pr=/^(\.[\w-]{1,16}|[\w.+-]+\/(\*|[\w.+-]+))$/,Rr=["low","medium","high"],Ie=e=>!!e&&typeof e=="object"&&!Array.isArray(e),X=e=>new g("INVALID_PARAMS",e),st=(e,t,n)=>typeof e=="number"&&Number.isInteger(e)&&e>=t&&e<=n,Nn=(e,t)=>{if(e===void 0)return{};if(!Ie(e)||Object.keys(e).length>Dn||Object.values(e).some(n=>typeof n!="string"))throw X(`${t} ph\u1EA3i l\xE0 object chu\u1ED7i (t\u1ED1i \u0111a ${Dn} key)`);return e},zn=e=>{var n,o,r,i;if(e!==void 0&&!Ie(e))throw X("Tu\u1EF3 ch\u1ECDn upload ph\u1EA3i l\xE0 object");let t=e!=null?e:{};if(t.source!==void 0&&(typeof t.source!="string"||!$n.test(t.source)))throw X("source ph\u1EA3i l\xE0 t\xEAn ngu\u1ED3n, vd library | camera | document");if(t.accept!==void 0&&(!Array.isArray(t.accept)||t.accept.length>50||t.accept.some(a=>typeof a!="string"||!Pr.test(a))))throw X("accept ph\u1EA3i l\xE0 m\u1EA3ng mime (image/*, application/pdf) ho\u1EB7c \u0111u\xF4i (.docx)");if(t.max_count!==void 0&&!st(t.max_count,1,Jt))throw X(`max_count ph\u1EA3i l\xE0 s\u1ED1 nguy\xEAn 1\u2013${Jt}`);if(t.max_size!==void 0&&!st(t.max_size,1,Number.MAX_SAFE_INTEGER))throw X("max_size ph\u1EA3i l\xE0 s\u1ED1 byte > 0");if(t.concurrency!==void 0&&!st(t.concurrency,1,5))throw X("concurrency ph\u1EA3i l\xE0 s\u1ED1 nguy\xEAn 1\u20135");return{source:(n=t.source)!=null?n:"library",accept:((o=t.accept)!=null?o:[]).map(a=>a.toLowerCase()),max_count:(r=t.max_count)!=null?r:1,max_size:t.max_size,process:Tr(t.process),target:Or(t.upload),concurrency:(i=t.concurrency)!=null?i:3}},Tr=e=>{if(e===void 0)return{};if(!Ie(e))throw X("process ph\u1EA3i l\xE0 object");let t={};if(e.image!==void 0){let n=e.image;if(!Ie(n))throw X("process.image ph\u1EA3i l\xE0 object");for(let o of["max_width","max_height"])if(n[o]!==void 0&&!st(n[o],1,1e4))throw X(`process.image.${o} ph\u1EA3i l\xE0 s\u1ED1 nguy\xEAn 1\u201310000`);if(n.quality!==void 0&&(typeof n.quality!="number"||n.quality<=0||n.quality>1))throw X("process.image.quality ph\u1EA3i trong kho\u1EA3ng (0, 1]");t.image={max_width:n.max_width,max_height:n.max_height,quality:n.quality}}if(e.video!==void 0){let n=e.video;if(!Ie(n))throw X("process.video ph\u1EA3i l\xE0 object");if(n.max_duration!==void 0&&!st(n.max_duration,1,3600))throw X("process.video.max_duration ph\u1EA3i l\xE0 s\u1ED1 gi\xE2y 1\u20133600");if(n.quality!==void 0&&!Rr.includes(n.quality))throw X("process.video.quality ph\u1EA3i l\xE0 low | medium | high");t.video={max_duration:n.max_duration,quality:n.quality}}return t},Or=e=>{var n,o,r,i;if(e===void 0)return{target:"host",params:{}};if(!Ie(e))throw X("upload ph\u1EA3i l\xE0 object");let t=(n=e.target)!=null?n:"host";if(typeof t!="string"||!$n.test(t))throw X("upload.target ph\u1EA3i l\xE0 t\xEAn \u0111\xEDch, vd host | url");if(t!=="url"){if(e.params!==void 0&&!Ie(e.params))throw X("upload.params ph\u1EA3i l\xE0 object");return{target:t,params:(o=e.params)!=null?o:{}}}if(typeof e.url!="string"||!/^https:\/\//i.test(e.url))throw X("upload.url ph\u1EA3i l\xE0 https");for(let a of["field_name","url_field"])if(e[a]!==void 0&&(typeof e[a]!="string"||!e[a]))throw X(`upload.${a} ph\u1EA3i l\xE0 chu\u1ED7i`);return{target:"url",url:e.url,headers:Nn(e.headers,"upload.headers"),form_data:Nn(e.form_data,"upload.form_data"),field_name:(r=e.field_name)!=null?r:"file",url_field:(i=e.url_field)!=null?i:"url"}},Wn=e=>{let t=e.lastIndexOf(".");return t>0?e.slice(t).toLowerCase():""},kr=(e,t)=>{if(!t.length)return!0;let n=e.mime_type.toLowerCase(),o=Wn(e.name);return t.some(r=>r==="*/*"?!0:r.startsWith(".")?r===o:r.endsWith("/*")?n.startsWith(r.slice(0,-1)):n===r)},Ir=e=>{let t=e.length>0&&e.every(o=>o.startsWith("image/")),n=e.length>0&&e.every(o=>o.startsWith("video/"));return t?"image":n?"video":"mixed"},ot,Lr=()=>(ot!=null||(ot=import("react-native-image-picker").catch(e=>{throw ot=void 0,new g("NOT_SUPPORTED",`Ch\u01B0a c\xF3 module ch\u1ECDn \u1EA3nh trong b\u1EA3n native: ${e instanceof Error?e.message:String(e)}`)})),ot),Un=e=>async({accept:t,max_count:n,process:o})=>{var l,s,d,u,y,p,f,O,R;let r=await Lr(),i=Ir(t),a={mediaType:i==="image"?"photo":i,maxWidth:(l=o.image)==null?void 0:l.max_width,maxHeight:(s=o.image)==null?void 0:s.max_height,quality:(u=(d=o.image)==null?void 0:d.quality)!=null?u:.8,videoQuality:(p=(y=o.video)==null?void 0:y.quality)!=null?p:"medium",durationLimit:(f=o.video)==null?void 0:f.max_duration,assetRepresentationMode:"compatible"},c=e==="camera"?await r.launchCamera({...a,saveToPhotos:!1}):await r.launchImageLibrary({...a,selectionLimit:n});if(c.didCancel)return[];if(c.errorCode){let C=c.errorCode==="permission"?"PERMISSION_DENIED":c.errorCode==="camera_unavailable"?"NOT_SUPPORTED":"HOST_ERROR";throw new g(C,(O=c.errorMessage)!=null?O:c.errorCode)}return((R=c.assets)!=null?R:[]).filter(C=>C.uri).map((C,M)=>{var q,W,oe;return{uri:C.uri,name:(q=C.fileName)!=null?q:`file_${M+1}`,mime_type:(W=C.type)!=null?W:"application/octet-stream",size:C.fileSize,width:C.width,height:C.height,duration:C.duration,processed:!((oe=C.type)!=null&&oe.startsWith("video/"))||Gt.Platform.OS==="ios"}})},Fr={"image/*":"images","video/*":"video","audio/*":"audio","text/plain":"plainText","text/csv":"csv","application/pdf":"pdf","application/json":"json","application/zip":"zip","application/msword":"doc","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"docx","application/vnd.ms-excel":"xls","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"xlsx","application/vnd.ms-powerpoint":"ppt","application/vnd.openxmlformats-officedocument.presentationml.presentation":"pptx"},Dr={".pdf":"pdf",".txt":"plainText",".csv":"csv",".json":"json",".zip":"zip",".doc":"doc",".docx":"docx",".xls":"xls",".xlsx":"xlsx",".ppt":"ppt",".pptx":"pptx"},Nr=e=>async({accept:t,max_count:n})=>{var i,a,c,l;let o=t.map(s=>{var d;return(d=Fr[s])!=null?d:Dr[s]}),r=!t.length||o.some(s=>!s||!e.types[s])?e.types.allFiles:[...new Set(o)].flatMap(s=>e.types[s]);try{let d=(await e.pick({type:r,allowMultiSelection:n>1,mode:"import"})).filter(p=>p.uri&&!p.error).map((p,f)=>{var O,R,C;return{uri:p.uri,name:(O=p.name)!=null?O:`file_${f+1}`,mime_type:(R=p.type)!=null?R:"application/octet-stream",size:(C=p.size)!=null?C:void 0}});if(Gt.Platform.OS!=="android"||!e.keepLocalCopy||!d.some(p=>p.uri.startsWith("content://")))return d;let u=await e.keepLocalCopy({files:d.map(p=>({uri:p.uri,fileName:p.name})),destination:"cachesDirectory"}),y=new Map(u.map(p=>[p.sourceUri,p.status==="success"?p.localUri:void 0]));return d.map(p=>{var f;return{...p,uri:(f=y.get(p.uri))!=null?f:p.uri}})}catch(s){let d=s==null?void 0:s.code;if(d===((a=(i=e.errorCodes)==null?void 0:i.OPERATION_CANCELED)!=null?a:"OPERATION_CANCELED"))return[];throw d===((l=(c=e.errorCodes)==null?void 0:c.IN_PROGRESS)!=null?l:"ASYNC_OP_IN_PROGRESS")?new g("BUSY","\u0110ang m\u1EDF tr\xECnh ch\u1ECDn file kh\xE1c"):s}},rt,Ur=async e=>(rt!=null||(rt=import("@react-native-documents/picker").then(t=>Nr(t)).catch(t=>{throw rt=void 0,new g("NOT_SUPPORTED",`Ch\u01B0a c\xF3 module ch\u1ECDn file trong b\u1EA3n native: ${t instanceof Error?t.message:String(t)}`)})),(await rt)(e)),jn={library:Un("library"),camera:Un("camera"),document:Ur},Vn={type:"image",label:"\u1EA2nh",accept:["image/*"]},Bn={type:"video",label:"Video",accept:["video/*"]},qn={library:[Vn,Bn],camera:[Vn,Bn],document:[{type:"any",label:"M\u1ECDi file",accept:[]},{type:"pdf",label:"PDF",accept:["application/pdf"]},{type:"word",label:"Word",accept:[".doc",".docx"]},{type:"excel",label:"Excel",accept:[".xls",".xlsx"]},{type:"powerpoint",label:"PowerPoint",accept:[".ppt",".pptx"]}]},it,Hn=()=>(it!=null||(it=import("react-native-compressor").catch(()=>(it=void 0,null))),it),Jn=async(e,t,n)=>{try{return Number(await e.getFileSize(t))||n}catch{return n}},Vr=new Set(["image/jpeg","image/jpg","image/heic","image/heif","image/webp"]),Br={low:640,medium:1280,high:1920},qr=async(e,{image:t})=>{var o;if(!t||!Vr.has(e.mime_type.toLowerCase()))return e;let n=await Hn();if(!n)return e;try{let r=await n.Image.compress(e.uri,{compressionMethod:"manual",maxWidth:t.max_width,maxHeight:t.max_height,quality:(o=t.quality)!=null?o:.8,output:"jpg"});return{...e,uri:r,mime_type:"image/jpeg",name:e.name.replace(/\.[^.]+$/,"")+".jpg",size:await Jn(n,r,e.size),processed:!0}}catch{return e}},$r=async(e,{video:t})=>{var o;let n=await Hn();if(!n)return e;try{let r=await n.Video.compress(e.uri,{compressionMethod:"auto",maxSize:Br[(o=t==null?void 0:t.quality)!=null?o:"medium"],minimumFileSizeForCompress:2});return{...e,uri:r,mime_type:"video/mp4",size:await Jn(n,r,e.size),processed:!0}}catch{return e}},zr={image:qr,video:$r},Wr=(e,t)=>t.split(".").reduce((n,o)=>Ie(n)?n[o]:void 0,e),Kt=({file:e,target:t,onProgress:n,signal:o})=>new Promise((r,i)=>{if(t.target!=="url"||!("url"in t)){i(new g("INVALID_PARAMS","Thi\u1EBFu upload.url"));return}let a=t;if(o.aborted){i(new g("CANCELLED","\u0110\xE3 hu\u1EF7 upload"));return}let c=new XMLHttpRequest,l=new FormData;Object.entries(a.form_data).forEach(([u,y])=>l.append(u,y)),l.append(a.field_name,{uri:e.uri,name:e.name,type:e.mime_type});let s=()=>c.abort();o.addEventListener("abort",s);let d=u=>{o.removeEventListener("abort",s),u()};c.open("POST",a.url),Object.entries(a.headers).forEach(([u,y])=>c.setRequestHeader(u,y)),c.upload.onprogress=u=>n(u.loaded,u.total||e.size||0),c.onload=()=>d(()=>{let u=c.responseText;try{u=JSON.parse(c.responseText)}catch{}if(c.status<200||c.status>=300){i(new g("UPLOAD_FAILED",`HTTP ${c.status}`));return}let y=Wr(u,a.url_field);if(typeof y!="string"||!y){i(new g("UPLOAD_FAILED",`Response kh\xF4ng c\xF3 "${a.url_field}"`));return}r({url:y,response:u})}),c.onerror=()=>d(()=>i(new g("UPLOAD_FAILED","L\u1ED7i m\u1EA1ng khi upload"))),c.onabort=()=>d(()=>i(new g("CANCELLED","\u0110\xE3 hu\u1EF7 upload"))),c.send(l)}),Gn=e=>{var o,r;let t={...jn};for(let[i,a]of Object.entries((o=e==null?void 0:e.sources)!=null?o:{}))a?t[i]=a:delete t[i];let n={url:Kt};for(let[i,a]of Object.entries((r=e==null?void 0:e.targets)!=null?r:{}))i!=="url"&&a&&(n[i]=a);return{sources:t,targets:n}},Kn=e=>{let{sources:t,targets:n}=Gn(e),o=Object.keys(t),r=Object.fromEntries(o.filter(i=>t[i]===jn[i]&&qn[i]).map(i=>[i,qn[i]]));return{sources:o,file_types:r,targets:Object.keys(n),max_count:Jt}},_t=new Map,Yn=(e,t)=>`${e}:${t}`,jr=0,Xn=(e,t)=>{var n;typeof t=="string"&&((n=_t.get(Yn(e,t)))==null||n.abort())},$e=e=>{for(let[t,n]of _t)t.startsWith(`${e}:`)&&n.abort()},St=()=>new g("CANCELLED","\u0110\xE3 hu\u1EF7 upload"),Hr=(e,t)=>{var n;return{name:e,code:typeof(t==null?void 0:t.code)=="string"?t.code:"UPLOAD_FAILED",message:String((n=t==null?void 0:t.message)!=null?n:t)}},Qn=async(e,t)=>{var l;let{sources:n,targets:o}=Gn(t.config),r=n[e.source];if(!r)throw new g("NOT_SUPPORTED",`\u1EE8ng d\u1EE5ng ch\u01B0a h\u1ED7 tr\u1EE3 ngu\u1ED3n "${e.source}"`);let i=o[e.target.target];if(!i)throw new g("NOT_SUPPORTED",`\u1EE8ng d\u1EE5ng ch\u01B0a h\u1ED7 tr\u1EE3 \u0111\xEDch upload "${e.target.target}"`);let a=new AbortController,c=Yn(t.instance_id,(l=t.task_id)!=null?l:`auto-${++jr}`);_t.set(c,a);try{return await Jr(e,t,r,i,a.signal)}finally{_t.delete(c)}},Jr=async(e,{instance_id:t,app_id:n,getContext:o,task_id:r,config:i,emit:a,exclusivePick:c=u=>u()},l,s,d)=>{var E,m,T;let u={app_id:n!=null?n:"",instance_id:t,context:{...(E=o==null?void 0:o())!=null?E:{}}},y=(await c(()=>l({accept:e.accept,max_count:e.max_count,process:e.process,caller:u}))).slice(0,e.max_count);if(d.aborted)throw St();if(!y.length)throw new g("CANCELLED","Ng\u01B0\u1EDDi d\xF9ng kh\xF4ng ch\u1ECDn file");let p=[],f=y.filter(x=>kr(x,e.accept)?!0:(p.push({name:x.name,code:"INVALID_FILE",message:`Kh\xF4ng cho ph\xE9p \u0111\u1ECBnh d\u1EA1ng ${x.mime_type||Wn(x.name)}`}),!1)),O=f.map(()=>0),R=f.map(x=>{var V;return(V=x.size)!=null?V:0}),C=0,M=0,q=(x=!1)=>{if(!a||!r)return;let V=Date.now();if(!x&&V-M<200)return;M=V;let Ae=R.reduce((L,re)=>L+re,0),Y=O.reduce((L,re)=>L+re,0);a("upload.progress",{task_id:r,loaded:Y,total:Ae,percent:Ae?Math.min(100,Math.round(Y/Ae*100)):0,done_count:C,count:f.length})},W=[],oe=0,Pe=async()=>{var x,V,Ae;for(;oe<f.length;){let Y=oe++,L=f[Y];try{if(d.aborted)throw St();let re=L.mime_type.startsWith("image/")?"image":L.mime_type.startsWith("video/")?"video":void 0,G=re&&!L.processed?(V=(x=i==null?void 0:i.processors)==null?void 0:x[re])!=null?V:zr[re]:void 0;if(G&&(L=await G(L,e.process),R[Y]=(Ae=L.size)!=null?Ae:R[Y],d.aborted))throw St();if(e.max_size&&L.size&&L.size>e.max_size)throw new g("FILE_TOO_LARGE",`File ${L.size} byte v\u01B0\u1EE3t gi\u1EDBi h\u1EA1n ${e.max_size}`);let ee=(He,xe)=>{O[Y]=He,xe&&(R[Y]=xe),q()},ie=await s({file:L,target:e.target,onProgress:ee,signal:d,caller:u});if(typeof(ie==null?void 0:ie.url)!="string"||!ie.url)throw new g("UPLOAD_FAILED","Upload kh\xF4ng tr\u1EA3 url");let{url:ve,...Me}=ie;W[Y]={url:ve,name:L.name,mime_type:L.mime_type,size:L.size,width:L.width,height:L.height,duration:L.duration,...Object.keys(Me).length?{response:"response"in Me?Me.response:Me}:{}},O[Y]=R[Y]}catch(re){p.push(Hr(f[Y].name,re))}finally{C++,q(!0)}}};if(await Promise.all(Array.from({length:Math.min(e.concurrency,f.length)},Pe)),d.aborted)throw St();let ce=W.filter(x=>!!x);if(!ce.length){let x=p[0];throw new g((m=x==null?void 0:x.code)!=null?m:"UPLOAD_FAILED",(T=x==null?void 0:x.message)!=null?T:"Kh\xF4ng upload \u0111\u01B0\u1EE3c file n\xE0o")}return{files:ce,failed:p}};var vt=require("react"),Le=e=>{let t=e,n=new Set;return{getState:()=>t,setState:o=>{let r=typeof o=="function"?o(t):o;t={...t,...r},n.forEach(i=>i())},subscribe:o=>(n.add(o),()=>{n.delete(o)})}},H=(e,t,n=Object.is)=>{let o=(0,vt.useRef)(null),r=()=>{let i=e.getState(),a=o.current;if(a&&a.state===i&&a.selector===t)return a.value;let c=t(i),l=a&&n(a.value,c)?a.value:c;return o.current={state:i,selector:t,value:l},l};return(0,vt.useSyncExternalStore)(e.subscribe,r)};var me={info:"info",success:"success",error:"error"},Gr=200,Zn={info:2e3,success:2e3,error:3e3},at=Le({message:"",type:me.info,tick:0}),eo=e=>{let{message:t,type:n}=e!=null?e:{},o=String(t!=null?t:"").trim().slice(0,Gr);return o?{message:o,type:Object.values(me).includes(n)?n:me.info}:null},to=(e,t=me.info)=>{at.setState(n=>({message:e,type:t,tick:n.tick+1}))};var ye=require("react-native");var ze=require("react-native");var fe,Ge=new Map,no=(e,t)=>{var o;let n=(o=Ge.get(e))!=null?o:new Set;n.add(t),Ge.set(e,n)},oo=(e,t)=>{let n=Ge.get(e);n&&(t?n.delete(t):n.clear(),n.size===0&&Ge.delete(e))},Xt=new Map,ro=(e,t)=>{Xt.set(e,t)},io=e=>Xt.get(e),so=()=>ze.Platform.OS==="android"&&!!(fe!=null&&fe.requesting_permission),Kr=1500,Mt=()=>new Promise(e=>{if(ze.Platform.OS!=="android"||ze.AppState.currentState==="active"){e();return}let t=()=>{clearTimeout(n),o.remove(),e()},n=setTimeout(t,Kr),o=ze.AppState.addEventListener("change",r=>{r==="active"&&t()})}),Yt=e=>{var t;if(fe===e&&(fe=void 0,e.subscriptions.forEach(n=>n.remove()),e.started&&ze.Platform.OS==="ios"))try{(t=e.native)==null||t.setAudioSessionActiveIOS(!1,{notifyOthersOnDeactivation:!0})}catch{}},ao=async(e,t,n,o=()=>!0)=>{var i,a,c,l,s;if(fe)throw new g("BUSY","Micro \u0111ang \u0111\u01B0\u1EE3c mini app kh\xE1c s\u1EED d\u1EE5ng");if(!o())throw new g("CANCELLED","Mini app kh\xF4ng c\xF2n ho\u1EA1t \u0111\u1ED9ng");let r={owner:e,emit:n,cancelled:!1,started:!1,subscriptions:[]};fe=r;try{let d;try{d=await import("expo-speech-recognition")}catch{throw new g("NOT_SUPPORTED","Ch\u01B0a c\xF3 module nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i trong b\u1EA3n native")}let u=d.ExpoSpeechRecognitionModule;if(r.native=u,r.cancelled||!o())throw new g("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");r.requesting_permission=!0;let y;try{y=await u.requestPermissionsAsync()}finally{r.requesting_permission=!1}if(await Mt(),r.cancelled||!o())throw new g("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");if(!y.granted)throw new g("PERMISSION_DENIED","Ch\u01B0a c\u1EA5p quy\u1EC1n micro / nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i");if(await u.getStateAsync()!=="inactive")throw new g("BUSY","Nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i \u0111ang \u0111\u01B0\u1EE3c t\xEDnh n\u0103ng kh\xE1c s\u1EED d\u1EE5ng");if(r.cancelled||!o())throw new g("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");r.subscriptions.push(u.addListener("result",p=>{var f,O;fe!==r||r.cancelled||n(p.isFinal?"speech.final":"speech.partial",{...p,text:(O=(f=p.results[0])==null?void 0:f.transcript)!=null?O:""})}),u.addListener("error",p=>{fe===r&&!r.cancelled&&n("speech.error",{...p,code:p.error})}),u.addListener("end",()=>{fe===r&&(Yt(r),n("speech.end"))})),r.started=!0,u.start({lang:(i=t.lang)!=null?i:"vi-VN",continuous:(a=t.continuous)!=null?a:!0,interimResults:(c=t.interimResults)!=null?c:!0,addsPunctuation:(l=t.addsPunctuation)!=null?l:!0,requiresOnDeviceRecognition:(s=t.requiresOnDeviceRecognition)!=null?s:!1,iosCategory:{category:d.AVAudioSessionCategory.playAndRecord,categoryOptions:[d.AVAudioSessionCategoryOptions.defaultToSpeaker,d.AVAudioSessionCategoryOptions.allowBluetooth],mode:d.AVAudioSessionMode.measurement}})}catch(d){throw Yt(r),d}},co=e=>{let t=fe;if(!(!t||t.owner!==e)){if(!t.started){t.cancelled=!0;return}t.native.stop()}},Ce=e=>{Xt.delete(e);let t=Ge.get(e);Ge.delete(e),t==null||t.forEach(o=>{var r;try{(r=o.release)==null||r.call(o,e)}catch{}});let n=fe;if(!(!n||n.owner!==e||n.cancelled)&&(n.cancelled=!0,n.started))try{n.native.abort()}catch{Yt(n)}};var lo={qr:"qr",ean13:"ean-13",ean8:"ean-8",upcA:"upc-a",upcE:"upc-e",code128:"code-128",code39:"code-39",code93:"code-93",codabar:"codabar",itf:"itf",pdf417:"pdf-417",aztec:"aztec",dataMatrix:"data-matrix"},te={...lo,all:Object.values(lo)},Ke={scan:"scanner.scan",start:"scanner.start",stop:"scanner.stop"},Et={result:"scanner.result",end:"scanner.end"},We={user:"user",web:"web",closed:"closed",error:"error"},pe={top:"top",full:"full"},Fe={once:"once",continuous:"continuous"},Yr=1500,po=6e4,z,Q=Le({active:null,last_value:null,hit_tick:0,scan_count:0,notice:null,is_picking:!1}),go=()=>ye.Platform.OS==="android"&&!!(z!=null&&z.requesting_permission),Zt=e=>{let{types:t,cooldown_ms:n,hint:o,layout:r,absolute:i}=e!=null?e:{},a={};if(t!==void 0){if(!Array.isArray(t)||!t.length||!t.every(c=>te.all.includes(c)))throw new g("INVALID_PARAMS","types ph\u1EA3i l\xE0 m\u1EA3ng CodeType");a.types=t}if(n!==void 0){if(typeof n!="number"||!Number.isFinite(n)||n<0||n>po)throw new g("INVALID_PARAMS",`cooldown_ms ph\u1EA3i t\u1EEB 0 \u0111\u1EBFn ${po}`);a.cooldown_ms=n}if(o!==void 0){if(typeof o!="string"||!o.trim()||o.length>80)throw new g("INVALID_PARAMS","hint ph\u1EA3i c\xF3 1\u201380 k\xFD t\u1EF1");a.hint=o}if(r!==void 0){if(!Object.values(pe).includes(r))throw new g("INVALID_PARAMS","layout ph\u1EA3i l\xE0 ScannerLayout");a.layout=r}if(i!==void 0){if(typeof i!="boolean")throw new g("INVALID_PARAMS","absolute ph\u1EA3i l\xE0 boolean");a.absolute=i}return a},en=e=>z!==e?!1:(z=void 0,Q.setState({active:null,last_value:null,scan_count:0,notice:null,is_picking:!1}),!0),Xr=()=>ye.Alert.alert("Ch\u01B0a c\u1EA5p quy\u1EC1n camera","H\xE3y b\u1EADt quy\u1EC1n camera trong C\xE0i \u0111\u1EB7t \u0111\u1EC3 qu\xE9t m\xE3.",[{text:"Hu\u1EF7",style:"cancel"},{text:"M\u1EDF C\xE0i \u0111\u1EB7t",onPress:()=>{ye.Linking.openSettings().catch(()=>{})}}]),ho=async(e,t)=>{if(z)throw new g("BUSY","Camera qu\xE9t m\xE3 \u0111ang \u0111\u01B0\u1EE3c s\u1EED d\u1EE5ng");if(!t())throw new g("CANCELLED","Mini app kh\xF4ng c\xF2n ho\u1EA1t \u0111\u1ED9ng");z=e;let n=()=>{if(e.cancelled||!t())throw new g("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng")};try{let o;try{o=await import("react-native-vision-camera")}catch{throw new g("NOT_SUPPORTED","Ch\u01B0a c\xF3 module camera trong b\u1EA3n native")}n();let r=o.Camera.getCameraPermissionStatus();if(r!=="granted"){let a=ye.Platform.OS==="ios"&&r==="denied";e.requesting_permission=!0;let c;try{c=await o.Camera.requestCameraPermission()}finally{e.requesting_permission=!1}if(await Mt(),n(),c!=="granted")throw a&&Xr(),new g("PERMISSION_DENIED","Ch\u01B0a c\u1EA5p quy\u1EC1n camera")}if(!o.Camera.getAvailableCameraDevices().some(a=>a.position==="back"))throw new g("NOT_SUPPORTED","Thi\u1EBFt b\u1ECB kh\xF4ng c\xF3 camera sau");let i=await tn();n(),Q.setState({active:{owner:e.owner,mode:e.mode,types:e.types,layout:e.layout,absolute:e.absolute,hint:e.hint,vision:o,glass_view:i},last_value:null,scan_count:0,notice:null})}catch(o){throw en(e),o}},xt;import("react-native-safe-area-context").then(({initialWindowMetrics:e})=>{xt=e==null?void 0:e.insets}).catch(()=>{});var Ct=()=>{var e;return xt!=null?xt:{top:ye.Platform.OS==="ios"?54:(e=ye.StatusBar.currentHeight)!=null?e:0,bottom:ye.Platform.OS==="ios"?34:48}},tn=async()=>{if(ye.Platform.OS==="ios")try{let e=await import("expo-glass-effect");return e.isLiquidGlassAvailable()?e.GlassView:void 0}catch{return}},mo=(e,t,n)=>{var o,r,i,a;return{owner:e,mode:t,types:(o=n.types)!=null?o:te.all,cooldown_ms:(r=n.cooldown_ms)!=null?r:Yr,hint:n.hint,layout:t===Fe.once?pe.full:(i=n.layout)!=null?i:pe.top,absolute:t!==Fe.once&&((a=n.layout)!=null?a:pe.top)===pe.top&&n.absolute===!0,cancelled:!1,requesting_permission:!1,last_seen:new Map}},fo=(e,t,n=()=>!0,o)=>new Promise((r,i)=>{let a=mo(e,Fe.once,t);a.onHit=o,a.resolve=r,a.reject=i,ho(a,n).catch(i)}),yo=(e,t,n,o=()=>!0,r)=>{let i=mo(e,Fe.continuous,t);return i.emit=n,i.onHit=r,ho(i,o)},Pt=(e,t,n)=>{var o,r;if(!Q.getState().active){e.cancelled=!0;return}if(en(e)){if(e.mode===Fe.once){(o=e.reject)==null||o.call(e,t===We.error?new g("HOST_ERROR",n!=null?n:"L\u1ED7i camera"):new g("CANCELLED","\u0110\xE3 \u0111\xF3ng camera qu\xE9t m\xE3"));return}(r=e.emit)==null||r.call(e,Et.end,n?{reason:t,message:n}:{reason:t})}},wo=e=>{(z==null?void 0:z.owner)===e&&Pt(z,We.web)},De=e=>{(z==null?void 0:z.owner)===e&&Pt(z,We.closed)},nn=()=>{z&&Pt(z,We.user)},bo=e=>{z&&Pt(z,We.error,e)},on=(e,t=Date.now(),n=!1)=>{var r,i,a;let o=z;if(!(!o||!Q.getState().active))for(let{value:c,type:l}of e){if(!c)continue;let s=o.last_seen.get(c);if(o.last_seen.set(c,t),!(!n&&s!==void 0&&t-s<o.cooldown_ms)){if((r=o.onHit)==null||r.call(o),o.mode===Fe.once){en(o),(i=o.resolve)==null||i.call(o,{value:c,type:l});return}Q.setState(d=>({last_value:c,hit_tick:d.hit_tick+1,scan_count:d.scan_count+1,notice:null})),(a=o.emit)==null||a.call(o,Et.result,{value:c,type:l})}}},Qr={1:te.code128,2:te.code39,4:te.code93,8:te.codabar,16:te.dataMatrix,32:te.ean13,64:te.ean8,128:te.itf,256:te.qr,512:te.upcA,1024:te.upcE,2048:te.pdf417,4096:te.aztec},Zr=2500,uo=2e3,Qt=e=>{Q.setState({notice:e}),setTimeout(()=>{Q.getState().notice===e&&Q.setState({notice:null})},Zr)},Ao=async()=>{var t,n;let e=z;if(!(!e||Q.getState().is_picking)){e.requesting_permission=!0,Q.setState({is_picking:!0,notice:null});try{let{launchImageLibrary:o}=await import("react-native-image-picker"),r=await o({mediaType:"photo",selectionLimit:1,maxWidth:uo,maxHeight:uo}),i=(n=(t=r.assets)==null?void 0:t[0])==null?void 0:n.uri;if(r.didCancel||z!==e)return;if(r.errorCode||!i){Qt("Kh\xF4ng m\u1EDF \u0111\u01B0\u1EE3c \u1EA3nh");return}let{default:a}=await import("@react-native-ml-kit/barcode-scanning"),c=await a.scan(i);if(z!==e)return;let l=c.map(({value:s,format:d})=>({value:s,code_type:Qr[d]})).filter(({code_type:s})=>!s||e.types.includes(s)).map(({value:s,code_type:d})=>({value:s,type:d!=null?d:"unknown"}));if(!l.length){Qt("Kh\xF4ng t\xECm th\u1EA5y m\xE3 trong \u1EA3nh");return}on(l,Date.now(),!0)}catch{z===e&&Qt("Kh\xF4ng \u0111\u1ECDc \u0111\u01B0\u1EE3c m\xE3 t\u1EEB \u1EA3nh")}finally{await Mt(),e.requesting_permission=!1,z===e&&Q.setState({is_picking:!1})}}};var Tt=1,g=class extends Error{constructor(n,o){super(o);this.code=n}},So=e=>{try{let t=JSON.parse(e);return(t==null?void 0:t.__retion)===Tt&&typeof t.method=="string"?t:null}catch{return null}},pt=e=>`window.__RETION_MINIAPP__ && window.__RETION_MINIAPP__.receive(${JSON.stringify(e)}); true;`,_o=(e,t)=>pt({id:e,result:t}),vo=(e,t)=>pt({id:e,error:{code:t.code,message:t.message}}),Mo=(e,t)=>pt({event:e,data:t}),sn=e=>pt({event:"context",data:e});var xo=()=>`(function () {
2
2
  var post = function (level, args) {
3
3
  try {
4
4
  var parts = [];
@@ -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;`,So=()=>`(function () {
22
+ })(); true;`,Eo=()=>`(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; }
@@ -38,7 +38,7 @@
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;`,Ao=()=>`(function () {
41
+ })(); true;`,Co=()=>`(function () {
42
42
  if (window.__retionSafeAreaFrozen) { return; }
43
43
  window.__retionSafeAreaFrozen = true;
44
44
  var max = {};
@@ -59,14 +59,14 @@
59
59
  },
60
60
  });
61
61
  };
62
- })(); true;`,vo=e=>ct({event:e}),Mo=(e,t)=>{let n=xo(t);return`try { history.replaceState(history.state, '', location.pathname + ${JSON.stringify(n?`?${n}`:"")} + location.hash); } catch (e) {}
63
- ${rn(e)}`},xo=e=>Object.entries(e).filter(([,t])=>t!=null&&t!=="").map(([t,n])=>`${encodeURIComponent(t)}=${encodeURIComponent(String(n))}`).join("&"),Eo=(e,t={})=>{let n=xo(t);return`window.__RETION_MINIAPP_HOST__ = { protocol: ${Tt} };
62
+ })(); true;`,Po=e=>pt({event:e}),Ro=(e,t)=>{let n=To(t);return`try { history.replaceState(history.state, '', location.pathname + ${JSON.stringify(n?`?${n}`:"")} + location.hash); } catch (e) {}
63
+ ${sn(e)}`},To=e=>Object.entries(e).filter(([,t])=>t!=null&&t!=="").map(([t,n])=>`${encodeURIComponent(t)}=${encodeURIComponent(String(n))}`).join("&"),Oo=(e,t={})=>{let n=To(t);return`window.__RETION_MINIAPP_HOST__ = { protocol: ${Tt} };
64
64
  window.__RETION_MINIAPP_CONTEXT__ = ${JSON.stringify(e)};
65
65
  ${n?`try { history.replaceState(history.state, '', location.pathname + '?' + ${JSON.stringify(n)} + location.hash); } catch (e) {}`:""}
66
- true;`},Ro={partner:"partner_token",chatbox:"chatbox_token"},Po=(e,t)=>{let n={...e};for(let o of Object.values(Ro))t.includes(o)||delete n[o];return n},on=new Set,st=async(e,t)=>{if(on.has(e))throw new g("BUSY",`${e} \u0111ang ch\u1EA1y \u2014 ch\u1EDD l\u01B0\u1EE3t tr\u01B0\u1EDBc xong`);on.add(e);try{return await t()}finally{on.delete(e)}},sn=e=>`(function () {
66
+ true;`},ko={partner:"partner_token",chatbox:"chatbox_token"},Io=(e,t)=>{let n={...e};for(let o of Object.values(ko))t.includes(o)||delete n[o];return n},rn=new Set,ct=async(e,t)=>{if(rn.has(e))throw new g("BUSY",`${e} \u0111ang ch\u1EA1y \u2014 ch\u1EDD l\u01B0\u1EE3t tr\u01B0\u1EDBc xong`);rn.add(e);try{return await t()}finally{rn.delete(e)}},an=e=>`(function () {
67
67
  window.__retionScannerHeight = ${Math.max(0,Math.round(e))};
68
68
  window.dispatchEvent(new Event('retionscannerheight'));
69
- })(); true;`,To=()=>`(function () {
69
+ })(); true;`,Lo=()=>`(function () {
70
70
  try {
71
71
  var AudioCtx = window.AudioContext || window.webkitAudioContext;
72
72
  if (!AudioCtx) { return; }
@@ -85,4 +85,4 @@
85
85
  // iOS c\xF3 th\u1EC3 \u0111\u1EC3 context \u1EDF suspended / interrupted (vd. khi camera m\u1EDF phi\xEAn quay): ch\u1EA1y l\u1EA1i xong m\u1EDBi ph\xE1t.
86
86
  if (ctx.state === 'running') { play(); } else { ctx.resume().then(play).catch(function () {}); }
87
87
  } catch (e) {}
88
- })(); true;`,Hr=new Set(["selection","impactLight","impactMedium","impactHeavy","rigid","soft","notificationSuccess","notificationWarning","notificationError"]),Pt=(e,t)=>{if(typeof e!="string"||!e)throw new g("INVALID_PARAMS",`Thi\u1EBFu ${t}`);return e},Co=async({method:e,params:t},{getHostData:n,getPermissions:o,getContext:r,is_dark:i,close:a,app_id:c,instance_id:l,options:s,emit:d,isActive:u,playBeep:y})=>{var R,M,V,W,oe,Pe,ce,E;let p=s==null?void 0:s.handlers,w={app_id:c,instance_id:l,close:a},F=()=>{var h;(h=s==null?void 0:s.haptic)==null||h.call(s,"impactLight"),y==null||y()},T=()=>new g("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF \u1EE9ng d\u1EE5ng n\xE0y`);switch(e){case"getCurrentLocation":{let h=Tn(t);return st(e,()=>Cn(h,u))}case"speech.start":{if(!d)throw T();let h={};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 g("INVALID_PARAMS","lang ph\u1EA3i l\xE0 m\xE3 ng\xF4n ng\u1EEF nh\u01B0 vi-VN");h.lang=t.lang}for(let D of["continuous","interimResults","addsPunctuation","requiresOnDeviceRecognition"])if((t==null?void 0:t[D])!==void 0){if(typeof t[D]!="boolean")throw new g("INVALID_PARAMS",`${D} ph\u1EA3i l\xE0 boolean`);h[D]=t[D]}if((t==null?void 0:t.mode)!==void 0&&t.mode!=="s2t"&&t.mode!=="voice")throw new g("INVALID_PARAMS","mode ph\u1EA3i l\xE0 's2t' ho\u1EB7c 'voice'");let C=(t==null?void 0:t.mode)==="s2t"?"s2t":"voice",x=C==="voice"?(R=s==null?void 0:s.voice)!=null?R:s==null?void 0:s.speech:void 0;if(Qn(l,x),x){Xn(l,x);try{return await x.start({owner:l,app_id:c,mode:C,options:h,emit:d,isActive:u!=null?u:(()=>!0)})}catch(D){throw Zn(l,x),D}}return no(l,h,d,u)}case"speech.stop":{let h=eo(l);return h?h.stop(l):oo(l)}case Je.scan:return po(l,Zt(t),u,F);case Je.start:{if(!d)throw T();return uo(l,Zt(t),d,u,F)}case Je.stop:return go(l);case"uploadFiles":{let{task_id:h,...C}=t!=null?t:{};if(h!==void 0&&(typeof h!="string"||!h))throw new g("INVALID_PARAMS","task_id ph\u1EA3i l\xE0 chu\u1ED7i");return Jn(Un(C),{instance_id:l,app_id:c,getContext:r,task_id:h,config:s==null?void 0:s.upload,emit:d,exclusivePick:x=>st("uploadFiles.pick",x)})}case"uploadFiles.cancel":Hn(l,t==null?void 0:t.task_id);return;case"getUploadCapabilities":return Wn(s==null?void 0:s.upload);case"getBiometricAvailability":return((M=s==null?void 0:s.biometrics)!=null?M:await jt()).getAvailability();case"authenticateBiometric":{let h=Pt(t==null?void 0:t.reason,"reason").trim();if(!h||h.length>200)throw new g("INVALID_PARAMS","reason must contain 1\u2013200 characters");let C=t==null?void 0:t.cancelButtonText;if(C!==void 0&&(typeof C!="string"||!C.trim()||C.length>80))throw new g("INVALID_PARAMS","Invalid cancelButtonText");return st(e,async()=>{var D;return((D=s==null?void 0:s.biometrics)!=null?D:await jt()).authenticate({reason:h,cancelButtonText:C})})}case"requestPayment":{let h=p==null?void 0:p.requestPayment;if(!h)throw T();let C=t==null?void 0:t.amount;if(typeof C!="number"||!Number.isFinite(C)||C<=0)throw new g("INVALID_PARAMS","amount ph\u1EA3i l\xE0 s\u1ED1 > 0");let x={...t,amount:C,currency:Pt(t==null?void 0:t.currency,"currency")};return st(e,()=>h(x,w))}case"printImage":{let h=p==null?void 0:p.printImage;if(!h)throw T();let C=Pt(t==null?void 0:t.image,"image");await st(e,()=>h({image:C},w));return}case"openScreen":if(!(p!=null&&p.openScreen))throw T();await p.openScreen({screen:Pt(t==null?void 0:t.screen,"screen"),params:t==null?void 0:t.params},w);return;case"closeApp":a();return;case"openWebview":{let h=String((V=t==null?void 0:t.url)!=null?V:"");if(!/^https?:\/\//i.test(h))throw new g("INVALID_PARAMS","url ph\u1EA3i l\xE0 http(s)");await(s!=null&&s.openUrl?s.openUrl(h):at.Linking.openURL(h));return}case"openLink":{let h=String((W=t==null?void 0:t.url)!=null?W:"").trim();if(!/^[a-z][a-z0-9+.-]*:/i.test(h)||/^(javascript|file|data|about|blob):/i.test(h))throw new g("INVALID_PARAMS","url kh\xF4ng h\u1EE3p l\u1EC7");try{await(s!=null&&s.openUrl?s.openUrl(h):at.Linking.openURL(h))}catch(C){throw new g("NOT_SUPPORTED",String((Pe=(oe=C==null?void 0:C.message)!=null?oe:C)!=null?Pe:"Kh\xF4ng m\u1EDF \u0111\u01B0\u1EE3c link"))}return}case"showToast":{let h=Kn(t);if(!h||(u==null?void 0:u())===!1)return;s!=null&&s.showToast?s.showToast(h.message,{type:h.type}):Yn(h.message,h.type);return}case"haptic":{let h=Hr.has(t==null?void 0:t.type)?t.type:"selection";(ce=s==null?void 0:s.haptic)==null||ce.call(s,h);return}case"getSystemInfo":return{platform:at.Platform.OS==="ios"?"ios":"android",appVersion:(E=s==null?void 0:s.app_version)!=null?E:"",theme:i?"dark":"light"};case"getAccessToken":{let h=n().access_token;if(!h)throw new g("HOST_ERROR","Mini app ch\u01B0a c\xF3 token cho page n\xE0y");return h}case"getToken":{let h=t==null?void 0:t.type;if(h==="access"){let D=n().access_token;if(!D)throw new g("HOST_ERROR","Mini app ch\u01B0a c\xF3 token cho page n\xE0y");return D}if(h!=="partner"&&h!=="chatbox")throw new g("HOST_ERROR",`Lo\u1EA1i token kh\xF4ng h\u1EE3p l\u1EC7: ${String(h)}`);let C=Ro[h];if(!o().includes(C))throw new g("PERMISSION_DENIED",`Mini app ch\u01B0a \u0111\u01B0\u1EE3c c\u1EA5p quy\u1EC1n ${C} (Console \u2192 Quy\u1EC1n l\u1EA5y token)`);let x=h==="partner"?n().partner_token:n().chatbox_token;if(!x)throw new g("HOST_ERROR",`Kh\xF4ng c\xF3 ${C}`);return x}case"getUserInfo":{let h=n().user;if(!h)throw new g("HOST_ERROR","Kh\xF4ng l\u1EA5y \u0111\u01B0\u1EE3c th\xF4ng tin nh\xE2n vi\xEAn");return h}case"getPageInfo":{let h=n().page;if(!h)throw new g("HOST_ERROR","Kh\xF4ng l\u1EA5y \u0111\u01B0\u1EE3c th\xF4ng tin page");return h}case"sendMessage":case"insertText":throw new g("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF phi\xEAn b\u1EA3n app n\xE0y`);default:throw new g("NOT_SUPPORTED",`API kh\xF4ng t\u1ED3n t\u1EA1i: ${e}`)}};var cn=e=>`bundle:${e}`,ln=()=>`${z().file_system.document_dir}/miniapps`,pn=ln,un=(e,t,n="index.html",o=!1,r=[])=>{let i=`${pn()}/${e}/${t}`;return{app_id:e,version:t,dir:i,entry_uri:`file://${i}/${n}`,context_update:o,permissions:r}},an=e=>{var t;z().storage.setString(cn(e.app_id),JSON.stringify({version:e.version,entry:e.entry,context_update:!!e.context_update,permissions:(t=e.permissions)!=null?t:[]}))},Jr=(e,t)=>/^https?:\/\//.test(t)?t:`${e.replace(/[^/]*$/,"")}${t}`,$=e=>{let t=z().storage.getString(cn(e));if(!t)return null;try{let{version:n,entry:o,context_update:r,permissions:i}=JSON.parse(t);return un(e,n,o,!!r,Array.isArray(i)?i:[])}catch{return null}},Ce=e=>z().file_system.exists(e.entry_uri.replace("file://","")),dn=async e=>{let t=$(e.app_id);return(t==null?void 0:t.version)===e.version&&await Ce(t)},ko=async(e,t)=>{let n=z().file_system,o=`${pn()}/${e}`,r=await n.listDir(o).catch(()=>[]);await Promise.all(r.filter(i=>!t.includes(i)).map(i=>n.remove(`${o}/${i}`).catch(()=>{})))},Io=async e=>{var t;await((t=pt[e])==null?void 0:t.catch(()=>{})),z().storage.setString(cn(e),""),await z().file_system.remove(`${pn()}/${e}`).catch(()=>{})},Ge=class extends Error{constructor(){super("cancelled"),this.name="MiniAppInstallCancelled"}},pt={},Lo=(e,t)=>{var i;let o=((i=pt[e])!=null?i:Promise.resolve()).catch(()=>{}).then(t),r=o.catch(()=>{});return pt[e]=r,r.then(()=>{pt[e]===r&&delete pt[e]}),o},Gr=(e,t)=>{var r,i;let n=e.split(".").map(a=>parseInt(a,10)||0),o=t.split(".").map(a=>parseInt(a,10)||0);for(let a=0;a<Math.max(n.length,o.length);a++){let c=((r=n[a])!=null?r:0)-((i=o[a])!=null?i:0);if(c)return c}return 0},Fo=({manifest:e,zip_path:t})=>Lo(e.app_id,async()=>{var i;let n=z().file_system,o=$(e.app_id);if(o&&Gr(o.version,e.version)>=0&&await Ce(o))return o;if(e.sha256&&n.sha256&&await n.sha256(t)!==e.sha256)throw new Error("sha256 mismatch");let r=un(e.app_id,e.version,e.entry,!!e.context_update,(i=e.permissions)!=null?i:[]);return await n.remove(r.dir).catch(()=>{}),await n.mkdir(r.dir),await n.unzip(t,r.dir),an(e),me("\u0111\xE3 c\xE0i b\u1EA3n \u0111\xF3ng s\u1EB5n",e.app_id,e.version),ko(e.app_id,[e.version,o==null?void 0:o.version].filter(Boolean)),r}),gn=(e,{base_url:t,onProgress:n}={})=>{let o=z().file_system,r=null,i=!1,a=`${o.cache_dir}/${e.app_id}-${e.version}.zip`,c=()=>{if(i)throw new Ge},l=async()=>{var u;c();let s=$(e.app_id);if((s==null?void 0:s.version)===e.version&&await o.exists(s.dir))return an(e),$(e.app_id);c();let d=o.download({url:t?Jr(t,e.bundle_url):e.bundle_url,to_file:a,onProgress:(y,p)=>{var F;let w=p>0?p:(F=e.size)!=null?F:0;w>0&&(n==null||n(Math.min(1,y/w)))}});r=d;try{let{status:y}=await d.promise;if(c(),y!==200)throw new Error(`bundle ${y}`);if(e.sha256)if(o.sha256){if(await o.sha256(a)!==e.sha256)throw new Error("sha256 mismatch")}else me("b\u1ECF qua ki\u1EC3m tra sha256 (file_system kh\xF4ng c\xF3 sha256)",e.app_id);c();let p=un(e.app_id,e.version,e.entry,!!e.context_update,(u=e.permissions)!=null?u:[]);return await o.remove(p.dir).catch(()=>{}),await o.mkdir(p.dir),await o.unzip(a,p.dir),an(e),ko(e.app_id,[e.version,s==null?void 0:s.version].filter(Boolean)),p}catch(y){throw i?new Ge:y}finally{r=null,o.remove(a).catch(()=>{})}};return{promise:Lo(e.app_id,l),cancel:()=>{i=!0,r==null||r.cancel()}}},lt={},Kr=__DEV__?0:60*1e3,Oo={},Do=(e,t)=>{var o,r;let n=$(e);return n&&Date.now()-((o=Oo[t])!=null?o:0)<Kr?Promise.resolve(n):((r=lt[e])!=null||(lt[e]=(async()=>{let i=await fetch(t,{headers:{"Cache-Control":"no-cache"}});if(!i.ok)throw new Error(`manifest ${i.status}`);let a=await i.json(),c=await gn(a,{base_url:t}).promise;return Oo[t]=Date.now(),c})().catch(i=>(console.warn("[miniapp] sync failed",e,i==null?void 0:i.message),$(e))).finally(()=>{lt[e]=void 0})),lt[e])};var Ct=new Map,No=(e,t)=>(Ct.set(e,t),()=>{Ct.get(e)===t&&Ct.delete(e)}),Uo=(e,t)=>{let n=Ct.get(e);return n?n(t):!1};var N=require("react"),f=require("react-native");var v=require("react/jsx-runtime"),ut="#22C55E",Yr="\u0110\u01B0a m\xE3 v\xE0o khung \u0111\u1EC3 qu\xE9t",Xr=2,kt=18,Zr=1600,dt=14,Qr=2e3,qo=.38,ei=40,Vo=2,ti=8,ni=2e3,oi=250,Ke=2e3,ri=[{top:0,left:0,borderTopWidth:4,borderLeftWidth:4,borderTopLeftRadius:dt},{top:0,right:0,borderTopWidth:4,borderRightWidth:4,borderTopRightRadius:dt},{bottom:0,left:0,borderBottomWidth:4,borderLeftWidth:4,borderBottomLeftRadius:dt},{bottom:0,right:0,borderBottomWidth:4,borderRightWidth:4,borderBottomRightRadius:dt}],Bo=({color:e})=>(0,v.jsx)(v.Fragment,{children:ri.map((t,n)=>(0,v.jsx)(f.View,{style:[A.corner,t,{borderColor:e}]},n))}),Ot=({style:e,children:t,...n})=>{let o=(0,N.useRef)(new f.Animated.Value(1)).current,r=i=>f.Animated.spring(o,{toValue:i,speed:40,bounciness:8,useNativeDriver:!0}).start();return(0,v.jsx)(f.Pressable,{...n,onPressIn:()=>r(.88),onPressOut:()=>r(1),children:(0,v.jsx)(f.Animated.View,{style:[e,{transform:[{scale:o}]}],children:t})})},hn=({scanner:e,closing:t=!1,onClosed:n,onHeight:o})=>{var m,b;let{vision:r,types:i,mode:a,layout:c,hint:l,glass_view:s,absolute:d}=e,u=c===pe.top,y=(0,N.useRef)(new f.Animated.Value(0)).current,p=r.useCameraDevice("back"),w=(0,N.useRef)(new f.Animated.Value(1)).current,[F,T]=(0,N.useState)(!1),[R,M]=(0,N.useState)(1),V=(0,N.useRef)(null),[W,oe]=(0,N.useState)(()=>{let{width:_,height:B}=f.Dimensions.get("window");return{width:_,height:u?B*qo:B,window_y:0}}),Pe=H(Z,_=>_.last_value),ce=H(Z,_=>_.hit_tick),E=H(Z,_=>_.scan_count),h=H(Z,_=>_.notice),C=H(Z,_=>_.is_picking),x=(0,N.useRef)(null),D=Et(),_e=D.top,Y=(0,N.useRef)(new f.Animated.Value(0)).current,I=(0,N.useRef)(new f.Animated.Value(0)).current,re=(0,N.useRef)(new f.Animated.Value(0)).current,G=(0,N.useRef)(n);G.current=n,(0,N.useEffect)(()=>{if(!t)return;y.setValue(W.height);let _=f.Animated.timing(y,{toValue:0,duration:oi,easing:f.Easing.out(f.Easing.cubic),useNativeDriver:!1});return _.start(({finished:B})=>{var se;B&&((se=G.current)==null||se.call(G))}),()=>_.stop()},[t,y]);let ee=Math.round(W.width*(u?.8:.78)),ie=Math.round(u?W.height*.46:ee*.78),ve=Math.round((W.height-ie)/2),Me=Math.round((W.width-ee)/2),je=r.useCodeScanner({codeTypes:i,onCodeScanned:(0,N.useCallback)(_=>nn(_),[])});(0,N.useEffect)(()=>{let _=f.BackHandler.addEventListener("hardwareBackPress",()=>(tn(),!0));return()=>_.remove()},[]);let xe=(0,N.useRef)(ce);(0,N.useEffect)(()=>{if(ce===xe.current)return;Y.setValue(1),re.setValue(1);let _=f.Animated.parallel([f.Animated.timing(Y,{toValue:0,duration:450,useNativeDriver:!0}),f.Animated.sequence([f.Animated.delay(Qr),f.Animated.timing(re,{toValue:0,duration:250,useNativeDriver:!0})])]);return _.start(),()=>_.stop()},[ce,Y,re]),(0,N.useEffect)(()=>{let _=se=>f.Animated.timing(I,{toValue:se,duration:Zr,easing:f.Easing.inOut(f.Easing.quad),useNativeDriver:!0}),B=f.Animated.loop(f.Animated.sequence([_(1),_(0)]));return B.start(),()=>B.stop()},[I]);let Te=(0,N.useCallback)(()=>{f.Animated.timing(w,{toValue:0,duration:220,useNativeDriver:!0}).start()},[w]);(0,N.useEffect)(()=>{let _=setTimeout(Te,ni);return()=>clearTimeout(_)},[Te]);let[Ze,qt]=(0,N.useState)(!1);(0,N.useEffect)(()=>{let _=requestAnimationFrame(()=>{_=requestAnimationFrame(()=>qt(!0))});return()=>cancelAnimationFrame(_)},[]);let Ve=!!(p!=null&&p.hasTorch),Qe=(m=p==null?void 0:p.neutralZoom)!=null?m:1,et=p?Math.min(p.maxZoom/Qe,ti):1,$t=Qe*Math.min(R,et),ht=_=>{var ae;let{touches:B}=_.nativeEvent;if(B.length!==2){V.current=null;return}let se=Math.hypot(B[0].pageX-B[1].pageX,B[0].pageY-B[1].pageY);(ae=V.current)!=null||(V.current={distance:se,level:R}),M(Math.max(1,Math.min(et,V.current.level*(se/V.current.distance))))},ft=(0,v.jsx)(f.Text,{style:[A.hint,!!h&&A.hint_notice],numberOfLines:1,children:(b=h!=null?h:l)!=null?b:Yr});return(0,v.jsx)(f.Animated.View,{ref:x,onTouchMove:ht,onTouchEnd:()=>{V.current=null},pointerEvents:t?"none":"auto",style:u?[A.top,d&&A.top_absolute,t&&{height:y}]:A.full,onLayout:({nativeEvent:{layout:_}})=>{var B;t||(o==null||o(_.height),(B=x.current)==null||B.measureInWindow((se,ae)=>{oe({width:_.width,height:_.height,window_y:ae||0})}))},children:(0,v.jsxs)(f.View,{style:t?[A.content_closing,{height:W.height}]:A.content,children:[p&&Ze&&(0,v.jsx)(r.Camera,{style:f.StyleSheet.absoluteFill,device:p,isActive:!C,codeScanner:je,torch:F&&Ve?"on":"off",zoom:$t,onPreviewStarted:Te,onError:_=>mo(_.message)}),(0,v.jsx)(f.Animated.View,{style:[A.preview_cover,{opacity:w}],pointerEvents:"none"}),W.height>0&&(0,v.jsxs)(f.View,{style:A.overlay,pointerEvents:"none",children:[(0,v.jsx)(f.View,{style:[A.dim_ring,{top:ve-Ke,left:Me-Ke,width:ee+Ke*2,height:ie+Ke*2}]}),(0,v.jsxs)(f.View,{style:{position:"absolute",top:ve,left:Me,width:ee,height:ie},children:[(0,v.jsx)(Bo,{color:"#FFFFFF"}),(0,v.jsx)(f.Animated.View,{style:[f.StyleSheet.absoluteFill,{opacity:Y}],children:(0,v.jsx)(Bo,{color:ut})}),(0,v.jsxs)(f.Animated.View,{style:[A.scan_line_wrap,{transform:[{translateY:I.interpolate({inputRange:[0,1],outputRange:[0,Math.max(0,ie-kt)]})}]}],children:[(0,v.jsx)(f.View,{style:A.scan_glow_outer}),(0,v.jsx)(f.View,{style:A.scan_glow_inner}),(0,v.jsx)(f.View,{style:A.scan_line})]})]}),(0,v.jsx)(f.View,{style:[A.hint_slot,u?{top:0,height:ve-6,justifyContent:"flex-end"}:{top:ve+ie+20}],children:ft}),a===Le.continuous&&!!Pe&&(0,v.jsx)(f.Animated.View,{style:[A.result_slot,{top:u?ve+ie-ei:ve+ie+52},{opacity:re}],children:(0,v.jsxs)(f.View,{style:A.result,children:[(0,v.jsx)(f.View,{style:A.check_badge,children:(0,v.jsx)(f.View,{style:A.check_mark})}),(0,v.jsx)(f.Text,{style:A.result_text,numberOfLines:1,children:Pe}),(0,v.jsxs)(f.Text,{style:A.result_count,children:["\xB7 ",E," m\xE3"]})]})})]}),W.height>0&&(0,v.jsx)(f.View,{style:[A.close_slot,u?A.close_slot_top:{top:Math.max(12,_e-W.window_y+12)}],children:(0,v.jsxs)(Ot,{style:[A.close_button,!!s&&A.glass_surface],onPress:tn,hitSlop:8,accessibilityRole:"button",accessibilityLabel:"\u0110\xF3ng",children:[s&&(0,v.jsx)(s,{style:A.glass_fill,glassEffectStyle:"regular",colorScheme:"dark",tintColor:"rgba(24,24,27,0.35)",isInteractive:!0}),(0,v.jsx)(f.View,{style:[A.close_bar,A.close_bar_a]}),(0,v.jsx)(f.View,{style:[A.close_bar,A.close_bar_b]})]})}),(0,v.jsx)(f.View,{style:[A.toolbar_wrap,!u&&{bottom:D.bottom+20}],pointerEvents:"box-none",children:(0,v.jsxs)(f.View,{style:[A.toolbar,!!s&&A.glass_surface],children:[s&&(0,v.jsx)(s,{style:A.glass_fill,glassEffectStyle:"regular",colorScheme:"dark",tintColor:"rgba(24,24,27,0.35)",isInteractive:!0}),(0,v.jsx)(Ot,{style:A.tool,onPress:ho,disabled:C,accessibilityRole:"button",accessibilityLabel:"Qu\xE9t t\u1EEB \u1EA3nh",children:(0,v.jsxs)(f.View,{style:A.image_icon,children:[(0,v.jsx)(f.View,{style:A.image_icon_dot}),(0,v.jsx)(f.View,{style:A.image_icon_hill})]})}),!!p&&et>=Vo&&(0,v.jsx)(Ot,{style:[A.tool,R>1&&A.tool_on],onPress:()=>M(_=>_>1?1:Vo),accessibilityRole:"button",accessibilityLabel:"Ph\xF3ng to",children:(0,v.jsxs)(f.Text,{style:[A.zoom_text,R>1&&A.zoom_text_on],children:[Math.round(R*10)/10,"x"]})}),Ve&&(0,v.jsx)(Ot,{style:[A.tool,F&&A.tool_on],onPress:()=>T(_=>!_),accessibilityRole:"button",accessibilityLabel:"\u0110\xE8n pin",accessibilityState:{selected:F},children:(0,v.jsx)(f.Text,{style:[A.torch_icon,F&&A.zoom_text_on],children:"\u26A1\uFE0E"})})]})})]})})},ii="rgba(0,0,0,0.5)",mn=50,A=f.StyleSheet.create({top:{height:`${qo*100}%`,overflow:"hidden",backgroundColor:"#000000"},full:{position:"absolute",top:0,left:0,right:0,bottom:0},content:{flex:1,backgroundColor:"#000000"},top_absolute:{position:"absolute",top:0,left:0,right:0,zIndex:1},content_closing:{position:"absolute",left:0,right:0,bottom:0,backgroundColor:"#000000"},preview_cover:{position:"absolute",top:0,left:0,right:0,bottom:0,backgroundColor:"#000000"},overlay:{position:"absolute",top:0,left:0,right:0,bottom:0,overflow:"hidden"},dim_ring:{position:"absolute",borderWidth:Ke,borderColor:ii,borderRadius:Ke+dt},hint_slot:{position:"absolute",left:16,right:16,alignItems:"center"},hint:{color:"#FFFFFF",fontSize:14,fontWeight:"500"},hint_notice:{color:"#FCA5A5"},corner:{position:"absolute",width:28,height:28},scan_line_wrap:{position:"absolute",top:0,left:10,right:10,height:kt,alignItems:"stretch",justifyContent:"center"},scan_glow_outer:{position:"absolute",left:0,right:0,height:kt,borderRadius:kt/2,backgroundColor:ut,opacity:.1},scan_glow_inner:{position:"absolute",left:4,right:4,height:8,borderRadius:4,backgroundColor:ut,opacity:.2},scan_line:{height:Xr,borderRadius:1,backgroundColor:ut},glass_surface:{backgroundColor:"transparent",overflow:"visible"},glass_fill:{position:"absolute",top:0,left:0,right:0,bottom:0,borderRadius:999},close_slot:{position:"absolute",right:12},close_slot_top:{bottom:15},close_button:{width:48,height:48,borderRadius:24,overflow:"hidden",alignItems:"center",justifyContent:"center",backgroundColor:"rgba(0,0,0,0.5)"},close_bar:{position:"absolute",width:20,height:2,borderRadius:1,backgroundColor:"#FFFFFF"},close_bar_a:{transform:[{rotate:"45deg"}]},close_bar_b:{transform:[{rotate:"-45deg"}]},toolbar_wrap:{position:"absolute",left:0,right:0,bottom:10,alignItems:"center"},toolbar:{flexDirection:"row",alignItems:"center",gap:4,padding:4,borderRadius:999,backgroundColor:"rgba(24,24,27,0.72)"},tool:{width:mn,height:mn,borderRadius:mn/2,alignItems:"center",justifyContent:"center"},tool_on:{backgroundColor:"#FFFFFF"},zoom_text:{color:"#FFFFFF",fontSize:16,fontWeight:"600"},zoom_text_on:{color:"#18181B"},torch_icon:{color:"#FFFFFF",fontSize:22,fontWeight:"600"},image_icon:{width:24,height:19,borderRadius:3,borderWidth:1.5,borderColor:"#FFFFFF",overflow:"hidden"},image_icon_dot:{position:"absolute",top:3,right:3,width:4,height:4,borderRadius:2,backgroundColor:"#FFFFFF"},image_icon_hill:{position:"absolute",left:2,bottom:-6,width:12,height:12,backgroundColor:"#FFFFFF",transform:[{rotate:"45deg"}]},result_slot:{position:"absolute",left:16,right:16,alignItems:"center"},result:{maxWidth:"100%",flexDirection:"row",alignItems:"center",gap:6,paddingHorizontal:12,paddingVertical:6,borderRadius:999,backgroundColor:"rgba(39,39,42,0.9)"},check_badge:{width:18,height:18,borderRadius:9,alignItems:"center",justifyContent:"center",backgroundColor:ut},check_mark:{width:5,height:9,marginTop:-2,borderRightWidth:2,borderBottomWidth:2,borderColor:"#FFFFFF",transform:[{rotate:"45deg"}]},result_text:{flexShrink:1,color:"#FFFFFF",fontWeight:"600",fontSize:13},result_count:{color:"#A1A1AA",fontSize:13}});var we=require("react"),P=require("react-native");var J=require("react/jsx-runtime"),fn={[he.info]:"#3B82F6",[he.success]:"#22C55E",[he.error]:"#EF4444"},$o=-120,It=P.Platform.OS==="android",zo=({type:e})=>e===he.success?(0,J.jsx)(P.View,{style:ne.check_mark}):e===he.error?(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(P.View,{style:[ne.cross_bar,ne.cross_a]}),(0,J.jsx)(P.View,{style:[ne.cross_bar,ne.cross_b]})]}):(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(P.View,{style:ne.info_dot}),(0,J.jsx)(P.View,{style:ne.info_bar})]}),Wo=()=>{let e=H(it,y=>y.message),t=H(it,y=>y.type),n=H(it,y=>y.tick),o=(0,we.useRef)(new P.Animated.Value($o)).current,r=(0,we.useRef)(new P.Animated.Value(0)).current,i=(0,we.useRef)(new P.Animated.Value(.92)).current,a=(0,we.useRef)(new P.Animated.Value(0)).current,[c,l]=(0,we.useState)(),[s,d]=(0,we.useState)(!1);(0,we.useEffect)(()=>{let y=!0;return en().then(p=>{y&&p&&l(()=>p)}),()=>{y=!1}},[]);let u=(0,we.useRef)(n);return(0,we.useEffect)(()=>{if(n===u.current)return;P.AccessibilityInfo.announceForAccessibility(e),d(!0),a.setValue(0),i.setValue(.92);let y=P.Animated.sequence([P.Animated.parallel([P.Animated.spring(o,{toValue:0,speed:16,bounciness:7,useNativeDriver:!0}),P.Animated.spring(i,{toValue:1,speed:16,bounciness:9,useNativeDriver:!0}),P.Animated.timing(r,{toValue:1,duration:140,useNativeDriver:!0}),P.Animated.sequence([P.Animated.delay(90),P.Animated.spring(a,{toValue:1,speed:18,bounciness:14,useNativeDriver:!0})])]),P.Animated.delay(Gn[t]),P.Animated.parallel([P.Animated.timing(o,{toValue:$o,duration:240,useNativeDriver:!0}),P.Animated.timing(r,{toValue:0,duration:200,useNativeDriver:!0})])]);return y.start(({finished:p})=>{p&&d(!1)}),()=>y.stop()},[n]),s?(0,J.jsx)(P.View,{style:[ne.layer,{top:Et().top+(It?12:8)}],pointerEvents:"none",children:(0,J.jsxs)(P.Animated.View,{style:[ne.toast,It&&ne.toast_android,!!c&&ne.toast_glass,{opacity:c?1:r,transform:[{translateY:o},{scale:i}]}],accessibilityLiveRegion:"polite",children:[c&&(0,J.jsx)(c,{style:ne.glass_fill,glassEffectStyle:"regular",colorScheme:"dark",tintColor:"rgba(24,24,27,0.55)"}),It?(0,J.jsx)(P.Animated.View,{style:[ne.badge_halo,{backgroundColor:`${fn[t]}33`,transform:[{scale:a}]}],children:(0,J.jsx)(P.View,{style:[ne.badge,{backgroundColor:fn[t]}],children:(0,J.jsx)(zo,{type:t})})}):(0,J.jsx)(P.Animated.View,{style:[ne.badge,{backgroundColor:fn[t],transform:[{scale:a}]}],children:(0,J.jsx)(zo,{type:t})}),(0,J.jsx)(P.Text,{style:[ne.message,It&&ne.message_android],numberOfLines:2,children:e})]})}):null},ne=P.StyleSheet.create({layer:{position:"absolute",left:16,right:16,alignItems:"center",zIndex:9999,elevation:9999},toast:{maxWidth:"100%",minHeight:50,flexDirection:"row",alignItems:"center",gap:10,paddingLeft:11,paddingRight:18,paddingVertical:11,borderRadius:25,backgroundColor:"#18181B",shadowColor:"#000000",shadowOpacity:.32,shadowRadius:18,shadowOffset:{width:0,height:8},elevation:12},toast_android:{width:"100%",minHeight:60,gap:12,paddingLeft:10,paddingRight:16,paddingVertical:10,borderRadius:20,borderWidth:P.StyleSheet.hairlineWidth,borderColor:"rgba(255,255,255,0.16)",backgroundColor:"#232327",elevation:16},toast_glass:{backgroundColor:"transparent"},badge_halo:{width:40,height:40,borderRadius:20,alignItems:"center",justifyContent:"center"},glass_fill:{position:"absolute",top:0,left:0,right:0,bottom:0,borderRadius:25},badge:{width:28,height:28,borderRadius:14,alignItems:"center",justifyContent:"center"},message:{flexShrink:1,color:"#FFFFFF",fontSize:15,lineHeight:20,fontWeight:"600"},message_android:{fontSize:14,fontWeight:"500",letterSpacing:.1,color:"#F4F4F5"},check_mark:{width:7,height:13,marginTop:-3,borderRightWidth:2.5,borderBottomWidth:2.5,borderColor:"#FFFFFF",transform:[{rotate:"45deg"}]},cross_bar:{position:"absolute",width:14,height:2.5,borderRadius:2,backgroundColor:"#FFFFFF"},cross_a:{transform:[{rotate:"45deg"}]},cross_b:{transform:[{rotate:"-45deg"}]},info_dot:{width:3,height:3,borderRadius:2,marginBottom:2,backgroundColor:"#FFFFFF"},info_bar:{width:2.5,height:10,borderRadius:2,backgroundColor:"#FFFFFF"}});var ue=Ie({active_key:null,instances:{}}),jo=({app:e,instance_id:t,context:n={},url_params:o={},host_data:r={}},i)=>{var c;let a=(c=z().keep_alive)==null?void 0:c.max_webviews;ue.setState(l=>{let s=t!=null?t:e.app_id,d={...l.instances,[s]:{key:s,app:e,context:n,url_params:o,host_data:r,last_used_at:Date.now()}},u=Object.keys(d);return a&&a>0&&u.length>a&&u.filter(y=>y!==s).sort((y,p)=>d[y].last_used_at-d[p].last_used_at).slice(0,u.length-a).forEach(y=>{delete d[y]}),i?{active_key:s,instances:d}:{instances:d}})},Ho=e=>jo(e,!0),Jo=e=>jo(e,!1),Ye=()=>ue.setState({active_key:null}),Lt=e=>{ue.setState(t=>{if(t.active_key===e||!t.instances[e])return{};let n={...t.instances};return delete n[e],{instances:n}})};var Go="catalog",si="paused_apps",ai="removed_apps",ci=10*1e3,li=2,pi=3e3,ui=()=>{var e;try{return JSON.parse((e=z().storage.getString(Go))!=null?e:"{}")}catch{return{}}},U=Ie({catalog:{},downloads:{},pause_reasons:[],updates:{},apply_ticks:{}}),Ko=e=>{var t;return!!((t=z().manual_update)!=null&&t.includes(e))},Nt=new Set,Yo=e=>{let t=new Set,n=()=>z().storage.setString(e,JSON.stringify([...t]));return{has:o=>t.has(o),values:()=>[...t],add:o=>t.has(o)?!1:(t.add(o),n(),!0),delete:o=>t.delete(o)?(n(),!0):!1,load:()=>{var o;t.clear();try{let r=JSON.parse((o=z().storage.getString(e))!=null?o:"[]");Array.isArray(r)&&r.forEach(i=>{typeof i=="string"&&t.add(i)})}catch{}}}},Ae=Yo(si),Ue=Yo(ai);En(()=>{Ae.load(),Ue.load();let e=ui(),t={};Object.keys(e).filter(n=>!Ue.has(n)).forEach(n=>{let o=$(n);o?t[n]={status:"installed",progress:1,version:o.version,has_local:!0}:Ae.has(n)&&(t[n]={status:"paused",progress:0,version:e[n].version,has_local:!1})}),U.setState({catalog:e,downloads:t})});var Ut=e=>H(U,t=>e?t.downloads[e]:void 0),Xo=()=>H(U,e=>e.pause_reasons.length>0),Se=(...e)=>me("queue",...e),Q=[],Oe={},O=null,Ft=new Set,We={},yn=new Set,De=e=>{yn.forEach(t=>{try{t(e)}catch(n){console.warn("[miniapp-queue] event listener error",n==null?void 0:n.message)}})},Zo=e=>(yn.add(e),()=>{yn.delete(e)}),Qo=()=>U.getState().downloads,de=(e,t)=>{let n=!!$(e),o=U.getState().downloads[e],r=t.status==="downloading"&&n?"updating":t.status,i={...o!=null?o:{status:"queued",progress:0},...t,...r?{status:r}:{},has_local:n};U.setState(a=>({downloads:{...a.downloads,[e]:i}})),(o==null?void 0:o.status)!==i.status||(o==null?void 0:o.version)!==i.version||(o==null?void 0:o.has_local)!==i.has_local?De({type:"status_change",app_id:e,state:i}):o.progress!==i.progress&&De({type:"progress",app_id:e,progress:i.progress,version:i.version})},Dt=(e,t)=>{var n;(n=We[e])==null||n.forEach(o=>o(t)),delete We[e]},di=()=>U.getState().pause_reasons.length>0,Ne=e=>{var c;if(O)return;let t=e?Q.indexOf(e):di()?-1:Q.findIndex(l=>!Ae.has(l));if(t<0||t>=Q.length)return;let[n]=Q.splice(t,1),o=U.getState().catalog[n];if(!o){Dt(n,$(n)),Ne();return}let r=Date.now();Oe[n]=((c=Oe[n])!=null?c:0)+1,de(n,{status:"downloading",progress:0,version:o.version,error:void 0});let i=0,a=gn(o,{onProgress:l=>{let s=Math.floor(l*100);s!==i&&(i=s,de(n,{progress:s/100,version:o.version}))}});O={app_id:n,handle:a,forced:!!e},Se("start",n,o.version,e?"(forced)":""),a.promise.then(l=>{Se("installed",n,o.version,`${Date.now()-r}ms`),de(n,{status:"installed",progress:1,version:o.version}),Dt(n,l)}).catch(l=>{var d;if(l instanceof Ge){if(Ft.has(n))return;Se("paused",n),Oe[n]-=1,Q.unshift(n),de(n,{status:Ae.has(n)?"paused":"queued",progress:0,version:o.version});return}let s=String((d=l==null?void 0:l.message)!=null?d:l);if(console.warn("[miniapp-queue] failed",n,s),Oe[n]<li){de(n,{status:"queued",progress:0,version:o.version,error:s}),setTimeout(()=>{var u;Q.includes(n)||(O==null?void 0:O.app_id)===n||(Q.push(n),Ne((u=We[n])!=null&&u.length?n:void 0))},pi);return}de(n,{status:"failed",progress:0,version:o.version,error:s}),Dt(n,$(n))}).finally(()=>{O=null;let l=Q.find(s=>{var d;return(d=We[s])==null?void 0:d.length});Ne(l)})},Vt=(e,{front:t=!1}={})=>{if((O==null?void 0:O.app_id)===e)return;let n=Q.indexOf(e);if(n>=0){if(!t)return;Q.splice(n,1)}t?Q.unshift(e):Q.push(e)},gi=async e=>{let{host_id:t,client_token:n}=z(),o=new AbortController,r=setTimeout(()=>o.abort(),ci);try{let i=`${wt}/api/hosts/${encodeURIComponent(t)}/miniapps?channel=${e}`,a=await fetch(i,{headers:{Authorization:`Bearer ${n}`,"Cache-Control":"no-cache"},signal:o.signal});if(!a.ok)throw new Error(`host list ${e} ${a.status}`);return(await a.json()).apps.map(l=>({...l,channel:e}))}finally{clearTimeout(r)}},gt=null,Bt=()=>(gt!=null||(gt=(async()=>{var t;let e=Date.now();try{let n=await Promise.all(z().channels.map(gi)),o={};[...n].reverse().flat().forEach(l=>{o[l.app_id]=l});let r=Object.keys(U.getState().catalog).filter(l=>!o[l]);z().storage.setString(Go,JSON.stringify(o)),U.setState({catalog:o}),await Promise.all(r.map(l=>er(l,{by_user:!1}))),r.forEach(l=>Ue.delete(l));let i=Object.keys(o).filter(l=>!Ue.has(l)),a=[],c={};for(let l of i.map(s=>o[s])){if(await dn(l)){de(l.app_id,{status:"installed",progress:1,version:l.version});continue}let s=$(l.app_id);if(Ko(l.app_id)&&!Nt.has(l.app_id)&&s&&await Ce(s)){de(l.app_id,{status:"installed",progress:1,version:s.version}),c[l.app_id]={app_id:l.app_id,current_version:s.version,next_version:l.version};continue}a.push(l)}return U.setState({updates:c}),a.forEach(l=>{Oe[l.app_id]=0,de(l.app_id,{status:Ae.has(l.app_id)?"paused":"queued",progress:0,version:l.version,error:void 0}),Vt(l.app_id)}),Se("catalog",i.length,"apps, outdated",a.map(l=>l.app_id),"removed",r,`${Date.now()-e}ms`),De({type:"sync_complete",app_ids:i,removed:r}),Object.values(c).forEach(l=>De({type:"update_available",...l})),Ne(),{ok:!0,app_ids:i,removed:r}}catch(n){let o=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",o),De({type:"sync_failed",error:o}),{ok:!1,error:o}}finally{gt=null}})()),gt),er=async(e,{by_user:t})=>{var r,i,a,c;if(t&&Ue.add(e),Ft.has(e))return;Ft.add(e),Ae.delete(e);let n=Q.indexOf(e);n>=0&&Q.splice(n,1),(O==null?void 0:O.app_id)===e&&O.handle.cancel();let o=(c=(a=(r=U.getState().downloads[e])==null?void 0:r.version)!=null?a:(i=$(e))==null?void 0:i.version)!=null?c:"";de(e,{status:"uninstalling",progress:0,version:o}),await Io(e),Lt(e),U.setState(l=>{let s={...l.downloads};return delete s[e],{downloads:s}}),delete Oe[e],Ft.delete(e),Dt(e,null),Se("uninstalled",e,t?"(user)":"(not in list)"),De({type:"uninstalled",app_id:e})},tr=e=>er(e,{by_user:!0}),nr=e=>{let t=Xe(e);return t?(Ue.delete(e),(O==null?void 0:O.app_id)===e||Q.includes(e)||(Oe[e]=0,de(e,{status:Ae.has(e)?"paused":"queued",progress:0,version:t.version,error:void 0}),Vt(e),Ne(),Se("restore",e)),!0):!1},or=e=>{if(Ae.has(e))return;if(Ae.add(e),Se("pause app",e),(O==null?void 0:O.app_id)===e&&!O.forced){O.handle.cancel();return}let t=U.getState().downloads[e];Q.includes(e)&&t&&de(e,{status:"paused",progress:0,version:t.version})},rr=e=>{if(!Ae.delete(e))return;Se("resume app",e);let t=U.getState().downloads[e];(t==null?void 0:t.status)==="paused"&&!Q.includes(e)&&Xe(e)&&(Oe[e]=0,Vt(e)),Q.includes(e)&&t&&de(e,{status:"queued",progress:0,version:t.version}),Ne()},ir=e=>{let{pause_reasons:t}=U.getState();t.includes(e)||(U.setState({pause_reasons:[...t,e]}),Se("pause",e),t.length===0&&De({type:"pause_change",paused:!0,reasons:[e]}),O&&!O.forced&&O.handle.cancel())},sr=e=>{let{pause_reasons:t}=U.getState();if(!t.includes(e))return;let n=t.filter(o=>o!==e);U.setState({pause_reasons:n}),Se("resume",e),n.length===0&&De({type:"pause_change",paused:!1,reasons:n}),Ne()},wn=e=>U.getState().updates[e],ar=async e=>{var n,o;let t=wn(e);Nt.add(e);try{let r=await mt(e),i=(o=t==null?void 0:t.next_version)!=null?o:(n=Xe(e))==null?void 0:n.version;return!r||!i||r.version!==i?!1:(U.setState(a=>{var l;let c={...a.updates};return delete c[e],{updates:c,apply_ticks:{...a.apply_ticks,[e]:((l=a.apply_ticks[e])!=null?l:0)+1}}}),Se("updated",e,t==null?void 0:t.current_version,"\u2192",r.version),!0)}finally{Nt.delete(e)}},cr=()=>Object.values(U.getState().catalog).map(e=>({...e,installed:!!$(e.app_id),removed_by_user:Ue.has(e.app_id)})),Xe=e=>U.getState().catalog[e],mt=async e=>{let t=Xe(e);if(!t)return;if(Ae.delete(e),Ue.delete(e),await dn(t))return $(e);let n=$(e);if(Ko(e)&&!Nt.has(e)&&n&&await Ce(n))return n;let o=new Promise(r=>{var i;((i=We[e])!=null?i:We[e]=[]).push(r)});return(O==null?void 0:O.app_id)===e?O.forced=!0:(Oe[e]=0,Vt(e,{front:!0}),O&&!O.forced?O.handle.cancel():Ne(e)),o};var L=require("react/jsx-runtime"),bn=e=>(e!=null?e:"").replace(/\?[^#]*/,""),lr=0,mi=()=>{let e=new Set;return{emit:t=>e.forEach(n=>n(t)),subscribe:t=>(e.add(t),()=>{e.delete(t)})}},hi=S.default.memo(({instance_key:e,is_active:t,is_front:n,is_dark:o,reload_tick:r,web_at_top:i,splash:a,bridge:c,opaque_background:l,allow_embedded_miniapps:s,onWebLoadEnd:d})=>{var ht,ft;let u=(0,S.useRef)(null),y=(0,S.useRef)(!1),p=H(ue,m=>m.instances[e]),w=p==null?void 0:p.app.app_id,F=p==null?void 0:p.app.manifest_url,T=p==null?void 0:p.context,R=p==null?void 0:p.url_params,M=H(Z,m=>{var b;return((b=m.active)==null?void 0:b.owner)===e?m.active:null}),[V,W]=(0,S.useState)(null),[oe,Pe]=(0,S.useState)(M);M!==oe&&(Pe(M),M?W(null):(oe==null?void 0:oe.layout)===pe.top&&W(oe));let ce=(M==null?void 0:M.layout)===pe.top?M:V,[E,h]=(0,S.useState)(()=>w?$(w):null),[C,x]=(0,S.useState)(!1),[D,_e]=(0,S.useState)(0),[Y,I]=(0,S.useState)(0),[re,G]=(0,S.useState)(!1),ee=(0,S.useRef)(null),ie=m=>{ee.current&&clearTimeout(ee.current),ee.current=setTimeout(()=>{ee.current=null,G(!0)},m)};(0,S.useEffect)(()=>()=>{ee.current&&clearTimeout(ee.current)},[]),(0,S.useEffect)(()=>{if(!w||!t&&E)return;let m=!0;return x(!1),(async()=>{let b=$(w),_=b?await Ce(b):!1;if(!m||(h(_?ae=>!ae||ae.version!==b.version||ae.permissions.join(",")!==b.permissions.join(",")?b:ae:null),__DEV__&&Date.now()-lr>1e4&&(lr=Date.now(),await Bt()),!m))return;let B=await mt(w),se=B!==void 0?B:F?await Do(w,F):$(w);if(m){if(!se){x(!0);return}h(ae=>ae!=null?ae:se)}})(),()=>{m=!1}},[t,w,F,D]),(0,S.useEffect)(()=>No(e,m=>u.current?(u.current.postMessage(m),!0):!1),[e]);let ve=H(U,m=>{let b=w?m.downloads[w]:void 0;return(b==null?void 0:b.status)==="installed"?b.version:void 0});(0,S.useEffect)(()=>{if(t||!w||!E)return;let m=$(w);if(!m||m.version===E.version)return;let b=!0;return Ce(m).then(_=>{!b||!_||(me(`webview:${e}`,"\u0111\u1ED5i bundle (\u1EA9n)",E.version,"\u2192",m.version),h(m))}),()=>{b=!1}},[t,w,ve,E==null?void 0:E.version]);let Me=H(U,m=>{var b;return w&&(b=m.apply_ticks[w])!=null?b:0});(0,S.useEffect)(()=>{if(!Me||!w)return;let m=$(w);if(!m||m.version===(E==null?void 0:E.version))return;let b=!0;return Ce(m).then(_=>{!b||!_||(me(`webview:${e}`,"c\u1EADp nh\u1EADt",E==null?void 0:E.version,"\u2192",m.version),G(!1),h(m))}),()=>{b=!1}},[Me]),(0,S.useEffect)(()=>{var _;let m=(_=z().keep_alive)==null?void 0:_.idle_close_ms;if(t||!m||m<=0)return;let b=setTimeout(()=>{Lt(e)},m);return()=>clearTimeout(b)},[t,e]),(0,S.useEffect)(()=>{r>0&&(x(!1),G(!1),I(m=>m+1),_e(m=>m+1))},[r]);let je=(0,S.useRef)(t);(0,S.useEffect)(()=>{var m;je.current!==t&&(je.current=t,y.current&&((m=u.current)==null||m.injectJavaScript(vo(t?"resumed":"paused"))))},[t]);let xe=`${(ht=E==null?void 0:E.version)!=null?ht:"none"}:${(ft=E==null?void 0:E.permissions.join(","))!=null?ft:""}:${Y}`,Te=(0,S.useMemo)(()=>JSON.stringify([T!=null?T:{},R!=null?R:{}]),[T,R]),Ze=(0,S.useMemo)(()=>{var m;return Po(R!=null?R:{},(m=E==null?void 0:E.permissions)!=null?m:[])},[Te,E==null?void 0:E.permissions]),qt=(0,S.useMemo)(()=>Eo(T!=null?T:{},Ze)+So()+Ao()+(z().debug?_o():""),[Ze]),Ve=(0,S.useRef)(null),Qe=(0,S.useRef)(null);(0,S.useEffect)(()=>{var b,_,B;if(!E)return;if(Qe.current!==xe){Qe.current=xe,Ve.current=Te;return}if(Ve.current===Te)return;let m=((_=JSON.parse((b=Ve.current)!=null?b:"[]")[0])!=null?_:{}).org_id;if(Ve.current=Te,m===(T==null?void 0:T.org_id)&&y.current){G(!1),ie(1500),(B=u.current)==null||B.injectJavaScript(Mo(T!=null?T:{},Ze));return}G(!1),I(se=>se+1)},[Te,E,xe]),(0,S.useEffect)(()=>(t||(Re(e),Fe(e),qe(e)),()=>{Re(e),Fe(e),qe(e)}),[t,e,xe,r]),(0,S.useEffect)(()=>{let m=k.AppState.addEventListener("change",b=>{b==="background"&&!to()&&Re(e),b==="background"&&!ao()&&Fe(e)});return()=>m.remove()},[e]);let et=(0,S.useCallback)(async m=>{var _,B,se,ae,zt,Sn;let b=fo(m.nativeEvent.data);if(!b){if(w&&(c!=null&&c.onWebEvent))try{Promise.resolve(c.onWebEvent(m.nativeEvent.data,{app_id:w,instance_id:e})).catch(j=>{console.warn("[miniapp] onWebEvent l\u1ED7i",w,j)})}catch(j){console.warn("[miniapp] onWebEvent l\u1ED7i",w,j)}return}if(b.method==="log"){let{level:j,text:K}=b;me(`web:${e}`,j!=null?j:"log",K!=null?K:"");return}if(b.method==="pong"){ee.current||G(!0);return}if(b.method==="touchAtTop"){i.emit(!!b.at_top);return}if(b.method==="contextApplied"){ee.current&&clearTimeout(ee.current),ee.current=null,G(!0);return}if(b.method==="ready"){y.current=!0,G(!0);let j=(_=ue.getState().instances[e])==null?void 0:_.context;j&&((B=u.current)==null||B.injectJavaScript(rn(j)));return}try{let j=await Co(b,{getHostData:()=>{var K,ge;return(ge=(K=ue.getState().instances[e])==null?void 0:K.host_data)!=null?ge:{}},getPermissions:()=>{var K,ge;return w?(ge=(K=$(w))==null?void 0:K.permissions)!=null?ge:[]:[]},getContext:()=>{var K,ge;return(ge=(K=ue.getState().instances[e])==null?void 0:K.context)!=null?ge:{}},is_dark:o,close:Ye,app_id:w!=null?w:"",instance_id:e,options:c,emit:(K,ge)=>{var An;(An=u.current)==null||An.injectJavaScript(bo(K,ge))},playBeep:(se=c==null?void 0:c.playScannerBeep)!=null?se:(()=>{var K;(K=u.current)==null||K.injectJavaScript(To())}),isActive:()=>ue.getState().active_key===e&&k.AppState.currentState!=="background"});b.id&&((ae=u.current)==null||ae.injectJavaScript(yo(b.id,j)))}catch(j){if(!b.id)return;let K=j==null?void 0:j.code,ge=j instanceof g?j:new g(typeof K=="string"?K:"HOST_ERROR",String((zt=j==null?void 0:j.message)!=null?zt:j));(Sn=u.current)==null||Sn.injectJavaScript(wo(b.id,ge))}},[e,o,w,i,c]),$t=(0,S.useCallback)(()=>{x(!1),I(m=>m+1),_e(m=>m+1)},[]);return(0,L.jsxs)(k.View,{style:[k.StyleSheet.absoluteFill,l&&{backgroundColor:o?"#09090B":"#FFFFFF"},!n&&be.behind],pointerEvents:t?"auto":"none",children:[ce&&(0,L.jsx)(hn,{scanner:ce,closing:ce===V,onClosed:()=>{var m;W(null),ce.absolute&&((m=u.current)==null||m.injectJavaScript(sn(0)))},onHeight:ce.absolute?m=>{var b;return(b=u.current)==null?void 0:b.injectJavaScript(sn(m))}:void 0}),E?(0,L.jsx)(ur.default,{ref:u,source:{uri:E.entry_uri},originWhitelist:["*"],hideKeyboardAccessoryView:!0,mediaPlaybackRequiresUserAction:!1,allowingReadAccessToURL:`file://${s?ln():E.dir}`,allowFileAccess:!0,allowFileAccessFromFileURLs:!0,allowUniversalAccessFromFileURLs:!0,injectedJavaScriptBeforeContentLoaded:qt,onMessage:et,onShouldStartLoadWithRequest:m=>{let b=m.url;return m.isTopFrame===!1||!/^https?:\/\//i.test(b)?!0:(Promise.resolve(c!=null&&c.openUrl?c.openUrl(b):k.Linking.openURL(b)).catch(()=>{}),!1)},setSupportMultipleWindows:!1,bounces:!1,overScrollMode:"never",onLoadStart:m=>{Re(e),Fe(e),qe(e),me(`webview:${e}`,"load start",bn(m.nativeEvent.url)),y.current=!1,G(!1)},onError:m=>{Re(e),Fe(e),qe(e),me(`webview:${e}`,"load error",bn(m.nativeEvent.url),m.nativeEvent.description),x(!0),G(!1)},onLoadEnd:m=>{let b=m.nativeEvent.url;me(`webview:${e}`,"load end",bn(b)),w&&(d==null||d({app_id:w,instance_id:e,url:b})),ie(1500)},onContentProcessDidTerminate:()=>{Re(e),Fe(e),qe(e),y.current=!1,G(!1),I(m=>m+1)},onRenderProcessGone:()=>(Re(e),Fe(e),qe(e),y.current=!1,G(!1),I(m=>m+1),!0),style:be.webview},xe):null,(M==null?void 0:M.layout)===pe.full&&(0,L.jsx)(hn,{scanner:M}),p&&(0,L.jsx)(yi,{visible:!E||!re,interactive:C,children:(0,L.jsx)(fi,{splash:a,app:p.app,is_dark:o,error:C,has_bundle:!!E,retry:$t})})]})}),fi=S.default.memo(({splash:e,app:t,is_dark:n,error:o,has_bundle:r,retry:i})=>{let a=e,c=Ut(t.app_id),l=o?"error":!r&&(c==null?void 0:c.status)==="downloading"?"downloading":"loading";return(0,L.jsx)(a,{app:t,is_dark:n,status:l,progress:l==="downloading"?c==null?void 0:c.progress:void 0,retry:i})}),yi=({visible:e,interactive:t,children:n})=>{let o=(0,S.useRef)(new k.Animated.Value(e?1:0)).current,[r,i]=(0,S.useState)(e);return(0,S.useEffect)(()=>{if(e){i(!0),o.setValue(1);return}let a=k.Animated.timing(o,{toValue:0,duration:180,useNativeDriver:!0});return a.start(({finished:c})=>{c&&i(!1)}),()=>a.stop()},[e,o]),r?(0,L.jsx)(k.Animated.View,{style:[k.StyleSheet.absoluteFill,{opacity:o}],pointerEvents:t?"auto":"none",children:n}):null},_n=({app:e,is_dark:t,status:n,progress:o,retry:r})=>{let i=t?"#FAFAFA":"#18181B";return(0,L.jsxs)(k.View,{style:[be.splash,{backgroundColor:t?"#09090B":"#FFFFFF"}],children:[(0,L.jsx)(k.View,{style:[be.splash_icon,{backgroundColor:t?"#18181B":"#F4F4F5"}],children:e.icon?(0,L.jsx)(k.Image,{source:{uri:e.icon},style:be.splash_icon_image}):(0,L.jsx)(k.Text,{style:be.splash_letter,children:(e.name||"?").slice(0,1).toUpperCase()})}),(0,L.jsx)(k.Text,{style:[be.splash_name,{color:i}],children:e.name}),n==="error"?(0,L.jsxs)(L.Fragment,{children:[(0,L.jsx)(k.Text,{style:be.splash_hint,children:"Kh\xF4ng t\u1EA3i \u0111\u01B0\u1EE3c mini app"}),(0,L.jsx)(k.TouchableOpacity,{activeOpacity:.7,style:[be.retry_button,{backgroundColor:t?"#27272A":"#F4F4F5"}],onPress:r,children:(0,L.jsx)(k.Text,{style:[be.retry_text,{color:i}],children:"Th\u1EED l\u1EA1i"})})]}):(0,L.jsxs)(L.Fragment,{children:[(0,L.jsx)(k.ActivityIndicator,{style:be.splash_spinner,color:t?"#A1A1AA":"#71717A"}),n==="downloading"&&(0,L.jsxs)(k.Text,{style:be.splash_hint,children:["\u0110ang t\u1EA3i mini app",o?` ${Math.round(o*100)}%`:"\u2026"]})]})]})},pr=(e,t)=>{let n=(0,S.useRef)(t),o=(0,S.useRef)(!1);__DEV__&&!o.current&&n.current!==t&&(o.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.`))},wi=({container:e,splash:t=_n,is_dark:n=!1,bridge:o,close_on_back:r=!0,opaque_background:i=!0,allow_embedded_miniapps:a=!1,onWebLoadEnd:c})=>{pr("container",e),pr("splash",t);let l=e,s=H(ue,M=>M.active_key),d=(0,S.useRef)(s);s&&(d.current=s);let u=H(ue,M=>Object.keys(M.instances).join("|")),y=H(ue,M=>{var V;return M.active_key?(V=M.instances[M.active_key])==null?void 0:V.app.name:void 0}),p=(0,S.useMemo)(()=>u?u.split("|"):[],[u]),[w,F]=(0,S.useState)({}),T=(0,S.useRef)(mi()).current;(0,S.useEffect)(()=>{if(!s||!r)return;let M=k.BackHandler.addEventListener("hardwareBackPress",()=>(Ye(),!0));return()=>M.remove()},[s,r]);let R=(0,S.useCallback)(()=>{let M=ue.getState().active_key;M&&F(V=>({...V,[M]:(V[M]||0)+1}))},[]);return p.length?(0,L.jsxs)(L.Fragment,{children:[(0,L.jsx)(l,{visible:!!s,title:y!=null?y:"",is_dark:n,close:Ye,reload:R,subscribeWebAtTop:T.subscribe,children:p.map(M=>(0,L.jsx)(hi,{instance_key:M,is_active:s===M,is_front:(s!=null?s:d.current)===M,is_dark:n,reload_tick:w[M]||0,web_at_top:T,splash:t,bridge:o,opaque_background:i,allow_embedded_miniapps:a,onWebLoadEnd:c},M))}),(0,L.jsx)(Wo,{})]}):null},be=k.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"}}),dr=S.default.memo(wi);0&&(module.exports={CodeType,DefaultMiniAppSplash,MINIAPP_PLATFORM_URL,MiniAppHost,MiniAppHostError,ScannerEndReason,ScannerEvent,ScannerLayout,ScannerMethod,ToastType,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,uploadToUrl,useMiniAppDownload,useMiniAppDownloadsPaused});
88
+ })(); true;`,ei=new Set(["selection","impactLight","impactMedium","impactHeavy","rigid","soft","notificationSuccess","notificationWarning","notificationError"]),Rt=(e,t)=>{if(typeof e!="string"||!e)throw new g("INVALID_PARAMS",`Thi\u1EBFu ${t}`);return e},Fo=async({method:e,params:t},{getHostData:n,getPermissions:o,getContext:r,is_dark:i,close:a,app_id:c,instance_id:l,options:s,emit:d,isActive:u,playBeep:y})=>{var C,M,q,W,oe,Pe,ce,E;let p=s==null?void 0:s.handlers,f={app_id:c,instance_id:l,close:a},O=()=>{var m;(m=s==null?void 0:s.haptic)==null||m.call(s,"impactLight"),y==null||y()},R=()=>new g("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF \u1EE9ng d\u1EE5ng n\xE0y`);switch(e){case"getCurrentLocation":{let m=Ln(t);return ct(e,()=>Fn(m,u))}case"speech.start":{if(!d)throw R();let m={};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 g("INVALID_PARAMS","lang ph\u1EA3i l\xE0 m\xE3 ng\xF4n ng\u1EEF nh\u01B0 vi-VN");m.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 g("INVALID_PARAMS",`${V} ph\u1EA3i l\xE0 boolean`);m[V]=t[V]}if((t==null?void 0:t.mode)!==void 0&&t.mode!=="s2t"&&t.mode!=="voice")throw new g("INVALID_PARAMS","mode ph\u1EA3i l\xE0 's2t' ho\u1EB7c 'voice'");let T=(t==null?void 0:t.mode)==="s2t"?"s2t":"voice",x=T==="voice"?(C=s==null?void 0:s.voice)!=null?C:s==null?void 0:s.speech:void 0;if(ro(l,x),x){no(l,x);try{return await x.start({owner:l,app_id:c,mode:T,options:m,emit:d,isActive:u!=null?u:(()=>!0)})}catch(V){throw oo(l,x),V}}return ao(l,m,d,u)}case"speech.stop":{let m=io(l);return m?m.stop(l):co(l)}case Ke.scan:return fo(l,Zt(t),u,O);case Ke.start:{if(!d)throw R();return yo(l,Zt(t),d,u,O)}case Ke.stop:return wo(l);case"uploadFiles":{let{task_id:m,...T}=t!=null?t:{};if(m!==void 0&&(typeof m!="string"||!m))throw new g("INVALID_PARAMS","task_id ph\u1EA3i l\xE0 chu\u1ED7i");return Qn(zn(T),{instance_id:l,app_id:c,getContext:r,task_id:m,config:s==null?void 0:s.upload,emit:d,exclusivePick:x=>ct("uploadFiles.pick",x)})}case"uploadFiles.cancel":Xn(l,t==null?void 0:t.task_id);return;case"getUploadCapabilities":return Kn(s==null?void 0:s.upload);case"getBiometricAvailability":return((M=s==null?void 0:s.biometrics)!=null?M:await Ht()).getAvailability();case"authenticateBiometric":{let m=Rt(t==null?void 0:t.reason,"reason").trim();if(!m||m.length>200)throw new g("INVALID_PARAMS","reason must contain 1\u2013200 characters");let T=t==null?void 0:t.cancelButtonText;if(T!==void 0&&(typeof T!="string"||!T.trim()||T.length>80))throw new g("INVALID_PARAMS","Invalid cancelButtonText");return ct(e,async()=>{var V;return((V=s==null?void 0:s.biometrics)!=null?V:await Ht()).authenticate({reason:m,cancelButtonText:T})})}case"requestPayment":{let m=p==null?void 0:p.requestPayment;if(!m)throw R();let T=t==null?void 0:t.amount;if(typeof T!="number"||!Number.isFinite(T)||T<=0)throw new g("INVALID_PARAMS","amount ph\u1EA3i l\xE0 s\u1ED1 > 0");let x={...t,amount:T,currency:Rt(t==null?void 0:t.currency,"currency")};return ct(e,()=>m(x,f))}case"printImage":{let m=p==null?void 0:p.printImage;if(!m)throw R();let T=Rt(t==null?void 0:t.image,"image");await ct(e,()=>m({image:T},f));return}case"openScreen":if(!(p!=null&&p.openScreen))throw R();await p.openScreen({screen:Rt(t==null?void 0:t.screen,"screen"),params:t==null?void 0:t.params},f);return;case"closeApp":a();return;case"openWebview":{let m=String((q=t==null?void 0:t.url)!=null?q:"");if(!/^https?:\/\//i.test(m))throw new g("INVALID_PARAMS","url ph\u1EA3i l\xE0 http(s)");await(s!=null&&s.openUrl?s.openUrl(m):lt.Linking.openURL(m));return}case"openLink":{let m=String((W=t==null?void 0:t.url)!=null?W:"").trim();if(!/^[a-z][a-z0-9+.-]*:/i.test(m)||/^(javascript|file|data|about|blob):/i.test(m))throw new g("INVALID_PARAMS","url kh\xF4ng h\u1EE3p l\u1EC7");try{await(s!=null&&s.openUrl?s.openUrl(m):lt.Linking.openURL(m))}catch(T){throw new g("NOT_SUPPORTED",String((Pe=(oe=T==null?void 0:T.message)!=null?oe:T)!=null?Pe:"Kh\xF4ng m\u1EDF \u0111\u01B0\u1EE3c link"))}return}case"showToast":{let m=eo(t);if(!m||(u==null?void 0:u())===!1)return;s!=null&&s.showToast?s.showToast(m.message,{type:m.type}):to(m.message,m.type);return}case"haptic":{let m=ei.has(t==null?void 0:t.type)?t.type:"selection";(ce=s==null?void 0:s.haptic)==null||ce.call(s,m);return}case"getSystemInfo":return{platform:lt.Platform.OS==="ios"?"ios":"android",appVersion:(E=s==null?void 0:s.app_version)!=null?E:"",theme:i?"dark":"light"};case"getAccessToken":{let m=n().access_token;if(!m)throw new g("HOST_ERROR","Mini app ch\u01B0a c\xF3 token cho page n\xE0y");return m}case"getToken":{let m=t==null?void 0:t.type;if(m==="access"){let V=n().access_token;if(!V)throw new g("HOST_ERROR","Mini app ch\u01B0a c\xF3 token cho page n\xE0y");return V}if(m!=="partner"&&m!=="chatbox")throw new g("HOST_ERROR",`Lo\u1EA1i token kh\xF4ng h\u1EE3p l\u1EC7: ${String(m)}`);let T=ko[m];if(!o().includes(T))throw new g("PERMISSION_DENIED",`Mini app ch\u01B0a \u0111\u01B0\u1EE3c c\u1EA5p quy\u1EC1n ${T} (Console \u2192 Quy\u1EC1n l\u1EA5y token)`);let x=m==="partner"?n().partner_token:n().chatbox_token;if(!x)throw new g("HOST_ERROR",`Kh\xF4ng c\xF3 ${T}`);return x}case"getUserInfo":{let m=n().user;if(!m)throw new g("HOST_ERROR","Kh\xF4ng l\u1EA5y \u0111\u01B0\u1EE3c th\xF4ng tin nh\xE2n vi\xEAn");return m}case"getPageInfo":{let m=n().page;if(!m)throw new g("HOST_ERROR","Kh\xF4ng l\u1EA5y \u0111\u01B0\u1EE3c th\xF4ng tin page");return m}case"sendMessage":case"insertText":throw new g("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF phi\xEAn b\u1EA3n app n\xE0y`);default:throw new g("NOT_SUPPORTED",`API kh\xF4ng t\u1ED3n t\u1EA1i: ${e}`)}};var ln=e=>`bundle:${e}`,pn=()=>`${D().file_system.document_dir}/miniapps`,un=pn,dn=(e,t,n="index.html",o=!1,r=[])=>{let i=`${un()}/${e}/${t}`;return{app_id:e,version:t,dir:i,entry_uri:`file://${i}/${n}`,context_update:o,permissions:r}},cn=e=>{var t;D().storage.setString(ln(e.app_id),JSON.stringify({version:e.version,entry:e.entry,context_update:!!e.context_update,permissions:(t=e.permissions)!=null?t:[]}))},ti=(e,t)=>/^https?:\/\//.test(t)?t:`${e.replace(/[^/]*$/,"")}${t}`,N=e=>{let t=D().storage.getString(ln(e));if(!t)return null;try{let{version:n,entry:o,context_update:r,permissions:i}=JSON.parse(t);return dn(e,n,o,!!r,Array.isArray(i)?i:[])}catch{return null}},Te=e=>D().file_system.exists(e.entry_uri.replace("file://","")),gn=async e=>{let t=N(e.app_id);return(t==null?void 0:t.version)===e.version&&await Te(t)},No=async(e,t)=>{let n=D().file_system,o=`${un()}/${e}`,r=await n.listDir(o).catch(()=>[]);await Promise.all(r.filter(i=>!t.includes(i)).map(i=>n.remove(`${o}/${i}`).catch(()=>{})))},Uo=async e=>{var t;await((t=dt[e])==null?void 0:t.catch(()=>{})),D().storage.setString(ln(e),""),await D().file_system.remove(`${un()}/${e}`).catch(()=>{})},Ye=class extends Error{constructor(){super("cancelled"),this.name="MiniAppInstallCancelled"}},dt={},Vo=(e,t)=>{var i;let o=((i=dt[e])!=null?i:Promise.resolve()).catch(()=>{}).then(t),r=o.catch(()=>{});return dt[e]=r,r.then(()=>{dt[e]===r&&delete dt[e]}),o},hn=(e,t)=>{var r,i;let n=e.split(".").map(a=>parseInt(a,10)||0),o=t.split(".").map(a=>parseInt(a,10)||0);for(let a=0;a<Math.max(n.length,o.length);a++){let c=((r=n[a])!=null?r:0)-((i=o[a])!=null?i:0);if(c)return c}return 0},Bo=({manifest:e,zip_path:t})=>Vo(e.app_id,async()=>{var i;let n=D().file_system,o=N(e.app_id);if(o&&hn(o.version,e.version)>=0&&await Te(o))return o;if(e.sha256&&n.sha256&&await n.sha256(t)!==e.sha256)throw new Error("sha256 mismatch");let r=dn(e.app_id,e.version,e.entry,!!e.context_update,(i=e.permissions)!=null?i:[]);return await n.remove(r.dir).catch(()=>{}),await n.mkdir(r.dir),await n.unzip(t,r.dir),cn(e),he("\u0111\xE3 c\xE0i b\u1EA3n \u0111\xF3ng s\u1EB5n",e.app_id,e.version),No(e.app_id,[e.version,o==null?void 0:o.version].filter(Boolean)),r}),mn=(e,{base_url:t,onProgress:n}={})=>{let o=D().file_system,r=null,i=!1,a=`${o.cache_dir}/${e.app_id}-${e.version}.zip`,c=()=>{if(i)throw new Ye},l=async()=>{var u;c();let s=N(e.app_id);if((s==null?void 0:s.version)===e.version&&await o.exists(s.dir))return cn(e),N(e.app_id);c();let d=o.download({url:t?ti(t,e.bundle_url):e.bundle_url,to_file:a,onProgress:(y,p)=>{var O;let f=p>0?p:(O=e.size)!=null?O:0;f>0&&(n==null||n(Math.min(1,y/f)))}});r=d;try{let{status:y}=await d.promise;if(c(),y!==200)throw new Error(`bundle ${y}`);if(e.sha256)if(o.sha256){if(await o.sha256(a)!==e.sha256)throw new Error("sha256 mismatch")}else he("b\u1ECF qua ki\u1EC3m tra sha256 (file_system kh\xF4ng c\xF3 sha256)",e.app_id);c();let p=dn(e.app_id,e.version,e.entry,!!e.context_update,(u=e.permissions)!=null?u:[]);return await o.remove(p.dir).catch(()=>{}),await o.mkdir(p.dir),await o.unzip(a,p.dir),cn(e),No(e.app_id,[e.version,s==null?void 0:s.version].filter(Boolean)),p}catch(y){throw i?new Ye:y}finally{r=null,o.remove(a).catch(()=>{})}};return{promise:Vo(e.app_id,l),cancel:()=>{i=!0,r==null||r.cancel()}}},ut={},ni=__DEV__?0:60*1e3,Do={},qo=(e,t)=>{var o,r;let n=N(e);return n&&Date.now()-((o=Do[t])!=null?o:0)<ni?Promise.resolve(n):((r=ut[e])!=null||(ut[e]=(async()=>{let i=await fetch(t,{headers:{"Cache-Control":"no-cache"}});if(!i.ok)throw new Error(`manifest ${i.status}`);let a=await i.json(),c=await mn(a,{base_url:t}).promise;return Do[t]=Date.now(),c})().catch(i=>(console.warn("[miniapp] sync failed",e,i==null?void 0:i.message),N(e))).finally(()=>{ut[e]=void 0})),ut[e])};var Ot=new Map,$o=(e,t)=>(Ot.set(e,t),()=>{Ot.get(e)===t&&Ot.delete(e)}),zo=(e,t)=>{let n=Ot.get(e);return n?n(t):!1};var B=require("react"),w=require("react-native");var v=require("react/jsx-runtime"),gt="#22C55E",oi="\u0110\u01B0a m\xE3 v\xE0o khung \u0111\u1EC3 qu\xE9t",ri=2,It=18,ii=1600,ht=14,si=2e3,Ho=.38,ai=40,Wo=2,ci=8,li=2e3,pi=250,Xe=2e3,ui=[{top:0,left:0,borderTopWidth:4,borderLeftWidth:4,borderTopLeftRadius:ht},{top:0,right:0,borderTopWidth:4,borderRightWidth:4,borderTopRightRadius:ht},{bottom:0,left:0,borderBottomWidth:4,borderLeftWidth:4,borderBottomLeftRadius:ht},{bottom:0,right:0,borderBottomWidth:4,borderRightWidth:4,borderBottomRightRadius:ht}],jo=({color:e})=>(0,v.jsx)(v.Fragment,{children:ui.map((t,n)=>(0,v.jsx)(w.View,{style:[_.corner,t,{borderColor:e}]},n))}),kt=({style:e,children:t,...n})=>{let o=(0,B.useRef)(new w.Animated.Value(1)).current,r=i=>w.Animated.spring(o,{toValue:i,speed:40,bounciness:8,useNativeDriver:!0}).start();return(0,v.jsx)(w.Pressable,{...n,onPressIn:()=>r(.88),onPressOut:()=>r(1),children:(0,v.jsx)(w.Animated.View,{style:[e,{transform:[{scale:o}]}],children:t})})},yn=({scanner:e,closing:t=!1,onClosed:n,onHeight:o})=>{var h,b;let{vision:r,types:i,mode:a,layout:c,hint:l,glass_view:s,absolute:d}=e,u=c===pe.top,y=(0,B.useRef)(new w.Animated.Value(0)).current,p=r.useCameraDevice("back"),f=(0,B.useRef)(new w.Animated.Value(1)).current,[O,R]=(0,B.useState)(!1),[C,M]=(0,B.useState)(1),q=(0,B.useRef)(null),[W,oe]=(0,B.useState)(()=>{let{width:A,height:$}=w.Dimensions.get("window");return{width:A,height:u?$*Ho:$,window_y:0}}),Pe=H(Q,A=>A.last_value),ce=H(Q,A=>A.hit_tick),E=H(Q,A=>A.scan_count),m=H(Q,A=>A.notice),T=H(Q,A=>A.is_picking),x=(0,B.useRef)(null),V=Ct(),Ae=V.top,Y=(0,B.useRef)(new w.Animated.Value(0)).current,L=(0,B.useRef)(new w.Animated.Value(0)).current,re=(0,B.useRef)(new w.Animated.Value(0)).current,G=(0,B.useRef)(n);G.current=n,(0,B.useEffect)(()=>{if(!t)return;y.setValue(W.height);let A=w.Animated.timing(y,{toValue:0,duration:pi,easing:w.Easing.out(w.Easing.cubic),useNativeDriver:!1});return A.start(({finished:$})=>{var se;$&&((se=G.current)==null||se.call(G))}),()=>A.stop()},[t,y]);let ee=Math.round(W.width*(u?.8:.78)),ie=Math.round(u?W.height*.46:ee*.78),ve=Math.round((W.height-ie)/2),Me=Math.round((W.width-ee)/2),He=r.useCodeScanner({codeTypes:i,onCodeScanned:(0,B.useCallback)(A=>on(A),[])});(0,B.useEffect)(()=>{let A=w.BackHandler.addEventListener("hardwareBackPress",()=>(nn(),!0));return()=>A.remove()},[]);let xe=(0,B.useRef)(ce);(0,B.useEffect)(()=>{if(ce===xe.current)return;Y.setValue(1),re.setValue(1);let A=w.Animated.parallel([w.Animated.timing(Y,{toValue:0,duration:450,useNativeDriver:!0}),w.Animated.sequence([w.Animated.delay(si),w.Animated.timing(re,{toValue:0,duration:250,useNativeDriver:!0})])]);return A.start(),()=>A.stop()},[ce,Y,re]),(0,B.useEffect)(()=>{let A=se=>w.Animated.timing(L,{toValue:se,duration:ii,easing:w.Easing.inOut(w.Easing.quad),useNativeDriver:!0}),$=w.Animated.loop(w.Animated.sequence([A(1),A(0)]));return $.start(),()=>$.stop()},[L]);let Re=(0,B.useCallback)(()=>{w.Animated.timing(f,{toValue:0,duration:220,useNativeDriver:!0}).start()},[f]);(0,B.useEffect)(()=>{let A=setTimeout(Re,li);return()=>clearTimeout(A)},[Re]);let[et,$t]=(0,B.useState)(!1);(0,B.useEffect)(()=>{let A=requestAnimationFrame(()=>{A=requestAnimationFrame(()=>$t(!0))});return()=>cancelAnimationFrame(A)},[]);let Be=!!(p!=null&&p.hasTorch),tt=(h=p==null?void 0:p.neutralZoom)!=null?h:1,nt=p?Math.min(p.maxZoom/tt,ci):1,zt=tt*Math.min(C,nt),yt=A=>{var ae;let{touches:$}=A.nativeEvent;if($.length!==2){q.current=null;return}let se=Math.hypot($[0].pageX-$[1].pageX,$[0].pageY-$[1].pageY);(ae=q.current)!=null||(q.current={distance:se,level:C}),M(Math.max(1,Math.min(nt,q.current.level*(se/q.current.distance))))},wt=(0,v.jsx)(w.Text,{style:[_.hint,!!m&&_.hint_notice],numberOfLines:1,children:(b=m!=null?m:l)!=null?b:oi});return(0,v.jsx)(w.Animated.View,{ref:x,onTouchMove:yt,onTouchEnd:()=>{q.current=null},pointerEvents:t?"none":"auto",style:u?[_.top,d&&_.top_absolute,t&&{height:y}]:_.full,onLayout:({nativeEvent:{layout:A}})=>{var $;t||(o==null||o(A.height),($=x.current)==null||$.measureInWindow((se,ae)=>{oe({width:A.width,height:A.height,window_y:ae||0})}))},children:(0,v.jsxs)(w.View,{style:t?[_.content_closing,{height:W.height}]:_.content,children:[p&&et&&(0,v.jsx)(r.Camera,{style:w.StyleSheet.absoluteFill,device:p,isActive:!T,codeScanner:He,torch:O&&Be?"on":"off",zoom:zt,onPreviewStarted:Re,onError:A=>bo(A.message)}),(0,v.jsx)(w.Animated.View,{style:[_.preview_cover,{opacity:f}],pointerEvents:"none"}),W.height>0&&(0,v.jsxs)(w.View,{style:_.overlay,pointerEvents:"none",children:[(0,v.jsx)(w.View,{style:[_.dim_ring,{top:ve-Xe,left:Me-Xe,width:ee+Xe*2,height:ie+Xe*2}]}),(0,v.jsxs)(w.View,{style:{position:"absolute",top:ve,left:Me,width:ee,height:ie},children:[(0,v.jsx)(jo,{color:"#FFFFFF"}),(0,v.jsx)(w.Animated.View,{style:[w.StyleSheet.absoluteFill,{opacity:Y}],children:(0,v.jsx)(jo,{color:gt})}),(0,v.jsxs)(w.Animated.View,{style:[_.scan_line_wrap,{transform:[{translateY:L.interpolate({inputRange:[0,1],outputRange:[0,Math.max(0,ie-It)]})}]}],children:[(0,v.jsx)(w.View,{style:_.scan_glow_outer}),(0,v.jsx)(w.View,{style:_.scan_glow_inner}),(0,v.jsx)(w.View,{style:_.scan_line})]})]}),(0,v.jsx)(w.View,{style:[_.hint_slot,u?{top:0,height:ve-6,justifyContent:"flex-end"}:{top:ve+ie+20}],children:wt}),a===Fe.continuous&&!!Pe&&(0,v.jsx)(w.Animated.View,{style:[_.result_slot,{top:u?ve+ie-ai:ve+ie+52},{opacity:re}],children:(0,v.jsxs)(w.View,{style:_.result,children:[(0,v.jsx)(w.View,{style:_.check_badge,children:(0,v.jsx)(w.View,{style:_.check_mark})}),(0,v.jsx)(w.Text,{style:_.result_text,numberOfLines:1,children:Pe}),(0,v.jsxs)(w.Text,{style:_.result_count,children:["\xB7 ",E," m\xE3"]})]})})]}),W.height>0&&(0,v.jsx)(w.View,{style:[_.close_slot,u?_.close_slot_top:{top:Math.max(12,Ae-W.window_y+12)}],children:(0,v.jsxs)(kt,{style:[_.close_button,!!s&&_.glass_surface],onPress:nn,hitSlop:8,accessibilityRole:"button",accessibilityLabel:"\u0110\xF3ng",children:[s&&(0,v.jsx)(s,{style:_.glass_fill,glassEffectStyle:"regular",colorScheme:"dark",tintColor:"rgba(24,24,27,0.35)",isInteractive:!0}),(0,v.jsx)(w.View,{style:[_.close_bar,_.close_bar_a]}),(0,v.jsx)(w.View,{style:[_.close_bar,_.close_bar_b]})]})}),(0,v.jsx)(w.View,{style:[_.toolbar_wrap,!u&&{bottom:V.bottom+20}],pointerEvents:"box-none",children:(0,v.jsxs)(w.View,{style:[_.toolbar,!!s&&_.glass_surface],children:[s&&(0,v.jsx)(s,{style:_.glass_fill,glassEffectStyle:"regular",colorScheme:"dark",tintColor:"rgba(24,24,27,0.35)",isInteractive:!0}),(0,v.jsx)(kt,{style:_.tool,onPress:Ao,disabled:T,accessibilityRole:"button",accessibilityLabel:"Qu\xE9t t\u1EEB \u1EA3nh",children:(0,v.jsxs)(w.View,{style:_.image_icon,children:[(0,v.jsx)(w.View,{style:_.image_icon_dot}),(0,v.jsx)(w.View,{style:_.image_icon_hill})]})}),!!p&&nt>=Wo&&(0,v.jsx)(kt,{style:[_.tool,C>1&&_.tool_on],onPress:()=>M(A=>A>1?1:Wo),accessibilityRole:"button",accessibilityLabel:"Ph\xF3ng to",children:(0,v.jsxs)(w.Text,{style:[_.zoom_text,C>1&&_.zoom_text_on],children:[Math.round(C*10)/10,"x"]})}),Be&&(0,v.jsx)(kt,{style:[_.tool,O&&_.tool_on],onPress:()=>R(A=>!A),accessibilityRole:"button",accessibilityLabel:"\u0110\xE8n pin",accessibilityState:{selected:O},children:(0,v.jsx)(w.Text,{style:[_.torch_icon,O&&_.zoom_text_on],children:"\u26A1\uFE0E"})})]})})]})})},di="rgba(0,0,0,0.5)",fn=50,_=w.StyleSheet.create({top:{height:`${Ho*100}%`,overflow:"hidden",backgroundColor:"#000000"},full:{position:"absolute",top:0,left:0,right:0,bottom:0},content:{flex:1,backgroundColor:"#000000"},top_absolute:{position:"absolute",top:0,left:0,right:0,zIndex:1},content_closing:{position:"absolute",left:0,right:0,bottom:0,backgroundColor:"#000000"},preview_cover:{position:"absolute",top:0,left:0,right:0,bottom:0,backgroundColor:"#000000"},overlay:{position:"absolute",top:0,left:0,right:0,bottom:0,overflow:"hidden"},dim_ring:{position:"absolute",borderWidth:Xe,borderColor:di,borderRadius:Xe+ht},hint_slot:{position:"absolute",left:16,right:16,alignItems:"center"},hint:{color:"#FFFFFF",fontSize:14,fontWeight:"500"},hint_notice:{color:"#FCA5A5"},corner:{position:"absolute",width:28,height:28},scan_line_wrap:{position:"absolute",top:0,left:10,right:10,height:It,alignItems:"stretch",justifyContent:"center"},scan_glow_outer:{position:"absolute",left:0,right:0,height:It,borderRadius:It/2,backgroundColor:gt,opacity:.1},scan_glow_inner:{position:"absolute",left:4,right:4,height:8,borderRadius:4,backgroundColor:gt,opacity:.2},scan_line:{height:ri,borderRadius:1,backgroundColor:gt},glass_surface:{backgroundColor:"transparent",overflow:"visible"},glass_fill:{position:"absolute",top:0,left:0,right:0,bottom:0,borderRadius:999},close_slot:{position:"absolute",right:12},close_slot_top:{bottom:15},close_button:{width:48,height:48,borderRadius:24,overflow:"hidden",alignItems:"center",justifyContent:"center",backgroundColor:"rgba(0,0,0,0.5)"},close_bar:{position:"absolute",width:20,height:2,borderRadius:1,backgroundColor:"#FFFFFF"},close_bar_a:{transform:[{rotate:"45deg"}]},close_bar_b:{transform:[{rotate:"-45deg"}]},toolbar_wrap:{position:"absolute",left:0,right:0,bottom:10,alignItems:"center"},toolbar:{flexDirection:"row",alignItems:"center",gap:4,padding:4,borderRadius:999,backgroundColor:"rgba(24,24,27,0.72)"},tool:{width:fn,height:fn,borderRadius:fn/2,alignItems:"center",justifyContent:"center"},tool_on:{backgroundColor:"#FFFFFF"},zoom_text:{color:"#FFFFFF",fontSize:16,fontWeight:"600"},zoom_text_on:{color:"#18181B"},torch_icon:{color:"#FFFFFF",fontSize:22,fontWeight:"600"},image_icon:{width:24,height:19,borderRadius:3,borderWidth:1.5,borderColor:"#FFFFFF",overflow:"hidden"},image_icon_dot:{position:"absolute",top:3,right:3,width:4,height:4,borderRadius:2,backgroundColor:"#FFFFFF"},image_icon_hill:{position:"absolute",left:2,bottom:-6,width:12,height:12,backgroundColor:"#FFFFFF",transform:[{rotate:"45deg"}]},result_slot:{position:"absolute",left:16,right:16,alignItems:"center"},result:{maxWidth:"100%",flexDirection:"row",alignItems:"center",gap:6,paddingHorizontal:12,paddingVertical:6,borderRadius:999,backgroundColor:"rgba(39,39,42,0.9)"},check_badge:{width:18,height:18,borderRadius:9,alignItems:"center",justifyContent:"center",backgroundColor:gt},check_mark:{width:5,height:9,marginTop:-2,borderRightWidth:2,borderBottomWidth:2,borderColor:"#FFFFFF",transform:[{rotate:"45deg"}]},result_text:{flexShrink:1,color:"#FFFFFF",fontWeight:"600",fontSize:13},result_count:{color:"#A1A1AA",fontSize:13}});var we=require("react"),P=require("react-native");var J=require("react/jsx-runtime"),wn={[me.info]:"#3B82F6",[me.success]:"#22C55E",[me.error]:"#EF4444"},Jo=-120,Lt=P.Platform.OS==="android",Go=({type:e})=>e===me.success?(0,J.jsx)(P.View,{style:ne.check_mark}):e===me.error?(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(P.View,{style:[ne.cross_bar,ne.cross_a]}),(0,J.jsx)(P.View,{style:[ne.cross_bar,ne.cross_b]})]}):(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(P.View,{style:ne.info_dot}),(0,J.jsx)(P.View,{style:ne.info_bar})]}),Ko=()=>{let e=H(at,y=>y.message),t=H(at,y=>y.type),n=H(at,y=>y.tick),o=(0,we.useRef)(new P.Animated.Value(Jo)).current,r=(0,we.useRef)(new P.Animated.Value(0)).current,i=(0,we.useRef)(new P.Animated.Value(.92)).current,a=(0,we.useRef)(new P.Animated.Value(0)).current,[c,l]=(0,we.useState)(),[s,d]=(0,we.useState)(!1);(0,we.useEffect)(()=>{let y=!0;return tn().then(p=>{y&&p&&l(()=>p)}),()=>{y=!1}},[]);let u=(0,we.useRef)(n);return(0,we.useEffect)(()=>{if(n===u.current)return;P.AccessibilityInfo.announceForAccessibility(e),d(!0),a.setValue(0),i.setValue(.92);let y=P.Animated.sequence([P.Animated.parallel([P.Animated.spring(o,{toValue:0,speed:16,bounciness:7,useNativeDriver:!0}),P.Animated.spring(i,{toValue:1,speed:16,bounciness:9,useNativeDriver:!0}),P.Animated.timing(r,{toValue:1,duration:140,useNativeDriver:!0}),P.Animated.sequence([P.Animated.delay(90),P.Animated.spring(a,{toValue:1,speed:18,bounciness:14,useNativeDriver:!0})])]),P.Animated.delay(Zn[t]),P.Animated.parallel([P.Animated.timing(o,{toValue:Jo,duration:240,useNativeDriver:!0}),P.Animated.timing(r,{toValue:0,duration:200,useNativeDriver:!0})])]);return y.start(({finished:p})=>{p&&d(!1)}),()=>y.stop()},[n]),s?(0,J.jsx)(P.View,{style:[ne.layer,{top:Ct().top+(Lt?12:8)}],pointerEvents:"none",children:(0,J.jsxs)(P.Animated.View,{style:[ne.toast,Lt&&ne.toast_android,!!c&&ne.toast_glass,{opacity:c?1:r,transform:[{translateY:o},{scale:i}]}],accessibilityLiveRegion:"polite",children:[c&&(0,J.jsx)(c,{style:ne.glass_fill,glassEffectStyle:"regular",colorScheme:"dark",tintColor:"rgba(24,24,27,0.55)"}),Lt?(0,J.jsx)(P.Animated.View,{style:[ne.badge_halo,{backgroundColor:`${wn[t]}33`,transform:[{scale:a}]}],children:(0,J.jsx)(P.View,{style:[ne.badge,{backgroundColor:wn[t]}],children:(0,J.jsx)(Go,{type:t})})}):(0,J.jsx)(P.Animated.View,{style:[ne.badge,{backgroundColor:wn[t],transform:[{scale:a}]}],children:(0,J.jsx)(Go,{type:t})}),(0,J.jsx)(P.Text,{style:[ne.message,Lt&&ne.message_android],numberOfLines:2,children:e})]})}):null},ne=P.StyleSheet.create({layer:{position:"absolute",left:16,right:16,alignItems:"center",zIndex:9999,elevation:9999},toast:{maxWidth:"100%",minHeight:50,flexDirection:"row",alignItems:"center",gap:10,paddingLeft:11,paddingRight:18,paddingVertical:11,borderRadius:25,backgroundColor:"#18181B",shadowColor:"#000000",shadowOpacity:.32,shadowRadius:18,shadowOffset:{width:0,height:8},elevation:12},toast_android:{width:"100%",minHeight:60,gap:12,paddingLeft:10,paddingRight:16,paddingVertical:10,borderRadius:20,borderWidth:P.StyleSheet.hairlineWidth,borderColor:"rgba(255,255,255,0.16)",backgroundColor:"#232327",elevation:16},toast_glass:{backgroundColor:"transparent"},badge_halo:{width:40,height:40,borderRadius:20,alignItems:"center",justifyContent:"center"},glass_fill:{position:"absolute",top:0,left:0,right:0,bottom:0,borderRadius:25},badge:{width:28,height:28,borderRadius:14,alignItems:"center",justifyContent:"center"},message:{flexShrink:1,color:"#FFFFFF",fontSize:15,lineHeight:20,fontWeight:"600"},message_android:{fontSize:14,fontWeight:"500",letterSpacing:.1,color:"#F4F4F5"},check_mark:{width:7,height:13,marginTop:-3,borderRightWidth:2.5,borderBottomWidth:2.5,borderColor:"#FFFFFF",transform:[{rotate:"45deg"}]},cross_bar:{position:"absolute",width:14,height:2.5,borderRadius:2,backgroundColor:"#FFFFFF"},cross_a:{transform:[{rotate:"45deg"}]},cross_b:{transform:[{rotate:"-45deg"}]},info_dot:{width:3,height:3,borderRadius:2,marginBottom:2,backgroundColor:"#FFFFFF"},info_bar:{width:2.5,height:10,borderRadius:2,backgroundColor:"#FFFFFF"}});var ue=Le({active_key:null,instances:{}}),Yo=({app:e,instance_id:t,context:n={},url_params:o={},host_data:r={}},i)=>{var c;let a=(c=D().keep_alive)==null?void 0:c.max_webviews;ue.setState(l=>{let s=t!=null?t:e.app_id,d={...l.instances,[s]:{key:s,app:e,context:n,url_params:o,host_data:r,last_used_at:Date.now()}},u=Object.keys(d);return a&&a>0&&u.length>a&&u.filter(y=>y!==s).sort((y,p)=>d[y].last_used_at-d[p].last_used_at).slice(0,u.length-a).forEach(y=>{delete d[y]}),i?{active_key:s,instances:d}:{instances:d}})},Xo=e=>Yo(e,!0),Qo=e=>Yo(e,!1),Qe=()=>ue.setState({active_key:null}),Ft=e=>{ue.setState(t=>{if(t.active_key===e||!t.instances[e])return{};let n={...t.instances};return delete n[e],{instances:n}})};var Zo="catalog",gi="paused_apps",hi="removed_apps",mi=10*1e3,fi=2,yi=3e3,wi=()=>{var e;try{return JSON.parse((e=D().storage.getString(Zo))!=null?e:"{}")}catch{return{}}},U=Le({catalog:{},downloads:{},pause_reasons:[],updates:{},apply_ticks:{}}),er=e=>{var t;return!!((t=D().manual_update)!=null&&t.includes(e))},Ut=new Set,tr=e=>{let t=new Set,n=()=>D().storage.setString(e,JSON.stringify([...t]));return{has:o=>t.has(o),values:()=>[...t],add:o=>t.has(o)?!1:(t.add(o),n(),!0),delete:o=>t.delete(o)?(n(),!0):!1,load:()=>{var o;t.clear();try{let r=JSON.parse((o=D().storage.getString(e))!=null?o:"[]");Array.isArray(r)&&r.forEach(i=>{typeof i=="string"&&t.add(i)})}catch{}}}},_e=tr(gi),Ve=tr(hi);On(()=>{_e.load(),Ve.load();let e=wi(),t={};Object.keys(e).filter(n=>!Ve.has(n)).forEach(n=>{let o=N(n);o?t[n]={status:"installed",progress:1,version:o.version,has_local:!0}:_e.has(n)&&(t[n]={status:"paused",progress:0,version:e[n].version,has_local:!1})}),U.setState({catalog:e,downloads:t})});var Vt=e=>H(U,t=>e?t.downloads[e]:void 0),nr=()=>H(U,e=>e.pause_reasons.length>0),Se=(...e)=>he("queue",...e),Z=[],Oe={},k=null,Dt=new Set,je={},bn=new Set,Ne=e=>{bn.forEach(t=>{try{t(e)}catch(n){console.warn("[miniapp-queue] event listener error",n==null?void 0:n.message)}})},or=e=>(bn.add(e),()=>{bn.delete(e)}),rr=()=>U.getState().downloads,de=(e,t)=>{let n=!!N(e),o=U.getState().downloads[e],r=t.status==="downloading"&&n?"updating":t.status,i={...o!=null?o:{status:"queued",progress:0},...t,...r?{status:r}:{},has_local:n};U.setState(a=>({downloads:{...a.downloads,[e]:i}})),(o==null?void 0:o.status)!==i.status||(o==null?void 0:o.version)!==i.version||(o==null?void 0:o.has_local)!==i.has_local?Ne({type:"status_change",app_id:e,state:i}):o.progress!==i.progress&&Ne({type:"progress",app_id:e,progress:i.progress,version:i.version})},Nt=(e,t)=>{var n;(n=je[e])==null||n.forEach(o=>o(t)),delete je[e]},bi=()=>U.getState().pause_reasons.length>0,Ue=e=>{var c;if(k)return;let t=e?Z.indexOf(e):bi()?-1:Z.findIndex(l=>!_e.has(l));if(t<0||t>=Z.length)return;let[n]=Z.splice(t,1),o=U.getState().catalog[n];if(!o){Nt(n,N(n)),Ue();return}let r=Date.now();Oe[n]=((c=Oe[n])!=null?c:0)+1,de(n,{status:"downloading",progress:0,version:o.version,error:void 0});let i=0,a=mn(o,{onProgress:l=>{let s=Math.floor(l*100);s!==i&&(i=s,de(n,{progress:s/100,version:o.version}))}});k={app_id:n,handle:a,forced:!!e},Se("start",n,o.version,e?"(forced)":""),a.promise.then(l=>{Se("installed",n,o.version,`${Date.now()-r}ms`),de(n,{status:"installed",progress:1,version:o.version}),Nt(n,l)}).catch(l=>{var d;if(l instanceof Ye){if(Dt.has(n))return;Se("paused",n),Oe[n]-=1,Z.unshift(n),de(n,{status:_e.has(n)?"paused":"queued",progress:0,version:o.version});return}let s=String((d=l==null?void 0:l.message)!=null?d:l);if(console.warn("[miniapp-queue] failed",n,s),Oe[n]<fi){de(n,{status:"queued",progress:0,version:o.version,error:s}),setTimeout(()=>{var u;Z.includes(n)||(k==null?void 0:k.app_id)===n||(Z.push(n),Ue((u=je[n])!=null&&u.length?n:void 0))},yi);return}de(n,{status:"failed",progress:0,version:o.version,error:s}),Nt(n,N(n))}).finally(()=>{k=null;let l=Z.find(s=>{var d;return(d=je[s])==null?void 0:d.length});Ue(l)})},Bt=(e,{front:t=!1}={})=>{if((k==null?void 0:k.app_id)===e)return;let n=Z.indexOf(e);if(n>=0){if(!t)return;Z.splice(n,1)}t?Z.unshift(e):Z.push(e)},Ai=async e=>{let{host_id:t,client_token:n}=D(),o=new AbortController,r=setTimeout(()=>o.abort(),mi);try{let i=`${Je}/api/hosts/${encodeURIComponent(t)}/miniapps?channel=${e}`,a=await fetch(i,{headers:{Authorization:`Bearer ${n}`,"Cache-Control":"no-cache"},signal:o.signal});if(!a.ok)throw new Error(`host list ${e} ${a.status}`);return(await a.json()).apps.map(l=>({...l,channel:e}))}finally{clearTimeout(r)}},mt=null,qt=()=>(mt!=null||(mt=(async()=>{var t;let e=Date.now();try{let n=await Promise.all(D().channels.map(Ai)),o={};[...n].reverse().flat().forEach(l=>{o[l.app_id]=l});let r=Object.keys(U.getState().catalog).filter(l=>!o[l]);D().storage.setString(Zo,JSON.stringify(o)),U.setState({catalog:o}),await Promise.all(r.map(l=>ir(l,{by_user:!1}))),r.forEach(l=>Ve.delete(l));let i=Object.keys(o).filter(l=>!Ve.has(l)),a=[],c={};for(let l of i.map(s=>o[s])){if(await gn(l)){de(l.app_id,{status:"installed",progress:1,version:l.version});continue}let s=N(l.app_id);if(er(l.app_id)&&!Ut.has(l.app_id)&&s&&await Te(s)){de(l.app_id,{status:"installed",progress:1,version:s.version}),c[l.app_id]={app_id:l.app_id,current_version:s.version,next_version:l.version};continue}a.push(l)}return U.setState({updates:c}),a.forEach(l=>{Oe[l.app_id]=0,de(l.app_id,{status:_e.has(l.app_id)?"paused":"queued",progress:0,version:l.version,error:void 0}),Bt(l.app_id)}),Se("catalog",i.length,"apps, outdated",a.map(l=>l.app_id),"removed",r,`${Date.now()-e}ms`),Ne({type:"sync_complete",app_ids:i,removed:r}),Object.values(c).forEach(l=>Ne({type:"update_available",...l})),Ue(),{ok:!0,app_ids:i,removed:r}}catch(n){let o=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",o),Ne({type:"sync_failed",error:o}),{ok:!1,error:o}}finally{mt=null}})()),mt),ir=async(e,{by_user:t})=>{var r,i,a,c;if(t&&Ve.add(e),Dt.has(e))return;Dt.add(e),_e.delete(e);let n=Z.indexOf(e);n>=0&&Z.splice(n,1),(k==null?void 0:k.app_id)===e&&k.handle.cancel();let o=(c=(a=(r=U.getState().downloads[e])==null?void 0:r.version)!=null?a:(i=N(e))==null?void 0:i.version)!=null?c:"";de(e,{status:"uninstalling",progress:0,version:o}),await Uo(e),Ft(e),U.setState(l=>{let s={...l.downloads};return delete s[e],{downloads:s}}),delete Oe[e],Dt.delete(e),Nt(e,null),Se("uninstalled",e,t?"(user)":"(not in list)"),Ne({type:"uninstalled",app_id:e})},sr=e=>ir(e,{by_user:!0}),ar=e=>{let t=Ze(e);return t?(Ve.delete(e),(k==null?void 0:k.app_id)===e||Z.includes(e)||(Oe[e]=0,de(e,{status:_e.has(e)?"paused":"queued",progress:0,version:t.version,error:void 0}),Bt(e),Ue(),Se("restore",e)),!0):!1},cr=e=>{if(_e.has(e))return;if(_e.add(e),Se("pause app",e),(k==null?void 0:k.app_id)===e&&!k.forced){k.handle.cancel();return}let t=U.getState().downloads[e];Z.includes(e)&&t&&de(e,{status:"paused",progress:0,version:t.version})},lr=e=>{if(!_e.delete(e))return;Se("resume app",e);let t=U.getState().downloads[e];(t==null?void 0:t.status)==="paused"&&!Z.includes(e)&&Ze(e)&&(Oe[e]=0,Bt(e)),Z.includes(e)&&t&&de(e,{status:"queued",progress:0,version:t.version}),Ue()},pr=e=>{let{pause_reasons:t}=U.getState();t.includes(e)||(U.setState({pause_reasons:[...t,e]}),Se("pause",e),t.length===0&&Ne({type:"pause_change",paused:!0,reasons:[e]}),k&&!k.forced&&k.handle.cancel())},ur=e=>{let{pause_reasons:t}=U.getState();if(!t.includes(e))return;let n=t.filter(o=>o!==e);U.setState({pause_reasons:n}),Se("resume",e),n.length===0&&Ne({type:"pause_change",paused:!1,reasons:n}),Ue()},An=e=>U.getState().updates[e],dr=async e=>{var n,o;let t=An(e);Ut.add(e);try{let r=await ft(e),i=(o=t==null?void 0:t.next_version)!=null?o:(n=Ze(e))==null?void 0:n.version;return!r||!i||r.version!==i?!1:(U.setState(a=>{var l;let c={...a.updates};return delete c[e],{updates:c,apply_ticks:{...a.apply_ticks,[e]:((l=a.apply_ticks[e])!=null?l:0)+1}}}),Se("updated",e,t==null?void 0:t.current_version,"\u2192",r.version),!0)}finally{Ut.delete(e)}},gr=()=>Object.values(U.getState().catalog).map(e=>({...e,installed:!!N(e.app_id),removed_by_user:Ve.has(e.app_id)})),Ze=e=>U.getState().catalog[e],ft=async e=>{let t=Ze(e);if(!t)return;if(_e.delete(e),Ve.delete(e),await gn(t))return N(e);let n=N(e);if(er(e)&&!Ut.has(e)&&n&&await Te(n))return n;let o=new Promise(r=>{var i;((i=je[e])!=null?i:je[e]=[]).push(r)});return(k==null?void 0:k.app_id)===e?k.forced=!0:(Oe[e]=0,Bt(e,{front:!0}),k&&!k.forced?k.handle.cancel():Ue(e)),o};var F=require("react/jsx-runtime"),Sn=e=>(e!=null?e:"").replace(/\?[^#]*/,""),hr=0,Si=()=>{let e=new Set;return{emit:t=>e.forEach(n=>n(t)),subscribe:t=>(e.add(t),()=>{e.delete(t)})}},_i=S.default.memo(({instance_key:e,is_active:t,is_front:n,is_dark:o,reload_tick:r,web_at_top:i,splash:a,bridge:c,opaque_background:l,allow_embedded_miniapps:s,onWebLoadEnd:d})=>{var yt,wt;let u=(0,S.useRef)(null),y=(0,S.useRef)(!1),p=H(ue,h=>h.instances[e]),f=p==null?void 0:p.app.app_id,O=p==null?void 0:p.app.manifest_url,R=p==null?void 0:p.context,C=p==null?void 0:p.url_params,M=H(Q,h=>{var b;return((b=h.active)==null?void 0:b.owner)===e?h.active:null}),[q,W]=(0,S.useState)(null),[oe,Pe]=(0,S.useState)(M);M!==oe&&(Pe(M),M?W(null):(oe==null?void 0:oe.layout)===pe.top&&W(oe));let ce=(M==null?void 0:M.layout)===pe.top?M:q,[E,m]=(0,S.useState)(()=>f?N(f):null),[T,x]=(0,S.useState)(!1),[V,Ae]=(0,S.useState)(0),[Y,L]=(0,S.useState)(0),[re,G]=(0,S.useState)(!1),ee=(0,S.useRef)(null),ie=h=>{ee.current&&clearTimeout(ee.current),ee.current=setTimeout(()=>{ee.current=null,G(!0)},h)};(0,S.useEffect)(()=>()=>{ee.current&&clearTimeout(ee.current)},[]),(0,S.useEffect)(()=>{if(!f||!t&&E)return;let h=!0;return x(!1),(async()=>{let b=N(f),A=b?await Te(b):!1;if(!h||(m(A?ae=>!ae||ae.version!==b.version||ae.permissions.join(",")!==b.permissions.join(",")?b:ae:null),__DEV__&&Date.now()-hr>1e4&&(hr=Date.now(),await qt()),!h))return;let $=await ft(f),se=$!==void 0?$:O?await qo(f,O):N(f);if(h){if(!se){x(!0);return}m(ae=>ae!=null?ae:se)}})(),()=>{h=!1}},[t,f,O,V]),(0,S.useEffect)(()=>$o(e,h=>u.current?(u.current.postMessage(h),!0):!1),[e]);let ve=H(U,h=>{let b=f?h.downloads[f]:void 0;return(b==null?void 0:b.status)==="installed"?b.version:void 0});(0,S.useEffect)(()=>{if(t||!f||!E)return;let h=N(f);if(!h||h.version===E.version)return;let b=!0;return Te(h).then(A=>{!b||!A||(he(`webview:${e}`,"\u0111\u1ED5i bundle (\u1EA9n)",E.version,"\u2192",h.version),m(h))}),()=>{b=!1}},[t,f,ve,E==null?void 0:E.version]);let Me=H(U,h=>{var b;return f&&(b=h.apply_ticks[f])!=null?b:0});(0,S.useEffect)(()=>{if(!Me||!f)return;let h=N(f);if(!h||h.version===(E==null?void 0:E.version))return;let b=!0;return Te(h).then(A=>{!b||!A||(he(`webview:${e}`,"c\u1EADp nh\u1EADt",E==null?void 0:E.version,"\u2192",h.version),G(!1),m(h))}),()=>{b=!1}},[Me]),(0,S.useEffect)(()=>{var A;let h=(A=D().keep_alive)==null?void 0:A.idle_close_ms;if(t||!h||h<=0)return;let b=setTimeout(()=>{Ft(e)},h);return()=>clearTimeout(b)},[t,e]),(0,S.useEffect)(()=>{r>0&&(x(!1),G(!1),L(h=>h+1),Ae(h=>h+1))},[r]);let He=(0,S.useRef)(t);(0,S.useEffect)(()=>{var h;He.current!==t&&(He.current=t,y.current&&((h=u.current)==null||h.injectJavaScript(Po(t?"resumed":"paused"))))},[t]);let xe=`${(yt=E==null?void 0:E.version)!=null?yt:"none"}:${(wt=E==null?void 0:E.permissions.join(","))!=null?wt:""}:${Y}`,Re=(0,S.useMemo)(()=>JSON.stringify([R!=null?R:{},C!=null?C:{}]),[R,C]),et=(0,S.useMemo)(()=>{var h;return Io(C!=null?C:{},(h=E==null?void 0:E.permissions)!=null?h:[])},[Re,E==null?void 0:E.permissions]),$t=(0,S.useMemo)(()=>Oo(R!=null?R:{},et)+Eo()+Co()+(D().debug?xo():""),[et]),Be=(0,S.useRef)(null),tt=(0,S.useRef)(null);(0,S.useEffect)(()=>{var b,A,$;if(!E)return;if(tt.current!==xe){tt.current=xe,Be.current=Re;return}if(Be.current===Re)return;let h=((A=JSON.parse((b=Be.current)!=null?b:"[]")[0])!=null?A:{}).org_id;if(Be.current=Re,h===(R==null?void 0:R.org_id)&&y.current){G(!1),ie(1500),($=u.current)==null||$.injectJavaScript(Ro(R!=null?R:{},et));return}G(!1),L(se=>se+1)},[Re,E,xe]),(0,S.useEffect)(()=>(t||(Ce(e),De(e),$e(e)),()=>{Ce(e),De(e),$e(e)}),[t,e,xe,r]),(0,S.useEffect)(()=>{let h=I.AppState.addEventListener("change",b=>{b==="background"&&!so()&&Ce(e),b==="background"&&!go()&&De(e)});return()=>h.remove()},[e]);let nt=(0,S.useCallback)(async h=>{var A,$,se,ae,Wt,En;let b=So(h.nativeEvent.data);if(!b){if(f&&(c!=null&&c.onWebEvent))try{Promise.resolve(c.onWebEvent(h.nativeEvent.data,{app_id:f,instance_id:e})).catch(j=>{console.warn("[miniapp] onWebEvent l\u1ED7i",f,j)})}catch(j){console.warn("[miniapp] onWebEvent l\u1ED7i",f,j)}return}if(b.method==="log"){let{level:j,text:K}=b;he(`web:${e}`,j!=null?j:"log",K!=null?K:"");return}if(b.method==="pong"){ee.current||G(!0);return}if(b.method==="touchAtTop"){i.emit(!!b.at_top);return}if(b.method==="contextApplied"){ee.current&&clearTimeout(ee.current),ee.current=null,G(!0);return}if(b.method==="ready"){y.current=!0,G(!0);let j=(A=ue.getState().instances[e])==null?void 0:A.context;j&&(($=u.current)==null||$.injectJavaScript(sn(j)));return}try{let j=await Fo(b,{getHostData:()=>{var K,ge;return(ge=(K=ue.getState().instances[e])==null?void 0:K.host_data)!=null?ge:{}},getPermissions:()=>{var K,ge;return f?(ge=(K=N(f))==null?void 0:K.permissions)!=null?ge:[]:[]},getContext:()=>{var K,ge;return(ge=(K=ue.getState().instances[e])==null?void 0:K.context)!=null?ge:{}},is_dark:o,close:Qe,app_id:f!=null?f:"",instance_id:e,options:c,emit:(K,ge)=>{var Cn;(Cn=u.current)==null||Cn.injectJavaScript(Mo(K,ge))},playBeep:(se=c==null?void 0:c.playScannerBeep)!=null?se:(()=>{var K;(K=u.current)==null||K.injectJavaScript(Lo())}),isActive:()=>ue.getState().active_key===e&&I.AppState.currentState!=="background"});b.id&&((ae=u.current)==null||ae.injectJavaScript(_o(b.id,j)))}catch(j){if(!b.id)return;let K=j==null?void 0:j.code,ge=j instanceof g?j:new g(typeof K=="string"?K:"HOST_ERROR",String((Wt=j==null?void 0:j.message)!=null?Wt:j));(En=u.current)==null||En.injectJavaScript(vo(b.id,ge))}},[e,o,f,i,c]),zt=(0,S.useCallback)(()=>{x(!1),L(h=>h+1),Ae(h=>h+1)},[]);return(0,F.jsxs)(I.View,{style:[I.StyleSheet.absoluteFill,l&&{backgroundColor:o?"#09090B":"#FFFFFF"},!n&&be.behind],pointerEvents:t?"auto":"none",children:[ce&&(0,F.jsx)(yn,{scanner:ce,closing:ce===q,onClosed:()=>{var h;W(null),ce.absolute&&((h=u.current)==null||h.injectJavaScript(an(0)))},onHeight:ce.absolute?h=>{var b;return(b=u.current)==null?void 0:b.injectJavaScript(an(h))}:void 0}),E?(0,F.jsx)(fr.default,{ref:u,source:{uri:E.entry_uri},originWhitelist:["*"],hideKeyboardAccessoryView:!0,mediaPlaybackRequiresUserAction:!1,allowingReadAccessToURL:`file://${s?pn():E.dir}`,allowFileAccess:!0,allowFileAccessFromFileURLs:!0,allowUniversalAccessFromFileURLs:!0,injectedJavaScriptBeforeContentLoaded:$t,onMessage:nt,onShouldStartLoadWithRequest:h=>{let b=h.url;return h.isTopFrame===!1||!/^https?:\/\//i.test(b)?!0:(Promise.resolve(c!=null&&c.openUrl?c.openUrl(b):I.Linking.openURL(b)).catch(()=>{}),!1)},setSupportMultipleWindows:!1,bounces:!1,overScrollMode:"never",onLoadStart:h=>{Ce(e),De(e),$e(e),he(`webview:${e}`,"load start",Sn(h.nativeEvent.url)),y.current=!1,G(!1)},onError:h=>{Ce(e),De(e),$e(e),he(`webview:${e}`,"load error",Sn(h.nativeEvent.url),h.nativeEvent.description),x(!0),G(!1)},onLoadEnd:h=>{let b=h.nativeEvent.url;he(`webview:${e}`,"load end",Sn(b)),f&&(d==null||d({app_id:f,instance_id:e,url:b})),ie(1500)},onContentProcessDidTerminate:()=>{Ce(e),De(e),$e(e),y.current=!1,G(!1),L(h=>h+1)},onRenderProcessGone:()=>(Ce(e),De(e),$e(e),y.current=!1,G(!1),L(h=>h+1),!0),style:be.webview},xe):null,(M==null?void 0:M.layout)===pe.full&&(0,F.jsx)(yn,{scanner:M}),p&&(0,F.jsx)(Mi,{visible:!E||!re,interactive:T,children:(0,F.jsx)(vi,{splash:a,app:p.app,is_dark:o,error:T,has_bundle:!!E,retry:zt})})]})}),vi=S.default.memo(({splash:e,app:t,is_dark:n,error:o,has_bundle:r,retry:i})=>{let a=e,c=Vt(t.app_id),l=o?"error":!r&&(c==null?void 0:c.status)==="downloading"?"downloading":"loading";return(0,F.jsx)(a,{app:t,is_dark:n,status:l,progress:l==="downloading"?c==null?void 0:c.progress:void 0,retry:i})}),Mi=({visible:e,interactive:t,children:n})=>{let o=(0,S.useRef)(new I.Animated.Value(e?1:0)).current,[r,i]=(0,S.useState)(e);return(0,S.useEffect)(()=>{if(e){i(!0),o.setValue(1);return}let a=I.Animated.timing(o,{toValue:0,duration:180,useNativeDriver:!0});return a.start(({finished:c})=>{c&&i(!1)}),()=>a.stop()},[e,o]),r?(0,F.jsx)(I.Animated.View,{style:[I.StyleSheet.absoluteFill,{opacity:o}],pointerEvents:t?"auto":"none",children:n}):null},_n=({app:e,is_dark:t,status:n,progress:o,retry:r})=>{let i=t?"#FAFAFA":"#18181B";return(0,F.jsxs)(I.View,{style:[be.splash,{backgroundColor:t?"#09090B":"#FFFFFF"}],children:[(0,F.jsx)(I.View,{style:[be.splash_icon,{backgroundColor:t?"#18181B":"#F4F4F5"}],children:e.icon?(0,F.jsx)(I.Image,{source:{uri:e.icon},style:be.splash_icon_image}):(0,F.jsx)(I.Text,{style:be.splash_letter,children:(e.name||"?").slice(0,1).toUpperCase()})}),(0,F.jsx)(I.Text,{style:[be.splash_name,{color:i}],children:e.name}),n==="error"?(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(I.Text,{style:be.splash_hint,children:"Kh\xF4ng t\u1EA3i \u0111\u01B0\u1EE3c mini app"}),(0,F.jsx)(I.TouchableOpacity,{activeOpacity:.7,style:[be.retry_button,{backgroundColor:t?"#27272A":"#F4F4F5"}],onPress:r,children:(0,F.jsx)(I.Text,{style:[be.retry_text,{color:i}],children:"Th\u1EED l\u1EA1i"})})]}):(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(I.ActivityIndicator,{style:be.splash_spinner,color:t?"#A1A1AA":"#71717A"}),n==="downloading"&&(0,F.jsxs)(I.Text,{style:be.splash_hint,children:["\u0110ang t\u1EA3i mini app",o?` ${Math.round(o*100)}%`:"\u2026"]})]})]})},mr=(e,t)=>{let n=(0,S.useRef)(t),o=(0,S.useRef)(!1);__DEV__&&!o.current&&n.current!==t&&(o.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.`))},xi=({container:e,splash:t=_n,is_dark:n=!1,bridge:o,close_on_back:r=!0,opaque_background:i=!0,allow_embedded_miniapps:a=!1,onWebLoadEnd:c})=>{mr("container",e),mr("splash",t);let l=e,s=H(ue,M=>M.active_key),d=(0,S.useRef)(s);s&&(d.current=s);let u=H(ue,M=>Object.keys(M.instances).join("|")),y=H(ue,M=>{var q;return M.active_key?(q=M.instances[M.active_key])==null?void 0:q.app.name:void 0}),p=(0,S.useMemo)(()=>u?u.split("|"):[],[u]),[f,O]=(0,S.useState)({}),R=(0,S.useRef)(Si()).current;(0,S.useEffect)(()=>{if(!s||!r)return;let M=I.BackHandler.addEventListener("hardwareBackPress",()=>(Qe(),!0));return()=>M.remove()},[s,r]);let C=(0,S.useCallback)(()=>{let M=ue.getState().active_key;M&&O(q=>({...q,[M]:(q[M]||0)+1}))},[]);return p.length?(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(l,{visible:!!s,title:y!=null?y:"",is_dark:n,close:Qe,reload:C,subscribeWebAtTop:R.subscribe,children:p.map(M=>(0,F.jsx)(_i,{instance_key:M,is_active:s===M,is_front:(s!=null?s:d.current)===M,is_dark:n,reload_tick:f[M]||0,web_at_top:R,splash:t,bridge:o,opaque_background:i,allow_embedded_miniapps:a,onWebLoadEnd:c},M))}),(0,F.jsx)(Ko,{})]}):null},be=I.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"}}),yr=S.default.memo(xi);var ke=require("react");var wr=e=>`changelog_seen:${e}`,Ei=10*1e3,vn=e=>D().storage.getString(wr(e))||null,Mn=(e,t=(n=>(n=N(e))==null?void 0:n.version)())=>{t&&D().storage.setString(wr(e),t)},br=e=>{var o;let t=(o=N(e))==null?void 0:o.version;if(!t)return null;let n=vn(e);return n?hn(t,n)>0?{app_id:e,from:n,to:t}:null:(Mn(e,t),null)},Ci=e=>{var t,n,o;return(o=(n=(t=U.getState().catalog[e])==null?void 0:t.channel)!=null?n:D().channels[0])!=null?o:"production"},xn=async(e,{from:t,to:n,channel:o=Ci(e)}={})=>{let{client_token:r}=D(),i=new URLSearchParams({channel:o});t&&i.set("from",t),n&&i.set("to",n);let a=new AbortController,c=setTimeout(()=>a.abort(),Ei);try{let l=await fetch(`${Je}/api/miniapps/${encodeURIComponent(e)}/changelog?${i}`,{headers:{Authorization:`Bearer ${r}`},signal:a.signal});if(!l.ok)throw new Error(`changelog ${e} ${l.status}`);return(await l.json()).versions}finally{clearTimeout(c)}},Ar=(e,{from:t,to:n,enabled:o=!0}={})=>{let[r,i]=(0,ke.useState)([]),[a,c]=(0,ke.useState)(!1),[l,s]=(0,ke.useState)(),[d,u]=(0,ke.useState)(0),y=(0,ke.useCallback)(()=>u(p=>p+1),[]);return(0,ke.useEffect)(()=>{if(!e||!o)return;let p=!0;return c(!0),s(void 0),xn(e,{from:t,to:n}).then(f=>{p&&i(f)}).catch(f=>{var O;p&&s(String((f==null?void 0:f.name)==="AbortError"?"timeout":(O=f==null?void 0:f.message)!=null?O:f))}).finally(()=>{p&&c(!1)}),()=>{p=!1}},[e,t,n,o,d]),{versions:r,loading:a,error:l,reload:y}};0&&(module.exports={CodeType,DefaultMiniAppSplash,MINIAPP_PLATFORM_URL,MiniAppHost,MiniAppHostError,ScannerEndReason,ScannerEvent,ScannerLayout,ScannerMethod,ToastType,closeMiniApp,configureMiniApp,createMmkvStorage,createReactNativeBiometrics,createRnfsFileSystem,ensureMiniApp,fetchMiniAppChangelog,getLocalMiniApp,getMiniAppCatalog,getMiniAppCatalogEntry,getMiniAppChangelogSeen,getMiniAppStatuses,getMiniAppUpdate,getPendingChangelog,installBundledMiniApp,markMiniAppChangelogSeen,onMiniAppEvent,openMiniApp,pauseMiniApp,pauseMiniAppDownloads,preloadMiniApp,releaseSpeechFor,restoreMiniApp,resumeMiniApp,resumeMiniAppDownloads,sendEventToWeb,syncMiniAppCatalog,uninstallMiniApp,updateMiniApp,uploadToUrl,useMiniAppChangelog,useMiniAppDownload,useMiniAppDownloadsPaused});
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- var Ht="https://retion-miniapp-platform.vercel.app",Ve=null,In=new Set,hr=e=>{Ve=e,In.forEach(t=>t())},N=()=>{if(!Ve)throw new Error("[miniapp] Ch\u01B0a g\u1ECDi configureMiniApp()");return Ve},Ln=e=>{In.add(e),Ve&&e()},ue=(...e)=>{Ve!=null&&Ve.debug&&console.log("[miniapp]",...e)};var fr=(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(o=>o.map(r=>r.name)).catch(()=>[]),sha256:n=>e.hash(n,"sha256"),unzip:async(n,o)=>{await t(n,o)},download:({url:n,to_file:o,onProgress:r})=>{let{jobId:i,promise:a}=e.downloadFile({fromUrl:n,toFile:o,progressInterval:250,begin:()=>{},progress:({bytesWritten:c,contentLength:l})=>r==null?void 0:r(c,l)});return{promise:a.then(({statusCode:c})=>({status:c})),cancel:()=>e.stopDownload(i)}}}),yr=e=>({getString:t=>e.getString(t),setString:(t,n)=>e.set(t,n)});import Tn,{useCallback as En,useEffect as le,useMemo as $t,useRef as be,useState as Ce}from"react";import{AppState as ur,ActivityIndicator as qi,Animated as Mn,BackHandler as $i,Image as zi,Linking as Wi,StyleSheet as Cn,Text as wt,TouchableOpacity as ji,View as Rn}from"react-native";import Hi from"react-native-webview";import{Linking as Eo,Platform as Yr}from"react-native";var Fn=e=>({getAvailability:()=>e.isSensorAvailable(),authenticate:({reason:t,cancelButtonText:n})=>e.simplePrompt({promptMessage:t,cancelButtonText:n,fallbackPromptMessage:""})}),St,Jt=()=>(St||(St=import("react-native-biometrics").then(({default:e})=>Fn(new e({allowDeviceCredentials:!1}))).catch(e=>{throw St=void 0,new g("NOT_SUPPORTED",`Biometric native module unavailable: ${e instanceof Error?e.message:String(e)}`)})),St);import{PermissionsAndroid as Be,Platform as wr}from"react-native";var Dn=e=>{var n,o,r;if(e!==void 0&&(e===null||typeof e!="object"||Array.isArray(e)))throw new g("INVALID_PARAMS","Tu\u1EF3 ch\u1ECDn v\u1ECB tr\xED ph\u1EA3i l\xE0 object");let t=e!=null?e:{};if(t.enableHighAccuracy!==void 0&&typeof t.enableHighAccuracy!="boolean")throw new g("INVALID_PARAMS","enableHighAccuracy ph\u1EA3i l\xE0 boolean");for(let[i,a,c]of[["timeout",1,6e4],["maximumAge",0,864e5]]){let l=t[i];if(l!==void 0&&(typeof l!="number"||!Number.isFinite(l)||l<a||l>c))throw new g("INVALID_PARAMS",`${i} ph\u1EA3i n\u1EB1m trong kho\u1EA3ng ${a}\u2013${c} ms`)}return{enableHighAccuracy:(n=t.enableHighAccuracy)!=null?n:!1,timeout:(o=t.timeout)!=null?o:15e3,maximumAge:(r=t.maximumAge)!=null?r:0}},Nn=(e,t=()=>!0)=>new Promise((n,o)=>{let r=!1,i=(l,s)=>{r||(r=!0,clearTimeout(a),l?o(l):n(s))},a=setTimeout(()=>i(new g("TIMEOUT","H\u1EBFt th\u1EDDi gian ch\u1EDD c\u1EA5p quy\u1EC1n/l\u1EA5y v\u1ECB tr\xED")),12e4+e.timeout),c=()=>r?!1:t()?!0:(i(new g("CANCELLED","Mini app kh\xF4ng c\xF2n ho\u1EA1t \u0111\u1ED9ng")),!1);(async()=>{if(!c())return;let l;try{l=(await import("@react-native-community/geolocation")).default}catch{throw new g("NOT_SUPPORTED","Ch\u01B0a c\xF3 module v\u1ECB tr\xED trong b\u1EA3n native")}if(c()){if(wr.OS==="android"){let s=Be.PERMISSIONS.ACCESS_FINE_LOCATION,d=Be.PERMISSIONS.ACCESS_COARSE_LOCATION,u=await Be.check(s);if(!c())return;let f=u||await Be.check(d);if(!c())return;if(!u&&!f){let p=await Be.requestMultiple([s,d]);if(!c())return;if(p[s]!==Be.RESULTS.GRANTED&&p[d]!==Be.RESULTS.GRANTED)throw new g("PERMISSION_DENIED","Ch\u01B0a c\u1EA5p quy\u1EC1n truy c\u1EADp v\u1ECB tr\xED")}}c()&&l.getCurrentPosition(s=>{c()&&i(void 0,s)},s=>{var u;if(!c())return;let d=(u={1:"PERMISSION_DENIED",2:"POSITION_UNAVAILABLE",3:"TIMEOUT"}[s.code])!=null?u:"LOCATION_ERROR";i(new g(d,s.message))},e)}})().catch(l=>i(l))});import{Platform as Wn}from"react-native";var Gt=20,Un=20,jn=/^[a-z][a-z0-9_-]{0,31}$/,br=/^(\.[\w-]{1,16}|[\w.+-]+\/(\*|[\w.+-]+))$/,_r=["low","medium","high"],Oe=e=>!!e&&typeof e=="object"&&!Array.isArray(e),H=e=>new g("INVALID_PARAMS",e),ot=(e,t,n)=>typeof e=="number"&&Number.isInteger(e)&&e>=t&&e<=n,Vn=(e,t)=>{if(e===void 0)return{};if(!Oe(e)||Object.keys(e).length>Un||Object.values(e).some(n=>typeof n!="string"))throw H(`${t} ph\u1EA3i l\xE0 object chu\u1ED7i (t\u1ED1i \u0111a ${Un} key)`);return e},Hn=e=>{var n,o,r,i;if(e!==void 0&&!Oe(e))throw H("Tu\u1EF3 ch\u1ECDn upload ph\u1EA3i l\xE0 object");let t=e!=null?e:{};if(t.source!==void 0&&(typeof t.source!="string"||!jn.test(t.source)))throw H("source ph\u1EA3i l\xE0 t\xEAn ngu\u1ED3n, vd library | camera | document");if(t.accept!==void 0&&(!Array.isArray(t.accept)||t.accept.length>50||t.accept.some(a=>typeof a!="string"||!br.test(a))))throw H("accept ph\u1EA3i l\xE0 m\u1EA3ng mime (image/*, application/pdf) ho\u1EB7c \u0111u\xF4i (.docx)");if(t.max_count!==void 0&&!ot(t.max_count,1,Gt))throw H(`max_count ph\u1EA3i l\xE0 s\u1ED1 nguy\xEAn 1\u2013${Gt}`);if(t.max_size!==void 0&&!ot(t.max_size,1,Number.MAX_SAFE_INTEGER))throw H("max_size ph\u1EA3i l\xE0 s\u1ED1 byte > 0");if(t.concurrency!==void 0&&!ot(t.concurrency,1,5))throw H("concurrency ph\u1EA3i l\xE0 s\u1ED1 nguy\xEAn 1\u20135");return{source:(n=t.source)!=null?n:"library",accept:((o=t.accept)!=null?o:[]).map(a=>a.toLowerCase()),max_count:(r=t.max_count)!=null?r:1,max_size:t.max_size,process:Sr(t.process),target:Ar(t.upload),concurrency:(i=t.concurrency)!=null?i:3}},Sr=e=>{if(e===void 0)return{};if(!Oe(e))throw H("process ph\u1EA3i l\xE0 object");let t={};if(e.image!==void 0){let n=e.image;if(!Oe(n))throw H("process.image ph\u1EA3i l\xE0 object");for(let o of["max_width","max_height"])if(n[o]!==void 0&&!ot(n[o],1,1e4))throw H(`process.image.${o} ph\u1EA3i l\xE0 s\u1ED1 nguy\xEAn 1\u201310000`);if(n.quality!==void 0&&(typeof n.quality!="number"||n.quality<=0||n.quality>1))throw H("process.image.quality ph\u1EA3i trong kho\u1EA3ng (0, 1]");t.image={max_width:n.max_width,max_height:n.max_height,quality:n.quality}}if(e.video!==void 0){let n=e.video;if(!Oe(n))throw H("process.video ph\u1EA3i l\xE0 object");if(n.max_duration!==void 0&&!ot(n.max_duration,1,3600))throw H("process.video.max_duration ph\u1EA3i l\xE0 s\u1ED1 gi\xE2y 1\u20133600");if(n.quality!==void 0&&!_r.includes(n.quality))throw H("process.video.quality ph\u1EA3i l\xE0 low | medium | high");t.video={max_duration:n.max_duration,quality:n.quality}}return t},Ar=e=>{var n,o,r,i;if(e===void 0)return{target:"host",params:{}};if(!Oe(e))throw H("upload ph\u1EA3i l\xE0 object");let t=(n=e.target)!=null?n:"host";if(typeof t!="string"||!jn.test(t))throw H("upload.target ph\u1EA3i l\xE0 t\xEAn \u0111\xEDch, vd host | url");if(t!=="url"){if(e.params!==void 0&&!Oe(e.params))throw H("upload.params ph\u1EA3i l\xE0 object");return{target:t,params:(o=e.params)!=null?o:{}}}if(typeof e.url!="string"||!/^https:\/\//i.test(e.url))throw H("upload.url ph\u1EA3i l\xE0 https");for(let a of["field_name","url_field"])if(e[a]!==void 0&&(typeof e[a]!="string"||!e[a]))throw H(`upload.${a} ph\u1EA3i l\xE0 chu\u1ED7i`);return{target:"url",url:e.url,headers:Vn(e.headers,"upload.headers"),form_data:Vn(e.form_data,"upload.form_data"),field_name:(r=e.field_name)!=null?r:"file",url_field:(i=e.url_field)!=null?i:"url"}},Jn=e=>{let t=e.lastIndexOf(".");return t>0?e.slice(t).toLowerCase():""},vr=(e,t)=>{if(!t.length)return!0;let n=e.mime_type.toLowerCase(),o=Jn(e.name);return t.some(r=>r==="*/*"?!0:r.startsWith(".")?r===o:r.endsWith("/*")?n.startsWith(r.slice(0,-1)):n===r)},Mr=e=>{let t=e.length>0&&e.every(o=>o.startsWith("image/")),n=e.length>0&&e.every(o=>o.startsWith("video/"));return t?"image":n?"video":"mixed"},et,xr=()=>(et!=null||(et=import("react-native-image-picker").catch(e=>{throw et=void 0,new g("NOT_SUPPORTED",`Ch\u01B0a c\xF3 module ch\u1ECDn \u1EA3nh trong b\u1EA3n native: ${e instanceof Error?e.message:String(e)}`)})),et),Bn=e=>async({accept:t,max_count:n,process:o})=>{var l,s,d,u,f,p,y,C,x;let r=await xr(),i=Mr(t),a={mediaType:i==="image"?"photo":i,maxWidth:(l=o.image)==null?void 0:l.max_width,maxHeight:(s=o.image)==null?void 0:s.max_height,quality:(u=(d=o.image)==null?void 0:d.quality)!=null?u:.8,videoQuality:(p=(f=o.video)==null?void 0:f.quality)!=null?p:"medium",durationLimit:(y=o.video)==null?void 0:y.max_duration,assetRepresentationMode:"compatible"},c=e==="camera"?await r.launchCamera({...a,saveToPhotos:!1}):await r.launchImageLibrary({...a,selectionLimit:n});if(c.didCancel)return[];if(c.errorCode){let M=c.errorCode==="permission"?"PERMISSION_DENIED":c.errorCode==="camera_unavailable"?"NOT_SUPPORTED":"HOST_ERROR";throw new g(M,(C=c.errorMessage)!=null?C:c.errorCode)}return((x=c.assets)!=null?x:[]).filter(M=>M.uri).map((M,S)=>{var I,V,Q;return{uri:M.uri,name:(I=M.fileName)!=null?I:`file_${S+1}`,mime_type:(V=M.type)!=null?V:"application/octet-stream",size:M.fileSize,width:M.width,height:M.height,duration:M.duration,processed:!((Q=M.type)!=null&&Q.startsWith("video/"))||Wn.OS==="ios"}})},Er={"image/*":"images","video/*":"video","audio/*":"audio","text/plain":"plainText","text/csv":"csv","application/pdf":"pdf","application/json":"json","application/zip":"zip","application/msword":"doc","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"docx","application/vnd.ms-excel":"xls","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"xlsx","application/vnd.ms-powerpoint":"ppt","application/vnd.openxmlformats-officedocument.presentationml.presentation":"pptx"},Rr={".pdf":"pdf",".txt":"plainText",".csv":"csv",".json":"json",".zip":"zip",".doc":"doc",".docx":"docx",".xls":"xls",".xlsx":"xlsx",".ppt":"ppt",".pptx":"pptx"},Pr=e=>async({accept:t,max_count:n})=>{var i,a,c,l;let o=t.map(s=>{var d;return(d=Er[s])!=null?d:Rr[s]}),r=!t.length||o.some(s=>!s||!e.types[s])?e.types.allFiles:[...new Set(o)].flatMap(s=>e.types[s]);try{let d=(await e.pick({type:r,allowMultiSelection:n>1,mode:"import"})).filter(p=>p.uri&&!p.error).map((p,y)=>{var C,x,M;return{uri:p.uri,name:(C=p.name)!=null?C:`file_${y+1}`,mime_type:(x=p.type)!=null?x:"application/octet-stream",size:(M=p.size)!=null?M:void 0}});if(Wn.OS!=="android"||!e.keepLocalCopy||!d.some(p=>p.uri.startsWith("content://")))return d;let u=await e.keepLocalCopy({files:d.map(p=>({uri:p.uri,fileName:p.name})),destination:"cachesDirectory"}),f=new Map(u.map(p=>[p.sourceUri,p.status==="success"?p.localUri:void 0]));return d.map(p=>{var y;return{...p,uri:(y=f.get(p.uri))!=null?y:p.uri}})}catch(s){let d=s==null?void 0:s.code;if(d===((a=(i=e.errorCodes)==null?void 0:i.OPERATION_CANCELED)!=null?a:"OPERATION_CANCELED"))return[];throw d===((l=(c=e.errorCodes)==null?void 0:c.IN_PROGRESS)!=null?l:"ASYNC_OP_IN_PROGRESS")?new g("BUSY","\u0110ang m\u1EDF tr\xECnh ch\u1ECDn file kh\xE1c"):s}},tt,Tr=async e=>(tt!=null||(tt=import("@react-native-documents/picker").then(t=>Pr(t)).catch(t=>{throw tt=void 0,new g("NOT_SUPPORTED",`Ch\u01B0a c\xF3 module ch\u1ECDn file trong b\u1EA3n native: ${t instanceof Error?t.message:String(t)}`)})),(await tt)(e)),Gn={library:Bn("library"),camera:Bn("camera"),document:Tr},qn={type:"image",label:"\u1EA2nh",accept:["image/*"]},$n={type:"video",label:"Video",accept:["video/*"]},zn={library:[qn,$n],camera:[qn,$n],document:[{type:"any",label:"M\u1ECDi file",accept:[]},{type:"pdf",label:"PDF",accept:["application/pdf"]},{type:"word",label:"Word",accept:[".doc",".docx"]},{type:"excel",label:"Excel",accept:[".xls",".xlsx"]},{type:"powerpoint",label:"PowerPoint",accept:[".ppt",".pptx"]}]},nt,Kn=()=>(nt!=null||(nt=import("react-native-compressor").catch(()=>(nt=void 0,null))),nt),Yn=async(e,t,n)=>{try{return Number(await e.getFileSize(t))||n}catch{return n}},Cr=new Set(["image/jpeg","image/jpg","image/heic","image/heif","image/webp"]),Or={low:640,medium:1280,high:1920},kr=async(e,{image:t})=>{var o;if(!t||!Cr.has(e.mime_type.toLowerCase()))return e;let n=await Kn();if(!n)return e;try{let r=await n.Image.compress(e.uri,{compressionMethod:"manual",maxWidth:t.max_width,maxHeight:t.max_height,quality:(o=t.quality)!=null?o:.8,output:"jpg"});return{...e,uri:r,mime_type:"image/jpeg",name:e.name.replace(/\.[^.]+$/,"")+".jpg",size:await Yn(n,r,e.size),processed:!0}}catch{return e}},Ir=async(e,{video:t})=>{var o;let n=await Kn();if(!n)return e;try{let r=await n.Video.compress(e.uri,{compressionMethod:"auto",maxSize:Or[(o=t==null?void 0:t.quality)!=null?o:"medium"],minimumFileSizeForCompress:2});return{...e,uri:r,mime_type:"video/mp4",size:await Yn(n,r,e.size),processed:!0}}catch{return e}},Lr={image:kr,video:Ir},Fr=(e,t)=>t.split(".").reduce((n,o)=>Oe(n)?n[o]:void 0,e),Xn=({file:e,target:t,onProgress:n,signal:o})=>new Promise((r,i)=>{if(t.target!=="url"||!("url"in t)){i(new g("INVALID_PARAMS","Thi\u1EBFu upload.url"));return}let a=t;if(o.aborted){i(new g("CANCELLED","\u0110\xE3 hu\u1EF7 upload"));return}let c=new XMLHttpRequest,l=new FormData;Object.entries(a.form_data).forEach(([u,f])=>l.append(u,f)),l.append(a.field_name,{uri:e.uri,name:e.name,type:e.mime_type});let s=()=>c.abort();o.addEventListener("abort",s);let d=u=>{o.removeEventListener("abort",s),u()};c.open("POST",a.url),Object.entries(a.headers).forEach(([u,f])=>c.setRequestHeader(u,f)),c.upload.onprogress=u=>n(u.loaded,u.total||e.size||0),c.onload=()=>d(()=>{let u=c.responseText;try{u=JSON.parse(c.responseText)}catch{}if(c.status<200||c.status>=300){i(new g("UPLOAD_FAILED",`HTTP ${c.status}`));return}let f=Fr(u,a.url_field);if(typeof f!="string"||!f){i(new g("UPLOAD_FAILED",`Response kh\xF4ng c\xF3 "${a.url_field}"`));return}r({url:f,response:u})}),c.onerror=()=>d(()=>i(new g("UPLOAD_FAILED","L\u1ED7i m\u1EA1ng khi upload"))),c.onabort=()=>d(()=>i(new g("CANCELLED","\u0110\xE3 hu\u1EF7 upload"))),c.send(l)}),Zn=e=>{var o,r;let t={...Gn};for(let[i,a]of Object.entries((o=e==null?void 0:e.sources)!=null?o:{}))a?t[i]=a:delete t[i];let n={url:Xn};for(let[i,a]of Object.entries((r=e==null?void 0:e.targets)!=null?r:{}))i!=="url"&&a&&(n[i]=a);return{sources:t,targets:n}},Qn=e=>{let{sources:t,targets:n}=Zn(e),o=Object.keys(t),r=Object.fromEntries(o.filter(i=>t[i]===Gn[i]&&zn[i]).map(i=>[i,zn[i]]));return{sources:o,file_types:r,targets:Object.keys(n),max_count:Gt}},vt=new Map,eo=(e,t)=>`${e}:${t}`,Dr=0,to=(e,t)=>{var n;typeof t=="string"&&((n=vt.get(eo(e,t)))==null||n.abort())},qe=e=>{for(let[t,n]of vt)t.startsWith(`${e}:`)&&n.abort()},At=()=>new g("CANCELLED","\u0110\xE3 hu\u1EF7 upload"),Nr=(e,t)=>{var n;return{name:e,code:typeof(t==null?void 0:t.code)=="string"?t.code:"UPLOAD_FAILED",message:String((n=t==null?void 0:t.message)!=null?n:t)}},no=async(e,t)=>{var l;let{sources:n,targets:o}=Zn(t.config),r=n[e.source];if(!r)throw new g("NOT_SUPPORTED",`\u1EE8ng d\u1EE5ng ch\u01B0a h\u1ED7 tr\u1EE3 ngu\u1ED3n "${e.source}"`);let i=o[e.target.target];if(!i)throw new g("NOT_SUPPORTED",`\u1EE8ng d\u1EE5ng ch\u01B0a h\u1ED7 tr\u1EE3 \u0111\xEDch upload "${e.target.target}"`);let a=new AbortController,c=eo(t.instance_id,(l=t.task_id)!=null?l:`auto-${++Dr}`);vt.set(c,a);try{return await Ur(e,t,r,i,a.signal)}finally{vt.delete(c)}},Ur=async(e,{instance_id:t,app_id:n,getContext:o,task_id:r,config:i,emit:a,exclusivePick:c=u=>u()},l,s,d)=>{var v,h,E;let u={app_id:n!=null?n:"",instance_id:t,context:{...(v=o==null?void 0:o())!=null?v:{}}},f=(await c(()=>l({accept:e.accept,max_count:e.max_count,process:e.process,caller:u}))).slice(0,e.max_count);if(d.aborted)throw At();if(!f.length)throw new g("CANCELLED","Ng\u01B0\u1EDDi d\xF9ng kh\xF4ng ch\u1ECDn file");let p=[],y=f.filter(A=>vr(A,e.accept)?!0:(p.push({name:A.name,code:"INVALID_FILE",message:`Kh\xF4ng cho ph\xE9p \u0111\u1ECBnh d\u1EA1ng ${A.mime_type||Jn(A.name)}`}),!1)),C=y.map(()=>0),x=y.map(A=>{var O;return(O=A.size)!=null?O:0}),M=0,S=0,I=(A=!1)=>{if(!a||!r)return;let O=Date.now();if(!A&&O-S<200)return;S=O;let he=x.reduce((T,ee)=>T+ee,0),j=C.reduce((T,ee)=>T+ee,0);a("upload.progress",{task_id:r,loaded:j,total:he,percent:he?Math.min(100,Math.round(j/he*100)):0,done_count:M,count:y.length})},V=[],Q=0,xe=async()=>{var A,O,he;for(;Q<y.length;){let j=Q++,T=y[j];try{if(d.aborted)throw At();let ee=T.mime_type.startsWith("image/")?"image":T.mime_type.startsWith("video/")?"video":void 0,$=ee&&!T.processed?(O=(A=i==null?void 0:i.processors)==null?void 0:A[ee])!=null?O:Lr[ee]:void 0;if($&&(T=await $(T,e.process),x[j]=(he=T.size)!=null?he:x[j],d.aborted))throw At();if(e.max_size&&T.size&&T.size>e.max_size)throw new g("FILE_TOO_LARGE",`File ${T.size} byte v\u01B0\u1EE3t gi\u1EDBi h\u1EA1n ${e.max_size}`);let X=(We,Ae)=>{C[j]=We,Ae&&(x[j]=Ae),I()},te=await s({file:T,target:e.target,onProgress:X,signal:d,caller:u});if(typeof(te==null?void 0:te.url)!="string"||!te.url)throw new g("UPLOAD_FAILED","Upload kh\xF4ng tr\u1EA3 url");let{url:_e,...Se}=te;V[j]={url:_e,name:T.name,mime_type:T.mime_type,size:T.size,width:T.width,height:T.height,duration:T.duration,...Object.keys(Se).length?{response:"response"in Se?Se.response:Se}:{}},C[j]=x[j]}catch(ee){p.push(Nr(y[j].name,ee))}finally{M++,I(!0)}}};if(await Promise.all(Array.from({length:Math.min(e.concurrency,y.length)},xe)),d.aborted)throw At();let ie=V.filter(A=>!!A);if(!ie.length){let A=p[0];throw new g((h=A==null?void 0:A.code)!=null?h:"UPLOAD_FAILED",(E=A==null?void 0:A.message)!=null?E:"Kh\xF4ng upload \u0111\u01B0\u1EE3c file n\xE0o")}return{files:ie,failed:p}};import{useRef as Vr,useSyncExternalStore as Br}from"react";var ke=e=>{let t=e,n=new Set;return{getState:()=>t,setState:o=>{let r=typeof o=="function"?o(t):o;t={...t,...r},n.forEach(i=>i())},subscribe:o=>(n.add(o),()=>{n.delete(o)})}},q=(e,t,n=Object.is)=>{let o=Vr(null),r=()=>{let i=e.getState(),a=o.current;if(a&&a.state===i&&a.selector===t)return a.value;let c=t(i),l=a&&n(a.value,c)?a.value:c;return o.current={state:i,selector:t,value:l},l};return Br(e.subscribe,r)};var fe={info:"info",success:"success",error:"error"},qr=200,oo={info:2e3,success:2e3,error:3e3},rt=ke({message:"",type:fe.info,tick:0}),ro=e=>{let{message:t,type:n}=e!=null?e:{},o=String(t!=null?t:"").trim().slice(0,qr);return o?{message:o,type:Object.values(fe).includes(n)?n:fe.info}:null},io=(e,t=fe.info)=>{rt.setState(n=>({message:e,type:t,tick:n.tick+1}))};import{Alert as zr,Linking as Wr,Platform as it,StatusBar as jr}from"react-native";import{AppState as so,Platform as Yt}from"react-native";var de,je=new Map,ao=(e,t)=>{var o;let n=(o=je.get(e))!=null?o:new Set;n.add(t),je.set(e,n)},co=(e,t)=>{let n=je.get(e);n&&(t?n.delete(t):n.clear(),n.size===0&&je.delete(e))},Xt=new Map,lo=(e,t)=>{Xt.set(e,t)},po=e=>Xt.get(e),uo=()=>Yt.OS==="android"&&!!(de!=null&&de.requesting_permission),$r=1500,Mt=()=>new Promise(e=>{if(Yt.OS!=="android"||so.currentState==="active"){e();return}let t=()=>{clearTimeout(n),o.remove(),e()},n=setTimeout(t,$r),o=so.addEventListener("change",r=>{r==="active"&&t()})}),Kt=e=>{var t;if(de===e&&(de=void 0,e.subscriptions.forEach(n=>n.remove()),e.started&&Yt.OS==="ios"))try{(t=e.native)==null||t.setAudioSessionActiveIOS(!1,{notifyOthersOnDeactivation:!0})}catch{}},go=async(e,t,n,o=()=>!0)=>{var i,a,c,l,s;if(de)throw new g("BUSY","Micro \u0111ang \u0111\u01B0\u1EE3c mini app kh\xE1c s\u1EED d\u1EE5ng");if(!o())throw new g("CANCELLED","Mini app kh\xF4ng c\xF2n ho\u1EA1t \u0111\u1ED9ng");let r={owner:e,emit:n,cancelled:!1,started:!1,subscriptions:[]};de=r;try{let d;try{d=await import("expo-speech-recognition")}catch{throw new g("NOT_SUPPORTED","Ch\u01B0a c\xF3 module nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i trong b\u1EA3n native")}let u=d.ExpoSpeechRecognitionModule;if(r.native=u,r.cancelled||!o())throw new g("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");r.requesting_permission=!0;let f;try{f=await u.requestPermissionsAsync()}finally{r.requesting_permission=!1}if(await Mt(),r.cancelled||!o())throw new g("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");if(!f.granted)throw new g("PERMISSION_DENIED","Ch\u01B0a c\u1EA5p quy\u1EC1n micro / nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i");if(await u.getStateAsync()!=="inactive")throw new g("BUSY","Nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i \u0111ang \u0111\u01B0\u1EE3c t\xEDnh n\u0103ng kh\xE1c s\u1EED d\u1EE5ng");if(r.cancelled||!o())throw new g("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");r.subscriptions.push(u.addListener("result",p=>{var y,C;de!==r||r.cancelled||n(p.isFinal?"speech.final":"speech.partial",{...p,text:(C=(y=p.results[0])==null?void 0:y.transcript)!=null?C:""})}),u.addListener("error",p=>{de===r&&!r.cancelled&&n("speech.error",{...p,code:p.error})}),u.addListener("end",()=>{de===r&&(Kt(r),n("speech.end"))})),r.started=!0,u.start({lang:(i=t.lang)!=null?i:"vi-VN",continuous:(a=t.continuous)!=null?a:!0,interimResults:(c=t.interimResults)!=null?c:!0,addsPunctuation:(l=t.addsPunctuation)!=null?l:!0,requiresOnDeviceRecognition:(s=t.requiresOnDeviceRecognition)!=null?s:!1,iosCategory:{category:d.AVAudioSessionCategory.playAndRecord,categoryOptions:[d.AVAudioSessionCategoryOptions.defaultToSpeaker,d.AVAudioSessionCategoryOptions.allowBluetooth],mode:d.AVAudioSessionMode.measurement}})}catch(d){throw Kt(r),d}},mo=e=>{let t=de;if(!(!t||t.owner!==e)){if(!t.started){t.cancelled=!0;return}t.native.stop()}},Re=e=>{Xt.delete(e);let t=je.get(e);je.delete(e),t==null||t.forEach(o=>{var r;try{(r=o.release)==null||r.call(o,e)}catch{}});let n=de;if(!(!n||n.owner!==e||n.cancelled)&&(n.cancelled=!0,n.started))try{n.native.abort()}catch{Kt(n)}};var ho={qr:"qr",ean13:"ean-13",ean8:"ean-8",upcA:"upc-a",upcE:"upc-e",code128:"code-128",code39:"code-39",code93:"code-93",codabar:"codabar",itf:"itf",pdf417:"pdf-417",aztec:"aztec",dataMatrix:"data-matrix"},re={...ho,all:Object.values(ho)},st={scan:"scanner.scan",start:"scanner.start",stop:"scanner.stop"},Qt={result:"scanner.result",end:"scanner.end"},He={user:"user",web:"web",closed:"closed",error:"error"},ge={top:"top",full:"full"},Ie={once:"once",continuous:"continuous"},Hr=1500,fo=6e4,F,J=ke({active:null,last_value:null,hit_tick:0,scan_count:0,notice:null,is_picking:!1}),wo=()=>it.OS==="android"&&!!(F!=null&&F.requesting_permission),en=e=>{let{types:t,cooldown_ms:n,hint:o,layout:r,absolute:i}=e!=null?e:{},a={};if(t!==void 0){if(!Array.isArray(t)||!t.length||!t.every(c=>re.all.includes(c)))throw new g("INVALID_PARAMS","types ph\u1EA3i l\xE0 m\u1EA3ng CodeType");a.types=t}if(n!==void 0){if(typeof n!="number"||!Number.isFinite(n)||n<0||n>fo)throw new g("INVALID_PARAMS",`cooldown_ms ph\u1EA3i t\u1EEB 0 \u0111\u1EBFn ${fo}`);a.cooldown_ms=n}if(o!==void 0){if(typeof o!="string"||!o.trim()||o.length>80)throw new g("INVALID_PARAMS","hint ph\u1EA3i c\xF3 1\u201380 k\xFD t\u1EF1");a.hint=o}if(r!==void 0){if(!Object.values(ge).includes(r))throw new g("INVALID_PARAMS","layout ph\u1EA3i l\xE0 ScannerLayout");a.layout=r}if(i!==void 0){if(typeof i!="boolean")throw new g("INVALID_PARAMS","absolute ph\u1EA3i l\xE0 boolean");a.absolute=i}return a},tn=e=>F!==e?!1:(F=void 0,J.setState({active:null,last_value:null,scan_count:0,notice:null,is_picking:!1}),!0),Jr=()=>zr.alert("Ch\u01B0a c\u1EA5p quy\u1EC1n camera","H\xE3y b\u1EADt quy\u1EC1n camera trong C\xE0i \u0111\u1EB7t \u0111\u1EC3 qu\xE9t m\xE3.",[{text:"Hu\u1EF7",style:"cancel"},{text:"M\u1EDF C\xE0i \u0111\u1EB7t",onPress:()=>{Wr.openSettings().catch(()=>{})}}]),bo=async(e,t)=>{if(F)throw new g("BUSY","Camera qu\xE9t m\xE3 \u0111ang \u0111\u01B0\u1EE3c s\u1EED d\u1EE5ng");if(!t())throw new g("CANCELLED","Mini app kh\xF4ng c\xF2n ho\u1EA1t \u0111\u1ED9ng");F=e;let n=()=>{if(e.cancelled||!t())throw new g("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng")};try{let o;try{o=await import("react-native-vision-camera")}catch{throw new g("NOT_SUPPORTED","Ch\u01B0a c\xF3 module camera trong b\u1EA3n native")}n();let r=o.Camera.getCameraPermissionStatus();if(r!=="granted"){let a=it.OS==="ios"&&r==="denied";e.requesting_permission=!0;let c;try{c=await o.Camera.requestCameraPermission()}finally{e.requesting_permission=!1}if(await Mt(),n(),c!=="granted")throw a&&Jr(),new g("PERMISSION_DENIED","Ch\u01B0a c\u1EA5p quy\u1EC1n camera")}if(!o.Camera.getAvailableCameraDevices().some(a=>a.position==="back"))throw new g("NOT_SUPPORTED","Thi\u1EBFt b\u1ECB kh\xF4ng c\xF3 camera sau");let i=await nn();n(),J.setState({active:{owner:e.owner,mode:e.mode,types:e.types,layout:e.layout,absolute:e.absolute,hint:e.hint,vision:o,glass_view:i},last_value:null,scan_count:0,notice:null})}catch(o){throw tn(e),o}},xt;import("react-native-safe-area-context").then(({initialWindowMetrics:e})=>{xt=e==null?void 0:e.insets}).catch(()=>{});var Et=()=>{var e;return xt!=null?xt:{top:it.OS==="ios"?54:(e=jr.currentHeight)!=null?e:0,bottom:it.OS==="ios"?34:48}},nn=async()=>{if(it.OS==="ios")try{let e=await import("expo-glass-effect");return e.isLiquidGlassAvailable()?e.GlassView:void 0}catch{return}},_o=(e,t,n)=>{var o,r,i,a;return{owner:e,mode:t,types:(o=n.types)!=null?o:re.all,cooldown_ms:(r=n.cooldown_ms)!=null?r:Hr,hint:n.hint,layout:t===Ie.once?ge.full:(i=n.layout)!=null?i:ge.top,absolute:t!==Ie.once&&((a=n.layout)!=null?a:ge.top)===ge.top&&n.absolute===!0,cancelled:!1,requesting_permission:!1,last_seen:new Map}},So=(e,t,n=()=>!0,o)=>new Promise((r,i)=>{let a=_o(e,Ie.once,t);a.onHit=o,a.resolve=r,a.reject=i,bo(a,n).catch(i)}),Ao=(e,t,n,o=()=>!0,r)=>{let i=_o(e,Ie.continuous,t);return i.emit=n,i.onHit=r,bo(i,o)},Rt=(e,t,n)=>{var o,r;if(!J.getState().active){e.cancelled=!0;return}if(tn(e)){if(e.mode===Ie.once){(o=e.reject)==null||o.call(e,t===He.error?new g("HOST_ERROR",n!=null?n:"L\u1ED7i camera"):new g("CANCELLED","\u0110\xE3 \u0111\xF3ng camera qu\xE9t m\xE3"));return}(r=e.emit)==null||r.call(e,Qt.end,n?{reason:t,message:n}:{reason:t})}},vo=e=>{(F==null?void 0:F.owner)===e&&Rt(F,He.web)},Le=e=>{(F==null?void 0:F.owner)===e&&Rt(F,He.closed)},on=()=>{F&&Rt(F,He.user)},Mo=e=>{F&&Rt(F,He.error,e)},rn=(e,t=Date.now(),n=!1)=>{var r,i,a;let o=F;if(!(!o||!J.getState().active))for(let{value:c,type:l}of e){if(!c)continue;let s=o.last_seen.get(c);if(o.last_seen.set(c,t),!(!n&&s!==void 0&&t-s<o.cooldown_ms)){if((r=o.onHit)==null||r.call(o),o.mode===Ie.once){tn(o),(i=o.resolve)==null||i.call(o,{value:c,type:l});return}J.setState(d=>({last_value:c,hit_tick:d.hit_tick+1,scan_count:d.scan_count+1,notice:null})),(a=o.emit)==null||a.call(o,Qt.result,{value:c,type:l})}}},Gr={1:re.code128,2:re.code39,4:re.code93,8:re.codabar,16:re.dataMatrix,32:re.ean13,64:re.ean8,128:re.itf,256:re.qr,512:re.upcA,1024:re.upcE,2048:re.pdf417,4096:re.aztec},Kr=2500,yo=2e3,Zt=e=>{J.setState({notice:e}),setTimeout(()=>{J.getState().notice===e&&J.setState({notice:null})},Kr)},xo=async()=>{var t,n;let e=F;if(!(!e||J.getState().is_picking)){e.requesting_permission=!0,J.setState({is_picking:!0,notice:null});try{let{launchImageLibrary:o}=await import("react-native-image-picker"),r=await o({mediaType:"photo",selectionLimit:1,maxWidth:yo,maxHeight:yo}),i=(n=(t=r.assets)==null?void 0:t[0])==null?void 0:n.uri;if(r.didCancel||F!==e)return;if(r.errorCode||!i){Zt("Kh\xF4ng m\u1EDF \u0111\u01B0\u1EE3c \u1EA3nh");return}let{default:a}=await import("@react-native-ml-kit/barcode-scanning"),c=await a.scan(i);if(F!==e)return;let l=c.map(({value:s,format:d})=>({value:s,code_type:Gr[d]})).filter(({code_type:s})=>!s||e.types.includes(s)).map(({value:s,code_type:d})=>({value:s,type:d!=null?d:"unknown"}));if(!l.length){Zt("Kh\xF4ng t\xECm th\u1EA5y m\xE3 trong \u1EA3nh");return}rn(l,Date.now(),!0)}catch{F===e&&Zt("Kh\xF4ng \u0111\u1ECDc \u0111\u01B0\u1EE3c m\xE3 t\u1EEB \u1EA3nh")}finally{await Mt(),e.requesting_permission=!1,F===e&&J.setState({is_picking:!1})}}};var Tt=1,g=class extends Error{constructor(n,o){super(o);this.code=n}},Ro=e=>{try{let t=JSON.parse(e);return(t==null?void 0:t.__retion)===Tt&&typeof t.method=="string"?t:null}catch{return null}},ct=e=>`window.__RETION_MINIAPP__ && window.__RETION_MINIAPP__.receive(${JSON.stringify(e)}); true;`,Po=(e,t)=>ct({id:e,result:t}),To=(e,t)=>ct({id:e,error:{code:t.code,message:t.message}}),Co=(e,t)=>ct({event:e,data:t}),an=e=>ct({event:"context",data:e});var Oo=()=>`(function () {
1
+ var et="https://retion-miniapp-platform.vercel.app",Ve=null,Fn=new Set,Sr=e=>{Ve=e,Fn.forEach(t=>t())},O=()=>{if(!Ve)throw new Error("[miniapp] Ch\u01B0a g\u1ECDi configureMiniApp()");return Ve},Dn=e=>{Fn.add(e),Ve&&e()},ue=(...e)=>{Ve!=null&&Ve.debug&&console.log("[miniapp]",...e)};var _r=(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(o=>o.map(r=>r.name)).catch(()=>[]),sha256:n=>e.hash(n,"sha256"),unzip:async(n,o)=>{await t(n,o)},download:({url:n,to_file:o,onProgress:r})=>{let{jobId:i,promise:a}=e.downloadFile({fromUrl:n,toFile:o,progressInterval:250,begin:()=>{},progress:({bytesWritten:c,contentLength:l})=>r==null?void 0:r(c,l)});return{promise:a.then(({statusCode:c})=>({status:c})),cancel:()=>e.stopDownload(i)}}}),vr=e=>({getString:t=>e.getString(t),setString:(t,n)=>e.set(t,n)});import On,{useCallback as Pn,useEffect as le,useMemo as zt,useRef as be,useState as Te}from"react";import{AppState as gr,ActivityIndicator as Hi,Animated as En,BackHandler as Ji,Image as Gi,Linking as Ki,StyleSheet as kn,Text as bt,TouchableOpacity as Yi,View as Rn}from"react-native";import Xi from"react-native-webview";import{Linking as Po,Platform as ni}from"react-native";var Nn=e=>({getAvailability:()=>e.isSensorAvailable(),authenticate:({reason:t,cancelButtonText:n})=>e.simplePrompt({promptMessage:t,cancelButtonText:n,fallbackPromptMessage:""})}),_t,Gt=()=>(_t||(_t=import("react-native-biometrics").then(({default:e})=>Nn(new e({allowDeviceCredentials:!1}))).catch(e=>{throw _t=void 0,new g("NOT_SUPPORTED",`Biometric native module unavailable: ${e instanceof Error?e.message:String(e)}`)})),_t);import{PermissionsAndroid as Be,Platform as Mr}from"react-native";var Un=e=>{var n,o,r;if(e!==void 0&&(e===null||typeof e!="object"||Array.isArray(e)))throw new g("INVALID_PARAMS","Tu\u1EF3 ch\u1ECDn v\u1ECB tr\xED ph\u1EA3i l\xE0 object");let t=e!=null?e:{};if(t.enableHighAccuracy!==void 0&&typeof t.enableHighAccuracy!="boolean")throw new g("INVALID_PARAMS","enableHighAccuracy ph\u1EA3i l\xE0 boolean");for(let[i,a,c]of[["timeout",1,6e4],["maximumAge",0,864e5]]){let l=t[i];if(l!==void 0&&(typeof l!="number"||!Number.isFinite(l)||l<a||l>c))throw new g("INVALID_PARAMS",`${i} ph\u1EA3i n\u1EB1m trong kho\u1EA3ng ${a}\u2013${c} ms`)}return{enableHighAccuracy:(n=t.enableHighAccuracy)!=null?n:!1,timeout:(o=t.timeout)!=null?o:15e3,maximumAge:(r=t.maximumAge)!=null?r:0}},Vn=(e,t=()=>!0)=>new Promise((n,o)=>{let r=!1,i=(l,s)=>{r||(r=!0,clearTimeout(a),l?o(l):n(s))},a=setTimeout(()=>i(new g("TIMEOUT","H\u1EBFt th\u1EDDi gian ch\u1EDD c\u1EA5p quy\u1EC1n/l\u1EA5y v\u1ECB tr\xED")),12e4+e.timeout),c=()=>r?!1:t()?!0:(i(new g("CANCELLED","Mini app kh\xF4ng c\xF2n ho\u1EA1t \u0111\u1ED9ng")),!1);(async()=>{if(!c())return;let l;try{l=(await import("@react-native-community/geolocation")).default}catch{throw new g("NOT_SUPPORTED","Ch\u01B0a c\xF3 module v\u1ECB tr\xED trong b\u1EA3n native")}if(c()){if(Mr.OS==="android"){let s=Be.PERMISSIONS.ACCESS_FINE_LOCATION,d=Be.PERMISSIONS.ACCESS_COARSE_LOCATION,u=await Be.check(s);if(!c())return;let y=u||await Be.check(d);if(!c())return;if(!u&&!y){let p=await Be.requestMultiple([s,d]);if(!c())return;if(p[s]!==Be.RESULTS.GRANTED&&p[d]!==Be.RESULTS.GRANTED)throw new g("PERMISSION_DENIED","Ch\u01B0a c\u1EA5p quy\u1EC1n truy c\u1EADp v\u1ECB tr\xED")}}c()&&l.getCurrentPosition(s=>{c()&&i(void 0,s)},s=>{var u;if(!c())return;let d=(u={1:"PERMISSION_DENIED",2:"POSITION_UNAVAILABLE",3:"TIMEOUT"}[s.code])!=null?u:"LOCATION_ERROR";i(new g(d,s.message))},e)}})().catch(l=>i(l))});import{Platform as Hn}from"react-native";var Kt=20,Bn=20,Jn=/^[a-z][a-z0-9_-]{0,31}$/,xr=/^(\.[\w-]{1,16}|[\w.+-]+\/(\*|[\w.+-]+))$/,Er=["low","medium","high"],Oe=e=>!!e&&typeof e=="object"&&!Array.isArray(e),H=e=>new g("INVALID_PARAMS",e),rt=(e,t,n)=>typeof e=="number"&&Number.isInteger(e)&&e>=t&&e<=n,qn=(e,t)=>{if(e===void 0)return{};if(!Oe(e)||Object.keys(e).length>Bn||Object.values(e).some(n=>typeof n!="string"))throw H(`${t} ph\u1EA3i l\xE0 object chu\u1ED7i (t\u1ED1i \u0111a ${Bn} key)`);return e},Gn=e=>{var n,o,r,i;if(e!==void 0&&!Oe(e))throw H("Tu\u1EF3 ch\u1ECDn upload ph\u1EA3i l\xE0 object");let t=e!=null?e:{};if(t.source!==void 0&&(typeof t.source!="string"||!Jn.test(t.source)))throw H("source ph\u1EA3i l\xE0 t\xEAn ngu\u1ED3n, vd library | camera | document");if(t.accept!==void 0&&(!Array.isArray(t.accept)||t.accept.length>50||t.accept.some(a=>typeof a!="string"||!xr.test(a))))throw H("accept ph\u1EA3i l\xE0 m\u1EA3ng mime (image/*, application/pdf) ho\u1EB7c \u0111u\xF4i (.docx)");if(t.max_count!==void 0&&!rt(t.max_count,1,Kt))throw H(`max_count ph\u1EA3i l\xE0 s\u1ED1 nguy\xEAn 1\u2013${Kt}`);if(t.max_size!==void 0&&!rt(t.max_size,1,Number.MAX_SAFE_INTEGER))throw H("max_size ph\u1EA3i l\xE0 s\u1ED1 byte > 0");if(t.concurrency!==void 0&&!rt(t.concurrency,1,5))throw H("concurrency ph\u1EA3i l\xE0 s\u1ED1 nguy\xEAn 1\u20135");return{source:(n=t.source)!=null?n:"library",accept:((o=t.accept)!=null?o:[]).map(a=>a.toLowerCase()),max_count:(r=t.max_count)!=null?r:1,max_size:t.max_size,process:Cr(t.process),target:Pr(t.upload),concurrency:(i=t.concurrency)!=null?i:3}},Cr=e=>{if(e===void 0)return{};if(!Oe(e))throw H("process ph\u1EA3i l\xE0 object");let t={};if(e.image!==void 0){let n=e.image;if(!Oe(n))throw H("process.image ph\u1EA3i l\xE0 object");for(let o of["max_width","max_height"])if(n[o]!==void 0&&!rt(n[o],1,1e4))throw H(`process.image.${o} ph\u1EA3i l\xE0 s\u1ED1 nguy\xEAn 1\u201310000`);if(n.quality!==void 0&&(typeof n.quality!="number"||n.quality<=0||n.quality>1))throw H("process.image.quality ph\u1EA3i trong kho\u1EA3ng (0, 1]");t.image={max_width:n.max_width,max_height:n.max_height,quality:n.quality}}if(e.video!==void 0){let n=e.video;if(!Oe(n))throw H("process.video ph\u1EA3i l\xE0 object");if(n.max_duration!==void 0&&!rt(n.max_duration,1,3600))throw H("process.video.max_duration ph\u1EA3i l\xE0 s\u1ED1 gi\xE2y 1\u20133600");if(n.quality!==void 0&&!Er.includes(n.quality))throw H("process.video.quality ph\u1EA3i l\xE0 low | medium | high");t.video={max_duration:n.max_duration,quality:n.quality}}return t},Pr=e=>{var n,o,r,i;if(e===void 0)return{target:"host",params:{}};if(!Oe(e))throw H("upload ph\u1EA3i l\xE0 object");let t=(n=e.target)!=null?n:"host";if(typeof t!="string"||!Jn.test(t))throw H("upload.target ph\u1EA3i l\xE0 t\xEAn \u0111\xEDch, vd host | url");if(t!=="url"){if(e.params!==void 0&&!Oe(e.params))throw H("upload.params ph\u1EA3i l\xE0 object");return{target:t,params:(o=e.params)!=null?o:{}}}if(typeof e.url!="string"||!/^https:\/\//i.test(e.url))throw H("upload.url ph\u1EA3i l\xE0 https");for(let a of["field_name","url_field"])if(e[a]!==void 0&&(typeof e[a]!="string"||!e[a]))throw H(`upload.${a} ph\u1EA3i l\xE0 chu\u1ED7i`);return{target:"url",url:e.url,headers:qn(e.headers,"upload.headers"),form_data:qn(e.form_data,"upload.form_data"),field_name:(r=e.field_name)!=null?r:"file",url_field:(i=e.url_field)!=null?i:"url"}},Kn=e=>{let t=e.lastIndexOf(".");return t>0?e.slice(t).toLowerCase():""},Rr=(e,t)=>{if(!t.length)return!0;let n=e.mime_type.toLowerCase(),o=Kn(e.name);return t.some(r=>r==="*/*"?!0:r.startsWith(".")?r===o:r.endsWith("/*")?n.startsWith(r.slice(0,-1)):n===r)},Tr=e=>{let t=e.length>0&&e.every(o=>o.startsWith("image/")),n=e.length>0&&e.every(o=>o.startsWith("video/"));return t?"image":n?"video":"mixed"},tt,Or=()=>(tt!=null||(tt=import("react-native-image-picker").catch(e=>{throw tt=void 0,new g("NOT_SUPPORTED",`Ch\u01B0a c\xF3 module ch\u1ECDn \u1EA3nh trong b\u1EA3n native: ${e instanceof Error?e.message:String(e)}`)})),tt),$n=e=>async({accept:t,max_count:n,process:o})=>{var l,s,d,u,y,p,f,C,x;let r=await Or(),i=Tr(t),a={mediaType:i==="image"?"photo":i,maxWidth:(l=o.image)==null?void 0:l.max_width,maxHeight:(s=o.image)==null?void 0:s.max_height,quality:(u=(d=o.image)==null?void 0:d.quality)!=null?u:.8,videoQuality:(p=(y=o.video)==null?void 0:y.quality)!=null?p:"medium",durationLimit:(f=o.video)==null?void 0:f.max_duration,assetRepresentationMode:"compatible"},c=e==="camera"?await r.launchCamera({...a,saveToPhotos:!1}):await r.launchImageLibrary({...a,selectionLimit:n});if(c.didCancel)return[];if(c.errorCode){let M=c.errorCode==="permission"?"PERMISSION_DENIED":c.errorCode==="camera_unavailable"?"NOT_SUPPORTED":"HOST_ERROR";throw new g(M,(C=c.errorMessage)!=null?C:c.errorCode)}return((x=c.assets)!=null?x:[]).filter(M=>M.uri).map((M,S)=>{var F,V,Z;return{uri:M.uri,name:(F=M.fileName)!=null?F:`file_${S+1}`,mime_type:(V=M.type)!=null?V:"application/octet-stream",size:M.fileSize,width:M.width,height:M.height,duration:M.duration,processed:!((Z=M.type)!=null&&Z.startsWith("video/"))||Hn.OS==="ios"}})},kr={"image/*":"images","video/*":"video","audio/*":"audio","text/plain":"plainText","text/csv":"csv","application/pdf":"pdf","application/json":"json","application/zip":"zip","application/msword":"doc","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"docx","application/vnd.ms-excel":"xls","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"xlsx","application/vnd.ms-powerpoint":"ppt","application/vnd.openxmlformats-officedocument.presentationml.presentation":"pptx"},Ir={".pdf":"pdf",".txt":"plainText",".csv":"csv",".json":"json",".zip":"zip",".doc":"doc",".docx":"docx",".xls":"xls",".xlsx":"xlsx",".ppt":"ppt",".pptx":"pptx"},Lr=e=>async({accept:t,max_count:n})=>{var i,a,c,l;let o=t.map(s=>{var d;return(d=kr[s])!=null?d:Ir[s]}),r=!t.length||o.some(s=>!s||!e.types[s])?e.types.allFiles:[...new Set(o)].flatMap(s=>e.types[s]);try{let d=(await e.pick({type:r,allowMultiSelection:n>1,mode:"import"})).filter(p=>p.uri&&!p.error).map((p,f)=>{var C,x,M;return{uri:p.uri,name:(C=p.name)!=null?C:`file_${f+1}`,mime_type:(x=p.type)!=null?x:"application/octet-stream",size:(M=p.size)!=null?M:void 0}});if(Hn.OS!=="android"||!e.keepLocalCopy||!d.some(p=>p.uri.startsWith("content://")))return d;let u=await e.keepLocalCopy({files:d.map(p=>({uri:p.uri,fileName:p.name})),destination:"cachesDirectory"}),y=new Map(u.map(p=>[p.sourceUri,p.status==="success"?p.localUri:void 0]));return d.map(p=>{var f;return{...p,uri:(f=y.get(p.uri))!=null?f:p.uri}})}catch(s){let d=s==null?void 0:s.code;if(d===((a=(i=e.errorCodes)==null?void 0:i.OPERATION_CANCELED)!=null?a:"OPERATION_CANCELED"))return[];throw d===((l=(c=e.errorCodes)==null?void 0:c.IN_PROGRESS)!=null?l:"ASYNC_OP_IN_PROGRESS")?new g("BUSY","\u0110ang m\u1EDF tr\xECnh ch\u1ECDn file kh\xE1c"):s}},nt,Fr=async e=>(nt!=null||(nt=import("@react-native-documents/picker").then(t=>Lr(t)).catch(t=>{throw nt=void 0,new g("NOT_SUPPORTED",`Ch\u01B0a c\xF3 module ch\u1ECDn file trong b\u1EA3n native: ${t instanceof Error?t.message:String(t)}`)})),(await nt)(e)),Yn={library:$n("library"),camera:$n("camera"),document:Fr},zn={type:"image",label:"\u1EA2nh",accept:["image/*"]},Wn={type:"video",label:"Video",accept:["video/*"]},jn={library:[zn,Wn],camera:[zn,Wn],document:[{type:"any",label:"M\u1ECDi file",accept:[]},{type:"pdf",label:"PDF",accept:["application/pdf"]},{type:"word",label:"Word",accept:[".doc",".docx"]},{type:"excel",label:"Excel",accept:[".xls",".xlsx"]},{type:"powerpoint",label:"PowerPoint",accept:[".ppt",".pptx"]}]},ot,Xn=()=>(ot!=null||(ot=import("react-native-compressor").catch(()=>(ot=void 0,null))),ot),Qn=async(e,t,n)=>{try{return Number(await e.getFileSize(t))||n}catch{return n}},Dr=new Set(["image/jpeg","image/jpg","image/heic","image/heif","image/webp"]),Nr={low:640,medium:1280,high:1920},Ur=async(e,{image:t})=>{var o;if(!t||!Dr.has(e.mime_type.toLowerCase()))return e;let n=await Xn();if(!n)return e;try{let r=await n.Image.compress(e.uri,{compressionMethod:"manual",maxWidth:t.max_width,maxHeight:t.max_height,quality:(o=t.quality)!=null?o:.8,output:"jpg"});return{...e,uri:r,mime_type:"image/jpeg",name:e.name.replace(/\.[^.]+$/,"")+".jpg",size:await Qn(n,r,e.size),processed:!0}}catch{return e}},Vr=async(e,{video:t})=>{var o;let n=await Xn();if(!n)return e;try{let r=await n.Video.compress(e.uri,{compressionMethod:"auto",maxSize:Nr[(o=t==null?void 0:t.quality)!=null?o:"medium"],minimumFileSizeForCompress:2});return{...e,uri:r,mime_type:"video/mp4",size:await Qn(n,r,e.size),processed:!0}}catch{return e}},Br={image:Ur,video:Vr},qr=(e,t)=>t.split(".").reduce((n,o)=>Oe(n)?n[o]:void 0,e),Zn=({file:e,target:t,onProgress:n,signal:o})=>new Promise((r,i)=>{if(t.target!=="url"||!("url"in t)){i(new g("INVALID_PARAMS","Thi\u1EBFu upload.url"));return}let a=t;if(o.aborted){i(new g("CANCELLED","\u0110\xE3 hu\u1EF7 upload"));return}let c=new XMLHttpRequest,l=new FormData;Object.entries(a.form_data).forEach(([u,y])=>l.append(u,y)),l.append(a.field_name,{uri:e.uri,name:e.name,type:e.mime_type});let s=()=>c.abort();o.addEventListener("abort",s);let d=u=>{o.removeEventListener("abort",s),u()};c.open("POST",a.url),Object.entries(a.headers).forEach(([u,y])=>c.setRequestHeader(u,y)),c.upload.onprogress=u=>n(u.loaded,u.total||e.size||0),c.onload=()=>d(()=>{let u=c.responseText;try{u=JSON.parse(c.responseText)}catch{}if(c.status<200||c.status>=300){i(new g("UPLOAD_FAILED",`HTTP ${c.status}`));return}let y=qr(u,a.url_field);if(typeof y!="string"||!y){i(new g("UPLOAD_FAILED",`Response kh\xF4ng c\xF3 "${a.url_field}"`));return}r({url:y,response:u})}),c.onerror=()=>d(()=>i(new g("UPLOAD_FAILED","L\u1ED7i m\u1EA1ng khi upload"))),c.onabort=()=>d(()=>i(new g("CANCELLED","\u0110\xE3 hu\u1EF7 upload"))),c.send(l)}),eo=e=>{var o,r;let t={...Yn};for(let[i,a]of Object.entries((o=e==null?void 0:e.sources)!=null?o:{}))a?t[i]=a:delete t[i];let n={url:Zn};for(let[i,a]of Object.entries((r=e==null?void 0:e.targets)!=null?r:{}))i!=="url"&&a&&(n[i]=a);return{sources:t,targets:n}},to=e=>{let{sources:t,targets:n}=eo(e),o=Object.keys(t),r=Object.fromEntries(o.filter(i=>t[i]===Yn[i]&&jn[i]).map(i=>[i,jn[i]]));return{sources:o,file_types:r,targets:Object.keys(n),max_count:Kt}},Mt=new Map,no=(e,t)=>`${e}:${t}`,$r=0,oo=(e,t)=>{var n;typeof t=="string"&&((n=Mt.get(no(e,t)))==null||n.abort())},qe=e=>{for(let[t,n]of Mt)t.startsWith(`${e}:`)&&n.abort()},vt=()=>new g("CANCELLED","\u0110\xE3 hu\u1EF7 upload"),zr=(e,t)=>{var n;return{name:e,code:typeof(t==null?void 0:t.code)=="string"?t.code:"UPLOAD_FAILED",message:String((n=t==null?void 0:t.message)!=null?n:t)}},ro=async(e,t)=>{var l;let{sources:n,targets:o}=eo(t.config),r=n[e.source];if(!r)throw new g("NOT_SUPPORTED",`\u1EE8ng d\u1EE5ng ch\u01B0a h\u1ED7 tr\u1EE3 ngu\u1ED3n "${e.source}"`);let i=o[e.target.target];if(!i)throw new g("NOT_SUPPORTED",`\u1EE8ng d\u1EE5ng ch\u01B0a h\u1ED7 tr\u1EE3 \u0111\xEDch upload "${e.target.target}"`);let a=new AbortController,c=no(t.instance_id,(l=t.task_id)!=null?l:`auto-${++$r}`);Mt.set(c,a);try{return await Wr(e,t,r,i,a.signal)}finally{Mt.delete(c)}},Wr=async(e,{instance_id:t,app_id:n,getContext:o,task_id:r,config:i,emit:a,exclusivePick:c=u=>u()},l,s,d)=>{var v,m,E;let u={app_id:n!=null?n:"",instance_id:t,context:{...(v=o==null?void 0:o())!=null?v:{}}},y=(await c(()=>l({accept:e.accept,max_count:e.max_count,process:e.process,caller:u}))).slice(0,e.max_count);if(d.aborted)throw vt();if(!y.length)throw new g("CANCELLED","Ng\u01B0\u1EDDi d\xF9ng kh\xF4ng ch\u1ECDn file");let p=[],f=y.filter(_=>Rr(_,e.accept)?!0:(p.push({name:_.name,code:"INVALID_FILE",message:`Kh\xF4ng cho ph\xE9p \u0111\u1ECBnh d\u1EA1ng ${_.mime_type||Kn(_.name)}`}),!1)),C=f.map(()=>0),x=f.map(_=>{var I;return(I=_.size)!=null?I:0}),M=0,S=0,F=(_=!1)=>{if(!a||!r)return;let I=Date.now();if(!_&&I-S<200)return;S=I;let me=x.reduce((T,ee)=>T+ee,0),j=C.reduce((T,ee)=>T+ee,0);a("upload.progress",{task_id:r,loaded:j,total:me,percent:me?Math.min(100,Math.round(j/me*100)):0,done_count:M,count:f.length})},V=[],Z=0,xe=async()=>{var _,I,me;for(;Z<f.length;){let j=Z++,T=f[j];try{if(d.aborted)throw vt();let ee=T.mime_type.startsWith("image/")?"image":T.mime_type.startsWith("video/")?"video":void 0,$=ee&&!T.processed?(I=(_=i==null?void 0:i.processors)==null?void 0:_[ee])!=null?I:Br[ee]:void 0;if($&&(T=await $(T,e.process),x[j]=(me=T.size)!=null?me:x[j],d.aborted))throw vt();if(e.max_size&&T.size&&T.size>e.max_size)throw new g("FILE_TOO_LARGE",`File ${T.size} byte v\u01B0\u1EE3t gi\u1EDBi h\u1EA1n ${e.max_size}`);let X=(We,_e)=>{C[j]=We,_e&&(x[j]=_e),F()},te=await s({file:T,target:e.target,onProgress:X,signal:d,caller:u});if(typeof(te==null?void 0:te.url)!="string"||!te.url)throw new g("UPLOAD_FAILED","Upload kh\xF4ng tr\u1EA3 url");let{url:Ae,...Se}=te;V[j]={url:Ae,name:T.name,mime_type:T.mime_type,size:T.size,width:T.width,height:T.height,duration:T.duration,...Object.keys(Se).length?{response:"response"in Se?Se.response:Se}:{}},C[j]=x[j]}catch(ee){p.push(zr(f[j].name,ee))}finally{M++,F(!0)}}};if(await Promise.all(Array.from({length:Math.min(e.concurrency,f.length)},xe)),d.aborted)throw vt();let ie=V.filter(_=>!!_);if(!ie.length){let _=p[0];throw new g((m=_==null?void 0:_.code)!=null?m:"UPLOAD_FAILED",(E=_==null?void 0:_.message)!=null?E:"Kh\xF4ng upload \u0111\u01B0\u1EE3c file n\xE0o")}return{files:ie,failed:p}};import{useRef as jr,useSyncExternalStore as Hr}from"react";var ke=e=>{let t=e,n=new Set;return{getState:()=>t,setState:o=>{let r=typeof o=="function"?o(t):o;t={...t,...r},n.forEach(i=>i())},subscribe:o=>(n.add(o),()=>{n.delete(o)})}},q=(e,t,n=Object.is)=>{let o=jr(null),r=()=>{let i=e.getState(),a=o.current;if(a&&a.state===i&&a.selector===t)return a.value;let c=t(i),l=a&&n(a.value,c)?a.value:c;return o.current={state:i,selector:t,value:l},l};return Hr(e.subscribe,r)};var fe={info:"info",success:"success",error:"error"},Jr=200,io={info:2e3,success:2e3,error:3e3},it=ke({message:"",type:fe.info,tick:0}),so=e=>{let{message:t,type:n}=e!=null?e:{},o=String(t!=null?t:"").trim().slice(0,Jr);return o?{message:o,type:Object.values(fe).includes(n)?n:fe.info}:null},ao=(e,t=fe.info)=>{it.setState(n=>({message:e,type:t,tick:n.tick+1}))};import{Alert as Kr,Linking as Yr,Platform as st,StatusBar as Xr}from"react-native";import{AppState as co,Platform as Xt}from"react-native";var de,je=new Map,lo=(e,t)=>{var o;let n=(o=je.get(e))!=null?o:new Set;n.add(t),je.set(e,n)},po=(e,t)=>{let n=je.get(e);n&&(t?n.delete(t):n.clear(),n.size===0&&je.delete(e))},Qt=new Map,uo=(e,t)=>{Qt.set(e,t)},go=e=>Qt.get(e),ho=()=>Xt.OS==="android"&&!!(de!=null&&de.requesting_permission),Gr=1500,xt=()=>new Promise(e=>{if(Xt.OS!=="android"||co.currentState==="active"){e();return}let t=()=>{clearTimeout(n),o.remove(),e()},n=setTimeout(t,Gr),o=co.addEventListener("change",r=>{r==="active"&&t()})}),Yt=e=>{var t;if(de===e&&(de=void 0,e.subscriptions.forEach(n=>n.remove()),e.started&&Xt.OS==="ios"))try{(t=e.native)==null||t.setAudioSessionActiveIOS(!1,{notifyOthersOnDeactivation:!0})}catch{}},mo=async(e,t,n,o=()=>!0)=>{var i,a,c,l,s;if(de)throw new g("BUSY","Micro \u0111ang \u0111\u01B0\u1EE3c mini app kh\xE1c s\u1EED d\u1EE5ng");if(!o())throw new g("CANCELLED","Mini app kh\xF4ng c\xF2n ho\u1EA1t \u0111\u1ED9ng");let r={owner:e,emit:n,cancelled:!1,started:!1,subscriptions:[]};de=r;try{let d;try{d=await import("expo-speech-recognition")}catch{throw new g("NOT_SUPPORTED","Ch\u01B0a c\xF3 module nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i trong b\u1EA3n native")}let u=d.ExpoSpeechRecognitionModule;if(r.native=u,r.cancelled||!o())throw new g("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");r.requesting_permission=!0;let y;try{y=await u.requestPermissionsAsync()}finally{r.requesting_permission=!1}if(await xt(),r.cancelled||!o())throw new g("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");if(!y.granted)throw new g("PERMISSION_DENIED","Ch\u01B0a c\u1EA5p quy\u1EC1n micro / nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i");if(await u.getStateAsync()!=="inactive")throw new g("BUSY","Nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i \u0111ang \u0111\u01B0\u1EE3c t\xEDnh n\u0103ng kh\xE1c s\u1EED d\u1EE5ng");if(r.cancelled||!o())throw new g("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");r.subscriptions.push(u.addListener("result",p=>{var f,C;de!==r||r.cancelled||n(p.isFinal?"speech.final":"speech.partial",{...p,text:(C=(f=p.results[0])==null?void 0:f.transcript)!=null?C:""})}),u.addListener("error",p=>{de===r&&!r.cancelled&&n("speech.error",{...p,code:p.error})}),u.addListener("end",()=>{de===r&&(Yt(r),n("speech.end"))})),r.started=!0,u.start({lang:(i=t.lang)!=null?i:"vi-VN",continuous:(a=t.continuous)!=null?a:!0,interimResults:(c=t.interimResults)!=null?c:!0,addsPunctuation:(l=t.addsPunctuation)!=null?l:!0,requiresOnDeviceRecognition:(s=t.requiresOnDeviceRecognition)!=null?s:!1,iosCategory:{category:d.AVAudioSessionCategory.playAndRecord,categoryOptions:[d.AVAudioSessionCategoryOptions.defaultToSpeaker,d.AVAudioSessionCategoryOptions.allowBluetooth],mode:d.AVAudioSessionMode.measurement}})}catch(d){throw Yt(r),d}},fo=e=>{let t=de;if(!(!t||t.owner!==e)){if(!t.started){t.cancelled=!0;return}t.native.stop()}},Ce=e=>{Qt.delete(e);let t=je.get(e);je.delete(e),t==null||t.forEach(o=>{var r;try{(r=o.release)==null||r.call(o,e)}catch{}});let n=de;if(!(!n||n.owner!==e||n.cancelled)&&(n.cancelled=!0,n.started))try{n.native.abort()}catch{Yt(n)}};var yo={qr:"qr",ean13:"ean-13",ean8:"ean-8",upcA:"upc-a",upcE:"upc-e",code128:"code-128",code39:"code-39",code93:"code-93",codabar:"codabar",itf:"itf",pdf417:"pdf-417",aztec:"aztec",dataMatrix:"data-matrix"},re={...yo,all:Object.values(yo)},at={scan:"scanner.scan",start:"scanner.start",stop:"scanner.stop"},en={result:"scanner.result",end:"scanner.end"},He={user:"user",web:"web",closed:"closed",error:"error"},ge={top:"top",full:"full"},Ie={once:"once",continuous:"continuous"},Qr=1500,wo=6e4,N,J=ke({active:null,last_value:null,hit_tick:0,scan_count:0,notice:null,is_picking:!1}),Ao=()=>st.OS==="android"&&!!(N!=null&&N.requesting_permission),tn=e=>{let{types:t,cooldown_ms:n,hint:o,layout:r,absolute:i}=e!=null?e:{},a={};if(t!==void 0){if(!Array.isArray(t)||!t.length||!t.every(c=>re.all.includes(c)))throw new g("INVALID_PARAMS","types ph\u1EA3i l\xE0 m\u1EA3ng CodeType");a.types=t}if(n!==void 0){if(typeof n!="number"||!Number.isFinite(n)||n<0||n>wo)throw new g("INVALID_PARAMS",`cooldown_ms ph\u1EA3i t\u1EEB 0 \u0111\u1EBFn ${wo}`);a.cooldown_ms=n}if(o!==void 0){if(typeof o!="string"||!o.trim()||o.length>80)throw new g("INVALID_PARAMS","hint ph\u1EA3i c\xF3 1\u201380 k\xFD t\u1EF1");a.hint=o}if(r!==void 0){if(!Object.values(ge).includes(r))throw new g("INVALID_PARAMS","layout ph\u1EA3i l\xE0 ScannerLayout");a.layout=r}if(i!==void 0){if(typeof i!="boolean")throw new g("INVALID_PARAMS","absolute ph\u1EA3i l\xE0 boolean");a.absolute=i}return a},nn=e=>N!==e?!1:(N=void 0,J.setState({active:null,last_value:null,scan_count:0,notice:null,is_picking:!1}),!0),Zr=()=>Kr.alert("Ch\u01B0a c\u1EA5p quy\u1EC1n camera","H\xE3y b\u1EADt quy\u1EC1n camera trong C\xE0i \u0111\u1EB7t \u0111\u1EC3 qu\xE9t m\xE3.",[{text:"Hu\u1EF7",style:"cancel"},{text:"M\u1EDF C\xE0i \u0111\u1EB7t",onPress:()=>{Yr.openSettings().catch(()=>{})}}]),So=async(e,t)=>{if(N)throw new g("BUSY","Camera qu\xE9t m\xE3 \u0111ang \u0111\u01B0\u1EE3c s\u1EED d\u1EE5ng");if(!t())throw new g("CANCELLED","Mini app kh\xF4ng c\xF2n ho\u1EA1t \u0111\u1ED9ng");N=e;let n=()=>{if(e.cancelled||!t())throw new g("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng")};try{let o;try{o=await import("react-native-vision-camera")}catch{throw new g("NOT_SUPPORTED","Ch\u01B0a c\xF3 module camera trong b\u1EA3n native")}n();let r=o.Camera.getCameraPermissionStatus();if(r!=="granted"){let a=st.OS==="ios"&&r==="denied";e.requesting_permission=!0;let c;try{c=await o.Camera.requestCameraPermission()}finally{e.requesting_permission=!1}if(await xt(),n(),c!=="granted")throw a&&Zr(),new g("PERMISSION_DENIED","Ch\u01B0a c\u1EA5p quy\u1EC1n camera")}if(!o.Camera.getAvailableCameraDevices().some(a=>a.position==="back"))throw new g("NOT_SUPPORTED","Thi\u1EBFt b\u1ECB kh\xF4ng c\xF3 camera sau");let i=await on();n(),J.setState({active:{owner:e.owner,mode:e.mode,types:e.types,layout:e.layout,absolute:e.absolute,hint:e.hint,vision:o,glass_view:i},last_value:null,scan_count:0,notice:null})}catch(o){throw nn(e),o}},Et;import("react-native-safe-area-context").then(({initialWindowMetrics:e})=>{Et=e==null?void 0:e.insets}).catch(()=>{});var Ct=()=>{var e;return Et!=null?Et:{top:st.OS==="ios"?54:(e=Xr.currentHeight)!=null?e:0,bottom:st.OS==="ios"?34:48}},on=async()=>{if(st.OS==="ios")try{let e=await import("expo-glass-effect");return e.isLiquidGlassAvailable()?e.GlassView:void 0}catch{return}},_o=(e,t,n)=>{var o,r,i,a;return{owner:e,mode:t,types:(o=n.types)!=null?o:re.all,cooldown_ms:(r=n.cooldown_ms)!=null?r:Qr,hint:n.hint,layout:t===Ie.once?ge.full:(i=n.layout)!=null?i:ge.top,absolute:t!==Ie.once&&((a=n.layout)!=null?a:ge.top)===ge.top&&n.absolute===!0,cancelled:!1,requesting_permission:!1,last_seen:new Map}},vo=(e,t,n=()=>!0,o)=>new Promise((r,i)=>{let a=_o(e,Ie.once,t);a.onHit=o,a.resolve=r,a.reject=i,So(a,n).catch(i)}),Mo=(e,t,n,o=()=>!0,r)=>{let i=_o(e,Ie.continuous,t);return i.emit=n,i.onHit=r,So(i,o)},Pt=(e,t,n)=>{var o,r;if(!J.getState().active){e.cancelled=!0;return}if(nn(e)){if(e.mode===Ie.once){(o=e.reject)==null||o.call(e,t===He.error?new g("HOST_ERROR",n!=null?n:"L\u1ED7i camera"):new g("CANCELLED","\u0110\xE3 \u0111\xF3ng camera qu\xE9t m\xE3"));return}(r=e.emit)==null||r.call(e,en.end,n?{reason:t,message:n}:{reason:t})}},xo=e=>{(N==null?void 0:N.owner)===e&&Pt(N,He.web)},Le=e=>{(N==null?void 0:N.owner)===e&&Pt(N,He.closed)},rn=()=>{N&&Pt(N,He.user)},Eo=e=>{N&&Pt(N,He.error,e)},sn=(e,t=Date.now(),n=!1)=>{var r,i,a;let o=N;if(!(!o||!J.getState().active))for(let{value:c,type:l}of e){if(!c)continue;let s=o.last_seen.get(c);if(o.last_seen.set(c,t),!(!n&&s!==void 0&&t-s<o.cooldown_ms)){if((r=o.onHit)==null||r.call(o),o.mode===Ie.once){nn(o),(i=o.resolve)==null||i.call(o,{value:c,type:l});return}J.setState(d=>({last_value:c,hit_tick:d.hit_tick+1,scan_count:d.scan_count+1,notice:null})),(a=o.emit)==null||a.call(o,en.result,{value:c,type:l})}}},ei={1:re.code128,2:re.code39,4:re.code93,8:re.codabar,16:re.dataMatrix,32:re.ean13,64:re.ean8,128:re.itf,256:re.qr,512:re.upcA,1024:re.upcE,2048:re.pdf417,4096:re.aztec},ti=2500,bo=2e3,Zt=e=>{J.setState({notice:e}),setTimeout(()=>{J.getState().notice===e&&J.setState({notice:null})},ti)},Co=async()=>{var t,n;let e=N;if(!(!e||J.getState().is_picking)){e.requesting_permission=!0,J.setState({is_picking:!0,notice:null});try{let{launchImageLibrary:o}=await import("react-native-image-picker"),r=await o({mediaType:"photo",selectionLimit:1,maxWidth:bo,maxHeight:bo}),i=(n=(t=r.assets)==null?void 0:t[0])==null?void 0:n.uri;if(r.didCancel||N!==e)return;if(r.errorCode||!i){Zt("Kh\xF4ng m\u1EDF \u0111\u01B0\u1EE3c \u1EA3nh");return}let{default:a}=await import("@react-native-ml-kit/barcode-scanning"),c=await a.scan(i);if(N!==e)return;let l=c.map(({value:s,format:d})=>({value:s,code_type:ei[d]})).filter(({code_type:s})=>!s||e.types.includes(s)).map(({value:s,code_type:d})=>({value:s,type:d!=null?d:"unknown"}));if(!l.length){Zt("Kh\xF4ng t\xECm th\u1EA5y m\xE3 trong \u1EA3nh");return}sn(l,Date.now(),!0)}catch{N===e&&Zt("Kh\xF4ng \u0111\u1ECDc \u0111\u01B0\u1EE3c m\xE3 t\u1EEB \u1EA3nh")}finally{await xt(),e.requesting_permission=!1,N===e&&J.setState({is_picking:!1})}}};var Tt=1,g=class extends Error{constructor(n,o){super(o);this.code=n}},Ro=e=>{try{let t=JSON.parse(e);return(t==null?void 0:t.__retion)===Tt&&typeof t.method=="string"?t:null}catch{return null}},lt=e=>`window.__RETION_MINIAPP__ && window.__RETION_MINIAPP__.receive(${JSON.stringify(e)}); true;`,To=(e,t)=>lt({id:e,result:t}),Oo=(e,t)=>lt({id:e,error:{code:t.code,message:t.message}}),ko=(e,t)=>lt({event:e,data:t}),cn=e=>lt({event:"context",data:e});var Io=()=>`(function () {
2
2
  var post = function (level, args) {
3
3
  try {
4
4
  var parts = [];
@@ -19,7 +19,7 @@ var Ht="https://retion-miniapp-platform.vercel.app",Ve=null,In=new Set,hr=e=>{Ve
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;`,ko=()=>`(function () {
22
+ })(); true;`,Lo=()=>`(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; }
@@ -38,7 +38,7 @@ var Ht="https://retion-miniapp-platform.vercel.app",Ve=null,In=new Set,hr=e=>{Ve
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;`,Io=()=>`(function () {
41
+ })(); true;`,Fo=()=>`(function () {
42
42
  if (window.__retionSafeAreaFrozen) { return; }
43
43
  window.__retionSafeAreaFrozen = true;
44
44
  var max = {};
@@ -59,14 +59,14 @@ var Ht="https://retion-miniapp-platform.vercel.app",Ve=null,In=new Set,hr=e=>{Ve
59
59
  },
60
60
  });
61
61
  };
62
- })(); true;`,Lo=e=>ct({event:e}),Fo=(e,t)=>{let n=Do(t);return`try { history.replaceState(history.state, '', location.pathname + ${JSON.stringify(n?`?${n}`:"")} + location.hash); } catch (e) {}
63
- ${an(e)}`},Do=e=>Object.entries(e).filter(([,t])=>t!=null&&t!=="").map(([t,n])=>`${encodeURIComponent(t)}=${encodeURIComponent(String(n))}`).join("&"),No=(e,t={})=>{let n=Do(t);return`window.__RETION_MINIAPP_HOST__ = { protocol: ${Tt} };
62
+ })(); true;`,Do=e=>lt({event:e}),No=(e,t)=>{let n=Uo(t);return`try { history.replaceState(history.state, '', location.pathname + ${JSON.stringify(n?`?${n}`:"")} + location.hash); } catch (e) {}
63
+ ${cn(e)}`},Uo=e=>Object.entries(e).filter(([,t])=>t!=null&&t!=="").map(([t,n])=>`${encodeURIComponent(t)}=${encodeURIComponent(String(n))}`).join("&"),Vo=(e,t={})=>{let n=Uo(t);return`window.__RETION_MINIAPP_HOST__ = { protocol: ${Tt} };
64
64
  window.__RETION_MINIAPP_CONTEXT__ = ${JSON.stringify(e)};
65
65
  ${n?`try { history.replaceState(history.state, '', location.pathname + '?' + ${JSON.stringify(n)} + location.hash); } catch (e) {}`:""}
66
- true;`},Uo={partner:"partner_token",chatbox:"chatbox_token"},Vo=(e,t)=>{let n={...e};for(let o of Object.values(Uo))t.includes(o)||delete n[o];return n},sn=new Set,at=async(e,t)=>{if(sn.has(e))throw new g("BUSY",`${e} \u0111ang ch\u1EA1y \u2014 ch\u1EDD l\u01B0\u1EE3t tr\u01B0\u1EDBc xong`);sn.add(e);try{return await t()}finally{sn.delete(e)}},cn=e=>`(function () {
66
+ true;`},Bo={partner:"partner_token",chatbox:"chatbox_token"},qo=(e,t)=>{let n={...e};for(let o of Object.values(Bo))t.includes(o)||delete n[o];return n},an=new Set,ct=async(e,t)=>{if(an.has(e))throw new g("BUSY",`${e} \u0111ang ch\u1EA1y \u2014 ch\u1EDD l\u01B0\u1EE3t tr\u01B0\u1EDBc xong`);an.add(e);try{return await t()}finally{an.delete(e)}},ln=e=>`(function () {
67
67
  window.__retionScannerHeight = ${Math.max(0,Math.round(e))};
68
68
  window.dispatchEvent(new Event('retionscannerheight'));
69
- })(); true;`,Bo=()=>`(function () {
69
+ })(); true;`,$o=()=>`(function () {
70
70
  try {
71
71
  var AudioCtx = window.AudioContext || window.webkitAudioContext;
72
72
  if (!AudioCtx) { return; }
@@ -85,4 +85,4 @@ var Ht="https://retion-miniapp-platform.vercel.app",Ve=null,In=new Set,hr=e=>{Ve
85
85
  // iOS c\xF3 th\u1EC3 \u0111\u1EC3 context \u1EDF suspended / interrupted (vd. khi camera m\u1EDF phi\xEAn quay): ch\u1EA1y l\u1EA1i xong m\u1EDBi ph\xE1t.
86
86
  if (ctx.state === 'running') { play(); } else { ctx.resume().then(play).catch(function () {}); }
87
87
  } catch (e) {}
88
- })(); true;`,Xr=new Set(["selection","impactLight","impactMedium","impactHeavy","rigid","soft","notificationSuccess","notificationWarning","notificationError"]),Pt=(e,t)=>{if(typeof e!="string"||!e)throw new g("INVALID_PARAMS",`Thi\u1EBFu ${t}`);return e},qo=async({method:e,params:t},{getHostData:n,getPermissions:o,getContext:r,is_dark:i,close:a,app_id:c,instance_id:l,options:s,emit:d,isActive:u,playBeep:f})=>{var M,S,I,V,Q,xe,ie,v;let p=s==null?void 0:s.handlers,y={app_id:c,instance_id:l,close:a},C=()=>{var h;(h=s==null?void 0:s.haptic)==null||h.call(s,"impactLight"),f==null||f()},x=()=>new g("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF \u1EE9ng d\u1EE5ng n\xE0y`);switch(e){case"getCurrentLocation":{let h=Dn(t);return at(e,()=>Nn(h,u))}case"speech.start":{if(!d)throw x();let h={};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 g("INVALID_PARAMS","lang ph\u1EA3i l\xE0 m\xE3 ng\xF4n ng\u1EEF nh\u01B0 vi-VN");h.lang=t.lang}for(let O of["continuous","interimResults","addsPunctuation","requiresOnDeviceRecognition"])if((t==null?void 0:t[O])!==void 0){if(typeof t[O]!="boolean")throw new g("INVALID_PARAMS",`${O} ph\u1EA3i l\xE0 boolean`);h[O]=t[O]}if((t==null?void 0:t.mode)!==void 0&&t.mode!=="s2t"&&t.mode!=="voice")throw new g("INVALID_PARAMS","mode ph\u1EA3i l\xE0 's2t' ho\u1EB7c 'voice'");let E=(t==null?void 0:t.mode)==="s2t"?"s2t":"voice",A=E==="voice"?(M=s==null?void 0:s.voice)!=null?M:s==null?void 0:s.speech:void 0;if(lo(l,A),A){ao(l,A);try{return await A.start({owner:l,app_id:c,mode:E,options:h,emit:d,isActive:u!=null?u:(()=>!0)})}catch(O){throw co(l,A),O}}return go(l,h,d,u)}case"speech.stop":{let h=po(l);return h?h.stop(l):mo(l)}case st.scan:return So(l,en(t),u,C);case st.start:{if(!d)throw x();return Ao(l,en(t),d,u,C)}case st.stop:return vo(l);case"uploadFiles":{let{task_id:h,...E}=t!=null?t:{};if(h!==void 0&&(typeof h!="string"||!h))throw new g("INVALID_PARAMS","task_id ph\u1EA3i l\xE0 chu\u1ED7i");return no(Hn(E),{instance_id:l,app_id:c,getContext:r,task_id:h,config:s==null?void 0:s.upload,emit:d,exclusivePick:A=>at("uploadFiles.pick",A)})}case"uploadFiles.cancel":to(l,t==null?void 0:t.task_id);return;case"getUploadCapabilities":return Qn(s==null?void 0:s.upload);case"getBiometricAvailability":return((S=s==null?void 0:s.biometrics)!=null?S:await Jt()).getAvailability();case"authenticateBiometric":{let h=Pt(t==null?void 0:t.reason,"reason").trim();if(!h||h.length>200)throw new g("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 g("INVALID_PARAMS","Invalid cancelButtonText");return at(e,async()=>{var O;return((O=s==null?void 0:s.biometrics)!=null?O:await Jt()).authenticate({reason:h,cancelButtonText:E})})}case"requestPayment":{let h=p==null?void 0:p.requestPayment;if(!h)throw x();let E=t==null?void 0:t.amount;if(typeof E!="number"||!Number.isFinite(E)||E<=0)throw new g("INVALID_PARAMS","amount ph\u1EA3i l\xE0 s\u1ED1 > 0");let A={...t,amount:E,currency:Pt(t==null?void 0:t.currency,"currency")};return at(e,()=>h(A,y))}case"printImage":{let h=p==null?void 0:p.printImage;if(!h)throw x();let E=Pt(t==null?void 0:t.image,"image");await at(e,()=>h({image:E},y));return}case"openScreen":if(!(p!=null&&p.openScreen))throw x();await p.openScreen({screen:Pt(t==null?void 0:t.screen,"screen"),params:t==null?void 0:t.params},y);return;case"closeApp":a();return;case"openWebview":{let h=String((I=t==null?void 0:t.url)!=null?I:"");if(!/^https?:\/\//i.test(h))throw new g("INVALID_PARAMS","url ph\u1EA3i l\xE0 http(s)");await(s!=null&&s.openUrl?s.openUrl(h):Eo.openURL(h));return}case"openLink":{let h=String((V=t==null?void 0:t.url)!=null?V:"").trim();if(!/^[a-z][a-z0-9+.-]*:/i.test(h)||/^(javascript|file|data|about|blob):/i.test(h))throw new g("INVALID_PARAMS","url kh\xF4ng h\u1EE3p l\u1EC7");try{await(s!=null&&s.openUrl?s.openUrl(h):Eo.openURL(h))}catch(E){throw new g("NOT_SUPPORTED",String((xe=(Q=E==null?void 0:E.message)!=null?Q:E)!=null?xe:"Kh\xF4ng m\u1EDF \u0111\u01B0\u1EE3c link"))}return}case"showToast":{let h=ro(t);if(!h||(u==null?void 0:u())===!1)return;s!=null&&s.showToast?s.showToast(h.message,{type:h.type}):io(h.message,h.type);return}case"haptic":{let h=Xr.has(t==null?void 0:t.type)?t.type:"selection";(ie=s==null?void 0:s.haptic)==null||ie.call(s,h);return}case"getSystemInfo":return{platform:Yr.OS==="ios"?"ios":"android",appVersion:(v=s==null?void 0:s.app_version)!=null?v:"",theme:i?"dark":"light"};case"getAccessToken":{let h=n().access_token;if(!h)throw new g("HOST_ERROR","Mini app ch\u01B0a c\xF3 token cho page n\xE0y");return h}case"getToken":{let h=t==null?void 0:t.type;if(h==="access"){let O=n().access_token;if(!O)throw new g("HOST_ERROR","Mini app ch\u01B0a c\xF3 token cho page n\xE0y");return O}if(h!=="partner"&&h!=="chatbox")throw new g("HOST_ERROR",`Lo\u1EA1i token kh\xF4ng h\u1EE3p l\u1EC7: ${String(h)}`);let E=Uo[h];if(!o().includes(E))throw new g("PERMISSION_DENIED",`Mini app ch\u01B0a \u0111\u01B0\u1EE3c c\u1EA5p quy\u1EC1n ${E} (Console \u2192 Quy\u1EC1n l\u1EA5y token)`);let A=h==="partner"?n().partner_token:n().chatbox_token;if(!A)throw new g("HOST_ERROR",`Kh\xF4ng c\xF3 ${E}`);return A}case"getUserInfo":{let h=n().user;if(!h)throw new g("HOST_ERROR","Kh\xF4ng l\u1EA5y \u0111\u01B0\u1EE3c th\xF4ng tin nh\xE2n vi\xEAn");return h}case"getPageInfo":{let h=n().page;if(!h)throw new g("HOST_ERROR","Kh\xF4ng l\u1EA5y \u0111\u01B0\u1EE3c th\xF4ng tin page");return h}case"sendMessage":case"insertText":throw new g("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF phi\xEAn b\u1EA3n app n\xE0y`);default:throw new g("NOT_SUPPORTED",`API kh\xF4ng t\u1ED3n t\u1EA1i: ${e}`)}};var pn=e=>`bundle:${e}`,un=()=>`${N().file_system.document_dir}/miniapps`,dn=un,gn=(e,t,n="index.html",o=!1,r=[])=>{let i=`${dn()}/${e}/${t}`;return{app_id:e,version:t,dir:i,entry_uri:`file://${i}/${n}`,context_update:o,permissions:r}},ln=e=>{var t;N().storage.setString(pn(e.app_id),JSON.stringify({version:e.version,entry:e.entry,context_update:!!e.context_update,permissions:(t=e.permissions)!=null?t:[]}))},Zr=(e,t)=>/^https?:\/\//.test(t)?t:`${e.replace(/[^/]*$/,"")}${t}`,D=e=>{let t=N().storage.getString(pn(e));if(!t)return null;try{let{version:n,entry:o,context_update:r,permissions:i}=JSON.parse(t);return gn(e,n,o,!!r,Array.isArray(i)?i:[])}catch{return null}},Pe=e=>N().file_system.exists(e.entry_uri.replace("file://","")),mn=async e=>{let t=D(e.app_id);return(t==null?void 0:t.version)===e.version&&await Pe(t)},zo=async(e,t)=>{let n=N().file_system,o=`${dn()}/${e}`,r=await n.listDir(o).catch(()=>[]);await Promise.all(r.filter(i=>!t.includes(i)).map(i=>n.remove(`${o}/${i}`).catch(()=>{})))},Wo=async e=>{var t;await((t=pt[e])==null?void 0:t.catch(()=>{})),N().storage.setString(pn(e),""),await N().file_system.remove(`${dn()}/${e}`).catch(()=>{})},Je=class extends Error{constructor(){super("cancelled"),this.name="MiniAppInstallCancelled"}},pt={},jo=(e,t)=>{var i;let o=((i=pt[e])!=null?i:Promise.resolve()).catch(()=>{}).then(t),r=o.catch(()=>{});return pt[e]=r,r.then(()=>{pt[e]===r&&delete pt[e]}),o},Qr=(e,t)=>{var r,i;let n=e.split(".").map(a=>parseInt(a,10)||0),o=t.split(".").map(a=>parseInt(a,10)||0);for(let a=0;a<Math.max(n.length,o.length);a++){let c=((r=n[a])!=null?r:0)-((i=o[a])!=null?i:0);if(c)return c}return 0},ei=({manifest:e,zip_path:t})=>jo(e.app_id,async()=>{var i;let n=N().file_system,o=D(e.app_id);if(o&&Qr(o.version,e.version)>=0&&await Pe(o))return o;if(e.sha256&&n.sha256&&await n.sha256(t)!==e.sha256)throw new Error("sha256 mismatch");let r=gn(e.app_id,e.version,e.entry,!!e.context_update,(i=e.permissions)!=null?i:[]);return await n.remove(r.dir).catch(()=>{}),await n.mkdir(r.dir),await n.unzip(t,r.dir),ln(e),ue("\u0111\xE3 c\xE0i b\u1EA3n \u0111\xF3ng s\u1EB5n",e.app_id,e.version),zo(e.app_id,[e.version,o==null?void 0:o.version].filter(Boolean)),r}),hn=(e,{base_url:t,onProgress:n}={})=>{let o=N().file_system,r=null,i=!1,a=`${o.cache_dir}/${e.app_id}-${e.version}.zip`,c=()=>{if(i)throw new Je},l=async()=>{var u;c();let s=D(e.app_id);if((s==null?void 0:s.version)===e.version&&await o.exists(s.dir))return ln(e),D(e.app_id);c();let d=o.download({url:t?Zr(t,e.bundle_url):e.bundle_url,to_file:a,onProgress:(f,p)=>{var C;let y=p>0?p:(C=e.size)!=null?C:0;y>0&&(n==null||n(Math.min(1,f/y)))}});r=d;try{let{status:f}=await d.promise;if(c(),f!==200)throw new Error(`bundle ${f}`);if(e.sha256)if(o.sha256){if(await o.sha256(a)!==e.sha256)throw new Error("sha256 mismatch")}else ue("b\u1ECF qua ki\u1EC3m tra sha256 (file_system kh\xF4ng c\xF3 sha256)",e.app_id);c();let p=gn(e.app_id,e.version,e.entry,!!e.context_update,(u=e.permissions)!=null?u:[]);return await o.remove(p.dir).catch(()=>{}),await o.mkdir(p.dir),await o.unzip(a,p.dir),ln(e),zo(e.app_id,[e.version,s==null?void 0:s.version].filter(Boolean)),p}catch(f){throw i?new Je:f}finally{r=null,o.remove(a).catch(()=>{})}};return{promise:jo(e.app_id,l),cancel:()=>{i=!0,r==null||r.cancel()}}},lt={},ti=__DEV__?0:60*1e3,$o={},Ho=(e,t)=>{var o,r;let n=D(e);return n&&Date.now()-((o=$o[t])!=null?o:0)<ti?Promise.resolve(n):((r=lt[e])!=null||(lt[e]=(async()=>{let i=await fetch(t,{headers:{"Cache-Control":"no-cache"}});if(!i.ok)throw new Error(`manifest ${i.status}`);let a=await i.json(),c=await hn(a,{base_url:t}).promise;return $o[t]=Date.now(),c})().catch(i=>(console.warn("[miniapp] sync failed",e,i==null?void 0:i.message),D(e))).finally(()=>{lt[e]=void 0})),lt[e])};var Ct=new Map,Jo=(e,t)=>(Ct.set(e,t),()=>{Ct.get(e)===t&&Ct.delete(e)}),ni=(e,t)=>{let n=Ct.get(e);return n?n(t):!1};import{useCallback as Go,useEffect as Ge,useRef as Me,useState as Ot}from"react";import{Animated as U,BackHandler as oi,Dimensions as ri,Easing as kt,Pressable as ii,StyleSheet as yn,Text as ut,View as W}from"react-native";import{Fragment as fi,jsx as R,jsxs as ve}from"react/jsx-runtime";var dt="#22C55E",si="\u0110\u01B0a m\xE3 v\xE0o khung \u0111\u1EC3 qu\xE9t",ai=2,Lt=18,ci=1600,gt=14,li=2e3,Xo=.38,pi=40,Ko=2,ui=8,di=2e3,gi=250,Ke=2e3,mi=[{top:0,left:0,borderTopWidth:4,borderLeftWidth:4,borderTopLeftRadius:gt},{top:0,right:0,borderTopWidth:4,borderRightWidth:4,borderTopRightRadius:gt},{bottom:0,left:0,borderBottomWidth:4,borderLeftWidth:4,borderBottomLeftRadius:gt},{bottom:0,right:0,borderBottomWidth:4,borderRightWidth:4,borderBottomRightRadius:gt}],Yo=({color:e})=>R(fi,{children:mi.map((t,n)=>R(W,{style:[_.corner,t,{borderColor:e}]},n))}),It=({style:e,children:t,...n})=>{let o=Me(new U.Value(1)).current,r=i=>U.spring(o,{toValue:i,speed:40,bounciness:8,useNativeDriver:!0}).start();return R(ii,{...n,onPressIn:()=>r(.88),onPressOut:()=>r(1),children:R(U.View,{style:[e,{transform:[{scale:o}]}],children:t})})},wn=({scanner:e,closing:t=!1,onClosed:n,onHeight:o})=>{var m,w;let{vision:r,types:i,mode:a,layout:c,hint:l,glass_view:s,absolute:d}=e,u=c===ge.top,f=Me(new U.Value(0)).current,p=r.useCameraDevice("back"),y=Me(new U.Value(1)).current,[C,x]=Ot(!1),[M,S]=Ot(1),I=Me(null),[V,Q]=Ot(()=>{let{width:b,height:L}=ri.get("window");return{width:b,height:u?L*Xo:L,window_y:0}}),xe=q(J,b=>b.last_value),ie=q(J,b=>b.hit_tick),v=q(J,b=>b.scan_count),h=q(J,b=>b.notice),E=q(J,b=>b.is_picking),A=Me(null),O=Et(),he=O.top,j=Me(new U.Value(0)).current,T=Me(new U.Value(0)).current,ee=Me(new U.Value(0)).current,$=Me(n);$.current=n,Ge(()=>{if(!t)return;f.setValue(V.height);let b=U.timing(f,{toValue:0,duration:gi,easing:kt.out(kt.cubic),useNativeDriver:!1});return b.start(({finished:L})=>{var ne;L&&((ne=$.current)==null||ne.call($))}),()=>b.stop()},[t,f]);let X=Math.round(V.width*(u?.8:.78)),te=Math.round(u?V.height*.46:X*.78),_e=Math.round((V.height-te)/2),Se=Math.round((V.width-X)/2),We=r.useCodeScanner({codeTypes:i,onCodeScanned:Go(b=>rn(b),[])});Ge(()=>{let b=oi.addEventListener("hardwareBackPress",()=>(on(),!0));return()=>b.remove()},[]);let Ae=Me(ie);Ge(()=>{if(ie===Ae.current)return;j.setValue(1),ee.setValue(1);let b=U.parallel([U.timing(j,{toValue:0,duration:450,useNativeDriver:!0}),U.sequence([U.delay(li),U.timing(ee,{toValue:0,duration:250,useNativeDriver:!0})])]);return b.start(),()=>b.stop()},[ie,j,ee]),Ge(()=>{let b=ne=>U.timing(T,{toValue:ne,duration:ci,easing:kt.inOut(kt.quad),useNativeDriver:!0}),L=U.loop(U.sequence([b(1),b(0)]));return L.start(),()=>L.stop()},[T]);let Ee=Go(()=>{U.timing(y,{toValue:0,duration:220,useNativeDriver:!0}).start()},[y]);Ge(()=>{let b=setTimeout(Ee,di);return()=>clearTimeout(b)},[Ee]);let[Xe,zt]=Ot(!1);Ge(()=>{let b=requestAnimationFrame(()=>{b=requestAnimationFrame(()=>zt(!0))});return()=>cancelAnimationFrame(b)},[]);let Ue=!!(p!=null&&p.hasTorch),Ze=(m=p==null?void 0:p.neutralZoom)!=null?m:1,Qe=p?Math.min(p.maxZoom/Ze,ui):1,Wt=Ze*Math.min(M,Qe),bt=b=>{var oe;let{touches:L}=b.nativeEvent;if(L.length!==2){I.current=null;return}let ne=Math.hypot(L[0].pageX-L[1].pageX,L[0].pageY-L[1].pageY);(oe=I.current)!=null||(I.current={distance:ne,level:M}),S(Math.max(1,Math.min(Qe,I.current.level*(ne/I.current.distance))))},_t=R(ut,{style:[_.hint,!!h&&_.hint_notice],numberOfLines:1,children:(w=h!=null?h:l)!=null?w:si});return R(U.View,{ref:A,onTouchMove:bt,onTouchEnd:()=>{I.current=null},pointerEvents:t?"none":"auto",style:u?[_.top,d&&_.top_absolute,t&&{height:f}]:_.full,onLayout:({nativeEvent:{layout:b}})=>{var L;t||(o==null||o(b.height),(L=A.current)==null||L.measureInWindow((ne,oe)=>{Q({width:b.width,height:b.height,window_y:oe||0})}))},children:ve(W,{style:t?[_.content_closing,{height:V.height}]:_.content,children:[p&&Xe&&R(r.Camera,{style:yn.absoluteFill,device:p,isActive:!E,codeScanner:We,torch:C&&Ue?"on":"off",zoom:Wt,onPreviewStarted:Ee,onError:b=>Mo(b.message)}),R(U.View,{style:[_.preview_cover,{opacity:y}],pointerEvents:"none"}),V.height>0&&ve(W,{style:_.overlay,pointerEvents:"none",children:[R(W,{style:[_.dim_ring,{top:_e-Ke,left:Se-Ke,width:X+Ke*2,height:te+Ke*2}]}),ve(W,{style:{position:"absolute",top:_e,left:Se,width:X,height:te},children:[R(Yo,{color:"#FFFFFF"}),R(U.View,{style:[yn.absoluteFill,{opacity:j}],children:R(Yo,{color:dt})}),ve(U.View,{style:[_.scan_line_wrap,{transform:[{translateY:T.interpolate({inputRange:[0,1],outputRange:[0,Math.max(0,te-Lt)]})}]}],children:[R(W,{style:_.scan_glow_outer}),R(W,{style:_.scan_glow_inner}),R(W,{style:_.scan_line})]})]}),R(W,{style:[_.hint_slot,u?{top:0,height:_e-6,justifyContent:"flex-end"}:{top:_e+te+20}],children:_t}),a===Ie.continuous&&!!xe&&R(U.View,{style:[_.result_slot,{top:u?_e+te-pi:_e+te+52},{opacity:ee}],children:ve(W,{style:_.result,children:[R(W,{style:_.check_badge,children:R(W,{style:_.check_mark})}),R(ut,{style:_.result_text,numberOfLines:1,children:xe}),ve(ut,{style:_.result_count,children:["\xB7 ",v," m\xE3"]})]})})]}),V.height>0&&R(W,{style:[_.close_slot,u?_.close_slot_top:{top:Math.max(12,he-V.window_y+12)}],children:ve(It,{style:[_.close_button,!!s&&_.glass_surface],onPress:on,hitSlop:8,accessibilityRole:"button",accessibilityLabel:"\u0110\xF3ng",children:[s&&R(s,{style:_.glass_fill,glassEffectStyle:"regular",colorScheme:"dark",tintColor:"rgba(24,24,27,0.35)",isInteractive:!0}),R(W,{style:[_.close_bar,_.close_bar_a]}),R(W,{style:[_.close_bar,_.close_bar_b]})]})}),R(W,{style:[_.toolbar_wrap,!u&&{bottom:O.bottom+20}],pointerEvents:"box-none",children:ve(W,{style:[_.toolbar,!!s&&_.glass_surface],children:[s&&R(s,{style:_.glass_fill,glassEffectStyle:"regular",colorScheme:"dark",tintColor:"rgba(24,24,27,0.35)",isInteractive:!0}),R(It,{style:_.tool,onPress:xo,disabled:E,accessibilityRole:"button",accessibilityLabel:"Qu\xE9t t\u1EEB \u1EA3nh",children:ve(W,{style:_.image_icon,children:[R(W,{style:_.image_icon_dot}),R(W,{style:_.image_icon_hill})]})}),!!p&&Qe>=Ko&&R(It,{style:[_.tool,M>1&&_.tool_on],onPress:()=>S(b=>b>1?1:Ko),accessibilityRole:"button",accessibilityLabel:"Ph\xF3ng to",children:ve(ut,{style:[_.zoom_text,M>1&&_.zoom_text_on],children:[Math.round(M*10)/10,"x"]})}),Ue&&R(It,{style:[_.tool,C&&_.tool_on],onPress:()=>x(b=>!b),accessibilityRole:"button",accessibilityLabel:"\u0110\xE8n pin",accessibilityState:{selected:C},children:R(ut,{style:[_.torch_icon,C&&_.zoom_text_on],children:"\u26A1\uFE0E"})})]})})]})})},hi="rgba(0,0,0,0.5)",fn=50,_=yn.create({top:{height:`${Xo*100}%`,overflow:"hidden",backgroundColor:"#000000"},full:{position:"absolute",top:0,left:0,right:0,bottom:0},content:{flex:1,backgroundColor:"#000000"},top_absolute:{position:"absolute",top:0,left:0,right:0,zIndex:1},content_closing:{position:"absolute",left:0,right:0,bottom:0,backgroundColor:"#000000"},preview_cover:{position:"absolute",top:0,left:0,right:0,bottom:0,backgroundColor:"#000000"},overlay:{position:"absolute",top:0,left:0,right:0,bottom:0,overflow:"hidden"},dim_ring:{position:"absolute",borderWidth:Ke,borderColor:hi,borderRadius:Ke+gt},hint_slot:{position:"absolute",left:16,right:16,alignItems:"center"},hint:{color:"#FFFFFF",fontSize:14,fontWeight:"500"},hint_notice:{color:"#FCA5A5"},corner:{position:"absolute",width:28,height:28},scan_line_wrap:{position:"absolute",top:0,left:10,right:10,height:Lt,alignItems:"stretch",justifyContent:"center"},scan_glow_outer:{position:"absolute",left:0,right:0,height:Lt,borderRadius:Lt/2,backgroundColor:dt,opacity:.1},scan_glow_inner:{position:"absolute",left:4,right:4,height:8,borderRadius:4,backgroundColor:dt,opacity:.2},scan_line:{height:ai,borderRadius:1,backgroundColor:dt},glass_surface:{backgroundColor:"transparent",overflow:"visible"},glass_fill:{position:"absolute",top:0,left:0,right:0,bottom:0,borderRadius:999},close_slot:{position:"absolute",right:12},close_slot_top:{bottom:15},close_button:{width:48,height:48,borderRadius:24,overflow:"hidden",alignItems:"center",justifyContent:"center",backgroundColor:"rgba(0,0,0,0.5)"},close_bar:{position:"absolute",width:20,height:2,borderRadius:1,backgroundColor:"#FFFFFF"},close_bar_a:{transform:[{rotate:"45deg"}]},close_bar_b:{transform:[{rotate:"-45deg"}]},toolbar_wrap:{position:"absolute",left:0,right:0,bottom:10,alignItems:"center"},toolbar:{flexDirection:"row",alignItems:"center",gap:4,padding:4,borderRadius:999,backgroundColor:"rgba(24,24,27,0.72)"},tool:{width:fn,height:fn,borderRadius:fn/2,alignItems:"center",justifyContent:"center"},tool_on:{backgroundColor:"#FFFFFF"},zoom_text:{color:"#FFFFFF",fontSize:16,fontWeight:"600"},zoom_text_on:{color:"#18181B"},torch_icon:{color:"#FFFFFF",fontSize:22,fontWeight:"600"},image_icon:{width:24,height:19,borderRadius:3,borderWidth:1.5,borderColor:"#FFFFFF",overflow:"hidden"},image_icon_dot:{position:"absolute",top:3,right:3,width:4,height:4,borderRadius:2,backgroundColor:"#FFFFFF"},image_icon_hill:{position:"absolute",left:2,bottom:-6,width:12,height:12,backgroundColor:"#FFFFFF",transform:[{rotate:"45deg"}]},result_slot:{position:"absolute",left:16,right:16,alignItems:"center"},result:{maxWidth:"100%",flexDirection:"row",alignItems:"center",gap:6,paddingHorizontal:12,paddingVertical:6,borderRadius:999,backgroundColor:"rgba(39,39,42,0.9)"},check_badge:{width:18,height:18,borderRadius:9,alignItems:"center",justifyContent:"center",backgroundColor:dt},check_mark:{width:5,height:9,marginTop:-2,borderRightWidth:2,borderBottomWidth:2,borderColor:"#FFFFFF",transform:[{rotate:"45deg"}]},result_text:{flexShrink:1,color:"#FFFFFF",fontWeight:"600",fontSize:13},result_count:{color:"#A1A1AA",fontSize:13}});import{useEffect as Zo,useRef as mt,useState as Qo}from"react";import{AccessibilityInfo as yi,Animated as G,Platform as wi,StyleSheet as er,Text as bi,View as $e}from"react-native";import{Fragment as or,jsx as se,jsxs as _n}from"react/jsx-runtime";var bn={[fe.info]:"#3B82F6",[fe.success]:"#22C55E",[fe.error]:"#EF4444"},tr=-120,Ft=wi.OS==="android",nr=({type:e})=>e===fe.success?se($e,{style:Z.check_mark}):e===fe.error?_n(or,{children:[se($e,{style:[Z.cross_bar,Z.cross_a]}),se($e,{style:[Z.cross_bar,Z.cross_b]})]}):_n(or,{children:[se($e,{style:Z.info_dot}),se($e,{style:Z.info_bar})]}),rr=()=>{let e=q(rt,f=>f.message),t=q(rt,f=>f.type),n=q(rt,f=>f.tick),o=mt(new G.Value(tr)).current,r=mt(new G.Value(0)).current,i=mt(new G.Value(.92)).current,a=mt(new G.Value(0)).current,[c,l]=Qo(),[s,d]=Qo(!1);Zo(()=>{let f=!0;return nn().then(p=>{f&&p&&l(()=>p)}),()=>{f=!1}},[]);let u=mt(n);return Zo(()=>{if(n===u.current)return;yi.announceForAccessibility(e),d(!0),a.setValue(0),i.setValue(.92);let f=G.sequence([G.parallel([G.spring(o,{toValue:0,speed:16,bounciness:7,useNativeDriver:!0}),G.spring(i,{toValue:1,speed:16,bounciness:9,useNativeDriver:!0}),G.timing(r,{toValue:1,duration:140,useNativeDriver:!0}),G.sequence([G.delay(90),G.spring(a,{toValue:1,speed:18,bounciness:14,useNativeDriver:!0})])]),G.delay(oo[t]),G.parallel([G.timing(o,{toValue:tr,duration:240,useNativeDriver:!0}),G.timing(r,{toValue:0,duration:200,useNativeDriver:!0})])]);return f.start(({finished:p})=>{p&&d(!1)}),()=>f.stop()},[n]),s?se($e,{style:[Z.layer,{top:Et().top+(Ft?12:8)}],pointerEvents:"none",children:_n(G.View,{style:[Z.toast,Ft&&Z.toast_android,!!c&&Z.toast_glass,{opacity:c?1:r,transform:[{translateY:o},{scale:i}]}],accessibilityLiveRegion:"polite",children:[c&&se(c,{style:Z.glass_fill,glassEffectStyle:"regular",colorScheme:"dark",tintColor:"rgba(24,24,27,0.55)"}),Ft?se(G.View,{style:[Z.badge_halo,{backgroundColor:`${bn[t]}33`,transform:[{scale:a}]}],children:se($e,{style:[Z.badge,{backgroundColor:bn[t]}],children:se(nr,{type:t})})}):se(G.View,{style:[Z.badge,{backgroundColor:bn[t],transform:[{scale:a}]}],children:se(nr,{type:t})}),se(bi,{style:[Z.message,Ft&&Z.message_android],numberOfLines:2,children:e})]})}):null},Z=er.create({layer:{position:"absolute",left:16,right:16,alignItems:"center",zIndex:9999,elevation:9999},toast:{maxWidth:"100%",minHeight:50,flexDirection:"row",alignItems:"center",gap:10,paddingLeft:11,paddingRight:18,paddingVertical:11,borderRadius:25,backgroundColor:"#18181B",shadowColor:"#000000",shadowOpacity:.32,shadowRadius:18,shadowOffset:{width:0,height:8},elevation:12},toast_android:{width:"100%",minHeight:60,gap:12,paddingLeft:10,paddingRight:16,paddingVertical:10,borderRadius:20,borderWidth:er.hairlineWidth,borderColor:"rgba(255,255,255,0.16)",backgroundColor:"#232327",elevation:16},toast_glass:{backgroundColor:"transparent"},badge_halo:{width:40,height:40,borderRadius:20,alignItems:"center",justifyContent:"center"},glass_fill:{position:"absolute",top:0,left:0,right:0,bottom:0,borderRadius:25},badge:{width:28,height:28,borderRadius:14,alignItems:"center",justifyContent:"center"},message:{flexShrink:1,color:"#FFFFFF",fontSize:15,lineHeight:20,fontWeight:"600"},message_android:{fontSize:14,fontWeight:"500",letterSpacing:.1,color:"#F4F4F5"},check_mark:{width:7,height:13,marginTop:-3,borderRightWidth:2.5,borderBottomWidth:2.5,borderColor:"#FFFFFF",transform:[{rotate:"45deg"}]},cross_bar:{position:"absolute",width:14,height:2.5,borderRadius:2,backgroundColor:"#FFFFFF"},cross_a:{transform:[{rotate:"45deg"}]},cross_b:{transform:[{rotate:"-45deg"}]},info_dot:{width:3,height:3,borderRadius:2,marginBottom:2,backgroundColor:"#FFFFFF"},info_bar:{width:2.5,height:10,borderRadius:2,backgroundColor:"#FFFFFF"}});var ae=ke({active_key:null,instances:{}}),ir=({app:e,instance_id:t,context:n={},url_params:o={},host_data:r={}},i)=>{var c;let a=(c=N().keep_alive)==null?void 0:c.max_webviews;ae.setState(l=>{let s=t!=null?t:e.app_id,d={...l.instances,[s]:{key:s,app:e,context:n,url_params:o,host_data:r,last_used_at:Date.now()}},u=Object.keys(d);return a&&a>0&&u.length>a&&u.filter(f=>f!==s).sort((f,p)=>d[f].last_used_at-d[p].last_used_at).slice(0,u.length-a).forEach(f=>{delete d[f]}),i?{active_key:s,instances:d}:{instances:d}})},_i=e=>ir(e,!0),Si=e=>ir(e,!1),ht=()=>ae.setState({active_key:null}),Dt=e=>{ae.setState(t=>{if(t.active_key===e||!t.instances[e])return{};let n={...t.instances};return delete n[e],{instances:n}})};var sr="catalog",Ai="paused_apps",vi="removed_apps",Mi=10*1e3,xi=2,Ei=3e3,Ri=()=>{var e;try{return JSON.parse((e=N().storage.getString(sr))!=null?e:"{}")}catch{return{}}},k=ke({catalog:{},downloads:{},pause_reasons:[],updates:{},apply_ticks:{}}),ar=e=>{var t;return!!((t=N().manual_update)!=null&&t.includes(e))},Vt=new Set,cr=e=>{let t=new Set,n=()=>N().storage.setString(e,JSON.stringify([...t]));return{has:o=>t.has(o),values:()=>[...t],add:o=>t.has(o)?!1:(t.add(o),n(),!0),delete:o=>t.delete(o)?(n(),!0):!1,load:()=>{var o;t.clear();try{let r=JSON.parse((o=N().storage.getString(e))!=null?o:"[]");Array.isArray(r)&&r.forEach(i=>{typeof i=="string"&&t.add(i)})}catch{}}}},we=cr(Ai),Ne=cr(vi);Ln(()=>{we.load(),Ne.load();let e=Ri(),t={};Object.keys(e).filter(n=>!Ne.has(n)).forEach(n=>{let o=D(n);o?t[n]={status:"installed",progress:1,version:o.version,has_local:!0}:we.has(n)&&(t[n]={status:"paused",progress:0,version:e[n].version,has_local:!1})}),k.setState({catalog:e,downloads:t})});var An=e=>q(k,t=>e?t.downloads[e]:void 0),Pi=()=>q(k,e=>e.pause_reasons.length>0),ye=(...e)=>ue("queue",...e),K=[],Te={},P=null,Nt=new Set,ze={},Sn=new Set,Fe=e=>{Sn.forEach(t=>{try{t(e)}catch(n){console.warn("[miniapp-queue] event listener error",n==null?void 0:n.message)}})},Ti=e=>(Sn.add(e),()=>{Sn.delete(e)}),Ci=()=>k.getState().downloads,ce=(e,t)=>{let n=!!D(e),o=k.getState().downloads[e],r=t.status==="downloading"&&n?"updating":t.status,i={...o!=null?o:{status:"queued",progress:0},...t,...r?{status:r}:{},has_local:n};k.setState(a=>({downloads:{...a.downloads,[e]:i}})),(o==null?void 0:o.status)!==i.status||(o==null?void 0:o.version)!==i.version||(o==null?void 0:o.has_local)!==i.has_local?Fe({type:"status_change",app_id:e,state:i}):o.progress!==i.progress&&Fe({type:"progress",app_id:e,progress:i.progress,version:i.version})},Ut=(e,t)=>{var n;(n=ze[e])==null||n.forEach(o=>o(t)),delete ze[e]},Oi=()=>k.getState().pause_reasons.length>0,De=e=>{var c;if(P)return;let t=e?K.indexOf(e):Oi()?-1:K.findIndex(l=>!we.has(l));if(t<0||t>=K.length)return;let[n]=K.splice(t,1),o=k.getState().catalog[n];if(!o){Ut(n,D(n)),De();return}let r=Date.now();Te[n]=((c=Te[n])!=null?c:0)+1,ce(n,{status:"downloading",progress:0,version:o.version,error:void 0});let i=0,a=hn(o,{onProgress:l=>{let s=Math.floor(l*100);s!==i&&(i=s,ce(n,{progress:s/100,version:o.version}))}});P={app_id:n,handle:a,forced:!!e},ye("start",n,o.version,e?"(forced)":""),a.promise.then(l=>{ye("installed",n,o.version,`${Date.now()-r}ms`),ce(n,{status:"installed",progress:1,version:o.version}),Ut(n,l)}).catch(l=>{var d;if(l instanceof Je){if(Nt.has(n))return;ye("paused",n),Te[n]-=1,K.unshift(n),ce(n,{status:we.has(n)?"paused":"queued",progress:0,version:o.version});return}let s=String((d=l==null?void 0:l.message)!=null?d:l);if(console.warn("[miniapp-queue] failed",n,s),Te[n]<xi){ce(n,{status:"queued",progress:0,version:o.version,error:s}),setTimeout(()=>{var u;K.includes(n)||(P==null?void 0:P.app_id)===n||(K.push(n),De((u=ze[n])!=null&&u.length?n:void 0))},Ei);return}ce(n,{status:"failed",progress:0,version:o.version,error:s}),Ut(n,D(n))}).finally(()=>{P=null;let l=K.find(s=>{var d;return(d=ze[s])==null?void 0:d.length});De(l)})},Bt=(e,{front:t=!1}={})=>{if((P==null?void 0:P.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)},ki=async e=>{let{host_id:t,client_token:n}=N(),o=new AbortController,r=setTimeout(()=>o.abort(),Mi);try{let i=`${Ht}/api/hosts/${encodeURIComponent(t)}/miniapps?channel=${e}`,a=await fetch(i,{headers:{Authorization:`Bearer ${n}`,"Cache-Control":"no-cache"},signal:o.signal});if(!a.ok)throw new Error(`host list ${e} ${a.status}`);return(await a.json()).apps.map(l=>({...l,channel:e}))}finally{clearTimeout(r)}},ft=null,vn=()=>(ft!=null||(ft=(async()=>{var t;let e=Date.now();try{let n=await Promise.all(N().channels.map(ki)),o={};[...n].reverse().flat().forEach(l=>{o[l.app_id]=l});let r=Object.keys(k.getState().catalog).filter(l=>!o[l]);N().storage.setString(sr,JSON.stringify(o)),k.setState({catalog:o}),await Promise.all(r.map(l=>lr(l,{by_user:!1}))),r.forEach(l=>Ne.delete(l));let i=Object.keys(o).filter(l=>!Ne.has(l)),a=[],c={};for(let l of i.map(s=>o[s])){if(await mn(l)){ce(l.app_id,{status:"installed",progress:1,version:l.version});continue}let s=D(l.app_id);if(ar(l.app_id)&&!Vt.has(l.app_id)&&s&&await Pe(s)){ce(l.app_id,{status:"installed",progress:1,version:s.version}),c[l.app_id]={app_id:l.app_id,current_version:s.version,next_version:l.version};continue}a.push(l)}return k.setState({updates:c}),a.forEach(l=>{Te[l.app_id]=0,ce(l.app_id,{status:we.has(l.app_id)?"paused":"queued",progress:0,version:l.version,error:void 0}),Bt(l.app_id)}),ye("catalog",i.length,"apps, outdated",a.map(l=>l.app_id),"removed",r,`${Date.now()-e}ms`),Fe({type:"sync_complete",app_ids:i,removed:r}),Object.values(c).forEach(l=>Fe({type:"update_available",...l})),De(),{ok:!0,app_ids:i,removed:r}}catch(n){let o=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",o),Fe({type:"sync_failed",error:o}),{ok:!1,error:o}}finally{ft=null}})()),ft),lr=async(e,{by_user:t})=>{var r,i,a,c;if(t&&Ne.add(e),Nt.has(e))return;Nt.add(e),we.delete(e);let n=K.indexOf(e);n>=0&&K.splice(n,1),(P==null?void 0:P.app_id)===e&&P.handle.cancel();let o=(c=(a=(r=k.getState().downloads[e])==null?void 0:r.version)!=null?a:(i=D(e))==null?void 0:i.version)!=null?c:"";ce(e,{status:"uninstalling",progress:0,version:o}),await Wo(e),Dt(e),k.setState(l=>{let s={...l.downloads};return delete s[e],{downloads:s}}),delete Te[e],Nt.delete(e),Ut(e,null),ye("uninstalled",e,t?"(user)":"(not in list)"),Fe({type:"uninstalled",app_id:e})},Ii=e=>lr(e,{by_user:!0}),Li=e=>{let t=yt(e);return t?(Ne.delete(e),(P==null?void 0:P.app_id)===e||K.includes(e)||(Te[e]=0,ce(e,{status:we.has(e)?"paused":"queued",progress:0,version:t.version,error:void 0}),Bt(e),De(),ye("restore",e)),!0):!1},Fi=e=>{if(we.has(e))return;if(we.add(e),ye("pause app",e),(P==null?void 0:P.app_id)===e&&!P.forced){P.handle.cancel();return}let t=k.getState().downloads[e];K.includes(e)&&t&&ce(e,{status:"paused",progress:0,version:t.version})},Di=e=>{if(!we.delete(e))return;ye("resume app",e);let t=k.getState().downloads[e];(t==null?void 0:t.status)==="paused"&&!K.includes(e)&&yt(e)&&(Te[e]=0,Bt(e)),K.includes(e)&&t&&ce(e,{status:"queued",progress:0,version:t.version}),De()},Ni=e=>{let{pause_reasons:t}=k.getState();t.includes(e)||(k.setState({pause_reasons:[...t,e]}),ye("pause",e),t.length===0&&Fe({type:"pause_change",paused:!0,reasons:[e]}),P&&!P.forced&&P.handle.cancel())},Ui=e=>{let{pause_reasons:t}=k.getState();if(!t.includes(e))return;let n=t.filter(o=>o!==e);k.setState({pause_reasons:n}),ye("resume",e),n.length===0&&Fe({type:"pause_change",paused:!1,reasons:n}),De()},pr=e=>k.getState().updates[e],Vi=async e=>{var n,o;let t=pr(e);Vt.add(e);try{let r=await qt(e),i=(o=t==null?void 0:t.next_version)!=null?o:(n=yt(e))==null?void 0:n.version;return!r||!i||r.version!==i?!1:(k.setState(a=>{var l;let c={...a.updates};return delete c[e],{updates:c,apply_ticks:{...a.apply_ticks,[e]:((l=a.apply_ticks[e])!=null?l:0)+1}}}),ye("updated",e,t==null?void 0:t.current_version,"\u2192",r.version),!0)}finally{Vt.delete(e)}},Bi=()=>Object.values(k.getState().catalog).map(e=>({...e,installed:!!D(e.app_id),removed_by_user:Ne.has(e.app_id)})),yt=e=>k.getState().catalog[e],qt=async e=>{let t=yt(e);if(!t)return;if(we.delete(e),Ne.delete(e),await mn(t))return D(e);let n=D(e);if(ar(e)&&!Vt.has(e)&&n&&await Pe(n))return n;let o=new Promise(r=>{var i;((i=ze[e])!=null?i:ze[e]=[]).push(r)});return(P==null?void 0:P.app_id)===e?P.forced=!0:(Te[e]=0,Bt(e,{front:!0}),P&&!P.forced?P.handle.cancel():De(e)),o};import{Fragment as Pn,jsx as Y,jsxs as Ye}from"react/jsx-runtime";var xn=e=>(e!=null?e:"").replace(/\?[^#]*/,""),dr=0,Ji=()=>{let e=new Set;return{emit:t=>e.forEach(n=>n(t)),subscribe:t=>(e.add(t),()=>{e.delete(t)})}},Gi=Tn.memo(({instance_key:e,is_active:t,is_front:n,is_dark:o,reload_tick:r,web_at_top:i,splash:a,bridge:c,opaque_background:l,allow_embedded_miniapps:s,onWebLoadEnd:d})=>{var bt,_t;let u=be(null),f=be(!1),p=q(ae,m=>m.instances[e]),y=p==null?void 0:p.app.app_id,C=p==null?void 0:p.app.manifest_url,x=p==null?void 0:p.context,M=p==null?void 0:p.url_params,S=q(J,m=>{var w;return((w=m.active)==null?void 0:w.owner)===e?m.active:null}),[I,V]=Ce(null),[Q,xe]=Ce(S);S!==Q&&(xe(S),S?V(null):(Q==null?void 0:Q.layout)===ge.top&&V(Q));let ie=(S==null?void 0:S.layout)===ge.top?S:I,[v,h]=Ce(()=>y?D(y):null),[E,A]=Ce(!1),[O,he]=Ce(0),[j,T]=Ce(0),[ee,$]=Ce(!1),X=be(null),te=m=>{X.current&&clearTimeout(X.current),X.current=setTimeout(()=>{X.current=null,$(!0)},m)};le(()=>()=>{X.current&&clearTimeout(X.current)},[]),le(()=>{if(!y||!t&&v)return;let m=!0;return A(!1),(async()=>{let w=D(y),b=w?await Pe(w):!1;if(!m||(h(b?oe=>!oe||oe.version!==w.version||oe.permissions.join(",")!==w.permissions.join(",")?w:oe:null),__DEV__&&Date.now()-dr>1e4&&(dr=Date.now(),await vn()),!m))return;let L=await qt(y),ne=L!==void 0?L:C?await Ho(y,C):D(y);if(m){if(!ne){A(!0);return}h(oe=>oe!=null?oe:ne)}})(),()=>{m=!1}},[t,y,C,O]),le(()=>Jo(e,m=>u.current?(u.current.postMessage(m),!0):!1),[e]);let _e=q(k,m=>{let w=y?m.downloads[y]:void 0;return(w==null?void 0:w.status)==="installed"?w.version:void 0});le(()=>{if(t||!y||!v)return;let m=D(y);if(!m||m.version===v.version)return;let w=!0;return Pe(m).then(b=>{!w||!b||(ue(`webview:${e}`,"\u0111\u1ED5i bundle (\u1EA9n)",v.version,"\u2192",m.version),h(m))}),()=>{w=!1}},[t,y,_e,v==null?void 0:v.version]);let Se=q(k,m=>{var w;return y&&(w=m.apply_ticks[y])!=null?w:0});le(()=>{if(!Se||!y)return;let m=D(y);if(!m||m.version===(v==null?void 0:v.version))return;let w=!0;return Pe(m).then(b=>{!w||!b||(ue(`webview:${e}`,"c\u1EADp nh\u1EADt",v==null?void 0:v.version,"\u2192",m.version),$(!1),h(m))}),()=>{w=!1}},[Se]),le(()=>{var b;let m=(b=N().keep_alive)==null?void 0:b.idle_close_ms;if(t||!m||m<=0)return;let w=setTimeout(()=>{Dt(e)},m);return()=>clearTimeout(w)},[t,e]),le(()=>{r>0&&(A(!1),$(!1),T(m=>m+1),he(m=>m+1))},[r]);let We=be(t);le(()=>{var m;We.current!==t&&(We.current=t,f.current&&((m=u.current)==null||m.injectJavaScript(Lo(t?"resumed":"paused"))))},[t]);let Ae=`${(bt=v==null?void 0:v.version)!=null?bt:"none"}:${(_t=v==null?void 0:v.permissions.join(","))!=null?_t:""}:${j}`,Ee=$t(()=>JSON.stringify([x!=null?x:{},M!=null?M:{}]),[x,M]),Xe=$t(()=>{var m;return Vo(M!=null?M:{},(m=v==null?void 0:v.permissions)!=null?m:[])},[Ee,v==null?void 0:v.permissions]),zt=$t(()=>No(x!=null?x:{},Xe)+ko()+Io()+(N().debug?Oo():""),[Xe]),Ue=be(null),Ze=be(null);le(()=>{var w,b,L;if(!v)return;if(Ze.current!==Ae){Ze.current=Ae,Ue.current=Ee;return}if(Ue.current===Ee)return;let m=((b=JSON.parse((w=Ue.current)!=null?w:"[]")[0])!=null?b:{}).org_id;if(Ue.current=Ee,m===(x==null?void 0:x.org_id)&&f.current){$(!1),te(1500),(L=u.current)==null||L.injectJavaScript(Fo(x!=null?x:{},Xe));return}$(!1),T(ne=>ne+1)},[Ee,v,Ae]),le(()=>(t||(Re(e),Le(e),qe(e)),()=>{Re(e),Le(e),qe(e)}),[t,e,Ae,r]),le(()=>{let m=ur.addEventListener("change",w=>{w==="background"&&!uo()&&Re(e),w==="background"&&!wo()&&Le(e)});return()=>m.remove()},[e]);let Qe=En(async m=>{var b,L,ne,oe,jt,On;let w=Ro(m.nativeEvent.data);if(!w){if(y&&(c!=null&&c.onWebEvent))try{Promise.resolve(c.onWebEvent(m.nativeEvent.data,{app_id:y,instance_id:e})).catch(B=>{console.warn("[miniapp] onWebEvent l\u1ED7i",y,B)})}catch(B){console.warn("[miniapp] onWebEvent l\u1ED7i",y,B)}return}if(w.method==="log"){let{level:B,text:z}=w;ue(`web:${e}`,B!=null?B:"log",z!=null?z:"");return}if(w.method==="pong"){X.current||$(!0);return}if(w.method==="touchAtTop"){i.emit(!!w.at_top);return}if(w.method==="contextApplied"){X.current&&clearTimeout(X.current),X.current=null,$(!0);return}if(w.method==="ready"){f.current=!0,$(!0);let B=(b=ae.getState().instances[e])==null?void 0:b.context;B&&((L=u.current)==null||L.injectJavaScript(an(B)));return}try{let B=await qo(w,{getHostData:()=>{var z,pe;return(pe=(z=ae.getState().instances[e])==null?void 0:z.host_data)!=null?pe:{}},getPermissions:()=>{var z,pe;return y?(pe=(z=D(y))==null?void 0:z.permissions)!=null?pe:[]:[]},getContext:()=>{var z,pe;return(pe=(z=ae.getState().instances[e])==null?void 0:z.context)!=null?pe:{}},is_dark:o,close:ht,app_id:y!=null?y:"",instance_id:e,options:c,emit:(z,pe)=>{var kn;(kn=u.current)==null||kn.injectJavaScript(Co(z,pe))},playBeep:(ne=c==null?void 0:c.playScannerBeep)!=null?ne:(()=>{var z;(z=u.current)==null||z.injectJavaScript(Bo())}),isActive:()=>ae.getState().active_key===e&&ur.currentState!=="background"});w.id&&((oe=u.current)==null||oe.injectJavaScript(Po(w.id,B)))}catch(B){if(!w.id)return;let z=B==null?void 0:B.code,pe=B instanceof g?B:new g(typeof z=="string"?z:"HOST_ERROR",String((jt=B==null?void 0:B.message)!=null?jt:B));(On=u.current)==null||On.injectJavaScript(To(w.id,pe))}},[e,o,y,i,c]),Wt=En(()=>{A(!1),T(m=>m+1),he(m=>m+1)},[]);return Ye(Rn,{style:[Cn.absoluteFill,l&&{backgroundColor:o?"#09090B":"#FFFFFF"},!n&&me.behind],pointerEvents:t?"auto":"none",children:[ie&&Y(wn,{scanner:ie,closing:ie===I,onClosed:()=>{var m;V(null),ie.absolute&&((m=u.current)==null||m.injectJavaScript(cn(0)))},onHeight:ie.absolute?m=>{var w;return(w=u.current)==null?void 0:w.injectJavaScript(cn(m))}:void 0}),v?Y(Hi,{ref:u,source:{uri:v.entry_uri},originWhitelist:["*"],hideKeyboardAccessoryView:!0,mediaPlaybackRequiresUserAction:!1,allowingReadAccessToURL:`file://${s?un():v.dir}`,allowFileAccess:!0,allowFileAccessFromFileURLs:!0,allowUniversalAccessFromFileURLs:!0,injectedJavaScriptBeforeContentLoaded:zt,onMessage:Qe,onShouldStartLoadWithRequest:m=>{let w=m.url;return m.isTopFrame===!1||!/^https?:\/\//i.test(w)?!0:(Promise.resolve(c!=null&&c.openUrl?c.openUrl(w):Wi.openURL(w)).catch(()=>{}),!1)},setSupportMultipleWindows:!1,bounces:!1,overScrollMode:"never",onLoadStart:m=>{Re(e),Le(e),qe(e),ue(`webview:${e}`,"load start",xn(m.nativeEvent.url)),f.current=!1,$(!1)},onError:m=>{Re(e),Le(e),qe(e),ue(`webview:${e}`,"load error",xn(m.nativeEvent.url),m.nativeEvent.description),A(!0),$(!1)},onLoadEnd:m=>{let w=m.nativeEvent.url;ue(`webview:${e}`,"load end",xn(w)),y&&(d==null||d({app_id:y,instance_id:e,url:w})),te(1500)},onContentProcessDidTerminate:()=>{Re(e),Le(e),qe(e),f.current=!1,$(!1),T(m=>m+1)},onRenderProcessGone:()=>(Re(e),Le(e),qe(e),f.current=!1,$(!1),T(m=>m+1),!0),style:me.webview},Ae):null,(S==null?void 0:S.layout)===ge.full&&Y(wn,{scanner:S}),p&&Y(Yi,{visible:!v||!ee,interactive:E,children:Y(Ki,{splash:a,app:p.app,is_dark:o,error:E,has_bundle:!!v,retry:Wt})})]})}),Ki=Tn.memo(({splash:e,app:t,is_dark:n,error:o,has_bundle:r,retry:i})=>{let a=e,c=An(t.app_id),l=o?"error":!r&&(c==null?void 0:c.status)==="downloading"?"downloading":"loading";return Y(a,{app:t,is_dark:n,status:l,progress:l==="downloading"?c==null?void 0:c.progress:void 0,retry:i})}),Yi=({visible:e,interactive:t,children:n})=>{let o=be(new Mn.Value(e?1:0)).current,[r,i]=Ce(e);return le(()=>{if(e){i(!0),o.setValue(1);return}let a=Mn.timing(o,{toValue:0,duration:180,useNativeDriver:!0});return a.start(({finished:c})=>{c&&i(!1)}),()=>a.stop()},[e,o]),r?Y(Mn.View,{style:[Cn.absoluteFill,{opacity:o}],pointerEvents:t?"auto":"none",children:n}):null},mr=({app:e,is_dark:t,status:n,progress:o,retry:r})=>{let i=t?"#FAFAFA":"#18181B";return Ye(Rn,{style:[me.splash,{backgroundColor:t?"#09090B":"#FFFFFF"}],children:[Y(Rn,{style:[me.splash_icon,{backgroundColor:t?"#18181B":"#F4F4F5"}],children:e.icon?Y(zi,{source:{uri:e.icon},style:me.splash_icon_image}):Y(wt,{style:me.splash_letter,children:(e.name||"?").slice(0,1).toUpperCase()})}),Y(wt,{style:[me.splash_name,{color:i}],children:e.name}),n==="error"?Ye(Pn,{children:[Y(wt,{style:me.splash_hint,children:"Kh\xF4ng t\u1EA3i \u0111\u01B0\u1EE3c mini app"}),Y(ji,{activeOpacity:.7,style:[me.retry_button,{backgroundColor:t?"#27272A":"#F4F4F5"}],onPress:r,children:Y(wt,{style:[me.retry_text,{color:i}],children:"Th\u1EED l\u1EA1i"})})]}):Ye(Pn,{children:[Y(qi,{style:me.splash_spinner,color:t?"#A1A1AA":"#71717A"}),n==="downloading"&&Ye(wt,{style:me.splash_hint,children:["\u0110ang t\u1EA3i mini app",o?` ${Math.round(o*100)}%`:"\u2026"]})]})]})},gr=(e,t)=>{let n=be(t),o=be(!1);__DEV__&&!o.current&&n.current!==t&&(o.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.`))},Xi=({container:e,splash:t=mr,is_dark:n=!1,bridge:o,close_on_back:r=!0,opaque_background:i=!0,allow_embedded_miniapps:a=!1,onWebLoadEnd:c})=>{gr("container",e),gr("splash",t);let l=e,s=q(ae,S=>S.active_key),d=be(s);s&&(d.current=s);let u=q(ae,S=>Object.keys(S.instances).join("|")),f=q(ae,S=>{var I;return S.active_key?(I=S.instances[S.active_key])==null?void 0:I.app.name:void 0}),p=$t(()=>u?u.split("|"):[],[u]),[y,C]=Ce({}),x=be(Ji()).current;le(()=>{if(!s||!r)return;let S=$i.addEventListener("hardwareBackPress",()=>(ht(),!0));return()=>S.remove()},[s,r]);let M=En(()=>{let S=ae.getState().active_key;S&&C(I=>({...I,[S]:(I[S]||0)+1}))},[]);return p.length?Ye(Pn,{children:[Y(l,{visible:!!s,title:f!=null?f:"",is_dark:n,close:ht,reload:M,subscribeWebAtTop:x.subscribe,children:p.map(S=>Y(Gi,{instance_key:S,is_active:s===S,is_front:(s!=null?s:d.current)===S,is_dark:n,reload_tick:y[S]||0,web_at_top:x,splash:t,bridge:o,opaque_background:i,allow_embedded_miniapps:a,onWebLoadEnd:c},S))}),Y(rr,{})]}):null},me=Cn.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"}}),Zi=Tn.memo(Xi);export{re as CodeType,mr as DefaultMiniAppSplash,Ht as MINIAPP_PLATFORM_URL,Zi as MiniAppHost,g as MiniAppHostError,He as ScannerEndReason,Qt as ScannerEvent,ge as ScannerLayout,st as ScannerMethod,fe as ToastType,ht as closeMiniApp,hr as configureMiniApp,yr as createMmkvStorage,Fn as createReactNativeBiometrics,fr as createRnfsFileSystem,qt as ensureMiniApp,D as getLocalMiniApp,Bi as getMiniAppCatalog,yt as getMiniAppCatalogEntry,Ci as getMiniAppStatuses,pr as getMiniAppUpdate,ei as installBundledMiniApp,Ti as onMiniAppEvent,_i as openMiniApp,Fi as pauseMiniApp,Ni as pauseMiniAppDownloads,Si as preloadMiniApp,Re as releaseSpeechFor,Li as restoreMiniApp,Di as resumeMiniApp,Ui as resumeMiniAppDownloads,ni as sendEventToWeb,vn as syncMiniAppCatalog,Ii as uninstallMiniApp,Vi as updateMiniApp,Xn as uploadToUrl,An as useMiniAppDownload,Pi as useMiniAppDownloadsPaused};
88
+ })(); true;`,oi=new Set(["selection","impactLight","impactMedium","impactHeavy","rigid","soft","notificationSuccess","notificationWarning","notificationError"]),Rt=(e,t)=>{if(typeof e!="string"||!e)throw new g("INVALID_PARAMS",`Thi\u1EBFu ${t}`);return e},zo=async({method:e,params:t},{getHostData:n,getPermissions:o,getContext:r,is_dark:i,close:a,app_id:c,instance_id:l,options:s,emit:d,isActive:u,playBeep:y})=>{var M,S,F,V,Z,xe,ie,v;let p=s==null?void 0:s.handlers,f={app_id:c,instance_id:l,close:a},C=()=>{var m;(m=s==null?void 0:s.haptic)==null||m.call(s,"impactLight"),y==null||y()},x=()=>new g("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF \u1EE9ng d\u1EE5ng n\xE0y`);switch(e){case"getCurrentLocation":{let m=Un(t);return ct(e,()=>Vn(m,u))}case"speech.start":{if(!d)throw x();let m={};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 g("INVALID_PARAMS","lang ph\u1EA3i l\xE0 m\xE3 ng\xF4n ng\u1EEF nh\u01B0 vi-VN");m.lang=t.lang}for(let I of["continuous","interimResults","addsPunctuation","requiresOnDeviceRecognition"])if((t==null?void 0:t[I])!==void 0){if(typeof t[I]!="boolean")throw new g("INVALID_PARAMS",`${I} ph\u1EA3i l\xE0 boolean`);m[I]=t[I]}if((t==null?void 0:t.mode)!==void 0&&t.mode!=="s2t"&&t.mode!=="voice")throw new g("INVALID_PARAMS","mode ph\u1EA3i l\xE0 's2t' ho\u1EB7c 'voice'");let E=(t==null?void 0:t.mode)==="s2t"?"s2t":"voice",_=E==="voice"?(M=s==null?void 0:s.voice)!=null?M:s==null?void 0:s.speech:void 0;if(uo(l,_),_){lo(l,_);try{return await _.start({owner:l,app_id:c,mode:E,options:m,emit:d,isActive:u!=null?u:(()=>!0)})}catch(I){throw po(l,_),I}}return mo(l,m,d,u)}case"speech.stop":{let m=go(l);return m?m.stop(l):fo(l)}case at.scan:return vo(l,tn(t),u,C);case at.start:{if(!d)throw x();return Mo(l,tn(t),d,u,C)}case at.stop:return xo(l);case"uploadFiles":{let{task_id:m,...E}=t!=null?t:{};if(m!==void 0&&(typeof m!="string"||!m))throw new g("INVALID_PARAMS","task_id ph\u1EA3i l\xE0 chu\u1ED7i");return ro(Gn(E),{instance_id:l,app_id:c,getContext:r,task_id:m,config:s==null?void 0:s.upload,emit:d,exclusivePick:_=>ct("uploadFiles.pick",_)})}case"uploadFiles.cancel":oo(l,t==null?void 0:t.task_id);return;case"getUploadCapabilities":return to(s==null?void 0:s.upload);case"getBiometricAvailability":return((S=s==null?void 0:s.biometrics)!=null?S:await Gt()).getAvailability();case"authenticateBiometric":{let m=Rt(t==null?void 0:t.reason,"reason").trim();if(!m||m.length>200)throw new g("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 g("INVALID_PARAMS","Invalid cancelButtonText");return ct(e,async()=>{var I;return((I=s==null?void 0:s.biometrics)!=null?I:await Gt()).authenticate({reason:m,cancelButtonText:E})})}case"requestPayment":{let m=p==null?void 0:p.requestPayment;if(!m)throw x();let E=t==null?void 0:t.amount;if(typeof E!="number"||!Number.isFinite(E)||E<=0)throw new g("INVALID_PARAMS","amount ph\u1EA3i l\xE0 s\u1ED1 > 0");let _={...t,amount:E,currency:Rt(t==null?void 0:t.currency,"currency")};return ct(e,()=>m(_,f))}case"printImage":{let m=p==null?void 0:p.printImage;if(!m)throw x();let E=Rt(t==null?void 0:t.image,"image");await ct(e,()=>m({image:E},f));return}case"openScreen":if(!(p!=null&&p.openScreen))throw x();await p.openScreen({screen:Rt(t==null?void 0:t.screen,"screen"),params:t==null?void 0:t.params},f);return;case"closeApp":a();return;case"openWebview":{let m=String((F=t==null?void 0:t.url)!=null?F:"");if(!/^https?:\/\//i.test(m))throw new g("INVALID_PARAMS","url ph\u1EA3i l\xE0 http(s)");await(s!=null&&s.openUrl?s.openUrl(m):Po.openURL(m));return}case"openLink":{let m=String((V=t==null?void 0:t.url)!=null?V:"").trim();if(!/^[a-z][a-z0-9+.-]*:/i.test(m)||/^(javascript|file|data|about|blob):/i.test(m))throw new g("INVALID_PARAMS","url kh\xF4ng h\u1EE3p l\u1EC7");try{await(s!=null&&s.openUrl?s.openUrl(m):Po.openURL(m))}catch(E){throw new g("NOT_SUPPORTED",String((xe=(Z=E==null?void 0:E.message)!=null?Z:E)!=null?xe:"Kh\xF4ng m\u1EDF \u0111\u01B0\u1EE3c link"))}return}case"showToast":{let m=so(t);if(!m||(u==null?void 0:u())===!1)return;s!=null&&s.showToast?s.showToast(m.message,{type:m.type}):ao(m.message,m.type);return}case"haptic":{let m=oi.has(t==null?void 0:t.type)?t.type:"selection";(ie=s==null?void 0:s.haptic)==null||ie.call(s,m);return}case"getSystemInfo":return{platform:ni.OS==="ios"?"ios":"android",appVersion:(v=s==null?void 0:s.app_version)!=null?v:"",theme:i?"dark":"light"};case"getAccessToken":{let m=n().access_token;if(!m)throw new g("HOST_ERROR","Mini app ch\u01B0a c\xF3 token cho page n\xE0y");return m}case"getToken":{let m=t==null?void 0:t.type;if(m==="access"){let I=n().access_token;if(!I)throw new g("HOST_ERROR","Mini app ch\u01B0a c\xF3 token cho page n\xE0y");return I}if(m!=="partner"&&m!=="chatbox")throw new g("HOST_ERROR",`Lo\u1EA1i token kh\xF4ng h\u1EE3p l\u1EC7: ${String(m)}`);let E=Bo[m];if(!o().includes(E))throw new g("PERMISSION_DENIED",`Mini app ch\u01B0a \u0111\u01B0\u1EE3c c\u1EA5p quy\u1EC1n ${E} (Console \u2192 Quy\u1EC1n l\u1EA5y token)`);let _=m==="partner"?n().partner_token:n().chatbox_token;if(!_)throw new g("HOST_ERROR",`Kh\xF4ng c\xF3 ${E}`);return _}case"getUserInfo":{let m=n().user;if(!m)throw new g("HOST_ERROR","Kh\xF4ng l\u1EA5y \u0111\u01B0\u1EE3c th\xF4ng tin nh\xE2n vi\xEAn");return m}case"getPageInfo":{let m=n().page;if(!m)throw new g("HOST_ERROR","Kh\xF4ng l\u1EA5y \u0111\u01B0\u1EE3c th\xF4ng tin page");return m}case"sendMessage":case"insertText":throw new g("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF phi\xEAn b\u1EA3n app n\xE0y`);default:throw new g("NOT_SUPPORTED",`API kh\xF4ng t\u1ED3n t\u1EA1i: ${e}`)}};var un=e=>`bundle:${e}`,dn=()=>`${O().file_system.document_dir}/miniapps`,gn=dn,hn=(e,t,n="index.html",o=!1,r=[])=>{let i=`${gn()}/${e}/${t}`;return{app_id:e,version:t,dir:i,entry_uri:`file://${i}/${n}`,context_update:o,permissions:r}},pn=e=>{var t;O().storage.setString(un(e.app_id),JSON.stringify({version:e.version,entry:e.entry,context_update:!!e.context_update,permissions:(t=e.permissions)!=null?t:[]}))},ri=(e,t)=>/^https?:\/\//.test(t)?t:`${e.replace(/[^/]*$/,"")}${t}`,L=e=>{let t=O().storage.getString(un(e));if(!t)return null;try{let{version:n,entry:o,context_update:r,permissions:i}=JSON.parse(t);return hn(e,n,o,!!r,Array.isArray(i)?i:[])}catch{return null}},Pe=e=>O().file_system.exists(e.entry_uri.replace("file://","")),mn=async e=>{let t=L(e.app_id);return(t==null?void 0:t.version)===e.version&&await Pe(t)},jo=async(e,t)=>{let n=O().file_system,o=`${gn()}/${e}`,r=await n.listDir(o).catch(()=>[]);await Promise.all(r.filter(i=>!t.includes(i)).map(i=>n.remove(`${o}/${i}`).catch(()=>{})))},Ho=async e=>{var t;await((t=ut[e])==null?void 0:t.catch(()=>{})),O().storage.setString(un(e),""),await O().file_system.remove(`${gn()}/${e}`).catch(()=>{})},Je=class extends Error{constructor(){super("cancelled"),this.name="MiniAppInstallCancelled"}},ut={},Jo=(e,t)=>{var i;let o=((i=ut[e])!=null?i:Promise.resolve()).catch(()=>{}).then(t),r=o.catch(()=>{});return ut[e]=r,r.then(()=>{ut[e]===r&&delete ut[e]}),o},fn=(e,t)=>{var r,i;let n=e.split(".").map(a=>parseInt(a,10)||0),o=t.split(".").map(a=>parseInt(a,10)||0);for(let a=0;a<Math.max(n.length,o.length);a++){let c=((r=n[a])!=null?r:0)-((i=o[a])!=null?i:0);if(c)return c}return 0},ii=({manifest:e,zip_path:t})=>Jo(e.app_id,async()=>{var i;let n=O().file_system,o=L(e.app_id);if(o&&fn(o.version,e.version)>=0&&await Pe(o))return o;if(e.sha256&&n.sha256&&await n.sha256(t)!==e.sha256)throw new Error("sha256 mismatch");let r=hn(e.app_id,e.version,e.entry,!!e.context_update,(i=e.permissions)!=null?i:[]);return await n.remove(r.dir).catch(()=>{}),await n.mkdir(r.dir),await n.unzip(t,r.dir),pn(e),ue("\u0111\xE3 c\xE0i b\u1EA3n \u0111\xF3ng s\u1EB5n",e.app_id,e.version),jo(e.app_id,[e.version,o==null?void 0:o.version].filter(Boolean)),r}),yn=(e,{base_url:t,onProgress:n}={})=>{let o=O().file_system,r=null,i=!1,a=`${o.cache_dir}/${e.app_id}-${e.version}.zip`,c=()=>{if(i)throw new Je},l=async()=>{var u;c();let s=L(e.app_id);if((s==null?void 0:s.version)===e.version&&await o.exists(s.dir))return pn(e),L(e.app_id);c();let d=o.download({url:t?ri(t,e.bundle_url):e.bundle_url,to_file:a,onProgress:(y,p)=>{var C;let f=p>0?p:(C=e.size)!=null?C:0;f>0&&(n==null||n(Math.min(1,y/f)))}});r=d;try{let{status:y}=await d.promise;if(c(),y!==200)throw new Error(`bundle ${y}`);if(e.sha256)if(o.sha256){if(await o.sha256(a)!==e.sha256)throw new Error("sha256 mismatch")}else ue("b\u1ECF qua ki\u1EC3m tra sha256 (file_system kh\xF4ng c\xF3 sha256)",e.app_id);c();let p=hn(e.app_id,e.version,e.entry,!!e.context_update,(u=e.permissions)!=null?u:[]);return await o.remove(p.dir).catch(()=>{}),await o.mkdir(p.dir),await o.unzip(a,p.dir),pn(e),jo(e.app_id,[e.version,s==null?void 0:s.version].filter(Boolean)),p}catch(y){throw i?new Je:y}finally{r=null,o.remove(a).catch(()=>{})}};return{promise:Jo(e.app_id,l),cancel:()=>{i=!0,r==null||r.cancel()}}},pt={},si=__DEV__?0:60*1e3,Wo={},Go=(e,t)=>{var o,r;let n=L(e);return n&&Date.now()-((o=Wo[t])!=null?o:0)<si?Promise.resolve(n):((r=pt[e])!=null||(pt[e]=(async()=>{let i=await fetch(t,{headers:{"Cache-Control":"no-cache"}});if(!i.ok)throw new Error(`manifest ${i.status}`);let a=await i.json(),c=await yn(a,{base_url:t}).promise;return Wo[t]=Date.now(),c})().catch(i=>(console.warn("[miniapp] sync failed",e,i==null?void 0:i.message),L(e))).finally(()=>{pt[e]=void 0})),pt[e])};var Ot=new Map,Ko=(e,t)=>(Ot.set(e,t),()=>{Ot.get(e)===t&&Ot.delete(e)}),ai=(e,t)=>{let n=Ot.get(e);return n?n(t):!1};import{useCallback as Yo,useEffect as Ge,useRef as Me,useState as kt}from"react";import{Animated as U,BackHandler as ci,Dimensions as li,Easing as It,Pressable as pi,StyleSheet as bn,Text as dt,View as W}from"react-native";import{Fragment as Si,jsx as P,jsxs as ve}from"react/jsx-runtime";var gt="#22C55E",ui="\u0110\u01B0a m\xE3 v\xE0o khung \u0111\u1EC3 qu\xE9t",di=2,Ft=18,gi=1600,ht=14,hi=2e3,Zo=.38,mi=40,Xo=2,fi=8,yi=2e3,wi=250,Ke=2e3,bi=[{top:0,left:0,borderTopWidth:4,borderLeftWidth:4,borderTopLeftRadius:ht},{top:0,right:0,borderTopWidth:4,borderRightWidth:4,borderTopRightRadius:ht},{bottom:0,left:0,borderBottomWidth:4,borderLeftWidth:4,borderBottomLeftRadius:ht},{bottom:0,right:0,borderBottomWidth:4,borderRightWidth:4,borderBottomRightRadius:ht}],Qo=({color:e})=>P(Si,{children:bi.map((t,n)=>P(W,{style:[A.corner,t,{borderColor:e}]},n))}),Lt=({style:e,children:t,...n})=>{let o=Me(new U.Value(1)).current,r=i=>U.spring(o,{toValue:i,speed:40,bounciness:8,useNativeDriver:!0}).start();return P(pi,{...n,onPressIn:()=>r(.88),onPressOut:()=>r(1),children:P(U.View,{style:[e,{transform:[{scale:o}]}],children:t})})},An=({scanner:e,closing:t=!1,onClosed:n,onHeight:o})=>{var h,w;let{vision:r,types:i,mode:a,layout:c,hint:l,glass_view:s,absolute:d}=e,u=c===ge.top,y=Me(new U.Value(0)).current,p=r.useCameraDevice("back"),f=Me(new U.Value(1)).current,[C,x]=kt(!1),[M,S]=kt(1),F=Me(null),[V,Z]=kt(()=>{let{width:b,height:D}=li.get("window");return{width:b,height:u?D*Zo:D,window_y:0}}),xe=q(J,b=>b.last_value),ie=q(J,b=>b.hit_tick),v=q(J,b=>b.scan_count),m=q(J,b=>b.notice),E=q(J,b=>b.is_picking),_=Me(null),I=Ct(),me=I.top,j=Me(new U.Value(0)).current,T=Me(new U.Value(0)).current,ee=Me(new U.Value(0)).current,$=Me(n);$.current=n,Ge(()=>{if(!t)return;y.setValue(V.height);let b=U.timing(y,{toValue:0,duration:wi,easing:It.out(It.cubic),useNativeDriver:!1});return b.start(({finished:D})=>{var ne;D&&((ne=$.current)==null||ne.call($))}),()=>b.stop()},[t,y]);let X=Math.round(V.width*(u?.8:.78)),te=Math.round(u?V.height*.46:X*.78),Ae=Math.round((V.height-te)/2),Se=Math.round((V.width-X)/2),We=r.useCodeScanner({codeTypes:i,onCodeScanned:Yo(b=>sn(b),[])});Ge(()=>{let b=ci.addEventListener("hardwareBackPress",()=>(rn(),!0));return()=>b.remove()},[]);let _e=Me(ie);Ge(()=>{if(ie===_e.current)return;j.setValue(1),ee.setValue(1);let b=U.parallel([U.timing(j,{toValue:0,duration:450,useNativeDriver:!0}),U.sequence([U.delay(hi),U.timing(ee,{toValue:0,duration:250,useNativeDriver:!0})])]);return b.start(),()=>b.stop()},[ie,j,ee]),Ge(()=>{let b=ne=>U.timing(T,{toValue:ne,duration:gi,easing:It.inOut(It.quad),useNativeDriver:!0}),D=U.loop(U.sequence([b(1),b(0)]));return D.start(),()=>D.stop()},[T]);let Ee=Yo(()=>{U.timing(f,{toValue:0,duration:220,useNativeDriver:!0}).start()},[f]);Ge(()=>{let b=setTimeout(Ee,yi);return()=>clearTimeout(b)},[Ee]);let[Xe,jt]=kt(!1);Ge(()=>{let b=requestAnimationFrame(()=>{b=requestAnimationFrame(()=>jt(!0))});return()=>cancelAnimationFrame(b)},[]);let Ue=!!(p!=null&&p.hasTorch),Qe=(h=p==null?void 0:p.neutralZoom)!=null?h:1,Ze=p?Math.min(p.maxZoom/Qe,fi):1,Ht=Qe*Math.min(M,Ze),At=b=>{var oe;let{touches:D}=b.nativeEvent;if(D.length!==2){F.current=null;return}let ne=Math.hypot(D[0].pageX-D[1].pageX,D[0].pageY-D[1].pageY);(oe=F.current)!=null||(F.current={distance:ne,level:M}),S(Math.max(1,Math.min(Ze,F.current.level*(ne/F.current.distance))))},St=P(dt,{style:[A.hint,!!m&&A.hint_notice],numberOfLines:1,children:(w=m!=null?m:l)!=null?w:ui});return P(U.View,{ref:_,onTouchMove:At,onTouchEnd:()=>{F.current=null},pointerEvents:t?"none":"auto",style:u?[A.top,d&&A.top_absolute,t&&{height:y}]:A.full,onLayout:({nativeEvent:{layout:b}})=>{var D;t||(o==null||o(b.height),(D=_.current)==null||D.measureInWindow((ne,oe)=>{Z({width:b.width,height:b.height,window_y:oe||0})}))},children:ve(W,{style:t?[A.content_closing,{height:V.height}]:A.content,children:[p&&Xe&&P(r.Camera,{style:bn.absoluteFill,device:p,isActive:!E,codeScanner:We,torch:C&&Ue?"on":"off",zoom:Ht,onPreviewStarted:Ee,onError:b=>Eo(b.message)}),P(U.View,{style:[A.preview_cover,{opacity:f}],pointerEvents:"none"}),V.height>0&&ve(W,{style:A.overlay,pointerEvents:"none",children:[P(W,{style:[A.dim_ring,{top:Ae-Ke,left:Se-Ke,width:X+Ke*2,height:te+Ke*2}]}),ve(W,{style:{position:"absolute",top:Ae,left:Se,width:X,height:te},children:[P(Qo,{color:"#FFFFFF"}),P(U.View,{style:[bn.absoluteFill,{opacity:j}],children:P(Qo,{color:gt})}),ve(U.View,{style:[A.scan_line_wrap,{transform:[{translateY:T.interpolate({inputRange:[0,1],outputRange:[0,Math.max(0,te-Ft)]})}]}],children:[P(W,{style:A.scan_glow_outer}),P(W,{style:A.scan_glow_inner}),P(W,{style:A.scan_line})]})]}),P(W,{style:[A.hint_slot,u?{top:0,height:Ae-6,justifyContent:"flex-end"}:{top:Ae+te+20}],children:St}),a===Ie.continuous&&!!xe&&P(U.View,{style:[A.result_slot,{top:u?Ae+te-mi:Ae+te+52},{opacity:ee}],children:ve(W,{style:A.result,children:[P(W,{style:A.check_badge,children:P(W,{style:A.check_mark})}),P(dt,{style:A.result_text,numberOfLines:1,children:xe}),ve(dt,{style:A.result_count,children:["\xB7 ",v," m\xE3"]})]})})]}),V.height>0&&P(W,{style:[A.close_slot,u?A.close_slot_top:{top:Math.max(12,me-V.window_y+12)}],children:ve(Lt,{style:[A.close_button,!!s&&A.glass_surface],onPress:rn,hitSlop:8,accessibilityRole:"button",accessibilityLabel:"\u0110\xF3ng",children:[s&&P(s,{style:A.glass_fill,glassEffectStyle:"regular",colorScheme:"dark",tintColor:"rgba(24,24,27,0.35)",isInteractive:!0}),P(W,{style:[A.close_bar,A.close_bar_a]}),P(W,{style:[A.close_bar,A.close_bar_b]})]})}),P(W,{style:[A.toolbar_wrap,!u&&{bottom:I.bottom+20}],pointerEvents:"box-none",children:ve(W,{style:[A.toolbar,!!s&&A.glass_surface],children:[s&&P(s,{style:A.glass_fill,glassEffectStyle:"regular",colorScheme:"dark",tintColor:"rgba(24,24,27,0.35)",isInteractive:!0}),P(Lt,{style:A.tool,onPress:Co,disabled:E,accessibilityRole:"button",accessibilityLabel:"Qu\xE9t t\u1EEB \u1EA3nh",children:ve(W,{style:A.image_icon,children:[P(W,{style:A.image_icon_dot}),P(W,{style:A.image_icon_hill})]})}),!!p&&Ze>=Xo&&P(Lt,{style:[A.tool,M>1&&A.tool_on],onPress:()=>S(b=>b>1?1:Xo),accessibilityRole:"button",accessibilityLabel:"Ph\xF3ng to",children:ve(dt,{style:[A.zoom_text,M>1&&A.zoom_text_on],children:[Math.round(M*10)/10,"x"]})}),Ue&&P(Lt,{style:[A.tool,C&&A.tool_on],onPress:()=>x(b=>!b),accessibilityRole:"button",accessibilityLabel:"\u0110\xE8n pin",accessibilityState:{selected:C},children:P(dt,{style:[A.torch_icon,C&&A.zoom_text_on],children:"\u26A1\uFE0E"})})]})})]})})},Ai="rgba(0,0,0,0.5)",wn=50,A=bn.create({top:{height:`${Zo*100}%`,overflow:"hidden",backgroundColor:"#000000"},full:{position:"absolute",top:0,left:0,right:0,bottom:0},content:{flex:1,backgroundColor:"#000000"},top_absolute:{position:"absolute",top:0,left:0,right:0,zIndex:1},content_closing:{position:"absolute",left:0,right:0,bottom:0,backgroundColor:"#000000"},preview_cover:{position:"absolute",top:0,left:0,right:0,bottom:0,backgroundColor:"#000000"},overlay:{position:"absolute",top:0,left:0,right:0,bottom:0,overflow:"hidden"},dim_ring:{position:"absolute",borderWidth:Ke,borderColor:Ai,borderRadius:Ke+ht},hint_slot:{position:"absolute",left:16,right:16,alignItems:"center"},hint:{color:"#FFFFFF",fontSize:14,fontWeight:"500"},hint_notice:{color:"#FCA5A5"},corner:{position:"absolute",width:28,height:28},scan_line_wrap:{position:"absolute",top:0,left:10,right:10,height:Ft,alignItems:"stretch",justifyContent:"center"},scan_glow_outer:{position:"absolute",left:0,right:0,height:Ft,borderRadius:Ft/2,backgroundColor:gt,opacity:.1},scan_glow_inner:{position:"absolute",left:4,right:4,height:8,borderRadius:4,backgroundColor:gt,opacity:.2},scan_line:{height:di,borderRadius:1,backgroundColor:gt},glass_surface:{backgroundColor:"transparent",overflow:"visible"},glass_fill:{position:"absolute",top:0,left:0,right:0,bottom:0,borderRadius:999},close_slot:{position:"absolute",right:12},close_slot_top:{bottom:15},close_button:{width:48,height:48,borderRadius:24,overflow:"hidden",alignItems:"center",justifyContent:"center",backgroundColor:"rgba(0,0,0,0.5)"},close_bar:{position:"absolute",width:20,height:2,borderRadius:1,backgroundColor:"#FFFFFF"},close_bar_a:{transform:[{rotate:"45deg"}]},close_bar_b:{transform:[{rotate:"-45deg"}]},toolbar_wrap:{position:"absolute",left:0,right:0,bottom:10,alignItems:"center"},toolbar:{flexDirection:"row",alignItems:"center",gap:4,padding:4,borderRadius:999,backgroundColor:"rgba(24,24,27,0.72)"},tool:{width:wn,height:wn,borderRadius:wn/2,alignItems:"center",justifyContent:"center"},tool_on:{backgroundColor:"#FFFFFF"},zoom_text:{color:"#FFFFFF",fontSize:16,fontWeight:"600"},zoom_text_on:{color:"#18181B"},torch_icon:{color:"#FFFFFF",fontSize:22,fontWeight:"600"},image_icon:{width:24,height:19,borderRadius:3,borderWidth:1.5,borderColor:"#FFFFFF",overflow:"hidden"},image_icon_dot:{position:"absolute",top:3,right:3,width:4,height:4,borderRadius:2,backgroundColor:"#FFFFFF"},image_icon_hill:{position:"absolute",left:2,bottom:-6,width:12,height:12,backgroundColor:"#FFFFFF",transform:[{rotate:"45deg"}]},result_slot:{position:"absolute",left:16,right:16,alignItems:"center"},result:{maxWidth:"100%",flexDirection:"row",alignItems:"center",gap:6,paddingHorizontal:12,paddingVertical:6,borderRadius:999,backgroundColor:"rgba(39,39,42,0.9)"},check_badge:{width:18,height:18,borderRadius:9,alignItems:"center",justifyContent:"center",backgroundColor:gt},check_mark:{width:5,height:9,marginTop:-2,borderRightWidth:2,borderBottomWidth:2,borderColor:"#FFFFFF",transform:[{rotate:"45deg"}]},result_text:{flexShrink:1,color:"#FFFFFF",fontWeight:"600",fontSize:13},result_count:{color:"#A1A1AA",fontSize:13}});import{useEffect as er,useRef as mt,useState as tr}from"react";import{AccessibilityInfo as _i,Animated as G,Platform as vi,StyleSheet as nr,Text as Mi,View as $e}from"react-native";import{Fragment as ir,jsx as se,jsxs as _n}from"react/jsx-runtime";var Sn={[fe.info]:"#3B82F6",[fe.success]:"#22C55E",[fe.error]:"#EF4444"},or=-120,Dt=vi.OS==="android",rr=({type:e})=>e===fe.success?se($e,{style:Q.check_mark}):e===fe.error?_n(ir,{children:[se($e,{style:[Q.cross_bar,Q.cross_a]}),se($e,{style:[Q.cross_bar,Q.cross_b]})]}):_n(ir,{children:[se($e,{style:Q.info_dot}),se($e,{style:Q.info_bar})]}),sr=()=>{let e=q(it,y=>y.message),t=q(it,y=>y.type),n=q(it,y=>y.tick),o=mt(new G.Value(or)).current,r=mt(new G.Value(0)).current,i=mt(new G.Value(.92)).current,a=mt(new G.Value(0)).current,[c,l]=tr(),[s,d]=tr(!1);er(()=>{let y=!0;return on().then(p=>{y&&p&&l(()=>p)}),()=>{y=!1}},[]);let u=mt(n);return er(()=>{if(n===u.current)return;_i.announceForAccessibility(e),d(!0),a.setValue(0),i.setValue(.92);let y=G.sequence([G.parallel([G.spring(o,{toValue:0,speed:16,bounciness:7,useNativeDriver:!0}),G.spring(i,{toValue:1,speed:16,bounciness:9,useNativeDriver:!0}),G.timing(r,{toValue:1,duration:140,useNativeDriver:!0}),G.sequence([G.delay(90),G.spring(a,{toValue:1,speed:18,bounciness:14,useNativeDriver:!0})])]),G.delay(io[t]),G.parallel([G.timing(o,{toValue:or,duration:240,useNativeDriver:!0}),G.timing(r,{toValue:0,duration:200,useNativeDriver:!0})])]);return y.start(({finished:p})=>{p&&d(!1)}),()=>y.stop()},[n]),s?se($e,{style:[Q.layer,{top:Ct().top+(Dt?12:8)}],pointerEvents:"none",children:_n(G.View,{style:[Q.toast,Dt&&Q.toast_android,!!c&&Q.toast_glass,{opacity:c?1:r,transform:[{translateY:o},{scale:i}]}],accessibilityLiveRegion:"polite",children:[c&&se(c,{style:Q.glass_fill,glassEffectStyle:"regular",colorScheme:"dark",tintColor:"rgba(24,24,27,0.55)"}),Dt?se(G.View,{style:[Q.badge_halo,{backgroundColor:`${Sn[t]}33`,transform:[{scale:a}]}],children:se($e,{style:[Q.badge,{backgroundColor:Sn[t]}],children:se(rr,{type:t})})}):se(G.View,{style:[Q.badge,{backgroundColor:Sn[t],transform:[{scale:a}]}],children:se(rr,{type:t})}),se(Mi,{style:[Q.message,Dt&&Q.message_android],numberOfLines:2,children:e})]})}):null},Q=nr.create({layer:{position:"absolute",left:16,right:16,alignItems:"center",zIndex:9999,elevation:9999},toast:{maxWidth:"100%",minHeight:50,flexDirection:"row",alignItems:"center",gap:10,paddingLeft:11,paddingRight:18,paddingVertical:11,borderRadius:25,backgroundColor:"#18181B",shadowColor:"#000000",shadowOpacity:.32,shadowRadius:18,shadowOffset:{width:0,height:8},elevation:12},toast_android:{width:"100%",minHeight:60,gap:12,paddingLeft:10,paddingRight:16,paddingVertical:10,borderRadius:20,borderWidth:nr.hairlineWidth,borderColor:"rgba(255,255,255,0.16)",backgroundColor:"#232327",elevation:16},toast_glass:{backgroundColor:"transparent"},badge_halo:{width:40,height:40,borderRadius:20,alignItems:"center",justifyContent:"center"},glass_fill:{position:"absolute",top:0,left:0,right:0,bottom:0,borderRadius:25},badge:{width:28,height:28,borderRadius:14,alignItems:"center",justifyContent:"center"},message:{flexShrink:1,color:"#FFFFFF",fontSize:15,lineHeight:20,fontWeight:"600"},message_android:{fontSize:14,fontWeight:"500",letterSpacing:.1,color:"#F4F4F5"},check_mark:{width:7,height:13,marginTop:-3,borderRightWidth:2.5,borderBottomWidth:2.5,borderColor:"#FFFFFF",transform:[{rotate:"45deg"}]},cross_bar:{position:"absolute",width:14,height:2.5,borderRadius:2,backgroundColor:"#FFFFFF"},cross_a:{transform:[{rotate:"45deg"}]},cross_b:{transform:[{rotate:"-45deg"}]},info_dot:{width:3,height:3,borderRadius:2,marginBottom:2,backgroundColor:"#FFFFFF"},info_bar:{width:2.5,height:10,borderRadius:2,backgroundColor:"#FFFFFF"}});var ae=ke({active_key:null,instances:{}}),ar=({app:e,instance_id:t,context:n={},url_params:o={},host_data:r={}},i)=>{var c;let a=(c=O().keep_alive)==null?void 0:c.max_webviews;ae.setState(l=>{let s=t!=null?t:e.app_id,d={...l.instances,[s]:{key:s,app:e,context:n,url_params:o,host_data:r,last_used_at:Date.now()}},u=Object.keys(d);return a&&a>0&&u.length>a&&u.filter(y=>y!==s).sort((y,p)=>d[y].last_used_at-d[p].last_used_at).slice(0,u.length-a).forEach(y=>{delete d[y]}),i?{active_key:s,instances:d}:{instances:d}})},xi=e=>ar(e,!0),Ei=e=>ar(e,!1),ft=()=>ae.setState({active_key:null}),Nt=e=>{ae.setState(t=>{if(t.active_key===e||!t.instances[e])return{};let n={...t.instances};return delete n[e],{instances:n}})};var cr="catalog",Ci="paused_apps",Pi="removed_apps",Ri=10*1e3,Ti=2,Oi=3e3,ki=()=>{var e;try{return JSON.parse((e=O().storage.getString(cr))!=null?e:"{}")}catch{return{}}},k=ke({catalog:{},downloads:{},pause_reasons:[],updates:{},apply_ticks:{}}),lr=e=>{var t;return!!((t=O().manual_update)!=null&&t.includes(e))},Bt=new Set,pr=e=>{let t=new Set,n=()=>O().storage.setString(e,JSON.stringify([...t]));return{has:o=>t.has(o),values:()=>[...t],add:o=>t.has(o)?!1:(t.add(o),n(),!0),delete:o=>t.delete(o)?(n(),!0):!1,load:()=>{var o;t.clear();try{let r=JSON.parse((o=O().storage.getString(e))!=null?o:"[]");Array.isArray(r)&&r.forEach(i=>{typeof i=="string"&&t.add(i)})}catch{}}}},we=pr(Ci),Ne=pr(Pi);Dn(()=>{we.load(),Ne.load();let e=ki(),t={};Object.keys(e).filter(n=>!Ne.has(n)).forEach(n=>{let o=L(n);o?t[n]={status:"installed",progress:1,version:o.version,has_local:!0}:we.has(n)&&(t[n]={status:"paused",progress:0,version:e[n].version,has_local:!1})}),k.setState({catalog:e,downloads:t})});var Mn=e=>q(k,t=>e?t.downloads[e]:void 0),Ii=()=>q(k,e=>e.pause_reasons.length>0),ye=(...e)=>ue("queue",...e),K=[],Re={},R=null,Ut=new Set,ze={},vn=new Set,Fe=e=>{vn.forEach(t=>{try{t(e)}catch(n){console.warn("[miniapp-queue] event listener error",n==null?void 0:n.message)}})},Li=e=>(vn.add(e),()=>{vn.delete(e)}),Fi=()=>k.getState().downloads,ce=(e,t)=>{let n=!!L(e),o=k.getState().downloads[e],r=t.status==="downloading"&&n?"updating":t.status,i={...o!=null?o:{status:"queued",progress:0},...t,...r?{status:r}:{},has_local:n};k.setState(a=>({downloads:{...a.downloads,[e]:i}})),(o==null?void 0:o.status)!==i.status||(o==null?void 0:o.version)!==i.version||(o==null?void 0:o.has_local)!==i.has_local?Fe({type:"status_change",app_id:e,state:i}):o.progress!==i.progress&&Fe({type:"progress",app_id:e,progress:i.progress,version:i.version})},Vt=(e,t)=>{var n;(n=ze[e])==null||n.forEach(o=>o(t)),delete ze[e]},Di=()=>k.getState().pause_reasons.length>0,De=e=>{var c;if(R)return;let t=e?K.indexOf(e):Di()?-1:K.findIndex(l=>!we.has(l));if(t<0||t>=K.length)return;let[n]=K.splice(t,1),o=k.getState().catalog[n];if(!o){Vt(n,L(n)),De();return}let r=Date.now();Re[n]=((c=Re[n])!=null?c:0)+1,ce(n,{status:"downloading",progress:0,version:o.version,error:void 0});let i=0,a=yn(o,{onProgress:l=>{let s=Math.floor(l*100);s!==i&&(i=s,ce(n,{progress:s/100,version:o.version}))}});R={app_id:n,handle:a,forced:!!e},ye("start",n,o.version,e?"(forced)":""),a.promise.then(l=>{ye("installed",n,o.version,`${Date.now()-r}ms`),ce(n,{status:"installed",progress:1,version:o.version}),Vt(n,l)}).catch(l=>{var d;if(l instanceof Je){if(Ut.has(n))return;ye("paused",n),Re[n]-=1,K.unshift(n),ce(n,{status:we.has(n)?"paused":"queued",progress:0,version:o.version});return}let s=String((d=l==null?void 0:l.message)!=null?d:l);if(console.warn("[miniapp-queue] failed",n,s),Re[n]<Ti){ce(n,{status:"queued",progress:0,version:o.version,error:s}),setTimeout(()=>{var u;K.includes(n)||(R==null?void 0:R.app_id)===n||(K.push(n),De((u=ze[n])!=null&&u.length?n:void 0))},Oi);return}ce(n,{status:"failed",progress:0,version:o.version,error:s}),Vt(n,L(n))}).finally(()=>{R=null;let l=K.find(s=>{var d;return(d=ze[s])==null?void 0:d.length});De(l)})},qt=(e,{front:t=!1}={})=>{if((R==null?void 0:R.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)},Ni=async e=>{let{host_id:t,client_token:n}=O(),o=new AbortController,r=setTimeout(()=>o.abort(),Ri);try{let i=`${et}/api/hosts/${encodeURIComponent(t)}/miniapps?channel=${e}`,a=await fetch(i,{headers:{Authorization:`Bearer ${n}`,"Cache-Control":"no-cache"},signal:o.signal});if(!a.ok)throw new Error(`host list ${e} ${a.status}`);return(await a.json()).apps.map(l=>({...l,channel:e}))}finally{clearTimeout(r)}},yt=null,xn=()=>(yt!=null||(yt=(async()=>{var t;let e=Date.now();try{let n=await Promise.all(O().channels.map(Ni)),o={};[...n].reverse().flat().forEach(l=>{o[l.app_id]=l});let r=Object.keys(k.getState().catalog).filter(l=>!o[l]);O().storage.setString(cr,JSON.stringify(o)),k.setState({catalog:o}),await Promise.all(r.map(l=>ur(l,{by_user:!1}))),r.forEach(l=>Ne.delete(l));let i=Object.keys(o).filter(l=>!Ne.has(l)),a=[],c={};for(let l of i.map(s=>o[s])){if(await mn(l)){ce(l.app_id,{status:"installed",progress:1,version:l.version});continue}let s=L(l.app_id);if(lr(l.app_id)&&!Bt.has(l.app_id)&&s&&await Pe(s)){ce(l.app_id,{status:"installed",progress:1,version:s.version}),c[l.app_id]={app_id:l.app_id,current_version:s.version,next_version:l.version};continue}a.push(l)}return k.setState({updates:c}),a.forEach(l=>{Re[l.app_id]=0,ce(l.app_id,{status:we.has(l.app_id)?"paused":"queued",progress:0,version:l.version,error:void 0}),qt(l.app_id)}),ye("catalog",i.length,"apps, outdated",a.map(l=>l.app_id),"removed",r,`${Date.now()-e}ms`),Fe({type:"sync_complete",app_ids:i,removed:r}),Object.values(c).forEach(l=>Fe({type:"update_available",...l})),De(),{ok:!0,app_ids:i,removed:r}}catch(n){let o=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",o),Fe({type:"sync_failed",error:o}),{ok:!1,error:o}}finally{yt=null}})()),yt),ur=async(e,{by_user:t})=>{var r,i,a,c;if(t&&Ne.add(e),Ut.has(e))return;Ut.add(e),we.delete(e);let n=K.indexOf(e);n>=0&&K.splice(n,1),(R==null?void 0:R.app_id)===e&&R.handle.cancel();let o=(c=(a=(r=k.getState().downloads[e])==null?void 0:r.version)!=null?a:(i=L(e))==null?void 0:i.version)!=null?c:"";ce(e,{status:"uninstalling",progress:0,version:o}),await Ho(e),Nt(e),k.setState(l=>{let s={...l.downloads};return delete s[e],{downloads:s}}),delete Re[e],Ut.delete(e),Vt(e,null),ye("uninstalled",e,t?"(user)":"(not in list)"),Fe({type:"uninstalled",app_id:e})},Ui=e=>ur(e,{by_user:!0}),Vi=e=>{let t=wt(e);return t?(Ne.delete(e),(R==null?void 0:R.app_id)===e||K.includes(e)||(Re[e]=0,ce(e,{status:we.has(e)?"paused":"queued",progress:0,version:t.version,error:void 0}),qt(e),De(),ye("restore",e)),!0):!1},Bi=e=>{if(we.has(e))return;if(we.add(e),ye("pause app",e),(R==null?void 0:R.app_id)===e&&!R.forced){R.handle.cancel();return}let t=k.getState().downloads[e];K.includes(e)&&t&&ce(e,{status:"paused",progress:0,version:t.version})},qi=e=>{if(!we.delete(e))return;ye("resume app",e);let t=k.getState().downloads[e];(t==null?void 0:t.status)==="paused"&&!K.includes(e)&&wt(e)&&(Re[e]=0,qt(e)),K.includes(e)&&t&&ce(e,{status:"queued",progress:0,version:t.version}),De()},$i=e=>{let{pause_reasons:t}=k.getState();t.includes(e)||(k.setState({pause_reasons:[...t,e]}),ye("pause",e),t.length===0&&Fe({type:"pause_change",paused:!0,reasons:[e]}),R&&!R.forced&&R.handle.cancel())},zi=e=>{let{pause_reasons:t}=k.getState();if(!t.includes(e))return;let n=t.filter(o=>o!==e);k.setState({pause_reasons:n}),ye("resume",e),n.length===0&&Fe({type:"pause_change",paused:!1,reasons:n}),De()},dr=e=>k.getState().updates[e],Wi=async e=>{var n,o;let t=dr(e);Bt.add(e);try{let r=await $t(e),i=(o=t==null?void 0:t.next_version)!=null?o:(n=wt(e))==null?void 0:n.version;return!r||!i||r.version!==i?!1:(k.setState(a=>{var l;let c={...a.updates};return delete c[e],{updates:c,apply_ticks:{...a.apply_ticks,[e]:((l=a.apply_ticks[e])!=null?l:0)+1}}}),ye("updated",e,t==null?void 0:t.current_version,"\u2192",r.version),!0)}finally{Bt.delete(e)}},ji=()=>Object.values(k.getState().catalog).map(e=>({...e,installed:!!L(e.app_id),removed_by_user:Ne.has(e.app_id)})),wt=e=>k.getState().catalog[e],$t=async e=>{let t=wt(e);if(!t)return;if(we.delete(e),Ne.delete(e),await mn(t))return L(e);let n=L(e);if(lr(e)&&!Bt.has(e)&&n&&await Pe(n))return n;let o=new Promise(r=>{var i;((i=ze[e])!=null?i:ze[e]=[]).push(r)});return(R==null?void 0:R.app_id)===e?R.forced=!0:(Re[e]=0,qt(e,{front:!0}),R&&!R.forced?R.handle.cancel():De(e)),o};import{Fragment as Tn,jsx as Y,jsxs as Ye}from"react/jsx-runtime";var Cn=e=>(e!=null?e:"").replace(/\?[^#]*/,""),hr=0,Qi=()=>{let e=new Set;return{emit:t=>e.forEach(n=>n(t)),subscribe:t=>(e.add(t),()=>{e.delete(t)})}},Zi=On.memo(({instance_key:e,is_active:t,is_front:n,is_dark:o,reload_tick:r,web_at_top:i,splash:a,bridge:c,opaque_background:l,allow_embedded_miniapps:s,onWebLoadEnd:d})=>{var At,St;let u=be(null),y=be(!1),p=q(ae,h=>h.instances[e]),f=p==null?void 0:p.app.app_id,C=p==null?void 0:p.app.manifest_url,x=p==null?void 0:p.context,M=p==null?void 0:p.url_params,S=q(J,h=>{var w;return((w=h.active)==null?void 0:w.owner)===e?h.active:null}),[F,V]=Te(null),[Z,xe]=Te(S);S!==Z&&(xe(S),S?V(null):(Z==null?void 0:Z.layout)===ge.top&&V(Z));let ie=(S==null?void 0:S.layout)===ge.top?S:F,[v,m]=Te(()=>f?L(f):null),[E,_]=Te(!1),[I,me]=Te(0),[j,T]=Te(0),[ee,$]=Te(!1),X=be(null),te=h=>{X.current&&clearTimeout(X.current),X.current=setTimeout(()=>{X.current=null,$(!0)},h)};le(()=>()=>{X.current&&clearTimeout(X.current)},[]),le(()=>{if(!f||!t&&v)return;let h=!0;return _(!1),(async()=>{let w=L(f),b=w?await Pe(w):!1;if(!h||(m(b?oe=>!oe||oe.version!==w.version||oe.permissions.join(",")!==w.permissions.join(",")?w:oe:null),__DEV__&&Date.now()-hr>1e4&&(hr=Date.now(),await xn()),!h))return;let D=await $t(f),ne=D!==void 0?D:C?await Go(f,C):L(f);if(h){if(!ne){_(!0);return}m(oe=>oe!=null?oe:ne)}})(),()=>{h=!1}},[t,f,C,I]),le(()=>Ko(e,h=>u.current?(u.current.postMessage(h),!0):!1),[e]);let Ae=q(k,h=>{let w=f?h.downloads[f]:void 0;return(w==null?void 0:w.status)==="installed"?w.version:void 0});le(()=>{if(t||!f||!v)return;let h=L(f);if(!h||h.version===v.version)return;let w=!0;return Pe(h).then(b=>{!w||!b||(ue(`webview:${e}`,"\u0111\u1ED5i bundle (\u1EA9n)",v.version,"\u2192",h.version),m(h))}),()=>{w=!1}},[t,f,Ae,v==null?void 0:v.version]);let Se=q(k,h=>{var w;return f&&(w=h.apply_ticks[f])!=null?w:0});le(()=>{if(!Se||!f)return;let h=L(f);if(!h||h.version===(v==null?void 0:v.version))return;let w=!0;return Pe(h).then(b=>{!w||!b||(ue(`webview:${e}`,"c\u1EADp nh\u1EADt",v==null?void 0:v.version,"\u2192",h.version),$(!1),m(h))}),()=>{w=!1}},[Se]),le(()=>{var b;let h=(b=O().keep_alive)==null?void 0:b.idle_close_ms;if(t||!h||h<=0)return;let w=setTimeout(()=>{Nt(e)},h);return()=>clearTimeout(w)},[t,e]),le(()=>{r>0&&(_(!1),$(!1),T(h=>h+1),me(h=>h+1))},[r]);let We=be(t);le(()=>{var h;We.current!==t&&(We.current=t,y.current&&((h=u.current)==null||h.injectJavaScript(Do(t?"resumed":"paused"))))},[t]);let _e=`${(At=v==null?void 0:v.version)!=null?At:"none"}:${(St=v==null?void 0:v.permissions.join(","))!=null?St:""}:${j}`,Ee=zt(()=>JSON.stringify([x!=null?x:{},M!=null?M:{}]),[x,M]),Xe=zt(()=>{var h;return qo(M!=null?M:{},(h=v==null?void 0:v.permissions)!=null?h:[])},[Ee,v==null?void 0:v.permissions]),jt=zt(()=>Vo(x!=null?x:{},Xe)+Lo()+Fo()+(O().debug?Io():""),[Xe]),Ue=be(null),Qe=be(null);le(()=>{var w,b,D;if(!v)return;if(Qe.current!==_e){Qe.current=_e,Ue.current=Ee;return}if(Ue.current===Ee)return;let h=((b=JSON.parse((w=Ue.current)!=null?w:"[]")[0])!=null?b:{}).org_id;if(Ue.current=Ee,h===(x==null?void 0:x.org_id)&&y.current){$(!1),te(1500),(D=u.current)==null||D.injectJavaScript(No(x!=null?x:{},Xe));return}$(!1),T(ne=>ne+1)},[Ee,v,_e]),le(()=>(t||(Ce(e),Le(e),qe(e)),()=>{Ce(e),Le(e),qe(e)}),[t,e,_e,r]),le(()=>{let h=gr.addEventListener("change",w=>{w==="background"&&!ho()&&Ce(e),w==="background"&&!Ao()&&Le(e)});return()=>h.remove()},[e]);let Ze=Pn(async h=>{var b,D,ne,oe,Jt,In;let w=Ro(h.nativeEvent.data);if(!w){if(f&&(c!=null&&c.onWebEvent))try{Promise.resolve(c.onWebEvent(h.nativeEvent.data,{app_id:f,instance_id:e})).catch(B=>{console.warn("[miniapp] onWebEvent l\u1ED7i",f,B)})}catch(B){console.warn("[miniapp] onWebEvent l\u1ED7i",f,B)}return}if(w.method==="log"){let{level:B,text:z}=w;ue(`web:${e}`,B!=null?B:"log",z!=null?z:"");return}if(w.method==="pong"){X.current||$(!0);return}if(w.method==="touchAtTop"){i.emit(!!w.at_top);return}if(w.method==="contextApplied"){X.current&&clearTimeout(X.current),X.current=null,$(!0);return}if(w.method==="ready"){y.current=!0,$(!0);let B=(b=ae.getState().instances[e])==null?void 0:b.context;B&&((D=u.current)==null||D.injectJavaScript(cn(B)));return}try{let B=await zo(w,{getHostData:()=>{var z,pe;return(pe=(z=ae.getState().instances[e])==null?void 0:z.host_data)!=null?pe:{}},getPermissions:()=>{var z,pe;return f?(pe=(z=L(f))==null?void 0:z.permissions)!=null?pe:[]:[]},getContext:()=>{var z,pe;return(pe=(z=ae.getState().instances[e])==null?void 0:z.context)!=null?pe:{}},is_dark:o,close:ft,app_id:f!=null?f:"",instance_id:e,options:c,emit:(z,pe)=>{var Ln;(Ln=u.current)==null||Ln.injectJavaScript(ko(z,pe))},playBeep:(ne=c==null?void 0:c.playScannerBeep)!=null?ne:(()=>{var z;(z=u.current)==null||z.injectJavaScript($o())}),isActive:()=>ae.getState().active_key===e&&gr.currentState!=="background"});w.id&&((oe=u.current)==null||oe.injectJavaScript(To(w.id,B)))}catch(B){if(!w.id)return;let z=B==null?void 0:B.code,pe=B instanceof g?B:new g(typeof z=="string"?z:"HOST_ERROR",String((Jt=B==null?void 0:B.message)!=null?Jt:B));(In=u.current)==null||In.injectJavaScript(Oo(w.id,pe))}},[e,o,f,i,c]),Ht=Pn(()=>{_(!1),T(h=>h+1),me(h=>h+1)},[]);return Ye(Rn,{style:[kn.absoluteFill,l&&{backgroundColor:o?"#09090B":"#FFFFFF"},!n&&he.behind],pointerEvents:t?"auto":"none",children:[ie&&Y(An,{scanner:ie,closing:ie===F,onClosed:()=>{var h;V(null),ie.absolute&&((h=u.current)==null||h.injectJavaScript(ln(0)))},onHeight:ie.absolute?h=>{var w;return(w=u.current)==null?void 0:w.injectJavaScript(ln(h))}:void 0}),v?Y(Xi,{ref:u,source:{uri:v.entry_uri},originWhitelist:["*"],hideKeyboardAccessoryView:!0,mediaPlaybackRequiresUserAction:!1,allowingReadAccessToURL:`file://${s?dn():v.dir}`,allowFileAccess:!0,allowFileAccessFromFileURLs:!0,allowUniversalAccessFromFileURLs:!0,injectedJavaScriptBeforeContentLoaded:jt,onMessage:Ze,onShouldStartLoadWithRequest:h=>{let w=h.url;return h.isTopFrame===!1||!/^https?:\/\//i.test(w)?!0:(Promise.resolve(c!=null&&c.openUrl?c.openUrl(w):Ki.openURL(w)).catch(()=>{}),!1)},setSupportMultipleWindows:!1,bounces:!1,overScrollMode:"never",onLoadStart:h=>{Ce(e),Le(e),qe(e),ue(`webview:${e}`,"load start",Cn(h.nativeEvent.url)),y.current=!1,$(!1)},onError:h=>{Ce(e),Le(e),qe(e),ue(`webview:${e}`,"load error",Cn(h.nativeEvent.url),h.nativeEvent.description),_(!0),$(!1)},onLoadEnd:h=>{let w=h.nativeEvent.url;ue(`webview:${e}`,"load end",Cn(w)),f&&(d==null||d({app_id:f,instance_id:e,url:w})),te(1500)},onContentProcessDidTerminate:()=>{Ce(e),Le(e),qe(e),y.current=!1,$(!1),T(h=>h+1)},onRenderProcessGone:()=>(Ce(e),Le(e),qe(e),y.current=!1,$(!1),T(h=>h+1),!0),style:he.webview},_e):null,(S==null?void 0:S.layout)===ge.full&&Y(An,{scanner:S}),p&&Y(ts,{visible:!v||!ee,interactive:E,children:Y(es,{splash:a,app:p.app,is_dark:o,error:E,has_bundle:!!v,retry:Ht})})]})}),es=On.memo(({splash:e,app:t,is_dark:n,error:o,has_bundle:r,retry:i})=>{let a=e,c=Mn(t.app_id),l=o?"error":!r&&(c==null?void 0:c.status)==="downloading"?"downloading":"loading";return Y(a,{app:t,is_dark:n,status:l,progress:l==="downloading"?c==null?void 0:c.progress:void 0,retry:i})}),ts=({visible:e,interactive:t,children:n})=>{let o=be(new En.Value(e?1:0)).current,[r,i]=Te(e);return le(()=>{if(e){i(!0),o.setValue(1);return}let a=En.timing(o,{toValue:0,duration:180,useNativeDriver:!0});return a.start(({finished:c})=>{c&&i(!1)}),()=>a.stop()},[e,o]),r?Y(En.View,{style:[kn.absoluteFill,{opacity:o}],pointerEvents:t?"auto":"none",children:n}):null},fr=({app:e,is_dark:t,status:n,progress:o,retry:r})=>{let i=t?"#FAFAFA":"#18181B";return Ye(Rn,{style:[he.splash,{backgroundColor:t?"#09090B":"#FFFFFF"}],children:[Y(Rn,{style:[he.splash_icon,{backgroundColor:t?"#18181B":"#F4F4F5"}],children:e.icon?Y(Gi,{source:{uri:e.icon},style:he.splash_icon_image}):Y(bt,{style:he.splash_letter,children:(e.name||"?").slice(0,1).toUpperCase()})}),Y(bt,{style:[he.splash_name,{color:i}],children:e.name}),n==="error"?Ye(Tn,{children:[Y(bt,{style:he.splash_hint,children:"Kh\xF4ng t\u1EA3i \u0111\u01B0\u1EE3c mini app"}),Y(Yi,{activeOpacity:.7,style:[he.retry_button,{backgroundColor:t?"#27272A":"#F4F4F5"}],onPress:r,children:Y(bt,{style:[he.retry_text,{color:i}],children:"Th\u1EED l\u1EA1i"})})]}):Ye(Tn,{children:[Y(Hi,{style:he.splash_spinner,color:t?"#A1A1AA":"#71717A"}),n==="downloading"&&Ye(bt,{style:he.splash_hint,children:["\u0110ang t\u1EA3i mini app",o?` ${Math.round(o*100)}%`:"\u2026"]})]})]})},mr=(e,t)=>{let n=be(t),o=be(!1);__DEV__&&!o.current&&n.current!==t&&(o.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.`))},ns=({container:e,splash:t=fr,is_dark:n=!1,bridge:o,close_on_back:r=!0,opaque_background:i=!0,allow_embedded_miniapps:a=!1,onWebLoadEnd:c})=>{mr("container",e),mr("splash",t);let l=e,s=q(ae,S=>S.active_key),d=be(s);s&&(d.current=s);let u=q(ae,S=>Object.keys(S.instances).join("|")),y=q(ae,S=>{var F;return S.active_key?(F=S.instances[S.active_key])==null?void 0:F.app.name:void 0}),p=zt(()=>u?u.split("|"):[],[u]),[f,C]=Te({}),x=be(Qi()).current;le(()=>{if(!s||!r)return;let S=Ji.addEventListener("hardwareBackPress",()=>(ft(),!0));return()=>S.remove()},[s,r]);let M=Pn(()=>{let S=ae.getState().active_key;S&&C(F=>({...F,[S]:(F[S]||0)+1}))},[]);return p.length?Ye(Tn,{children:[Y(l,{visible:!!s,title:y!=null?y:"",is_dark:n,close:ft,reload:M,subscribeWebAtTop:x.subscribe,children:p.map(S=>Y(Zi,{instance_key:S,is_active:s===S,is_front:(s!=null?s:d.current)===S,is_dark:n,reload_tick:f[S]||0,web_at_top:x,splash:t,bridge:o,opaque_background:i,allow_embedded_miniapps:a,onWebLoadEnd:c},S))}),Y(sr,{})]}):null},he=kn.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"}}),os=On.memo(ns);import{useCallback as rs,useEffect as is,useState as Wt}from"react";var yr=e=>`changelog_seen:${e}`,ss=10*1e3,wr=e=>O().storage.getString(yr(e))||null,br=(e,t=(n=>(n=L(e))==null?void 0:n.version)())=>{t&&O().storage.setString(yr(e),t)},as=e=>{var o;let t=(o=L(e))==null?void 0:o.version;if(!t)return null;let n=wr(e);return n?fn(t,n)>0?{app_id:e,from:n,to:t}:null:(br(e,t),null)},cs=e=>{var t,n,o;return(o=(n=(t=k.getState().catalog[e])==null?void 0:t.channel)!=null?n:O().channels[0])!=null?o:"production"},Ar=async(e,{from:t,to:n,channel:o=cs(e)}={})=>{let{client_token:r}=O(),i=new URLSearchParams({channel:o});t&&i.set("from",t),n&&i.set("to",n);let a=new AbortController,c=setTimeout(()=>a.abort(),ss);try{let l=await fetch(`${et}/api/miniapps/${encodeURIComponent(e)}/changelog?${i}`,{headers:{Authorization:`Bearer ${r}`},signal:a.signal});if(!l.ok)throw new Error(`changelog ${e} ${l.status}`);return(await l.json()).versions}finally{clearTimeout(c)}},ls=(e,{from:t,to:n,enabled:o=!0}={})=>{let[r,i]=Wt([]),[a,c]=Wt(!1),[l,s]=Wt(),[d,u]=Wt(0),y=rs(()=>u(p=>p+1),[]);return is(()=>{if(!e||!o)return;let p=!0;return c(!0),s(void 0),Ar(e,{from:t,to:n}).then(f=>{p&&i(f)}).catch(f=>{var C;p&&s(String((f==null?void 0:f.name)==="AbortError"?"timeout":(C=f==null?void 0:f.message)!=null?C:f))}).finally(()=>{p&&c(!1)}),()=>{p=!1}},[e,t,n,o,d]),{versions:r,loading:a,error:l,reload:y}};export{re as CodeType,fr as DefaultMiniAppSplash,et as MINIAPP_PLATFORM_URL,os as MiniAppHost,g as MiniAppHostError,He as ScannerEndReason,en as ScannerEvent,ge as ScannerLayout,at as ScannerMethod,fe as ToastType,ft as closeMiniApp,Sr as configureMiniApp,vr as createMmkvStorage,Nn as createReactNativeBiometrics,_r as createRnfsFileSystem,$t as ensureMiniApp,Ar as fetchMiniAppChangelog,L as getLocalMiniApp,ji as getMiniAppCatalog,wt as getMiniAppCatalogEntry,wr as getMiniAppChangelogSeen,Fi as getMiniAppStatuses,dr as getMiniAppUpdate,as as getPendingChangelog,ii as installBundledMiniApp,br as markMiniAppChangelogSeen,Li as onMiniAppEvent,xi as openMiniApp,Bi as pauseMiniApp,$i as pauseMiniAppDownloads,Ei as preloadMiniApp,Ce as releaseSpeechFor,Vi as restoreMiniApp,qi as resumeMiniApp,zi as resumeMiniAppDownloads,ai as sendEventToWeb,xn as syncMiniAppCatalog,Ui as uninstallMiniApp,Wi as updateMiniApp,Zn as uploadToUrl,ls as useMiniAppChangelog,Mn as useMiniAppDownload,Ii as useMiniAppDownloadsPaused};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@retion-miniapp/react-native",
3
- "version": "0.16.0",
3
+ "version": "0.17.0",
4
4
  "description": "React Native host for Retion Mini Apps with built-in biometric authentication",
5
5
  "license": "MIT",
6
6
  "repository": {