@retion-miniapp/react-native 0.10.0 → 0.10.2

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/README.md CHANGED
@@ -22,8 +22,8 @@ Cài package không sửa được binary đã cài trên thiết bị. Nếu bi
22
22
 
23
23
  ## Phiên bản và điều kiện tích hợp
24
24
 
25
- Tài liệu hiện tại mô tả **Mini App React Native 0.10.0 + Web SDK 0.10.0**. Package khai báo React ≥18, React Native ≥0.72, Expo ≥52 và WebView ≥13; đây là giới hạn khai báo, không phải cam kết mọi tổ hợp phiên bản native đã được kiểm tra. App React Native thuần cần tích hợp Expo Modules để dùng thư viện speech.
25
+ Tài liệu hiện tại mô tả **Mini App React Native 0.10.1 + Web SDK 0.10.0**. Package khai báo React ≥18, React Native ≥0.72, Expo ≥52 và WebView ≥13; đây là giới hạn khai báo, không phải cam kết mọi tổ hợp phiên bản native đã được kiểm tra. App React Native thuần cần tích hợp Expo Modules để dùng thư viện speech.
26
26
 
27
- Package tự cài `react-native-biometrics@3.0.1`, `expo-speech-recognition@1.1.1`, `@react-native-community/geolocation@3.4.0` và `react-native-image-picker@8.2.1`. Nguồn tài liệu (`createDocumentPickerSource`) dùng `@react-native-documents/picker` do app tự cài. Nếu app cũng dùng các thư viện này cho chức năng khác, đồng bộ phiên bản để tránh trùng module native. Với Expo 57, xem lưu ý bản vá của thư viện speech trong [hướng dẫn speech](docs/SPEECH.md).
27
+ Package tự cài `react-native-biometrics@3.0.1`, `expo-speech-recognition@1.1.1`, `@react-native-community/geolocation@3.4.0`, `react-native-image-picker@8.2.1`, `@react-native-documents/picker@12.0.2` và `react-native-compressor@1.13.0`. Nếu app cũng dùng các thư viện này cho chức năng khác, đồng bộ phiên bản để tránh trùng module native. Với Expo 57, xem lưu ý bản vá của thư viện speech trong [hướng dẫn speech](docs/SPEECH.md).
28
28
 
29
29
  Trong lúc bản mới chưa phát hành lên npm, có thể dùng package local để thử. Trước khi phát hành app từ CI hoặc chia sẻ dự án độc lập, chuyển dependency `file:../...` về phiên bản npm đã publish và cập nhật lockfile.
package/dist/index.d.mts CHANGED
@@ -180,11 +180,19 @@ interface MiniAppPickedFile {
180
180
  /** Nguồn đã tự nén theo `process` → bỏ qua processors. */
181
181
  processed?: boolean;
182
182
  }
183
+ /** Mini app đang gọi upload — vd lấy page_id từ context để xin URL upload theo page. */
184
+ interface MiniAppUploadCaller {
185
+ app_id: string;
186
+ instance_id: string;
187
+ /** Context lúc openMiniApp (page_id, client_id…). */
188
+ context: MiniAppContext;
189
+ }
183
190
  interface MiniAppUploadSourceRequest {
184
191
  /** Như <input accept>; [] = mọi file. Lõi lọc lại sau khi chọn — nguồn chỉ cần dùng làm gợi ý. */
185
192
  accept: string[];
186
193
  max_count: number;
187
194
  process: MiniAppUploadProcessOptions;
195
+ caller: MiniAppUploadCaller;
188
196
  }
189
197
  /** Nguồn lấy file (UI chọn). Người dùng huỷ → trả []. */
190
198
  type MiniAppUploadSource = (request: MiniAppUploadSourceRequest) => Promise<MiniAppPickedFile[]>;
@@ -211,6 +219,7 @@ interface MiniAppUploadRequest {
211
219
  onProgress: (loaded: number, total: number) => void;
212
220
  /** Web huỷ / đóng mini app → abort; uploader nên dừng request. */
213
221
  signal: AbortSignal;
222
+ caller: MiniAppUploadCaller;
214
223
  }
215
224
  /** Upload 1 file, trả link (+ trường thêm → web nhận trong `response`). */
216
225
  type MiniAppUploader = (request: MiniAppUploadRequest) => Promise<{
@@ -218,8 +227,9 @@ type MiniAppUploader = (request: MiniAppUploadRequest) => Promise<{
218
227
  [key: string]: unknown;
219
228
  }>;
220
229
  /**
221
- * Cấu hình uploadFiles. Có sẵn: source `library`, `camera` (react-native-image-picker), target `url`.
222
- * Ghi đè / thêm theo tên; `null` để tắt 1 nguồn có sẵn.
230
+ * Cấu hình uploadFiles — TUỲ CHỌN. Không truyền gì vẫn có: source `library`, `camera`, `document`,
231
+ * nén ảnh / video (react-native-compressor), target `url`. App chỉ cần khai báo `targets.host` nếu muốn
232
+ * mini app upload lên máy chủ của app. Ghi đè / thêm theo tên; `null` để tắt 1 nguồn có sẵn.
223
233
  */
224
234
  interface MiniAppUploadOptions {
225
235
  sources?: Record<string, MiniAppUploadSource | null>;
@@ -227,7 +237,7 @@ interface MiniAppUploadOptions {
227
237
  image?: MiniAppUploadProcessor;
228
238
  video?: MiniAppUploadProcessor;
229
239
  };
230
- /** Vd `host`: upload lên máy chủ của app (token của app). `url` là đích chuẩn, không ghi đè được. */
240
+ /** `host`: upload lên máy chủ của app (API + token của app). `url` là đích chuẩn, không ghi đè được. */
231
241
  targets?: Record<string, MiniAppUploader>;
232
242
  }
233
243
  /** Kiểu rung web gửi qua haptic() — trùng tên trigger của react-native-haptic-feedback. */
@@ -670,34 +680,7 @@ interface UploadCapabilities {
670
680
  targets: string[];
671
681
  max_count: number;
672
682
  }
673
- /** Phần @react-native-documents/picker adapter dùng — app truyền module, package không import. */
674
- interface DocumentPickerLike {
675
- pick: (options: {
676
- type?: string | string[];
677
- allowMultiSelection?: boolean;
678
- mode?: 'import';
679
- }) => Promise<{
680
- uri: string;
681
- name: string | null;
682
- type: string | null;
683
- size: number | null;
684
- error?: string | null;
685
- }[]>;
686
- types: Record<string, string | readonly string[]>;
687
- isErrorWithCode?: (error: unknown) => boolean;
688
- errorCodes?: {
689
- OPERATION_CANCELED: string;
690
- IN_PROGRESS?: string;
691
- };
692
- }
693
- /**
694
- * Nguồn chọn mọi loại file. accept lạ (không map được) → mở toàn bộ file rồi lõi lọc lại theo accept.
695
- * @example
696
- * import * as DocumentPicker from '@react-native-documents/picker';
697
- * <MiniAppHost bridge={{ upload: { sources: { document: createDocumentPickerSource(DocumentPicker) } } }} />
698
- */
699
- declare const createDocumentPickerSource: (picker: DocumentPickerLike) => MiniAppUploadSource;
700
683
  /** 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. */
701
684
  declare const uploadToUrl: MiniAppUploader;
702
685
 
703
- export { DefaultMiniAppSplash, type DocumentPickerLike, 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 MiniAppSplashProps, type MiniAppStorage, type MiniAppSyncResult, type MiniAppUpdate, type MiniAppUploadOptions, type MiniAppUploadProcessOptions, type MiniAppUploadProcessor, type MiniAppUploadRequest, type MiniAppUploadSource, type MiniAppUploadSourceRequest, type MiniAppUploadTarget, type MiniAppUploader, type MiniAppUrlUploadTarget, type OpenMiniAppArgs, type ReactNativeBiometricsLike, type SpeechOptions, type UploadCapabilities, type UploadFilesResult, type UploadedFile, closeMiniApp, configureMiniApp, createDocumentPickerSource, 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 };
686
+ export { 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 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, type SpeechOptions, type UploadCapabilities, 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 };
package/dist/index.d.ts CHANGED
@@ -180,11 +180,19 @@ interface MiniAppPickedFile {
180
180
  /** Nguồn đã tự nén theo `process` → bỏ qua processors. */
181
181
  processed?: boolean;
182
182
  }
183
+ /** Mini app đang gọi upload — vd lấy page_id từ context để xin URL upload theo page. */
184
+ interface MiniAppUploadCaller {
185
+ app_id: string;
186
+ instance_id: string;
187
+ /** Context lúc openMiniApp (page_id, client_id…). */
188
+ context: MiniAppContext;
189
+ }
183
190
  interface MiniAppUploadSourceRequest {
184
191
  /** Như <input accept>; [] = mọi file. Lõi lọc lại sau khi chọn — nguồn chỉ cần dùng làm gợi ý. */
185
192
  accept: string[];
186
193
  max_count: number;
187
194
  process: MiniAppUploadProcessOptions;
195
+ caller: MiniAppUploadCaller;
188
196
  }
189
197
  /** Nguồn lấy file (UI chọn). Người dùng huỷ → trả []. */
190
198
  type MiniAppUploadSource = (request: MiniAppUploadSourceRequest) => Promise<MiniAppPickedFile[]>;
@@ -211,6 +219,7 @@ interface MiniAppUploadRequest {
211
219
  onProgress: (loaded: number, total: number) => void;
212
220
  /** Web huỷ / đóng mini app → abort; uploader nên dừng request. */
213
221
  signal: AbortSignal;
222
+ caller: MiniAppUploadCaller;
214
223
  }
215
224
  /** Upload 1 file, trả link (+ trường thêm → web nhận trong `response`). */
216
225
  type MiniAppUploader = (request: MiniAppUploadRequest) => Promise<{
@@ -218,8 +227,9 @@ type MiniAppUploader = (request: MiniAppUploadRequest) => Promise<{
218
227
  [key: string]: unknown;
219
228
  }>;
220
229
  /**
221
- * Cấu hình uploadFiles. Có sẵn: source `library`, `camera` (react-native-image-picker), target `url`.
222
- * Ghi đè / thêm theo tên; `null` để tắt 1 nguồn có sẵn.
230
+ * Cấu hình uploadFiles — TUỲ CHỌN. Không truyền gì vẫn có: source `library`, `camera`, `document`,
231
+ * nén ảnh / video (react-native-compressor), target `url`. App chỉ cần khai báo `targets.host` nếu muốn
232
+ * mini app upload lên máy chủ của app. Ghi đè / thêm theo tên; `null` để tắt 1 nguồn có sẵn.
223
233
  */
224
234
  interface MiniAppUploadOptions {
225
235
  sources?: Record<string, MiniAppUploadSource | null>;
@@ -227,7 +237,7 @@ interface MiniAppUploadOptions {
227
237
  image?: MiniAppUploadProcessor;
228
238
  video?: MiniAppUploadProcessor;
229
239
  };
230
- /** Vd `host`: upload lên máy chủ của app (token của app). `url` là đích chuẩn, không ghi đè được. */
240
+ /** `host`: upload lên máy chủ của app (API + token của app). `url` là đích chuẩn, không ghi đè được. */
231
241
  targets?: Record<string, MiniAppUploader>;
232
242
  }
233
243
  /** Kiểu rung web gửi qua haptic() — trùng tên trigger của react-native-haptic-feedback. */
@@ -670,34 +680,7 @@ interface UploadCapabilities {
670
680
  targets: string[];
671
681
  max_count: number;
672
682
  }
673
- /** Phần @react-native-documents/picker adapter dùng — app truyền module, package không import. */
674
- interface DocumentPickerLike {
675
- pick: (options: {
676
- type?: string | string[];
677
- allowMultiSelection?: boolean;
678
- mode?: 'import';
679
- }) => Promise<{
680
- uri: string;
681
- name: string | null;
682
- type: string | null;
683
- size: number | null;
684
- error?: string | null;
685
- }[]>;
686
- types: Record<string, string | readonly string[]>;
687
- isErrorWithCode?: (error: unknown) => boolean;
688
- errorCodes?: {
689
- OPERATION_CANCELED: string;
690
- IN_PROGRESS?: string;
691
- };
692
- }
693
- /**
694
- * Nguồn chọn mọi loại file. accept lạ (không map được) → mở toàn bộ file rồi lõi lọc lại theo accept.
695
- * @example
696
- * import * as DocumentPicker from '@react-native-documents/picker';
697
- * <MiniAppHost bridge={{ upload: { sources: { document: createDocumentPickerSource(DocumentPicker) } } }} />
698
- */
699
- declare const createDocumentPickerSource: (picker: DocumentPickerLike) => MiniAppUploadSource;
700
683
  /** 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. */
701
684
  declare const uploadToUrl: MiniAppUploader;
702
685
 
703
- export { DefaultMiniAppSplash, type DocumentPickerLike, 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 MiniAppSplashProps, type MiniAppStorage, type MiniAppSyncResult, type MiniAppUpdate, type MiniAppUploadOptions, type MiniAppUploadProcessOptions, type MiniAppUploadProcessor, type MiniAppUploadRequest, type MiniAppUploadSource, type MiniAppUploadSourceRequest, type MiniAppUploadTarget, type MiniAppUploader, type MiniAppUrlUploadTarget, type OpenMiniAppArgs, type ReactNativeBiometricsLike, type SpeechOptions, type UploadCapabilities, type UploadFilesResult, type UploadedFile, closeMiniApp, configureMiniApp, createDocumentPickerSource, 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 };
686
+ export { 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 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, type SpeechOptions, type UploadCapabilities, 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 };
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var Un=Object.create;var Ce=Object.defineProperty;var Fn=Object.getOwnPropertyDescriptor;var $n=Object.getOwnPropertyNames;var Bn=Object.getPrototypeOf,qn=Object.prototype.hasOwnProperty;var Vn=(e,t)=>{for(var n in t)Ce(e,n,{get:t[n],enumerable:!0})},Mt=(e,t,n,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of $n(t))!qn.call(e,o)&&o!==n&&Ce(e,o,{get:()=>t[o],enumerable:!(i=Fn(t,o))||i.enumerable});return e};var he=(e,t,n)=>(n=e!=null?Un(Bn(e)):{},Mt(t||!e||!e.__esModule?Ce(n,"default",{value:e,enumerable:!0}):n,e)),jn=e=>Mt(Ce({},"__esModule",{value:!0}),e);var vi={};Vn(vi,{DefaultMiniAppSplash:()=>mt,MINIAPP_PLATFORM_URL:()=>Ie,MiniAppHost:()=>In,MiniAppHostError:()=>d,closeMiniApp:()=>we,configureMiniApp:()=>_t,createDocumentPickerSource:()=>Dt,createMmkvStorage:()=>xt,createReactNativeBiometrics:()=>Xe,createRnfsFileSystem:()=>St,ensureMiniApp:()=>Oe,getLocalMiniApp:()=>O,getMiniAppCatalog:()=>On,getMiniAppCatalogEntry:()=>ye,getMiniAppStatuses:()=>Mn,getMiniAppUpdate:()=>gt,installBundledMiniApp:()=>cn,onMiniAppEvent:()=>yn,openMiniApp:()=>gn,pauseMiniApp:()=>Sn,pauseMiniAppDownloads:()=>En,preloadMiniApp:()=>fn,releaseSpeechFor:()=>X,restoreMiniApp:()=>bn,resumeMiniApp:()=>xn,resumeMiniAppDownloads:()=>Pn,sendEventToWeb:()=>un,syncMiniAppCatalog:()=>Ke,uninstallMiniApp:()=>_n,updateMiniApp:()=>Rn,uploadToUrl:()=>tt,useMiniAppDownload:()=>ze,useMiniAppDownloadsPaused:()=>wn});module.exports=jn(vi);var Ie="https://retion-miniapp-platform.vercel.app",ge=null,vt=new Set,_t=e=>{ge=e,vt.forEach(t=>t())},k=()=>{if(!ge)throw new Error("[miniapp] Ch\u01B0a g\u1ECDi configureMiniApp()");return ge},bt=e=>{vt.add(e),ge&&e()},H=(...e)=>{ge!=null&&ge.debug&&console.log("[miniapp]",...e)};var St=(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(i=>i.map(o=>o.name)).catch(()=>[]),sha256:n=>e.hash(n,"sha256"),unzip:async(n,i)=>{await t(n,i)},download:({url:n,to_file:i,onProgress:o})=>{let{jobId:s,promise:c}=e.downloadFile({fromUrl:n,toFile:i,progressInterval:250,begin:()=>{},progress:({bytesWritten:a,contentLength:r})=>o==null?void 0:o(a,r)});return{promise:c.then(({statusCode:a})=>({status:a})),cancel:()=>e.stopDownload(s)}}}),xt=e=>({getString:t=>e.getString(t),setString:(t,n)=>e.set(t,n)});var y=he(require("react")),S=require("react-native"),Cn=he(require("react-native-webview"));var Se=require("react-native");var Xe=e=>({getAvailability:()=>e.isSensorAvailable(),authenticate:({reason:t,cancelButtonText:n})=>e.simplePrompt({promptMessage:t,cancelButtonText:n,fallbackPromptMessage:""})}),Le,Ze=()=>(Le||(Le=import("react-native-biometrics").then(({default:e})=>Xe(new e({allowDeviceCredentials:!1}))).catch(e=>{throw Le=void 0,new d("NOT_SUPPORTED",`Biometric native module unavailable: ${e instanceof Error?e.message:String(e)}`)})),Le);var Q=require("react-native");var Et=e=>{var n,i,o;if(e!==void 0&&(e===null||typeof e!="object"||Array.isArray(e)))throw new d("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 d("INVALID_PARAMS","enableHighAccuracy ph\u1EA3i l\xE0 boolean");for(let[s,c,a]of[["timeout",1,6e4],["maximumAge",0,864e5]]){let r=t[s];if(r!==void 0&&(typeof r!="number"||!Number.isFinite(r)||r<c||r>a))throw new d("INVALID_PARAMS",`${s} ph\u1EA3i n\u1EB1m trong kho\u1EA3ng ${c}\u2013${a} ms`)}return{enableHighAccuracy:(n=t.enableHighAccuracy)!=null?n:!1,timeout:(i=t.timeout)!=null?i:15e3,maximumAge:(o=t.maximumAge)!=null?o:0}},Pt=(e,t=()=>!0)=>new Promise((n,i)=>{let o=!1,s=(r,l)=>{o||(o=!0,clearTimeout(c),r?i(r):n(l))},c=setTimeout(()=>s(new d("TIMEOUT","H\u1EBFt th\u1EDDi gian ch\u1EDD c\u1EA5p quy\u1EC1n/l\u1EA5y v\u1ECB tr\xED")),12e4+e.timeout),a=()=>o?!1:t()?!0:(s(new d("CANCELLED","Mini app kh\xF4ng c\xF2n ho\u1EA1t \u0111\u1ED9ng")),!1);(async()=>{if(!a())return;let r;try{r=(await import("@react-native-community/geolocation")).default}catch{throw new d("NOT_SUPPORTED","Ch\u01B0a c\xF3 module v\u1ECB tr\xED trong b\u1EA3n native")}if(a()){if(Q.Platform.OS==="android"){let l=Q.PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,u=Q.PermissionsAndroid.PERMISSIONS.ACCESS_COARSE_LOCATION,p=await Q.PermissionsAndroid.check(l);if(!a())return;let h=p||await Q.PermissionsAndroid.check(u);if(!a())return;if(!p&&!h){let A=await Q.PermissionsAndroid.requestMultiple([l,u]);if(!a())return;if(A[l]!==Q.PermissionsAndroid.RESULTS.GRANTED&&A[u]!==Q.PermissionsAndroid.RESULTS.GRANTED)throw new d("PERMISSION_DENIED","Ch\u01B0a c\u1EA5p quy\u1EC1n truy c\u1EADp v\u1ECB tr\xED")}}a()&&r.getCurrentPosition(l=>{a()&&s(void 0,l)},l=>{var p;if(!a())return;let u=(p={1:"PERMISSION_DENIED",2:"POSITION_UNAVAILABLE",3:"TIMEOUT"}[l.code])!=null?p:"LOCATION_ERROR";s(new d(u,l.message))},e)}})().catch(r=>s(r))});var kt=require("react-native");var et=20,Rt=20,Ct=/^[a-z][a-z0-9_-]{0,31}$/,Hn=/^(\.[\w-]{1,16}|[\w.+-]+\/(\*|[\w.+-]+))$/,Wn=["low","medium","high"],ae=e=>!!e&&typeof e=="object"&&!Array.isArray(e),N=e=>new d("INVALID_PARAMS",e),_e=(e,t,n)=>typeof e=="number"&&Number.isInteger(e)&&e>=t&&e<=n,Ot=(e,t)=>{if(e===void 0)return{};if(!ae(e)||Object.keys(e).length>Rt||Object.values(e).some(n=>typeof n!="string"))throw N(`${t} ph\u1EA3i l\xE0 object chu\u1ED7i (t\u1ED1i \u0111a ${Rt} key)`);return e},It=e=>{var n,i,o,s;if(e!==void 0&&!ae(e))throw N("Tu\u1EF3 ch\u1ECDn upload ph\u1EA3i l\xE0 object");let t=e!=null?e:{};if(t.source!==void 0&&(typeof t.source!="string"||!Ct.test(t.source)))throw N("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(c=>typeof c!="string"||!Hn.test(c))))throw N("accept ph\u1EA3i l\xE0 m\u1EA3ng mime (image/*, application/pdf) ho\u1EB7c \u0111u\xF4i (.docx)");if(t.max_count!==void 0&&!_e(t.max_count,1,et))throw N(`max_count ph\u1EA3i l\xE0 s\u1ED1 nguy\xEAn 1\u2013${et}`);if(t.max_size!==void 0&&!_e(t.max_size,1,Number.MAX_SAFE_INTEGER))throw N("max_size ph\u1EA3i l\xE0 s\u1ED1 byte > 0");if(t.concurrency!==void 0&&!_e(t.concurrency,1,5))throw N("concurrency ph\u1EA3i l\xE0 s\u1ED1 nguy\xEAn 1\u20135");return{source:(n=t.source)!=null?n:"library",accept:((i=t.accept)!=null?i:[]).map(c=>c.toLowerCase()),max_count:(o=t.max_count)!=null?o:1,max_size:t.max_size,process:zn(t.process),target:Jn(t.upload),concurrency:(s=t.concurrency)!=null?s:3}},zn=e=>{if(e===void 0)return{};if(!ae(e))throw N("process ph\u1EA3i l\xE0 object");let t={};if(e.image!==void 0){let n=e.image;if(!ae(n))throw N("process.image ph\u1EA3i l\xE0 object");for(let i of["max_width","max_height"])if(n[i]!==void 0&&!_e(n[i],1,1e4))throw N(`process.image.${i} 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 N("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(!ae(n))throw N("process.video ph\u1EA3i l\xE0 object");if(n.max_duration!==void 0&&!_e(n.max_duration,1,3600))throw N("process.video.max_duration ph\u1EA3i l\xE0 s\u1ED1 gi\xE2y 1\u20133600");if(n.quality!==void 0&&!Wn.includes(n.quality))throw N("process.video.quality ph\u1EA3i l\xE0 low | medium | high");t.video={max_duration:n.max_duration,quality:n.quality}}return t},Jn=e=>{var n,i,o,s;if(e===void 0)return{target:"host",params:{}};if(!ae(e))throw N("upload ph\u1EA3i l\xE0 object");let t=(n=e.target)!=null?n:"host";if(typeof t!="string"||!Ct.test(t))throw N("upload.target ph\u1EA3i l\xE0 t\xEAn \u0111\xEDch, vd host | url");if(t!=="url"){if(e.params!==void 0&&!ae(e.params))throw N("upload.params ph\u1EA3i l\xE0 object");return{target:t,params:(i=e.params)!=null?i:{}}}if(typeof e.url!="string"||!/^https:\/\//i.test(e.url))throw N("upload.url ph\u1EA3i l\xE0 https");for(let c of["field_name","url_field"])if(e[c]!==void 0&&(typeof e[c]!="string"||!e[c]))throw N(`upload.${c} ph\u1EA3i l\xE0 chu\u1ED7i`);return{target:"url",url:e.url,headers:Ot(e.headers,"upload.headers"),form_data:Ot(e.form_data,"upload.form_data"),field_name:(o=e.field_name)!=null?o:"file",url_field:(s=e.url_field)!=null?s:"url"}},Lt=e=>{let t=e.lastIndexOf(".");return t>0?e.slice(t).toLowerCase():""},Kn=(e,t)=>{if(!t.length)return!0;let n=e.mime_type.toLowerCase(),i=Lt(e.name);return t.some(o=>o==="*/*"?!0:o.startsWith(".")?o===i:o.endsWith("/*")?n.startsWith(o.slice(0,-1)):n===o)},Yn=e=>{let t=e.length>0&&e.every(i=>i.startsWith("image/")),n=e.length>0&&e.every(i=>i.startsWith("video/"));return t?"image":n?"video":"mixed"},ve,Gn=()=>(ve!=null||(ve=import("react-native-image-picker").catch(e=>{throw ve=void 0,new d("NOT_SUPPORTED",`Ch\u01B0a c\xF3 module ch\u1ECDn \u1EA3nh trong b\u1EA3n native: ${e instanceof Error?e.message:String(e)}`)})),ve),Tt=e=>async({accept:t,max_count:n,process:i})=>{var r,l,u,p,h,A,w,I,P;let o=await Gn(),s=Yn(t),c={mediaType:s==="image"?"photo":s,maxWidth:(r=i.image)==null?void 0:r.max_width,maxHeight:(l=i.image)==null?void 0:l.max_height,quality:(p=(u=i.image)==null?void 0:u.quality)!=null?p:.8,videoQuality:(A=(h=i.video)==null?void 0:h.quality)!=null?A:"medium",durationLimit:(w=i.video)==null?void 0:w.max_duration,assetRepresentationMode:"compatible"},a=e==="camera"?await o.launchCamera({...c,saveToPhotos:!1}):await o.launchImageLibrary({...c,selectionLimit:n});if(a.didCancel)return[];if(a.errorCode){let x=a.errorCode==="permission"?"PERMISSION_DENIED":a.errorCode==="camera_unavailable"?"NOT_SUPPORTED":"HOST_ERROR";throw new d(x,(I=a.errorMessage)!=null?I:a.errorCode)}return((P=a.assets)!=null?P:[]).filter(x=>x.uri).map((x,m)=>{var L,J,$;return{uri:x.uri,name:(L=x.fileName)!=null?L:`file_${m+1}`,mime_type:(J=x.type)!=null?J:"application/octet-stream",size:x.fileSize,width:x.width,height:x.height,duration:x.duration,processed:!(($=x.type)!=null&&$.startsWith("video/"))||kt.Platform.OS==="ios"}})},Qn={"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"},Xn={".pdf":"pdf",".txt":"plainText",".csv":"csv",".json":"json",".zip":"zip",".doc":"doc",".docx":"docx",".xls":"xls",".xlsx":"xlsx",".ppt":"ppt",".pptx":"pptx"},Dt=e=>async({accept:t,max_count:n})=>{var s,c,a,r;let i=t.map(l=>{var u;return(u=Qn[l])!=null?u:Xn[l]}),o=!t.length||i.some(l=>!l||!e.types[l])?e.types.allFiles:[...new Set(i)].flatMap(l=>e.types[l]);try{return(await e.pick({type:o,allowMultiSelection:n>1,mode:"import"})).filter(u=>u.uri&&!u.error).map((u,p)=>{var h,A,w;return{uri:u.uri,name:(h=u.name)!=null?h:`file_${p+1}`,mime_type:(A=u.type)!=null?A:"application/octet-stream",size:(w=u.size)!=null?w:void 0}})}catch(l){let u=l==null?void 0:l.code;if(u===((c=(s=e.errorCodes)==null?void 0:s.OPERATION_CANCELED)!=null?c:"OPERATION_CANCELED"))return[];throw u===((r=(a=e.errorCodes)==null?void 0:a.IN_PROGRESS)!=null?r:"ASYNC_OP_IN_PROGRESS")?new d("BUSY","\u0110ang m\u1EDF tr\xECnh ch\u1ECDn file kh\xE1c"):l}},Zn={library:Tt("library"),camera:Tt("camera")},ei=(e,t)=>t.split(".").reduce((n,i)=>ae(n)?n[i]:void 0,e),tt=({file:e,target:t,onProgress:n,signal:i})=>new Promise((o,s)=>{if(t.target!=="url"||!("url"in t)){s(new d("INVALID_PARAMS","Thi\u1EBFu upload.url"));return}let c=t;if(i.aborted){s(new d("CANCELLED","\u0110\xE3 hu\u1EF7 upload"));return}let a=new XMLHttpRequest,r=new FormData;Object.entries(c.form_data).forEach(([p,h])=>r.append(p,h)),r.append(c.field_name,{uri:e.uri,name:e.name,type:e.mime_type});let l=()=>a.abort();i.addEventListener("abort",l);let u=p=>{i.removeEventListener("abort",l),p()};a.open("POST",c.url),Object.entries(c.headers).forEach(([p,h])=>a.setRequestHeader(p,h)),a.upload.onprogress=p=>n(p.loaded,p.total||e.size||0),a.onload=()=>u(()=>{let p=a.responseText;try{p=JSON.parse(a.responseText)}catch{}if(a.status<200||a.status>=300){s(new d("UPLOAD_FAILED",`HTTP ${a.status}`));return}let h=ei(p,c.url_field);if(typeof h!="string"||!h){s(new d("UPLOAD_FAILED",`Response kh\xF4ng c\xF3 "${c.url_field}"`));return}o({url:h,response:p})}),a.onerror=()=>u(()=>s(new d("UPLOAD_FAILED","L\u1ED7i m\u1EA1ng khi upload"))),a.onabort=()=>u(()=>s(new d("CANCELLED","\u0110\xE3 hu\u1EF7 upload"))),a.send(r)}),Nt=e=>{var i,o;let t={...Zn};for(let[s,c]of Object.entries((i=e==null?void 0:e.sources)!=null?i:{}))c?t[s]=c:delete t[s];let n={url:tt};for(let[s,c]of Object.entries((o=e==null?void 0:e.targets)!=null?o:{}))s!=="url"&&c&&(n[s]=c);return{sources:t,targets:n}},Ut=e=>{let{sources:t,targets:n}=Nt(e);return{sources:Object.keys(t),targets:Object.keys(n),max_count:et}},Ne=new Map,Ft=(e,t)=>`${e}:${t}`,ti=0,$t=(e,t)=>{var n;typeof t=="string"&&((n=Ne.get(Ft(e,t)))==null||n.abort())},fe=e=>{for(let[t,n]of Ne)t.startsWith(`${e}:`)&&n.abort()},De=()=>new d("CANCELLED","\u0110\xE3 hu\u1EF7 upload"),ni=(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)}},Bt=async(e,t)=>{var r;let{sources:n,targets:i}=Nt(t.config),o=n[e.source];if(!o)throw new d("NOT_SUPPORTED",`\u1EE8ng d\u1EE5ng ch\u01B0a h\u1ED7 tr\u1EE3 ngu\u1ED3n "${e.source}"`);let s=i[e.target.target];if(!s)throw new d("NOT_SUPPORTED",`\u1EE8ng d\u1EE5ng ch\u01B0a h\u1ED7 tr\u1EE3 \u0111\xEDch upload "${e.target.target}"`);let c=new AbortController,a=Ft(t.instance_id,(r=t.task_id)!=null?r:`auto-${++ti}`);Ne.set(a,c);try{return await ii(e,t,o,s,c.signal)}finally{Ne.delete(a)}},ii=async(e,{task_id:t,config:n,emit:i,exclusivePick:o=r=>r()},s,c,a)=>{var J,$;let r=(await o(()=>s({accept:e.accept,max_count:e.max_count,process:e.process}))).slice(0,e.max_count);if(a.aborted)throw De();if(!r.length)throw new d("CANCELLED","Ng\u01B0\u1EDDi d\xF9ng kh\xF4ng ch\u1ECDn file");let l=[],u=r.filter(R=>Kn(R,e.accept)?!0:(l.push({name:R.name,code:"INVALID_FILE",message:`Kh\xF4ng cho ph\xE9p \u0111\u1ECBnh d\u1EA1ng ${R.mime_type||Lt(R.name)}`}),!1)),p=u.map(()=>0),h=u.map(R=>{var f;return(f=R.size)!=null?f:0}),A=0,w=0,I=(R=!1)=>{if(!i||!t)return;let f=Date.now();if(!R&&f-w<200)return;w=f;let M=h.reduce((F,D)=>F+D,0),_=p.reduce((F,D)=>F+D,0);i("upload.progress",{task_id:t,loaded:_,total:M,percent:M?Math.min(100,Math.round(_/M*100)):0,done_count:A,count:u.length})},P=[],x=0,m=async()=>{var R,f;for(;x<u.length;){let M=x++,_=u[M];try{if(a.aborted)throw De();let F=_.mime_type.startsWith("image/")?"image":_.mime_type.startsWith("video/")?"video":void 0,D=F&&!_.processed?(R=n==null?void 0:n.processors)==null?void 0:R[F]:void 0;if(D&&(_=await D(_,e.process),h[M]=(f=_.size)!=null?f:h[M],a.aborted))throw De();if(e.max_size&&_.size&&_.size>e.max_size)throw new d("FILE_TOO_LARGE",`File ${_.size} byte v\u01B0\u1EE3t gi\u1EDBi h\u1EA1n ${e.max_size}`);let j=(Te,oe)=>{p[M]=Te,oe&&(h[M]=oe),I()},re=await c({file:_,target:e.target,onProgress:j,signal:a});if(typeof(re==null?void 0:re.url)!="string"||!re.url)throw new d("UPLOAD_FAILED","Upload kh\xF4ng tr\u1EA3 url");let{url:Ye,...ue}=re;P[M]={url:Ye,name:_.name,mime_type:_.mime_type,size:_.size,width:_.width,height:_.height,duration:_.duration,...Object.keys(ue).length?{response:"response"in ue?ue.response:ue}:{}},p[M]=h[M]}catch(F){l.push(ni(u[M].name,F))}finally{A++,I(!0)}}};if(await Promise.all(Array.from({length:Math.min(e.concurrency,u.length)},m)),a.aborted)throw De();let L=P.filter(R=>!!R);if(!L.length){let R=l[0];throw new d((J=R==null?void 0:R.code)!=null?J:"UPLOAD_FAILED",($=R==null?void 0:R.message)!=null?$:"Kh\xF4ng upload \u0111\u01B0\u1EE3c file n\xE0o")}return{files:L,failed:l}};var qt=require("react-native");var te,nt=e=>{var t;if(te===e&&(te=void 0,e.subscriptions.forEach(n=>n.remove()),e.started&&qt.Platform.OS==="ios"))try{(t=e.native)==null||t.setAudioSessionActiveIOS(!1,{notifyOthersOnDeactivation:!0})}catch{}},Vt=async(e,t,n,i=()=>!0)=>{var s,c,a,r,l;if(te)throw new d("BUSY","Micro \u0111ang \u0111\u01B0\u1EE3c mini app kh\xE1c s\u1EED d\u1EE5ng");if(!i())throw new d("CANCELLED","Mini app kh\xF4ng c\xF2n ho\u1EA1t \u0111\u1ED9ng");let o={owner:e,emit:n,cancelled:!1,started:!1,subscriptions:[]};te=o;try{let u;try{u=await import("expo-speech-recognition")}catch{throw new d("NOT_SUPPORTED","Ch\u01B0a c\xF3 module nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i trong b\u1EA3n native")}let p=u.ExpoSpeechRecognitionModule;if(o.native=p,o.cancelled||!i())throw new d("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");let h=await p.requestPermissionsAsync();if(o.cancelled||!i())throw new d("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");if(!h.granted)throw new d("PERMISSION_DENIED","Ch\u01B0a c\u1EA5p quy\u1EC1n micro / nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i");if(await p.getStateAsync()!=="inactive")throw new d("BUSY","Nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i \u0111ang \u0111\u01B0\u1EE3c t\xEDnh n\u0103ng kh\xE1c s\u1EED d\u1EE5ng");if(o.cancelled||!i())throw new d("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");o.subscriptions.push(p.addListener("result",A=>{var w,I;te!==o||o.cancelled||n(A.isFinal?"speech.final":"speech.partial",{...A,text:(I=(w=A.results[0])==null?void 0:w.transcript)!=null?I:""})}),p.addListener("error",A=>{te===o&&!o.cancelled&&n("speech.error",{...A,code:A.error})}),p.addListener("end",()=>{te===o&&(nt(o),n("speech.end"))})),o.started=!0,p.start({lang:(s=t.lang)!=null?s:"vi-VN",continuous:(c=t.continuous)!=null?c:!0,interimResults:(a=t.interimResults)!=null?a:!0,addsPunctuation:(r=t.addsPunctuation)!=null?r:!0,requiresOnDeviceRecognition:(l=t.requiresOnDeviceRecognition)!=null?l:!1,iosCategory:{category:u.AVAudioSessionCategory.playAndRecord,categoryOptions:[u.AVAudioSessionCategoryOptions.defaultToSpeaker,u.AVAudioSessionCategoryOptions.allowBluetooth],mode:u.AVAudioSessionMode.measurement}})}catch(u){throw nt(o),u}},jt=e=>{let t=te;if(!(!t||t.owner!==e)){if(!t.started){t.cancelled=!0;return}t.native.stop()}},X=e=>{let t=te;if(!(!t||t.owner!==e||t.cancelled)&&(t.cancelled=!0,t.started))try{t.native.abort()}catch{nt(t)}};var Fe=1,d=class extends Error{constructor(n,i){super(i);this.code=n}},Ht=e=>{try{let t=JSON.parse(e);return(t==null?void 0:t.__retion)===Fe&&typeof t.method=="string"?t:null}catch{return null}},xe=e=>`window.__RETION_MINIAPP__ && window.__RETION_MINIAPP__.receive(${JSON.stringify(e)}); true;`,Wt=(e,t)=>xe({id:e,result:t}),zt=(e,t)=>xe({id:e,error:{code:t.code,message:t.message}}),Jt=(e,t)=>xe({event:e,data:t}),rt=e=>xe({event:"context",data:e});var Kt=()=>`(function () {
1
+ "use strict";var Vn=Object.create;var $e=Object.defineProperty;var jn=Object.getOwnPropertyDescriptor;var zn=Object.getOwnPropertyNames;var Hn=Object.getPrototypeOf,Wn=Object.prototype.hasOwnProperty;var Jn=(e,t)=>{for(var n in t)$e(e,n,{get:t[n],enumerable:!0})},Et=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of zn(t))!Wn.call(e,i)&&i!==n&&$e(e,i,{get:()=>t[i],enumerable:!(r=jn(t,i))||r.enumerable});return e};var ue=(e,t,n)=>(n=e!=null?Vn(Hn(e)):{},Et(t||!e||!e.__esModule?$e(n,"default",{value:e,enumerable:!0}):n,e)),Kn=e=>Et($e({},"__esModule",{value:!0}),e);var Dr={};Jn(Dr,{DefaultMiniAppSplash:()=>St,MINIAPP_PLATFORM_URL:()=>Be,MiniAppHost:()=>Bn,MiniAppHostError:()=>u,closeMiniApp:()=>be,configureMiniApp:()=>Rt,createMmkvStorage:()=>Ct,createReactNativeBiometrics:()=>it,createRnfsFileSystem:()=>Tt,ensureMiniApp:()=>Ne,getLocalMiniApp:()=>R,getMiniAppCatalog:()=>Nn,getMiniAppCatalogEntry:()=>xe,getMiniAppStatuses:()=>Pn,getMiniAppUpdate:()=>Mt,installBundledMiniApp:()=>fn,onMiniAppEvent:()=>En,openMiniApp:()=>Mn,pauseMiniApp:()=>Cn,pauseMiniAppDownloads:()=>In,preloadMiniApp:()=>vn,releaseSpeechFor:()=>te,restoreMiniApp:()=>Tn,resumeMiniApp:()=>kn,resumeMiniAppDownloads:()=>Ln,sendEventToWeb:()=>wn,syncMiniAppCatalog:()=>tt,uninstallMiniApp:()=>On,updateMiniApp:()=>Dn,uploadToUrl:()=>ct,useMiniAppDownload:()=>Ze,useMiniAppDownloadsPaused:()=>xn});module.exports=Kn(Dr);var Be="https://retion-miniapp-platform.vercel.app",we=null,Pt=new Set,Rt=e=>{we=e,Pt.forEach(t=>t())},k=()=>{if(!we)throw new Error("[miniapp] Ch\u01B0a g\u1ECDi configureMiniApp()");return we},Ot=e=>{Pt.add(e),we&&e()},J=(...e)=>{we!=null&&we.debug&&console.log("[miniapp]",...e)};var Tt=(e,t)=>({document_dir:e.DocumentDirectoryPath,cache_dir:e.CachesDirectoryPath,exists:n=>e.exists(n),mkdir:n=>e.mkdir(n),remove:n=>e.unlink(n).catch(()=>{}),listDir:n=>e.readDir(n).then(r=>r.map(i=>i.name)).catch(()=>[]),sha256:n=>e.hash(n,"sha256"),unzip:async(n,r)=>{await t(n,r)},download:({url:n,to_file:r,onProgress:i})=>{let{jobId:o,promise:c}=e.downloadFile({fromUrl:n,toFile:r,progressInterval:250,begin:()=>{},progress:({bytesWritten:p,contentLength:a})=>i==null?void 0:i(p,a)});return{promise:c.then(({statusCode:p})=>({status:p})),cancel:()=>e.stopDownload(o)}}}),Ct=e=>({getString:t=>e.getString(t),setString:(t,n)=>e.set(t,n)});var y=ue(require("react")),E=require("react-native"),$n=ue(require("react-native-webview"));var Ce=require("react-native");var it=e=>({getAvailability:()=>e.isSensorAvailable(),authenticate:({reason:t,cancelButtonText:n})=>e.simplePrompt({promptMessage:t,cancelButtonText:n,fallbackPromptMessage:""})}),qe,ot=()=>(qe||(qe=import("react-native-biometrics").then(({default:e})=>it(new e({allowDeviceCredentials:!1}))).catch(e=>{throw qe=void 0,new u("NOT_SUPPORTED",`Biometric native module unavailable: ${e instanceof Error?e.message:String(e)}`)})),qe);var ee=require("react-native");var kt=e=>{var n,r,i;if(e!==void 0&&(e===null||typeof e!="object"||Array.isArray(e)))throw new u("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 u("INVALID_PARAMS","enableHighAccuracy ph\u1EA3i l\xE0 boolean");for(let[o,c,p]of[["timeout",1,6e4],["maximumAge",0,864e5]]){let a=t[o];if(a!==void 0&&(typeof a!="number"||!Number.isFinite(a)||a<c||a>p))throw new u("INVALID_PARAMS",`${o} ph\u1EA3i n\u1EB1m trong kho\u1EA3ng ${c}\u2013${p} ms`)}return{enableHighAccuracy:(n=t.enableHighAccuracy)!=null?n:!1,timeout:(r=t.timeout)!=null?r:15e3,maximumAge:(i=t.maximumAge)!=null?i:0}},It=(e,t=()=>!0)=>new Promise((n,r)=>{let i=!1,o=(a,s)=>{i||(i=!0,clearTimeout(c),a?r(a):n(s))},c=setTimeout(()=>o(new u("TIMEOUT","H\u1EBFt th\u1EDDi gian ch\u1EDD c\u1EA5p quy\u1EC1n/l\u1EA5y v\u1ECB tr\xED")),12e4+e.timeout),p=()=>i?!1:t()?!0:(o(new u("CANCELLED","Mini app kh\xF4ng c\xF2n ho\u1EA1t \u0111\u1ED9ng")),!1);(async()=>{if(!p())return;let a;try{a=(await import("@react-native-community/geolocation")).default}catch{throw new u("NOT_SUPPORTED","Ch\u01B0a c\xF3 module v\u1ECB tr\xED trong b\u1EA3n native")}if(p()){if(ee.Platform.OS==="android"){let s=ee.PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,d=ee.PermissionsAndroid.PERMISSIONS.ACCESS_COARSE_LOCATION,g=await ee.PermissionsAndroid.check(s);if(!p())return;let A=g||await ee.PermissionsAndroid.check(d);if(!p())return;if(!g&&!A){let l=await ee.PermissionsAndroid.requestMultiple([s,d]);if(!p())return;if(l[s]!==ee.PermissionsAndroid.RESULTS.GRANTED&&l[d]!==ee.PermissionsAndroid.RESULTS.GRANTED)throw new u("PERMISSION_DENIED","Ch\u01B0a c\u1EA5p quy\u1EC1n truy c\u1EADp v\u1ECB tr\xED")}}p()&&a.getCurrentPosition(s=>{p()&&o(void 0,s)},s=>{var g;if(!p())return;let d=(g={1:"PERMISSION_DENIED",2:"POSITION_UNAVAILABLE",3:"TIMEOUT"}[s.code])!=null?g:"LOCATION_ERROR";o(new u(d,s.message))},e)}})().catch(a=>o(a))});var at=require("react-native");var st=20,Lt=20,Ut=/^[a-z][a-z0-9_-]{0,31}$/,Yn=/^(\.[\w-]{1,16}|[\w.+-]+\/(\*|[\w.+-]+))$/,Gn=["low","medium","high"],de=e=>!!e&&typeof e=="object"&&!Array.isArray(e),N=e=>new u("INVALID_PARAMS",e),Oe=(e,t,n)=>typeof e=="number"&&Number.isInteger(e)&&e>=t&&e<=n,Dt=(e,t)=>{if(e===void 0)return{};if(!de(e)||Object.keys(e).length>Lt||Object.values(e).some(n=>typeof n!="string"))throw N(`${t} ph\u1EA3i l\xE0 object chu\u1ED7i (t\u1ED1i \u0111a ${Lt} key)`);return e},Ft=e=>{var n,r,i,o;if(e!==void 0&&!de(e))throw N("Tu\u1EF3 ch\u1ECDn upload ph\u1EA3i l\xE0 object");let t=e!=null?e:{};if(t.source!==void 0&&(typeof t.source!="string"||!Ut.test(t.source)))throw N("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(c=>typeof c!="string"||!Yn.test(c))))throw N("accept ph\u1EA3i l\xE0 m\u1EA3ng mime (image/*, application/pdf) ho\u1EB7c \u0111u\xF4i (.docx)");if(t.max_count!==void 0&&!Oe(t.max_count,1,st))throw N(`max_count ph\u1EA3i l\xE0 s\u1ED1 nguy\xEAn 1\u2013${st}`);if(t.max_size!==void 0&&!Oe(t.max_size,1,Number.MAX_SAFE_INTEGER))throw N("max_size ph\u1EA3i l\xE0 s\u1ED1 byte > 0");if(t.concurrency!==void 0&&!Oe(t.concurrency,1,5))throw N("concurrency ph\u1EA3i l\xE0 s\u1ED1 nguy\xEAn 1\u20135");return{source:(n=t.source)!=null?n:"library",accept:((r=t.accept)!=null?r:[]).map(c=>c.toLowerCase()),max_count:(i=t.max_count)!=null?i:1,max_size:t.max_size,process:Qn(t.process),target:Xn(t.upload),concurrency:(o=t.concurrency)!=null?o:3}},Qn=e=>{if(e===void 0)return{};if(!de(e))throw N("process ph\u1EA3i l\xE0 object");let t={};if(e.image!==void 0){let n=e.image;if(!de(n))throw N("process.image ph\u1EA3i l\xE0 object");for(let r of["max_width","max_height"])if(n[r]!==void 0&&!Oe(n[r],1,1e4))throw N(`process.image.${r} 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 N("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(!de(n))throw N("process.video ph\u1EA3i l\xE0 object");if(n.max_duration!==void 0&&!Oe(n.max_duration,1,3600))throw N("process.video.max_duration ph\u1EA3i l\xE0 s\u1ED1 gi\xE2y 1\u20133600");if(n.quality!==void 0&&!Gn.includes(n.quality))throw N("process.video.quality ph\u1EA3i l\xE0 low | medium | high");t.video={max_duration:n.max_duration,quality:n.quality}}return t},Xn=e=>{var n,r,i,o;if(e===void 0)return{target:"host",params:{}};if(!de(e))throw N("upload ph\u1EA3i l\xE0 object");let t=(n=e.target)!=null?n:"host";if(typeof t!="string"||!Ut.test(t))throw N("upload.target ph\u1EA3i l\xE0 t\xEAn \u0111\xEDch, vd host | url");if(t!=="url"){if(e.params!==void 0&&!de(e.params))throw N("upload.params ph\u1EA3i l\xE0 object");return{target:t,params:(r=e.params)!=null?r:{}}}if(typeof e.url!="string"||!/^https:\/\//i.test(e.url))throw N("upload.url ph\u1EA3i l\xE0 https");for(let c of["field_name","url_field"])if(e[c]!==void 0&&(typeof e[c]!="string"||!e[c]))throw N(`upload.${c} ph\u1EA3i l\xE0 chu\u1ED7i`);return{target:"url",url:e.url,headers:Dt(e.headers,"upload.headers"),form_data:Dt(e.form_data,"upload.form_data"),field_name:(i=e.field_name)!=null?i:"file",url_field:(o=e.url_field)!=null?o:"url"}},$t=e=>{let t=e.lastIndexOf(".");return t>0?e.slice(t).toLowerCase():""},Zn=(e,t)=>{if(!t.length)return!0;let n=e.mime_type.toLowerCase(),r=$t(e.name);return t.some(i=>i==="*/*"?!0:i.startsWith(".")?i===r:i.endsWith("/*")?n.startsWith(i.slice(0,-1)):n===i)},er=e=>{let t=e.length>0&&e.every(r=>r.startsWith("image/")),n=e.length>0&&e.every(r=>r.startsWith("video/"));return t?"image":n?"video":"mixed"},Ee,tr=()=>(Ee!=null||(Ee=import("react-native-image-picker").catch(e=>{throw Ee=void 0,new u("NOT_SUPPORTED",`Ch\u01B0a c\xF3 module ch\u1ECDn \u1EA3nh trong b\u1EA3n native: ${e instanceof Error?e.message:String(e)}`)})),Ee),Nt=e=>async({accept:t,max_count:n,process:r})=>{var a,s,d,g,A,l,h,T,_;let i=await tr(),o=er(t),c={mediaType:o==="image"?"photo":o,maxWidth:(a=r.image)==null?void 0:a.max_width,maxHeight:(s=r.image)==null?void 0:s.max_height,quality:(g=(d=r.image)==null?void 0:d.quality)!=null?g:.8,videoQuality:(l=(A=r.video)==null?void 0:A.quality)!=null?l:"medium",durationLimit:(h=r.video)==null?void 0:h.max_duration,assetRepresentationMode:"compatible"},p=e==="camera"?await i.launchCamera({...c,saveToPhotos:!1}):await i.launchImageLibrary({...c,selectionLimit:n});if(p.didCancel)return[];if(p.errorCode){let b=p.errorCode==="permission"?"PERMISSION_DENIED":p.errorCode==="camera_unavailable"?"NOT_SUPPORTED":"HOST_ERROR";throw new u(b,(T=p.errorMessage)!=null?T:p.errorCode)}return((_=p.assets)!=null?_:[]).filter(b=>b.uri).map((b,f)=>{var L,G,$;return{uri:b.uri,name:(L=b.fileName)!=null?L:`file_${f+1}`,mime_type:(G=b.type)!=null?G:"application/octet-stream",size:b.fileSize,width:b.width,height:b.height,duration:b.duration,processed:!(($=b.type)!=null&&$.startsWith("video/"))||at.Platform.OS==="ios"}})},nr={"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"},ir=e=>async({accept:t,max_count:n})=>{var o,c,p,a;let r=t.map(s=>{var d;return(d=nr[s])!=null?d:rr[s]}),i=!t.length||r.some(s=>!s||!e.types[s])?e.types.allFiles:[...new Set(r)].flatMap(s=>e.types[s]);try{let d=(await e.pick({type:i,allowMultiSelection:n>1,mode:"import"})).filter(l=>l.uri&&!l.error).map((l,h)=>{var T,_,b;return{uri:l.uri,name:(T=l.name)!=null?T:`file_${h+1}`,mime_type:(_=l.type)!=null?_:"application/octet-stream",size:(b=l.size)!=null?b:void 0}});if(at.Platform.OS!=="android"||!e.keepLocalCopy||!d.some(l=>l.uri.startsWith("content://")))return d;let g=await e.keepLocalCopy({files:d.map(l=>({uri:l.uri,fileName:l.name})),destination:"cachesDirectory"}),A=new Map(g.map(l=>[l.sourceUri,l.status==="success"?l.localUri:void 0]));return d.map(l=>{var h;return{...l,uri:(h=A.get(l.uri))!=null?h:l.uri}})}catch(s){let d=s==null?void 0:s.code;if(d===((c=(o=e.errorCodes)==null?void 0:o.OPERATION_CANCELED)!=null?c:"OPERATION_CANCELED"))return[];throw d===((a=(p=e.errorCodes)==null?void 0:p.IN_PROGRESS)!=null?a:"ASYNC_OP_IN_PROGRESS")?new u("BUSY","\u0110ang m\u1EDF tr\xECnh ch\u1ECDn file kh\xE1c"):s}},Pe,or=async e=>(Pe!=null||(Pe=import("@react-native-documents/picker").then(t=>ir(t)).catch(t=>{throw Pe=void 0,new u("NOT_SUPPORTED",`Ch\u01B0a c\xF3 module ch\u1ECDn file trong b\u1EA3n native: ${t instanceof Error?t.message:String(t)}`)})),(await Pe)(e)),sr={library:Nt("library"),camera:Nt("camera"),document:or},Re,Bt=()=>(Re!=null||(Re=import("react-native-compressor").catch(()=>(Re=void 0,null))),Re),qt=async(e,t,n)=>{try{return Number(await e.getFileSize(t))||n}catch{return n}},ar=new Set(["image/jpeg","image/jpg","image/heic","image/heif","image/webp"]),cr={low:640,medium:1280,high:1920},pr=async(e,{image:t})=>{var r;if(!t||!ar.has(e.mime_type.toLowerCase()))return e;let n=await Bt();if(!n)return e;try{let i=await n.Image.compress(e.uri,{compressionMethod:"manual",maxWidth:t.max_width,maxHeight:t.max_height,quality:(r=t.quality)!=null?r:.8,output:"jpg"});return{...e,uri:i,mime_type:"image/jpeg",name:e.name.replace(/\.[^.]+$/,"")+".jpg",size:await qt(n,i,e.size),processed:!0}}catch{return e}},lr=async(e,{video:t})=>{var r;let n=await Bt();if(!n)return e;try{let i=await n.Video.compress(e.uri,{compressionMethod:"auto",maxSize:cr[(r=t==null?void 0:t.quality)!=null?r:"medium"],minimumFileSizeForCompress:2});return{...e,uri:i,mime_type:"video/mp4",size:await qt(n,i,e.size),processed:!0}}catch{return e}},ur={image:pr,video:lr},dr=(e,t)=>t.split(".").reduce((n,r)=>de(n)?n[r]:void 0,e),ct=({file:e,target:t,onProgress:n,signal:r})=>new Promise((i,o)=>{if(t.target!=="url"||!("url"in t)){o(new u("INVALID_PARAMS","Thi\u1EBFu upload.url"));return}let c=t;if(r.aborted){o(new u("CANCELLED","\u0110\xE3 hu\u1EF7 upload"));return}let p=new XMLHttpRequest,a=new FormData;Object.entries(c.form_data).forEach(([g,A])=>a.append(g,A)),a.append(c.field_name,{uri:e.uri,name:e.name,type:e.mime_type});let s=()=>p.abort();r.addEventListener("abort",s);let d=g=>{r.removeEventListener("abort",s),g()};p.open("POST",c.url),Object.entries(c.headers).forEach(([g,A])=>p.setRequestHeader(g,A)),p.upload.onprogress=g=>n(g.loaded,g.total||e.size||0),p.onload=()=>d(()=>{let g=p.responseText;try{g=JSON.parse(p.responseText)}catch{}if(p.status<200||p.status>=300){o(new u("UPLOAD_FAILED",`HTTP ${p.status}`));return}let A=dr(g,c.url_field);if(typeof A!="string"||!A){o(new u("UPLOAD_FAILED",`Response kh\xF4ng c\xF3 "${c.url_field}"`));return}i({url:A,response:g})}),p.onerror=()=>d(()=>o(new u("UPLOAD_FAILED","L\u1ED7i m\u1EA1ng khi upload"))),p.onabort=()=>d(()=>o(new u("CANCELLED","\u0110\xE3 hu\u1EF7 upload"))),p.send(a)}),Vt=e=>{var r,i;let t={...sr};for(let[o,c]of Object.entries((r=e==null?void 0:e.sources)!=null?r:{}))c?t[o]=c:delete t[o];let n={url:ct};for(let[o,c]of Object.entries((i=e==null?void 0:e.targets)!=null?i:{}))o!=="url"&&c&&(n[o]=c);return{sources:t,targets:n}},jt=e=>{let{sources:t,targets:n}=Vt(e);return{sources:Object.keys(t),targets:Object.keys(n),max_count:st}},je=new Map,zt=(e,t)=>`${e}:${t}`,gr=0,Ht=(e,t)=>{var n;typeof t=="string"&&((n=je.get(zt(e,t)))==null||n.abort())},ye=e=>{for(let[t,n]of je)t.startsWith(`${e}:`)&&n.abort()},Ve=()=>new u("CANCELLED","\u0110\xE3 hu\u1EF7 upload"),mr=(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)}},Wt=async(e,t)=>{var a;let{sources:n,targets:r}=Vt(t.config),i=n[e.source];if(!i)throw new u("NOT_SUPPORTED",`\u1EE8ng d\u1EE5ng ch\u01B0a h\u1ED7 tr\u1EE3 ngu\u1ED3n "${e.source}"`);let o=r[e.target.target];if(!o)throw new u("NOT_SUPPORTED",`\u1EE8ng d\u1EE5ng ch\u01B0a h\u1ED7 tr\u1EE3 \u0111\xEDch upload "${e.target.target}"`);let c=new AbortController,p=zt(t.instance_id,(a=t.task_id)!=null?a:`auto-${++gr}`);je.set(p,c);try{return await fr(e,t,i,o,c.signal)}finally{je.delete(p)}},fr=async(e,{instance_id:t,app_id:n,getContext:r,task_id:i,config:o,emit:c,exclusivePick:p=g=>g()},a,s,d)=>{var w,S,z;let g={app_id:n!=null?n:"",instance_id:t,context:{...(w=r==null?void 0:r())!=null?w:{}}},A=(await p(()=>a({accept:e.accept,max_count:e.max_count,process:e.process,caller:g}))).slice(0,e.max_count);if(d.aborted)throw Ve();if(!A.length)throw new u("CANCELLED","Ng\u01B0\u1EDDi d\xF9ng kh\xF4ng ch\u1ECDn file");let l=[],h=A.filter(v=>Zn(v,e.accept)?!0:(l.push({name:v.name,code:"INVALID_FILE",message:`Kh\xF4ng cho ph\xE9p \u0111\u1ECBnh d\u1EA1ng ${v.mime_type||$t(v.name)}`}),!1)),T=h.map(()=>0),_=h.map(v=>{var D;return(D=v.size)!=null?D:0}),b=0,f=0,L=(v=!1)=>{if(!c||!i)return;let D=Date.now();if(!v&&D-f<200)return;f=D;let re=_.reduce((C,H)=>C+H,0),B=T.reduce((C,H)=>C+H,0);c("upload.progress",{task_id:i,loaded:B,total:re,percent:re?Math.min(100,Math.round(B/re*100)):0,done_count:b,count:h.length})},G=[],$=0,Se=async()=>{var v,D,re;for(;$<h.length;){let B=$++,C=h[B];try{if(d.aborted)throw Ve();let H=C.mime_type.startsWith("image/")?"image":C.mime_type.startsWith("video/")?"video":void 0,pe=H&&!C.processed?(D=(v=o==null?void 0:o.processors)==null?void 0:v[H])!=null?D:ur[H]:void 0;if(pe&&(C=await pe(C,e.process),_[B]=(re=C.size)!=null?re:_[B],d.aborted))throw Ve();if(e.max_size&&C.size&&C.size>e.max_size)throw new u("FILE_TOO_LARGE",`File ${C.size} byte v\u01B0\u1EE3t gi\u1EDBi h\u1EA1n ${e.max_size}`);let he=(Ue,Fe)=>{T[B]=Ue,Fe&&(_[B]=Fe),L()},ie=await s({file:C,target:e.target,onProgress:he,signal:d,caller:g});if(typeof(ie==null?void 0:ie.url)!="string"||!ie.url)throw new u("UPLOAD_FAILED","Upload kh\xF4ng tr\u1EA3 url");let{url:nt,...oe}=ie;G[B]={url:nt,name:C.name,mime_type:C.mime_type,size:C.size,width:C.width,height:C.height,duration:C.duration,...Object.keys(oe).length?{response:"response"in oe?oe.response:oe}:{}},T[B]=_[B]}catch(H){l.push(mr(h[B].name,H))}finally{b++,L(!0)}}};if(await Promise.all(Array.from({length:Math.min(e.concurrency,h.length)},Se)),d.aborted)throw Ve();let ce=G.filter(v=>!!v);if(!ce.length){let v=l[0];throw new u((S=v==null?void 0:v.code)!=null?S:"UPLOAD_FAILED",(z=v==null?void 0:v.message)!=null?z:"Kh\xF4ng upload \u0111\u01B0\u1EE3c file n\xE0o")}return{files:ce,failed:l}};var Me=require("react-native");var K,Jt=()=>Me.Platform.OS==="android"&&!!(K!=null&&K.requesting_permission),hr=1500,Ar=()=>new Promise(e=>{if(Me.Platform.OS!=="android"||Me.AppState.currentState==="active"){e();return}let t=()=>{clearTimeout(n),r.remove(),e()},n=setTimeout(t,hr),r=Me.AppState.addEventListener("change",i=>{i==="active"&&t()})}),pt=e=>{var t;if(K===e&&(K=void 0,e.subscriptions.forEach(n=>n.remove()),e.started&&Me.Platform.OS==="ios"))try{(t=e.native)==null||t.setAudioSessionActiveIOS(!1,{notifyOthersOnDeactivation:!0})}catch{}},Kt=async(e,t,n,r=()=>!0)=>{var o,c,p,a,s;if(K)throw new u("BUSY","Micro \u0111ang \u0111\u01B0\u1EE3c mini app kh\xE1c s\u1EED d\u1EE5ng");if(!r())throw new u("CANCELLED","Mini app kh\xF4ng c\xF2n ho\u1EA1t \u0111\u1ED9ng");let i={owner:e,emit:n,cancelled:!1,started:!1,subscriptions:[]};K=i;try{let d;try{d=await import("expo-speech-recognition")}catch{throw new u("NOT_SUPPORTED","Ch\u01B0a c\xF3 module nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i trong b\u1EA3n native")}let g=d.ExpoSpeechRecognitionModule;if(i.native=g,i.cancelled||!r())throw new u("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");i.requesting_permission=!0;let A;try{A=await g.requestPermissionsAsync()}finally{i.requesting_permission=!1}if(await Ar(),i.cancelled||!r())throw new u("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");if(!A.granted)throw new u("PERMISSION_DENIED","Ch\u01B0a c\u1EA5p quy\u1EC1n micro / nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i");if(await g.getStateAsync()!=="inactive")throw new u("BUSY","Nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i \u0111ang \u0111\u01B0\u1EE3c t\xEDnh n\u0103ng kh\xE1c s\u1EED d\u1EE5ng");if(i.cancelled||!r())throw new u("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");i.subscriptions.push(g.addListener("result",l=>{var h,T;K!==i||i.cancelled||n(l.isFinal?"speech.final":"speech.partial",{...l,text:(T=(h=l.results[0])==null?void 0:h.transcript)!=null?T:""})}),g.addListener("error",l=>{K===i&&!i.cancelled&&n("speech.error",{...l,code:l.error})}),g.addListener("end",()=>{K===i&&(pt(i),n("speech.end"))})),i.started=!0,g.start({lang:(o=t.lang)!=null?o:"vi-VN",continuous:(c=t.continuous)!=null?c:!0,interimResults:(p=t.interimResults)!=null?p:!0,addsPunctuation:(a=t.addsPunctuation)!=null?a:!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 pt(i),d}},Yt=e=>{let t=K;if(!(!t||t.owner!==e)){if(!t.started){t.cancelled=!0;return}t.native.stop()}},te=e=>{let t=K;if(!(!t||t.owner!==e||t.cancelled)&&(t.cancelled=!0,t.started))try{t.native.abort()}catch{pt(t)}};var He=1,u=class extends Error{constructor(n,r){super(r);this.code=n}},Gt=e=>{try{let t=JSON.parse(e);return(t==null?void 0:t.__retion)===He&&typeof t.method=="string"?t:null}catch{return null}},ke=e=>`window.__RETION_MINIAPP__ && window.__RETION_MINIAPP__.receive(${JSON.stringify(e)}); true;`,Qt=(e,t)=>ke({id:e,result:t}),Xt=(e,t)=>ke({id:e,error:{code:t.code,message:t.message}}),Zt=(e,t)=>ke({event:e,data:t}),ut=e=>ke({event:"context",data:e});var en=()=>`(function () {
2
2
  var post = function (level, args) {
3
3
  try {
4
4
  var parts = [];
@@ -8,7 +8,7 @@
8
8
  else if (typeof a === 'object') { try { parts.push(JSON.stringify(a).slice(0, 800)); } catch (e) { parts.push(String(a)); } }
9
9
  else { parts.push(String(a)); }
10
10
  }
11
- window.ReactNativeWebView && window.ReactNativeWebView.postMessage(JSON.stringify({ __retion: ${Fe}, method: 'log', level: level, text: parts.join(' ') }));
11
+ window.ReactNativeWebView && window.ReactNativeWebView.postMessage(JSON.stringify({ __retion: ${He}, method: 'log', level: level, text: parts.join(' ') }));
12
12
  } catch (e) {}
13
13
  };
14
14
  ['log', 'info', 'warn', 'error'].forEach(function (level) {
@@ -19,7 +19,7 @@
19
19
  window.addEventListener('unhandledrejection', function (e) { post('error', ['[unhandledrejection]', e.reason]); });
20
20
  // Kh\xF4ng log query (c\xF3 th\u1EC3 ch\u1EE9a token) \u2014 ch\u1EC9 \u0111\u01B0\u1EDDng d\u1EABn + route.
21
21
  post('info', ['[page] ' + location.pathname + location.hash]);
22
- })(); true;`,Yt=()=>`(function () {
22
+ })(); true;`,tn=()=>`(function () {
23
23
  function atTop(el) {
24
24
  for (var n = el; n && n !== document.documentElement; n = n.parentElement) {
25
25
  if (n.scrollTop > 0) { return false; }
@@ -30,7 +30,7 @@
30
30
  function report(at_top) {
31
31
  if (at_top === last) { return; }
32
32
  last = at_top;
33
- window.ReactNativeWebView && window.ReactNativeWebView.postMessage(JSON.stringify({ __retion: ${Fe}, method: 'touchAtTop', at_top: at_top }));
33
+ window.ReactNativeWebView && window.ReactNativeWebView.postMessage(JSON.stringify({ __retion: ${He}, method: 'touchAtTop', at_top: at_top }));
34
34
  }
35
35
  document.addEventListener('touchstart', function (e) { report(atTop(e.target)); }, { capture: true, passive: true });
36
36
  // Cu\u1ED9n r\u1EDDi \u0111\u1EA7u trang \u2192 b\xE1o ngay, kh\xF4ng \u0111\u1EE3i l\u1EA7n ch\u1EA1m sau (tr\xE1nh host d\xF9ng gi\xE1 tr\u1ECB c\u0169 "\u0111ang \u1EDF \u0111\u1EA7u").
@@ -38,8 +38,29 @@
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;`,Gt=e=>xe({event:e}),Qt=(e,t)=>{let n=Xt(t);return`try { history.replaceState(history.state, '', location.pathname + ${JSON.stringify(n?`?${n}`:"")} + location.hash); } catch (e) {}
42
- ${rt(e)}`},Xt=e=>Object.entries(e).filter(([,t])=>t!=null&&t!=="").map(([t,n])=>`${encodeURIComponent(t)}=${encodeURIComponent(String(n))}`).join("&"),Zt=(e,t={})=>{let n=Xt(t);return`window.__RETION_MINIAPP_HOST__ = { protocol: ${Fe} };
41
+ })(); true;`,nn=()=>`(function () {
42
+ if (window.__retionSafeAreaFrozen) { return; }
43
+ window.__retionSafeAreaFrozen = true;
44
+ var max = {};
45
+ var orig = window.getComputedStyle;
46
+ window.getComputedStyle = function (el, pseudo) {
47
+ var style = orig.call(this, el, pseudo);
48
+ var m = el && el.style && /env\\(safe-area-inset-(top|right|bottom|left)\\)/.exec(el.style.cssText || '');
49
+ if (!m) { return style; }
50
+ var prop = 'padding-' + m[1];
51
+ var value = parseFloat(style.getPropertyValue(prop)) || 0;
52
+ if (!(prop in max) || value > max[prop]) { max[prop] = value; }
53
+ var frozen = max[prop] + 'px';
54
+ return new Proxy(style, {
55
+ get: function (t, k) {
56
+ if (k === 'getPropertyValue') { return function (p) { return p === prop ? frozen : t.getPropertyValue(p); }; }
57
+ var v = t[k];
58
+ return typeof v === 'function' ? v.bind(t) : v;
59
+ },
60
+ });
61
+ };
62
+ })(); true;`,rn=e=>ke({event:e}),on=(e,t)=>{let n=sn(t);return`try { history.replaceState(history.state, '', location.pathname + ${JSON.stringify(n?`?${n}`:"")} + location.hash); } catch (e) {}
63
+ ${ut(e)}`},sn=e=>Object.entries(e).filter(([,t])=>t!=null&&t!=="").map(([t,n])=>`${encodeURIComponent(t)}=${encodeURIComponent(String(n))}`).join("&"),an=(e,t={})=>{let n=sn(t);return`window.__RETION_MINIAPP_HOST__ = { protocol: ${He} };
43
64
  window.__RETION_MINIAPP_CONTEXT__ = ${JSON.stringify(e)};
44
65
  ${n?`try { history.replaceState(history.state, '', location.pathname + '?' + ${JSON.stringify(n)} + location.hash); } catch (e) {}`:""}
45
- true;`},en={partner:"partner_token",chatbox:"chatbox_token"},tn=(e,t)=>{let n={...e};for(let i of Object.values(en))t.includes(i)||delete n[i];return n},it=new Set,be=async(e,t)=>{if(it.has(e))throw new d("BUSY",`${e} \u0111ang ch\u1EA1y \u2014 ch\u1EDD l\u01B0\u1EE3t tr\u01B0\u1EDBc xong`);it.add(e);try{return await t()}finally{it.delete(e)}},ri=new Set(["selection","impactLight","impactMedium","impactHeavy","rigid","soft","notificationSuccess","notificationWarning","notificationError"]),Ue=(e,t)=>{if(typeof e!="string"||!e)throw new d("INVALID_PARAMS",`Thi\u1EBFu ${t}`);return e},nn=async({method:e,params:t},{getHostData:n,getPermissions:i,is_dark:o,close:s,app_id:c,instance_id:a,options:r,emit:l,isActive:u})=>{var w,I,P,x,m,L,J,$,R;let p=r==null?void 0:r.handlers,h={app_id:c,instance_id:a,close:s},A=()=>new d("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF \u1EE9ng d\u1EE5ng n\xE0y`);switch(e){case"getCurrentLocation":{let f=Et(t);return be(e,()=>Pt(f,u))}case"speech.start":{if(!l)throw A();let f={};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 d("INVALID_PARAMS","lang ph\u1EA3i l\xE0 m\xE3 ng\xF4n ng\u1EEF nh\u01B0 vi-VN");f.lang=t.lang}for(let M of["continuous","interimResults","addsPunctuation","requiresOnDeviceRecognition"])if((t==null?void 0:t[M])!==void 0){if(typeof t[M]!="boolean")throw new d("INVALID_PARAMS",`${M} ph\u1EA3i l\xE0 boolean`);f[M]=t[M]}return Vt(a,f,l,u)}case"speech.stop":return jt(a);case"uploadFiles":{let{task_id:f,...M}=t!=null?t:{};if(f!==void 0&&(typeof f!="string"||!f))throw new d("INVALID_PARAMS","task_id ph\u1EA3i l\xE0 chu\u1ED7i");return Bt(It(M),{instance_id:a,task_id:f,config:r==null?void 0:r.upload,emit:l,exclusivePick:_=>be("uploadFiles.pick",_)})}case"uploadFiles.cancel":$t(a,t==null?void 0:t.task_id);return;case"getUploadCapabilities":return Ut(r==null?void 0:r.upload);case"getBiometricAvailability":return((w=r==null?void 0:r.biometrics)!=null?w:await Ze()).getAvailability();case"authenticateBiometric":{let f=Ue(t==null?void 0:t.reason,"reason").trim();if(!f||f.length>200)throw new d("INVALID_PARAMS","reason must contain 1\u2013200 characters");let M=t==null?void 0:t.cancelButtonText;if(M!==void 0&&(typeof M!="string"||!M.trim()||M.length>80))throw new d("INVALID_PARAMS","Invalid cancelButtonText");return be(e,async()=>{var F;return((F=r==null?void 0:r.biometrics)!=null?F:await Ze()).authenticate({reason:f,cancelButtonText:M})})}case"requestPayment":{let f=p==null?void 0:p.requestPayment;if(!f)throw A();let M=t==null?void 0:t.amount;if(typeof M!="number"||!Number.isFinite(M)||M<=0)throw new d("INVALID_PARAMS","amount ph\u1EA3i l\xE0 s\u1ED1 > 0");let _={...t,amount:M,currency:Ue(t==null?void 0:t.currency,"currency")};return be(e,()=>f(_,h))}case"printImage":{let f=p==null?void 0:p.printImage;if(!f)throw A();let M=Ue(t==null?void 0:t.image,"image");await be(e,()=>f({image:M},h));return}case"openScreen":if(!(p!=null&&p.openScreen))throw A();await p.openScreen({screen:Ue(t==null?void 0:t.screen,"screen"),params:t==null?void 0:t.params},h);return;case"closeApp":s();return;case"openWebview":{let f=String((I=t==null?void 0:t.url)!=null?I:"");if(!/^https?:\/\//i.test(f))throw new d("INVALID_PARAMS","url ph\u1EA3i l\xE0 http(s)");await(r!=null&&r.openUrl?r.openUrl(f):Se.Linking.openURL(f));return}case"openLink":{let f=String((P=t==null?void 0:t.url)!=null?P:"").trim();if(!/^[a-z][a-z0-9+.-]*:/i.test(f)||/^(javascript|file|data|about|blob):/i.test(f))throw new d("INVALID_PARAMS","url kh\xF4ng h\u1EE3p l\u1EC7");try{await(r!=null&&r.openUrl?r.openUrl(f):Se.Linking.openURL(f))}catch(M){throw new d("NOT_SUPPORTED",String((m=(x=M==null?void 0:M.message)!=null?x:M)!=null?m:"Kh\xF4ng m\u1EDF \u0111\u01B0\u1EE3c link"))}return}case"showToast":(J=r==null?void 0:r.showToast)==null||J.call(r,String((L=t==null?void 0:t.message)!=null?L:""));return;case"haptic":{let f=ri.has(t==null?void 0:t.type)?t.type:"selection";($=r==null?void 0:r.haptic)==null||$.call(r,f);return}case"getSystemInfo":return{platform:Se.Platform.OS==="ios"?"ios":"android",appVersion:(R=r==null?void 0:r.app_version)!=null?R:"",theme:o?"dark":"light"};case"getAccessToken":{let f=n().access_token;if(!f)throw new d("HOST_ERROR","Mini app ch\u01B0a c\xF3 token cho page n\xE0y");return f}case"getToken":{let f=t==null?void 0:t.type;if(f==="access"){let F=n().access_token;if(!F)throw new d("HOST_ERROR","Mini app ch\u01B0a c\xF3 token cho page n\xE0y");return F}if(f!=="partner"&&f!=="chatbox")throw new d("HOST_ERROR",`Lo\u1EA1i token kh\xF4ng h\u1EE3p l\u1EC7: ${String(f)}`);let M=en[f];if(!i().includes(M))throw new d("PERMISSION_DENIED",`Mini app ch\u01B0a \u0111\u01B0\u1EE3c c\u1EA5p quy\u1EC1n ${M} (Console \u2192 Quy\u1EC1n l\u1EA5y token)`);let _=f==="partner"?n().partner_token:n().chatbox_token;if(!_)throw new d("HOST_ERROR",`Kh\xF4ng c\xF3 ${M}`);return _}case"getUserInfo":{let f=n().user;if(!f)throw new d("HOST_ERROR","Kh\xF4ng l\u1EA5y \u0111\u01B0\u1EE3c th\xF4ng tin nh\xE2n vi\xEAn");return f}case"getPageInfo":{let f=n().page;if(!f)throw new d("HOST_ERROR","Kh\xF4ng l\u1EA5y \u0111\u01B0\u1EE3c th\xF4ng tin page");return f}case"sendMessage":case"insertText":throw new d("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF phi\xEAn b\u1EA3n app n\xE0y`);default:throw new d("NOT_SUPPORTED",`API kh\xF4ng t\u1ED3n t\u1EA1i: ${e}`)}};var st=e=>`bundle:${e}`,at=()=>`${k().file_system.document_dir}/miniapps`,ct=at,lt=(e,t,n="index.html",i=!1,o=[])=>{let s=`${ct()}/${e}/${t}`;return{app_id:e,version:t,dir:s,entry_uri:`file://${s}/${n}`,context_update:i,permissions:o}},ot=e=>{var t;k().storage.setString(st(e.app_id),JSON.stringify({version:e.version,entry:e.entry,context_update:!!e.context_update,permissions:(t=e.permissions)!=null?t:[]}))},oi=(e,t)=>/^https?:\/\//.test(t)?t:`${e.replace(/[^/]*$/,"")}${t}`,O=e=>{let t=k().storage.getString(st(e));if(!t)return null;try{let{version:n,entry:i,context_update:o,permissions:s}=JSON.parse(t);return lt(e,n,i,!!o,Array.isArray(s)?s:[])}catch{return null}},ne=e=>k().file_system.exists(e.entry_uri.replace("file://","")),pt=async e=>{let t=O(e.app_id);return(t==null?void 0:t.version)===e.version&&await ne(t)},on=async(e,t)=>{let n=k().file_system,i=`${ct()}/${e}`,o=await n.listDir(i).catch(()=>[]);await Promise.all(o.filter(s=>!t.includes(s)).map(s=>n.remove(`${i}/${s}`).catch(()=>{})))},sn=async e=>{var t;await((t=Pe[e])==null?void 0:t.catch(()=>{})),k().storage.setString(st(e),""),await k().file_system.remove(`${ct()}/${e}`).catch(()=>{})},Ae=class extends Error{constructor(){super("cancelled"),this.name="MiniAppInstallCancelled"}},Pe={},an=(e,t)=>{var s;let i=((s=Pe[e])!=null?s:Promise.resolve()).catch(()=>{}).then(t),o=i.catch(()=>{});return Pe[e]=o,o.then(()=>{Pe[e]===o&&delete Pe[e]}),i},si=(e,t)=>{var o,s;let n=e.split(".").map(c=>parseInt(c,10)||0),i=t.split(".").map(c=>parseInt(c,10)||0);for(let c=0;c<Math.max(n.length,i.length);c++){let a=((o=n[c])!=null?o:0)-((s=i[c])!=null?s:0);if(a)return a}return 0},cn=({manifest:e,zip_path:t})=>an(e.app_id,async()=>{var s;let n=k().file_system,i=O(e.app_id);if(i&&si(i.version,e.version)>=0&&await ne(i))return i;if(e.sha256&&n.sha256&&await n.sha256(t)!==e.sha256)throw new Error("sha256 mismatch");let o=lt(e.app_id,e.version,e.entry,!!e.context_update,(s=e.permissions)!=null?s:[]);return await n.remove(o.dir).catch(()=>{}),await n.mkdir(o.dir),await n.unzip(t,o.dir),ot(e),H("\u0111\xE3 c\xE0i b\u1EA3n \u0111\xF3ng s\u1EB5n",e.app_id,e.version),on(e.app_id,[e.version,i==null?void 0:i.version].filter(Boolean)),o}),ut=(e,{base_url:t,onProgress:n}={})=>{let i=k().file_system,o=null,s=!1,c=`${i.cache_dir}/${e.app_id}-${e.version}.zip`,a=()=>{if(s)throw new Ae},r=async()=>{var p;a();let l=O(e.app_id);if((l==null?void 0:l.version)===e.version&&await i.exists(l.dir))return ot(e),O(e.app_id);a();let u=i.download({url:t?oi(t,e.bundle_url):e.bundle_url,to_file:c,onProgress:(h,A)=>{var I;let w=A>0?A:(I=e.size)!=null?I:0;w>0&&(n==null||n(Math.min(1,h/w)))}});o=u;try{let{status:h}=await u.promise;if(a(),h!==200)throw new Error(`bundle ${h}`);if(e.sha256)if(i.sha256){if(await i.sha256(c)!==e.sha256)throw new Error("sha256 mismatch")}else H("b\u1ECF qua ki\u1EC3m tra sha256 (file_system kh\xF4ng c\xF3 sha256)",e.app_id);a();let A=lt(e.app_id,e.version,e.entry,!!e.context_update,(p=e.permissions)!=null?p:[]);return await i.remove(A.dir).catch(()=>{}),await i.mkdir(A.dir),await i.unzip(c,A.dir),ot(e),on(e.app_id,[e.version,l==null?void 0:l.version].filter(Boolean)),A}catch(h){throw s?new Ae:h}finally{o=null,i.remove(c).catch(()=>{})}};return{promise:an(e.app_id,r),cancel:()=>{s=!0,o==null||o.cancel()}}},Ee={},ai=__DEV__?0:60*1e3,rn={},ln=(e,t)=>{var i,o;let n=O(e);return n&&Date.now()-((i=rn[t])!=null?i:0)<ai?Promise.resolve(n):((o=Ee[e])!=null||(Ee[e]=(async()=>{let s=await fetch(t,{headers:{"Cache-Control":"no-cache"}});if(!s.ok)throw new Error(`manifest ${s.status}`);let c=await s.json(),a=await ut(c,{base_url:t}).promise;return rn[t]=Date.now(),a})().catch(s=>(console.warn("[miniapp] sync failed",e,s==null?void 0:s.message),O(e))).finally(()=>{Ee[e]=void 0})),Ee[e])};var $e=new Map,pn=(e,t)=>($e.set(e,t),()=>{$e.get(e)===t&&$e.delete(e)}),un=(e,t)=>{let n=$e.get(e);return n?n(t):!1};var Be=require("react"),qe=e=>{let t=e,n=new Set;return{getState:()=>t,setState:i=>{let o=typeof i=="function"?i(t):i;t={...t,...o},n.forEach(s=>s())},subscribe:i=>(n.add(i),()=>{n.delete(i)})}},Z=(e,t,n=Object.is)=>{let i=(0,Be.useRef)(null),o=()=>{let s=e.getState(),c=i.current;if(c&&c.state===s&&c.selector===t)return c.value;let a=t(s),r=c&&n(c.value,a)?c.value:a;return i.current={state:s,selector:t,value:r},r};return(0,Be.useSyncExternalStore)(e.subscribe,o)};var W=qe({active_key:null,instances:{}}),dn=({app:e,instance_id:t,context:n={},url_params:i={},host_data:o={}},s)=>{var a;let c=(a=k().keep_alive)==null?void 0:a.max_webviews;W.setState(r=>{let l=t!=null?t:e.app_id,u={...r.instances,[l]:{key:l,app:e,context:n,url_params:i,host_data:o,last_used_at:Date.now()}},p=Object.keys(u);return c&&c>0&&p.length>c&&p.filter(h=>h!==l).sort((h,A)=>u[h].last_used_at-u[A].last_used_at).slice(0,p.length-c).forEach(h=>{delete u[h]}),s?{active_key:l,instances:u}:{instances:u}})},gn=e=>dn(e,!0),fn=e=>dn(e,!1),we=()=>W.setState({active_key:null}),Ve=e=>{W.setState(t=>{if(t.active_key===e||!t.instances[e])return{};let n={...t.instances};return delete n[e],{instances:n}})};var mn="catalog",ci="paused_apps",li="removed_apps",pi=10*1e3,ui=2,di=3e3,gi=()=>{var e;try{return JSON.parse((e=k().storage.getString(mn))!=null?e:"{}")}catch{return{}}},E=qe({catalog:{},downloads:{},pause_reasons:[],updates:{},apply_ticks:{}}),hn=e=>{var t;return!!((t=k().manual_update)!=null&&t.includes(e))},We=new Set,An=e=>{let t=new Set,n=()=>k().storage.setString(e,JSON.stringify([...t]));return{has:i=>t.has(i),values:()=>[...t],add:i=>t.has(i)?!1:(t.add(i),n(),!0),delete:i=>t.delete(i)?(n(),!0):!1,load:()=>{var i;t.clear();try{let o=JSON.parse((i=k().storage.getString(e))!=null?i:"[]");Array.isArray(o)&&o.forEach(s=>{typeof s=="string"&&t.add(s)})}catch{}}}},G=An(ci),pe=An(li);bt(()=>{G.load(),pe.load();let e=gi(),t={};Object.keys(e).filter(n=>!pe.has(n)).forEach(n=>{let i=O(n);i?t[n]={status:"installed",progress:1,version:i.version,has_local:!0}:G.has(n)&&(t[n]={status:"paused",progress:0,version:e[n].version,has_local:!1})}),E.setState({catalog:e,downloads:t})});var ze=e=>Z(E,t=>e?t.downloads[e]:void 0),wn=()=>Z(E,e=>e.pause_reasons.length>0),Y=(...e)=>H("queue",...e),U=[],ie={},b=null,je=new Set,me={},dt=new Set,ce=e=>{dt.forEach(t=>{try{t(e)}catch(n){console.warn("[miniapp-queue] event listener error",n==null?void 0:n.message)}})},yn=e=>(dt.add(e),()=>{dt.delete(e)}),Mn=()=>E.getState().downloads,V=(e,t)=>{let n=!!O(e),i=E.getState().downloads[e],o=t.status==="downloading"&&n?"updating":t.status,s={...i!=null?i:{status:"queued",progress:0},...t,...o?{status:o}:{},has_local:n};E.setState(c=>({downloads:{...c.downloads,[e]:s}})),(i==null?void 0:i.status)!==s.status||(i==null?void 0:i.version)!==s.version||(i==null?void 0:i.has_local)!==s.has_local?ce({type:"status_change",app_id:e,state:s}):i.progress!==s.progress&&ce({type:"progress",app_id:e,progress:s.progress,version:s.version})},He=(e,t)=>{var n;(n=me[e])==null||n.forEach(i=>i(t)),delete me[e]},fi=()=>E.getState().pause_reasons.length>0,le=e=>{var a;if(b)return;let t=e?U.indexOf(e):fi()?-1:U.findIndex(r=>!G.has(r));if(t<0||t>=U.length)return;let[n]=U.splice(t,1),i=E.getState().catalog[n];if(!i){He(n,O(n)),le();return}let o=Date.now();ie[n]=((a=ie[n])!=null?a:0)+1,V(n,{status:"downloading",progress:0,version:i.version,error:void 0});let s=0,c=ut(i,{onProgress:r=>{let l=Math.floor(r*100);l!==s&&(s=l,V(n,{progress:l/100,version:i.version}))}});b={app_id:n,handle:c,forced:!!e},Y("start",n,i.version,e?"(forced)":""),c.promise.then(r=>{Y("installed",n,i.version,`${Date.now()-o}ms`),V(n,{status:"installed",progress:1,version:i.version}),He(n,r)}).catch(r=>{var u;if(r instanceof Ae){if(je.has(n))return;Y("paused",n),ie[n]-=1,U.unshift(n),V(n,{status:G.has(n)?"paused":"queued",progress:0,version:i.version});return}let l=String((u=r==null?void 0:r.message)!=null?u:r);if(console.warn("[miniapp-queue] failed",n,l),ie[n]<ui){V(n,{status:"queued",progress:0,version:i.version,error:l}),setTimeout(()=>{var p;U.includes(n)||(b==null?void 0:b.app_id)===n||(U.push(n),le((p=me[n])!=null&&p.length?n:void 0))},di);return}V(n,{status:"failed",progress:0,version:i.version,error:l}),He(n,O(n))}).finally(()=>{b=null;let r=U.find(l=>{var u;return(u=me[l])==null?void 0:u.length});le(r)})},Je=(e,{front:t=!1}={})=>{if((b==null?void 0:b.app_id)===e)return;let n=U.indexOf(e);if(n>=0){if(!t)return;U.splice(n,1)}t?U.unshift(e):U.push(e)},mi=async e=>{let{host_id:t,client_token:n}=k(),i=new AbortController,o=setTimeout(()=>i.abort(),pi);try{let s=`${Ie}/api/hosts/${encodeURIComponent(t)}/miniapps?channel=${e}`,c=await fetch(s,{headers:{Authorization:`Bearer ${n}`,"Cache-Control":"no-cache"},signal:i.signal});if(!c.ok)throw new Error(`host list ${e} ${c.status}`);return(await c.json()).apps.map(r=>({...r,channel:e}))}finally{clearTimeout(o)}},Re=null,Ke=()=>(Re!=null||(Re=(async()=>{var t;let e=Date.now();try{let n=await Promise.all(k().channels.map(mi)),i={};[...n].reverse().flat().forEach(r=>{i[r.app_id]=r});let o=Object.keys(E.getState().catalog).filter(r=>!i[r]);k().storage.setString(mn,JSON.stringify(i)),E.setState({catalog:i}),await Promise.all(o.map(r=>vn(r,{by_user:!1}))),o.forEach(r=>pe.delete(r));let s=Object.keys(i).filter(r=>!pe.has(r)),c=[],a={};for(let r of s.map(l=>i[l])){if(await pt(r)){V(r.app_id,{status:"installed",progress:1,version:r.version});continue}let l=O(r.app_id);if(hn(r.app_id)&&!We.has(r.app_id)&&l&&await ne(l)){V(r.app_id,{status:"installed",progress:1,version:l.version}),a[r.app_id]={app_id:r.app_id,current_version:l.version,next_version:r.version};continue}c.push(r)}return E.setState({updates:a}),c.forEach(r=>{ie[r.app_id]=0,V(r.app_id,{status:G.has(r.app_id)?"paused":"queued",progress:0,version:r.version,error:void 0}),Je(r.app_id)}),Y("catalog",s.length,"apps, outdated",c.map(r=>r.app_id),"removed",o,`${Date.now()-e}ms`),ce({type:"sync_complete",app_ids:s,removed:o}),Object.values(a).forEach(r=>ce({type:"update_available",...r})),le(),{ok:!0,app_ids:s,removed:o}}catch(n){let i=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",i),ce({type:"sync_failed",error:i}),{ok:!1,error:i}}finally{Re=null}})()),Re),vn=async(e,{by_user:t})=>{var o,s,c,a;if(t&&pe.add(e),je.has(e))return;je.add(e),G.delete(e);let n=U.indexOf(e);n>=0&&U.splice(n,1),(b==null?void 0:b.app_id)===e&&b.handle.cancel();let i=(a=(c=(o=E.getState().downloads[e])==null?void 0:o.version)!=null?c:(s=O(e))==null?void 0:s.version)!=null?a:"";V(e,{status:"uninstalling",progress:0,version:i}),await sn(e),Ve(e),E.setState(r=>{let l={...r.downloads};return delete l[e],{downloads:l}}),delete ie[e],je.delete(e),He(e,null),Y("uninstalled",e,t?"(user)":"(not in list)"),ce({type:"uninstalled",app_id:e})},_n=e=>vn(e,{by_user:!0}),bn=e=>{let t=ye(e);return t?(pe.delete(e),(b==null?void 0:b.app_id)===e||U.includes(e)||(ie[e]=0,V(e,{status:G.has(e)?"paused":"queued",progress:0,version:t.version,error:void 0}),Je(e),le(),Y("restore",e)),!0):!1},Sn=e=>{if(G.has(e))return;if(G.add(e),Y("pause app",e),(b==null?void 0:b.app_id)===e&&!b.forced){b.handle.cancel();return}let t=E.getState().downloads[e];U.includes(e)&&t&&V(e,{status:"paused",progress:0,version:t.version})},xn=e=>{if(!G.delete(e))return;Y("resume app",e);let t=E.getState().downloads[e];(t==null?void 0:t.status)==="paused"&&!U.includes(e)&&ye(e)&&(ie[e]=0,Je(e)),U.includes(e)&&t&&V(e,{status:"queued",progress:0,version:t.version}),le()},En=e=>{let{pause_reasons:t}=E.getState();t.includes(e)||(E.setState({pause_reasons:[...t,e]}),Y("pause",e),t.length===0&&ce({type:"pause_change",paused:!0,reasons:[e]}),b&&!b.forced&&b.handle.cancel())},Pn=e=>{let{pause_reasons:t}=E.getState();if(!t.includes(e))return;let n=t.filter(i=>i!==e);E.setState({pause_reasons:n}),Y("resume",e),n.length===0&&ce({type:"pause_change",paused:!1,reasons:n}),le()},gt=e=>E.getState().updates[e],Rn=async e=>{var n,i;let t=gt(e);We.add(e);try{let o=await Oe(e),s=(i=t==null?void 0:t.next_version)!=null?i:(n=ye(e))==null?void 0:n.version;return!o||!s||o.version!==s?!1:(E.setState(c=>{var r;let a={...c.updates};return delete a[e],{updates:a,apply_ticks:{...c.apply_ticks,[e]:((r=c.apply_ticks[e])!=null?r:0)+1}}}),Y("updated",e,t==null?void 0:t.current_version,"\u2192",o.version),!0)}finally{We.delete(e)}},On=()=>Object.values(E.getState().catalog).map(e=>({...e,installed:!!O(e.app_id),removed_by_user:pe.has(e.app_id)})),ye=e=>E.getState().catalog[e],Oe=async e=>{let t=ye(e);if(!t)return;if(G.delete(e),pe.delete(e),await pt(t))return O(e);let n=O(e);if(hn(e)&&!We.has(e)&&n&&await ne(n))return n;let i=new Promise(o=>{var s;((s=me[e])!=null?s:me[e]=[]).push(o)});return(b==null?void 0:b.app_id)===e?b.forced=!0:(ie[e]=0,Je(e,{front:!0}),b&&!b.forced?b.handle.cancel():le(e)),i};var T=require("react/jsx-runtime"),ft=e=>(e!=null?e:"").replace(/\?[^#]*/,""),Tn=0,hi=()=>{let e=new Set;return{emit:t=>e.forEach(n=>n(t)),subscribe:t=>(e.add(t),()=>{e.delete(t)})}},Ai=y.default.memo(({instance_key:e,is_active:t,is_front:n,is_dark:i,reload_tick:o,web_at_top:s,splash:c,bridge:a,opaque_background:r,allow_embedded_miniapps:l,onWebLoadEnd:u})=>{var At,wt;let p=(0,y.useRef)(null),h=(0,y.useRef)(!1),A=Z(W,g=>g.instances[e]),w=A==null?void 0:A.app.app_id,I=A==null?void 0:A.app.manifest_url,P=A==null?void 0:A.context,x=A==null?void 0:A.url_params,[m,L]=(0,y.useState)(()=>w?O(w):null),[J,$]=(0,y.useState)(!1),[R,f]=(0,y.useState)(0),[M,_]=(0,y.useState)(0),[F,D]=(0,y.useState)(!1),j=(0,y.useRef)(null),re=g=>{j.current&&clearTimeout(j.current),j.current=setTimeout(()=>{j.current=null,D(!0)},g)};(0,y.useEffect)(()=>()=>{j.current&&clearTimeout(j.current)},[]),(0,y.useEffect)(()=>{if(!w||!t&&m)return;let g=!0;return $(!1),(async()=>{let v=O(w),B=v?await ne(v):!1;if(!g||(L(B?K=>!K||K.version!==v.version||K.permissions.join(",")!==v.permissions.join(",")?v:K:null),__DEV__&&Date.now()-Tn>1e4&&(Tn=Date.now(),await Ke()),!g))return;let se=await Oe(w),de=se!==void 0?se:I?await ln(w,I):O(w);if(g){if(!de){$(!0);return}L(K=>K!=null?K:de)}})(),()=>{g=!1}},[t,w,I,R]),(0,y.useEffect)(()=>pn(e,g=>p.current?(p.current.postMessage(g),!0):!1),[e]);let Ye=Z(E,g=>{let v=w?g.downloads[w]:void 0;return(v==null?void 0:v.status)==="installed"?v.version:void 0});(0,y.useEffect)(()=>{if(t||!w||!m)return;let g=O(w);if(!g||g.version===m.version)return;let v=!0;return ne(g).then(B=>{!v||!B||(H(`webview:${e}`,"\u0111\u1ED5i bundle (\u1EA9n)",m.version,"\u2192",g.version),L(g))}),()=>{v=!1}},[t,w,Ye,m==null?void 0:m.version]);let ue=Z(E,g=>{var v;return w&&(v=g.apply_ticks[w])!=null?v:0});(0,y.useEffect)(()=>{if(!ue||!w)return;let g=O(w);if(!g||g.version===(m==null?void 0:m.version))return;let v=!0;return ne(g).then(B=>{!v||!B||(H(`webview:${e}`,"c\u1EADp nh\u1EADt",m==null?void 0:m.version,"\u2192",g.version),D(!1),L(g))}),()=>{v=!1}},[ue]),(0,y.useEffect)(()=>{var B;let g=(B=k().keep_alive)==null?void 0:B.idle_close_ms;if(t||!g||g<=0)return;let v=setTimeout(()=>{Ve(e)},g);return()=>clearTimeout(v)},[t,e]),(0,y.useEffect)(()=>{o>0&&($(!1),D(!1),_(g=>g+1),f(g=>g+1))},[o]);let Te=(0,y.useRef)(t);(0,y.useEffect)(()=>{var g;Te.current!==t&&(Te.current=t,h.current&&((g=p.current)==null||g.injectJavaScript(Gt(t?"resumed":"paused"))))},[t]);let oe=`${(At=m==null?void 0:m.version)!=null?At:"none"}:${(wt=m==null?void 0:m.permissions.join(","))!=null?wt:""}:${M}`,Me=(0,y.useMemo)(()=>JSON.stringify([P!=null?P:{},x!=null?x:{}]),[P,x]),Ge=(0,y.useMemo)(()=>{var g;return tn(x!=null?x:{},(g=m==null?void 0:m.permissions)!=null?g:[])},[Me,m==null?void 0:m.permissions]),Ln=(0,y.useMemo)(()=>Zt(P!=null?P:{},Ge)+Yt()+(k().debug?Kt():""),[Ge]),ke=(0,y.useRef)(null),ht=(0,y.useRef)(null);(0,y.useEffect)(()=>{var v,B,se;if(!m)return;if(ht.current!==oe){ht.current=oe,ke.current=Me;return}if(ke.current===Me)return;let g=((B=JSON.parse((v=ke.current)!=null?v:"[]")[0])!=null?B:{}).org_id;if(ke.current=Me,g===(P==null?void 0:P.org_id)&&h.current){D(!1),re(1500),(se=p.current)==null||se.injectJavaScript(Qt(P!=null?P:{},Ge));return}D(!1),_(de=>de+1)},[Me,m,oe]),(0,y.useEffect)(()=>(t||(X(e),fe(e)),()=>{X(e),fe(e)}),[t,e,oe,o]),(0,y.useEffect)(()=>{let g=S.AppState.addEventListener("change",v=>{v==="background"&&X(e)});return()=>g.remove()},[e]);let Dn=(0,y.useCallback)(async g=>{var B,se,de,K,Qe;let v=Ht(g.nativeEvent.data);if(!v){if(w&&(a!=null&&a.onWebEvent))try{Promise.resolve(a.onWebEvent(g.nativeEvent.data,{app_id:w,instance_id:e})).catch(C=>{console.warn("[miniapp] onWebEvent l\u1ED7i",w,C)})}catch(C){console.warn("[miniapp] onWebEvent l\u1ED7i",w,C)}return}if(v.method==="log"){let{level:C,text:q}=v;H(`web:${e}`,C!=null?C:"log",q!=null?q:"");return}if(v.method==="pong"){j.current||D(!0);return}if(v.method==="touchAtTop"){s.emit(!!v.at_top);return}if(v.method==="contextApplied"){j.current&&clearTimeout(j.current),j.current=null,D(!0);return}if(v.method==="ready"){h.current=!0,D(!0);let C=(B=W.getState().instances[e])==null?void 0:B.context;C&&((se=p.current)==null||se.injectJavaScript(rt(C)));return}try{let C=await nn(v,{getHostData:()=>{var q,ee;return(ee=(q=W.getState().instances[e])==null?void 0:q.host_data)!=null?ee:{}},getPermissions:()=>{var q,ee;return w?(ee=(q=O(w))==null?void 0:q.permissions)!=null?ee:[]:[]},is_dark:i,close:we,app_id:w!=null?w:"",instance_id:e,options:a,emit:(q,ee)=>{var yt;(yt=p.current)==null||yt.injectJavaScript(Jt(q,ee))},isActive:()=>W.getState().active_key===e&&S.AppState.currentState!=="background"});v.id&&((de=p.current)==null||de.injectJavaScript(Wt(v.id,C)))}catch(C){if(!v.id)return;let q=C==null?void 0:C.code,ee=C instanceof d?C:new d(typeof q=="string"?q:"HOST_ERROR",String((K=C==null?void 0:C.message)!=null?K:C));(Qe=p.current)==null||Qe.injectJavaScript(zt(v.id,ee))}},[e,i,w,s,a]),Nn=(0,y.useCallback)(()=>{$(!1),_(g=>g+1),f(g=>g+1)},[]);return(0,T.jsxs)(S.View,{style:[S.StyleSheet.absoluteFill,r&&{backgroundColor:i?"#09090B":"#FFFFFF"},!n&&z.behind],pointerEvents:t?"auto":"none",children:[m?(0,T.jsx)(Cn.default,{ref:p,source:{uri:m.entry_uri},originWhitelist:["*"],allowingReadAccessToURL:`file://${l?at():m.dir}`,allowFileAccess:!0,allowFileAccessFromFileURLs:!0,allowUniversalAccessFromFileURLs:!0,injectedJavaScriptBeforeContentLoaded:Ln,onMessage:Dn,bounces:!1,overScrollMode:"never",onLoadStart:g=>{X(e),fe(e),H(`webview:${e}`,"load start",ft(g.nativeEvent.url)),h.current=!1,D(!1)},onError:g=>{X(e),fe(e),H(`webview:${e}`,"load error",ft(g.nativeEvent.url),g.nativeEvent.description),$(!0),D(!1)},onLoadEnd:g=>{let v=g.nativeEvent.url;H(`webview:${e}`,"load end",ft(v)),w&&(u==null||u({app_id:w,instance_id:e,url:v})),re(1500)},onContentProcessDidTerminate:()=>{X(e),fe(e),h.current=!1,D(!1),_(g=>g+1)},onRenderProcessGone:()=>(X(e),fe(e),h.current=!1,D(!1),_(g=>g+1),!0),style:z.webview},oe):null,A&&(0,T.jsx)(yi,{visible:!m||!F,interactive:J,children:(0,T.jsx)(wi,{splash:c,app:A.app,is_dark:i,error:J,has_bundle:!!m,retry:Nn})})]})}),wi=y.default.memo(({splash:e,app:t,is_dark:n,error:i,has_bundle:o,retry:s})=>{let c=e,a=ze(t.app_id),r=i?"error":!o&&(a==null?void 0:a.status)==="downloading"?"downloading":"loading";return(0,T.jsx)(c,{app:t,is_dark:n,status:r,progress:r==="downloading"?a==null?void 0:a.progress:void 0,retry:s})}),yi=({visible:e,interactive:t,children:n})=>{let i=(0,y.useRef)(new S.Animated.Value(e?1:0)).current,[o,s]=(0,y.useState)(e);return(0,y.useEffect)(()=>{if(e){s(!0),i.setValue(1);return}let c=S.Animated.timing(i,{toValue:0,duration:180,useNativeDriver:!0});return c.start(({finished:a})=>{a&&s(!1)}),()=>c.stop()},[e,i]),o?(0,T.jsx)(S.Animated.View,{style:[S.StyleSheet.absoluteFill,{opacity:i}],pointerEvents:t?"auto":"none",children:n}):null},mt=({app:e,is_dark:t,status:n,progress:i,retry:o})=>{let s=t?"#FAFAFA":"#18181B";return(0,T.jsxs)(S.View,{style:[z.splash,{backgroundColor:t?"#09090B":"#FFFFFF"}],children:[(0,T.jsx)(S.View,{style:[z.splash_icon,{backgroundColor:t?"#18181B":"#F4F4F5"}],children:e.icon?(0,T.jsx)(S.Image,{source:{uri:e.icon},style:z.splash_icon_image}):(0,T.jsx)(S.Text,{style:z.splash_letter,children:(e.name||"?").slice(0,1).toUpperCase()})}),(0,T.jsx)(S.Text,{style:[z.splash_name,{color:s}],children:e.name}),n==="error"?(0,T.jsxs)(T.Fragment,{children:[(0,T.jsx)(S.Text,{style:z.splash_hint,children:"Kh\xF4ng t\u1EA3i \u0111\u01B0\u1EE3c mini app"}),(0,T.jsx)(S.TouchableOpacity,{activeOpacity:.7,style:[z.retry_button,{backgroundColor:t?"#27272A":"#F4F4F5"}],onPress:o,children:(0,T.jsx)(S.Text,{style:[z.retry_text,{color:s}],children:"Th\u1EED l\u1EA1i"})})]}):(0,T.jsxs)(T.Fragment,{children:[(0,T.jsx)(S.ActivityIndicator,{style:z.splash_spinner,color:t?"#A1A1AA":"#71717A"}),n==="downloading"&&(0,T.jsxs)(S.Text,{style:z.splash_hint,children:["\u0110ang t\u1EA3i mini app",i?` ${Math.round(i*100)}%`:"\u2026"]})]})]})},kn=(e,t)=>{let n=(0,y.useRef)(t),i=(0,y.useRef)(!1);__DEV__&&!i.current&&n.current!==t&&(i.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.`))},Mi=({container:e,splash:t=mt,is_dark:n=!1,bridge:i,close_on_back:o=!0,opaque_background:s=!0,allow_embedded_miniapps:c=!1,onWebLoadEnd:a})=>{kn("container",e),kn("splash",t);let r=e,l=Z(W,m=>m.active_key),u=(0,y.useRef)(l);l&&(u.current=l);let p=Z(W,m=>Object.keys(m.instances).join("|")),h=Z(W,m=>{var L;return m.active_key?(L=m.instances[m.active_key])==null?void 0:L.app.name:void 0}),A=(0,y.useMemo)(()=>p?p.split("|"):[],[p]),[w,I]=(0,y.useState)({}),P=(0,y.useRef)(hi()).current;(0,y.useEffect)(()=>{if(!l||!o)return;let m=S.BackHandler.addEventListener("hardwareBackPress",()=>(we(),!0));return()=>m.remove()},[l,o]);let x=(0,y.useCallback)(()=>{let m=W.getState().active_key;m&&I(L=>({...L,[m]:(L[m]||0)+1}))},[]);return A.length?(0,T.jsx)(r,{visible:!!l,title:h!=null?h:"",is_dark:n,close:we,reload:x,subscribeWebAtTop:P.subscribe,children:A.map(m=>(0,T.jsx)(Ai,{instance_key:m,is_active:l===m,is_front:(l!=null?l:u.current)===m,is_dark:n,reload_tick:w[m]||0,web_at_top:P,splash:t,bridge:i,opaque_background:s,allow_embedded_miniapps:c,onWebLoadEnd:a},m))}):null},z=S.StyleSheet.create({webview:{flex:1,backgroundColor:"transparent"},behind:{zIndex:-1},splash:{flex:1,alignItems:"center",justifyContent:"center",gap:12},splash_icon:{width:72,height:72,borderRadius:20,alignItems:"center",justifyContent:"center",overflow:"hidden"},splash_icon_image:{width:72,height:72},splash_letter:{fontSize:28,fontWeight:"700",color:"#1D4ED8"},splash_name:{fontSize:16,fontWeight:"600"},splash_hint:{color:"#71717A"},splash_spinner:{marginTop:8},retry_button:{marginTop:4,paddingHorizontal:20,paddingVertical:10,borderRadius:999},retry_text:{fontWeight:"600"}}),In=y.default.memo(Mi);0&&(module.exports={DefaultMiniAppSplash,MINIAPP_PLATFORM_URL,MiniAppHost,MiniAppHostError,closeMiniApp,configureMiniApp,createDocumentPickerSource,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});
66
+ true;`},cn={partner:"partner_token",chatbox:"chatbox_token"},pn=(e,t)=>{let n={...e};for(let r of Object.values(cn))t.includes(r)||delete n[r];return n},lt=new Set,Te=async(e,t)=>{if(lt.has(e))throw new u("BUSY",`${e} \u0111ang ch\u1EA1y \u2014 ch\u1EDD l\u01B0\u1EE3t tr\u01B0\u1EDBc xong`);lt.add(e);try{return await t()}finally{lt.delete(e)}},wr=new Set(["selection","impactLight","impactMedium","impactHeavy","rigid","soft","notificationSuccess","notificationWarning","notificationError"]),ze=(e,t)=>{if(typeof e!="string"||!e)throw new u("INVALID_PARAMS",`Thi\u1EBFu ${t}`);return e},ln=async({method:e,params:t},{getHostData:n,getPermissions:r,getContext:i,is_dark:o,close:c,app_id:p,instance_id:a,options:s,emit:d,isActive:g})=>{var T,_,b,f,L,G,$,Se,ce;let A=s==null?void 0:s.handlers,l={app_id:p,instance_id:a,close:c},h=()=>new u("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF \u1EE9ng d\u1EE5ng n\xE0y`);switch(e){case"getCurrentLocation":{let w=kt(t);return Te(e,()=>It(w,g))}case"speech.start":{if(!d)throw h();let w={};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 u("INVALID_PARAMS","lang ph\u1EA3i l\xE0 m\xE3 ng\xF4n ng\u1EEF nh\u01B0 vi-VN");w.lang=t.lang}for(let S of["continuous","interimResults","addsPunctuation","requiresOnDeviceRecognition"])if((t==null?void 0:t[S])!==void 0){if(typeof t[S]!="boolean")throw new u("INVALID_PARAMS",`${S} ph\u1EA3i l\xE0 boolean`);w[S]=t[S]}return Kt(a,w,d,g)}case"speech.stop":return Yt(a);case"uploadFiles":{let{task_id:w,...S}=t!=null?t:{};if(w!==void 0&&(typeof w!="string"||!w))throw new u("INVALID_PARAMS","task_id ph\u1EA3i l\xE0 chu\u1ED7i");return Wt(Ft(S),{instance_id:a,app_id:p,getContext:i,task_id:w,config:s==null?void 0:s.upload,emit:d,exclusivePick:z=>Te("uploadFiles.pick",z)})}case"uploadFiles.cancel":Ht(a,t==null?void 0:t.task_id);return;case"getUploadCapabilities":return jt(s==null?void 0:s.upload);case"getBiometricAvailability":return((T=s==null?void 0:s.biometrics)!=null?T:await ot()).getAvailability();case"authenticateBiometric":{let w=ze(t==null?void 0:t.reason,"reason").trim();if(!w||w.length>200)throw new u("INVALID_PARAMS","reason must contain 1\u2013200 characters");let S=t==null?void 0:t.cancelButtonText;if(S!==void 0&&(typeof S!="string"||!S.trim()||S.length>80))throw new u("INVALID_PARAMS","Invalid cancelButtonText");return Te(e,async()=>{var v;return((v=s==null?void 0:s.biometrics)!=null?v:await ot()).authenticate({reason:w,cancelButtonText:S})})}case"requestPayment":{let w=A==null?void 0:A.requestPayment;if(!w)throw h();let S=t==null?void 0:t.amount;if(typeof S!="number"||!Number.isFinite(S)||S<=0)throw new u("INVALID_PARAMS","amount ph\u1EA3i l\xE0 s\u1ED1 > 0");let z={...t,amount:S,currency:ze(t==null?void 0:t.currency,"currency")};return Te(e,()=>w(z,l))}case"printImage":{let w=A==null?void 0:A.printImage;if(!w)throw h();let S=ze(t==null?void 0:t.image,"image");await Te(e,()=>w({image:S},l));return}case"openScreen":if(!(A!=null&&A.openScreen))throw h();await A.openScreen({screen:ze(t==null?void 0:t.screen,"screen"),params:t==null?void 0:t.params},l);return;case"closeApp":c();return;case"openWebview":{let w=String((_=t==null?void 0:t.url)!=null?_:"");if(!/^https?:\/\//i.test(w))throw new u("INVALID_PARAMS","url ph\u1EA3i l\xE0 http(s)");await(s!=null&&s.openUrl?s.openUrl(w):Ce.Linking.openURL(w));return}case"openLink":{let w=String((b=t==null?void 0:t.url)!=null?b:"").trim();if(!/^[a-z][a-z0-9+.-]*:/i.test(w)||/^(javascript|file|data|about|blob):/i.test(w))throw new u("INVALID_PARAMS","url kh\xF4ng h\u1EE3p l\u1EC7");try{await(s!=null&&s.openUrl?s.openUrl(w):Ce.Linking.openURL(w))}catch(S){throw new u("NOT_SUPPORTED",String((L=(f=S==null?void 0:S.message)!=null?f:S)!=null?L:"Kh\xF4ng m\u1EDF \u0111\u01B0\u1EE3c link"))}return}case"showToast":($=s==null?void 0:s.showToast)==null||$.call(s,String((G=t==null?void 0:t.message)!=null?G:""));return;case"haptic":{let w=wr.has(t==null?void 0:t.type)?t.type:"selection";(Se=s==null?void 0:s.haptic)==null||Se.call(s,w);return}case"getSystemInfo":return{platform:Ce.Platform.OS==="ios"?"ios":"android",appVersion:(ce=s==null?void 0:s.app_version)!=null?ce:"",theme:o?"dark":"light"};case"getAccessToken":{let w=n().access_token;if(!w)throw new u("HOST_ERROR","Mini app ch\u01B0a c\xF3 token cho page n\xE0y");return w}case"getToken":{let w=t==null?void 0:t.type;if(w==="access"){let v=n().access_token;if(!v)throw new u("HOST_ERROR","Mini app ch\u01B0a c\xF3 token cho page n\xE0y");return v}if(w!=="partner"&&w!=="chatbox")throw new u("HOST_ERROR",`Lo\u1EA1i token kh\xF4ng h\u1EE3p l\u1EC7: ${String(w)}`);let S=cn[w];if(!r().includes(S))throw new u("PERMISSION_DENIED",`Mini app ch\u01B0a \u0111\u01B0\u1EE3c c\u1EA5p quy\u1EC1n ${S} (Console \u2192 Quy\u1EC1n l\u1EA5y token)`);let z=w==="partner"?n().partner_token:n().chatbox_token;if(!z)throw new u("HOST_ERROR",`Kh\xF4ng c\xF3 ${S}`);return z}case"getUserInfo":{let w=n().user;if(!w)throw new u("HOST_ERROR","Kh\xF4ng l\u1EA5y \u0111\u01B0\u1EE3c th\xF4ng tin nh\xE2n vi\xEAn");return w}case"getPageInfo":{let w=n().page;if(!w)throw new u("HOST_ERROR","Kh\xF4ng l\u1EA5y \u0111\u01B0\u1EE3c th\xF4ng tin page");return w}case"sendMessage":case"insertText":throw new u("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF phi\xEAn b\u1EA3n app n\xE0y`);default:throw new u("NOT_SUPPORTED",`API kh\xF4ng t\u1ED3n t\u1EA1i: ${e}`)}};var gt=e=>`bundle:${e}`,mt=()=>`${k().file_system.document_dir}/miniapps`,ft=mt,ht=(e,t,n="index.html",r=!1,i=[])=>{let o=`${ft()}/${e}/${t}`;return{app_id:e,version:t,dir:o,entry_uri:`file://${o}/${n}`,context_update:r,permissions:i}},dt=e=>{var t;k().storage.setString(gt(e.app_id),JSON.stringify({version:e.version,entry:e.entry,context_update:!!e.context_update,permissions:(t=e.permissions)!=null?t:[]}))},yr=(e,t)=>/^https?:\/\//.test(t)?t:`${e.replace(/[^/]*$/,"")}${t}`,R=e=>{let t=k().storage.getString(gt(e));if(!t)return null;try{let{version:n,entry:r,context_update:i,permissions:o}=JSON.parse(t);return ht(e,n,r,!!i,Array.isArray(o)?o:[])}catch{return null}},se=e=>k().file_system.exists(e.entry_uri.replace("file://","")),At=async e=>{let t=R(e.app_id);return(t==null?void 0:t.version)===e.version&&await se(t)},dn=async(e,t)=>{let n=k().file_system,r=`${ft()}/${e}`,i=await n.listDir(r).catch(()=>[]);await Promise.all(i.filter(o=>!t.includes(o)).map(o=>n.remove(`${r}/${o}`).catch(()=>{})))},gn=async e=>{var t;await((t=Le[e])==null?void 0:t.catch(()=>{})),k().storage.setString(gt(e),""),await k().file_system.remove(`${ft()}/${e}`).catch(()=>{})},_e=class extends Error{constructor(){super("cancelled"),this.name="MiniAppInstallCancelled"}},Le={},mn=(e,t)=>{var o;let r=((o=Le[e])!=null?o:Promise.resolve()).catch(()=>{}).then(t),i=r.catch(()=>{});return Le[e]=i,i.then(()=>{Le[e]===i&&delete Le[e]}),r},Mr=(e,t)=>{var i,o;let n=e.split(".").map(c=>parseInt(c,10)||0),r=t.split(".").map(c=>parseInt(c,10)||0);for(let c=0;c<Math.max(n.length,r.length);c++){let p=((i=n[c])!=null?i:0)-((o=r[c])!=null?o:0);if(p)return p}return 0},fn=({manifest:e,zip_path:t})=>mn(e.app_id,async()=>{var o;let n=k().file_system,r=R(e.app_id);if(r&&Mr(r.version,e.version)>=0&&await se(r))return r;if(e.sha256&&n.sha256&&await n.sha256(t)!==e.sha256)throw new Error("sha256 mismatch");let i=ht(e.app_id,e.version,e.entry,!!e.context_update,(o=e.permissions)!=null?o:[]);return await n.remove(i.dir).catch(()=>{}),await n.mkdir(i.dir),await n.unzip(t,i.dir),dt(e),J("\u0111\xE3 c\xE0i b\u1EA3n \u0111\xF3ng s\u1EB5n",e.app_id,e.version),dn(e.app_id,[e.version,r==null?void 0:r.version].filter(Boolean)),i}),wt=(e,{base_url:t,onProgress:n}={})=>{let r=k().file_system,i=null,o=!1,c=`${r.cache_dir}/${e.app_id}-${e.version}.zip`,p=()=>{if(o)throw new _e},a=async()=>{var g;p();let s=R(e.app_id);if((s==null?void 0:s.version)===e.version&&await r.exists(s.dir))return dt(e),R(e.app_id);p();let d=r.download({url:t?yr(t,e.bundle_url):e.bundle_url,to_file:c,onProgress:(A,l)=>{var T;let h=l>0?l:(T=e.size)!=null?T:0;h>0&&(n==null||n(Math.min(1,A/h)))}});i=d;try{let{status:A}=await d.promise;if(p(),A!==200)throw new Error(`bundle ${A}`);if(e.sha256)if(r.sha256){if(await r.sha256(c)!==e.sha256)throw new Error("sha256 mismatch")}else J("b\u1ECF qua ki\u1EC3m tra sha256 (file_system kh\xF4ng c\xF3 sha256)",e.app_id);p();let l=ht(e.app_id,e.version,e.entry,!!e.context_update,(g=e.permissions)!=null?g:[]);return await r.remove(l.dir).catch(()=>{}),await r.mkdir(l.dir),await r.unzip(c,l.dir),dt(e),dn(e.app_id,[e.version,s==null?void 0:s.version].filter(Boolean)),l}catch(A){throw o?new _e:A}finally{i=null,r.remove(c).catch(()=>{})}};return{promise:mn(e.app_id,a),cancel:()=>{o=!0,i==null||i.cancel()}}},Ie={},vr=__DEV__?0:60*1e3,un={},hn=(e,t)=>{var r,i;let n=R(e);return n&&Date.now()-((r=un[t])!=null?r:0)<vr?Promise.resolve(n):((i=Ie[e])!=null||(Ie[e]=(async()=>{let o=await fetch(t,{headers:{"Cache-Control":"no-cache"}});if(!o.ok)throw new Error(`manifest ${o.status}`);let c=await o.json(),p=await wt(c,{base_url:t}).promise;return un[t]=Date.now(),p})().catch(o=>(console.warn("[miniapp] sync failed",e,o==null?void 0:o.message),R(e))).finally(()=>{Ie[e]=void 0})),Ie[e])};var We=new Map,An=(e,t)=>(We.set(e,t),()=>{We.get(e)===t&&We.delete(e)}),wn=(e,t)=>{let n=We.get(e);return n?n(t):!1};var Je=require("react"),Ke=e=>{let t=e,n=new Set;return{getState:()=>t,setState:r=>{let i=typeof r=="function"?r(t):r;t={...t,...i},n.forEach(o=>o())},subscribe:r=>(n.add(r),()=>{n.delete(r)})}},ne=(e,t,n=Object.is)=>{let r=(0,Je.useRef)(null),i=()=>{let o=e.getState(),c=r.current;if(c&&c.state===o&&c.selector===t)return c.value;let p=t(o),a=c&&n(c.value,p)?c.value:p;return r.current={state:o,selector:t,value:a},a};return(0,Je.useSyncExternalStore)(e.subscribe,i)};var V=Ke({active_key:null,instances:{}}),yn=({app:e,instance_id:t,context:n={},url_params:r={},host_data:i={}},o)=>{var p;let c=(p=k().keep_alive)==null?void 0:p.max_webviews;V.setState(a=>{let s=t!=null?t:e.app_id,d={...a.instances,[s]:{key:s,app:e,context:n,url_params:r,host_data:i,last_used_at:Date.now()}},g=Object.keys(d);return c&&c>0&&g.length>c&&g.filter(A=>A!==s).sort((A,l)=>d[A].last_used_at-d[l].last_used_at).slice(0,g.length-c).forEach(A=>{delete d[A]}),o?{active_key:s,instances:d}:{instances:d}})},Mn=e=>yn(e,!0),vn=e=>yn(e,!1),be=()=>V.setState({active_key:null}),Ye=e=>{V.setState(t=>{if(t.active_key===e||!t.instances[e])return{};let n={...t.instances};return delete n[e],{instances:n}})};var Sn="catalog",Sr="paused_apps",_r="removed_apps",br=10*1e3,xr=2,Er=3e3,Pr=()=>{var e;try{return JSON.parse((e=k().storage.getString(Sn))!=null?e:"{}")}catch{return{}}},P=Ke({catalog:{},downloads:{},pause_reasons:[],updates:{},apply_ticks:{}}),_n=e=>{var t;return!!((t=k().manual_update)!=null&&t.includes(e))},Xe=new Set,bn=e=>{let t=new Set,n=()=>k().storage.setString(e,JSON.stringify([...t]));return{has:r=>t.has(r),values:()=>[...t],add:r=>t.has(r)?!1:(t.add(r),n(),!0),delete:r=>t.delete(r)?(n(),!0):!1,load:()=>{var r;t.clear();try{let i=JSON.parse((r=k().storage.getString(e))!=null?r:"[]");Array.isArray(i)&&i.forEach(o=>{typeof o=="string"&&t.add(o)})}catch{}}}},Z=bn(Sr),fe=bn(_r);Ot(()=>{Z.load(),fe.load();let e=Pr(),t={};Object.keys(e).filter(n=>!fe.has(n)).forEach(n=>{let r=R(n);r?t[n]={status:"installed",progress:1,version:r.version,has_local:!0}:Z.has(n)&&(t[n]={status:"paused",progress:0,version:e[n].version,has_local:!1})}),P.setState({catalog:e,downloads:t})});var Ze=e=>ne(P,t=>e?t.downloads[e]:void 0),xn=()=>ne(P,e=>e.pause_reasons.length>0),X=(...e)=>J("queue",...e),U=[],ae={},x=null,Ge=new Set,ve={},yt=new Set,ge=e=>{yt.forEach(t=>{try{t(e)}catch(n){console.warn("[miniapp-queue] event listener error",n==null?void 0:n.message)}})},En=e=>(yt.add(e),()=>{yt.delete(e)}),Pn=()=>P.getState().downloads,j=(e,t)=>{let n=!!R(e),r=P.getState().downloads[e],i=t.status==="downloading"&&n?"updating":t.status,o={...r!=null?r:{status:"queued",progress:0},...t,...i?{status:i}:{},has_local:n};P.setState(c=>({downloads:{...c.downloads,[e]:o}})),(r==null?void 0:r.status)!==o.status||(r==null?void 0:r.version)!==o.version||(r==null?void 0:r.has_local)!==o.has_local?ge({type:"status_change",app_id:e,state:o}):r.progress!==o.progress&&ge({type:"progress",app_id:e,progress:o.progress,version:o.version})},Qe=(e,t)=>{var n;(n=ve[e])==null||n.forEach(r=>r(t)),delete ve[e]},Rr=()=>P.getState().pause_reasons.length>0,me=e=>{var p;if(x)return;let t=e?U.indexOf(e):Rr()?-1:U.findIndex(a=>!Z.has(a));if(t<0||t>=U.length)return;let[n]=U.splice(t,1),r=P.getState().catalog[n];if(!r){Qe(n,R(n)),me();return}let i=Date.now();ae[n]=((p=ae[n])!=null?p:0)+1,j(n,{status:"downloading",progress:0,version:r.version,error:void 0});let o=0,c=wt(r,{onProgress:a=>{let s=Math.floor(a*100);s!==o&&(o=s,j(n,{progress:s/100,version:r.version}))}});x={app_id:n,handle:c,forced:!!e},X("start",n,r.version,e?"(forced)":""),c.promise.then(a=>{X("installed",n,r.version,`${Date.now()-i}ms`),j(n,{status:"installed",progress:1,version:r.version}),Qe(n,a)}).catch(a=>{var d;if(a instanceof _e){if(Ge.has(n))return;X("paused",n),ae[n]-=1,U.unshift(n),j(n,{status:Z.has(n)?"paused":"queued",progress:0,version:r.version});return}let s=String((d=a==null?void 0:a.message)!=null?d:a);if(console.warn("[miniapp-queue] failed",n,s),ae[n]<xr){j(n,{status:"queued",progress:0,version:r.version,error:s}),setTimeout(()=>{var g;U.includes(n)||(x==null?void 0:x.app_id)===n||(U.push(n),me((g=ve[n])!=null&&g.length?n:void 0))},Er);return}j(n,{status:"failed",progress:0,version:r.version,error:s}),Qe(n,R(n))}).finally(()=>{x=null;let a=U.find(s=>{var d;return(d=ve[s])==null?void 0:d.length});me(a)})},et=(e,{front:t=!1}={})=>{if((x==null?void 0:x.app_id)===e)return;let n=U.indexOf(e);if(n>=0){if(!t)return;U.splice(n,1)}t?U.unshift(e):U.push(e)},Or=async e=>{let{host_id:t,client_token:n}=k(),r=new AbortController,i=setTimeout(()=>r.abort(),br);try{let o=`${Be}/api/hosts/${encodeURIComponent(t)}/miniapps?channel=${e}`,c=await fetch(o,{headers:{Authorization:`Bearer ${n}`,"Cache-Control":"no-cache"},signal:r.signal});if(!c.ok)throw new Error(`host list ${e} ${c.status}`);return(await c.json()).apps.map(a=>({...a,channel:e}))}finally{clearTimeout(i)}},De=null,tt=()=>(De!=null||(De=(async()=>{var t;let e=Date.now();try{let n=await Promise.all(k().channels.map(Or)),r={};[...n].reverse().flat().forEach(a=>{r[a.app_id]=a});let i=Object.keys(P.getState().catalog).filter(a=>!r[a]);k().storage.setString(Sn,JSON.stringify(r)),P.setState({catalog:r}),await Promise.all(i.map(a=>Rn(a,{by_user:!1}))),i.forEach(a=>fe.delete(a));let o=Object.keys(r).filter(a=>!fe.has(a)),c=[],p={};for(let a of o.map(s=>r[s])){if(await At(a)){j(a.app_id,{status:"installed",progress:1,version:a.version});continue}let s=R(a.app_id);if(_n(a.app_id)&&!Xe.has(a.app_id)&&s&&await se(s)){j(a.app_id,{status:"installed",progress:1,version:s.version}),p[a.app_id]={app_id:a.app_id,current_version:s.version,next_version:a.version};continue}c.push(a)}return P.setState({updates:p}),c.forEach(a=>{ae[a.app_id]=0,j(a.app_id,{status:Z.has(a.app_id)?"paused":"queued",progress:0,version:a.version,error:void 0}),et(a.app_id)}),X("catalog",o.length,"apps, outdated",c.map(a=>a.app_id),"removed",i,`${Date.now()-e}ms`),ge({type:"sync_complete",app_ids:o,removed:i}),Object.values(p).forEach(a=>ge({type:"update_available",...a})),me(),{ok:!0,app_ids:o,removed:i}}catch(n){let r=String((n==null?void 0:n.name)==="AbortError"?"timeout":(t=n==null?void 0:n.message)!=null?t:n);return console.warn("[miniapp-queue] sync catalog failed",r),ge({type:"sync_failed",error:r}),{ok:!1,error:r}}finally{De=null}})()),De),Rn=async(e,{by_user:t})=>{var i,o,c,p;if(t&&fe.add(e),Ge.has(e))return;Ge.add(e),Z.delete(e);let n=U.indexOf(e);n>=0&&U.splice(n,1),(x==null?void 0:x.app_id)===e&&x.handle.cancel();let r=(p=(c=(i=P.getState().downloads[e])==null?void 0:i.version)!=null?c:(o=R(e))==null?void 0:o.version)!=null?p:"";j(e,{status:"uninstalling",progress:0,version:r}),await gn(e),Ye(e),P.setState(a=>{let s={...a.downloads};return delete s[e],{downloads:s}}),delete ae[e],Ge.delete(e),Qe(e,null),X("uninstalled",e,t?"(user)":"(not in list)"),ge({type:"uninstalled",app_id:e})},On=e=>Rn(e,{by_user:!0}),Tn=e=>{let t=xe(e);return t?(fe.delete(e),(x==null?void 0:x.app_id)===e||U.includes(e)||(ae[e]=0,j(e,{status:Z.has(e)?"paused":"queued",progress:0,version:t.version,error:void 0}),et(e),me(),X("restore",e)),!0):!1},Cn=e=>{if(Z.has(e))return;if(Z.add(e),X("pause app",e),(x==null?void 0:x.app_id)===e&&!x.forced){x.handle.cancel();return}let t=P.getState().downloads[e];U.includes(e)&&t&&j(e,{status:"paused",progress:0,version:t.version})},kn=e=>{if(!Z.delete(e))return;X("resume app",e);let t=P.getState().downloads[e];(t==null?void 0:t.status)==="paused"&&!U.includes(e)&&xe(e)&&(ae[e]=0,et(e)),U.includes(e)&&t&&j(e,{status:"queued",progress:0,version:t.version}),me()},In=e=>{let{pause_reasons:t}=P.getState();t.includes(e)||(P.setState({pause_reasons:[...t,e]}),X("pause",e),t.length===0&&ge({type:"pause_change",paused:!0,reasons:[e]}),x&&!x.forced&&x.handle.cancel())},Ln=e=>{let{pause_reasons:t}=P.getState();if(!t.includes(e))return;let n=t.filter(r=>r!==e);P.setState({pause_reasons:n}),X("resume",e),n.length===0&&ge({type:"pause_change",paused:!1,reasons:n}),me()},Mt=e=>P.getState().updates[e],Dn=async e=>{var n,r;let t=Mt(e);Xe.add(e);try{let i=await Ne(e),o=(r=t==null?void 0:t.next_version)!=null?r:(n=xe(e))==null?void 0:n.version;return!i||!o||i.version!==o?!1:(P.setState(c=>{var a;let p={...c.updates};return delete p[e],{updates:p,apply_ticks:{...c.apply_ticks,[e]:((a=c.apply_ticks[e])!=null?a:0)+1}}}),X("updated",e,t==null?void 0:t.current_version,"\u2192",i.version),!0)}finally{Xe.delete(e)}},Nn=()=>Object.values(P.getState().catalog).map(e=>({...e,installed:!!R(e.app_id),removed_by_user:fe.has(e.app_id)})),xe=e=>P.getState().catalog[e],Ne=async e=>{let t=xe(e);if(!t)return;if(Z.delete(e),fe.delete(e),await At(t))return R(e);let n=R(e);if(_n(e)&&!Xe.has(e)&&n&&await se(n))return n;let r=new Promise(i=>{var o;((o=ve[e])!=null?o:ve[e]=[]).push(i)});return(x==null?void 0:x.app_id)===e?x.forced=!0:(ae[e]=0,et(e,{front:!0}),x&&!x.forced?x.handle.cancel():me(e)),r};var O=require("react/jsx-runtime"),vt=e=>(e!=null?e:"").replace(/\?[^#]*/,""),Un=0,Tr=()=>{let e=new Set;return{emit:t=>e.forEach(n=>n(t)),subscribe:t=>(e.add(t),()=>{e.delete(t)})}},Cr=y.default.memo(({instance_key:e,is_active:t,is_front:n,is_dark:r,reload_tick:i,web_at_top:o,splash:c,bridge:p,opaque_background:a,allow_embedded_miniapps:s,onWebLoadEnd:d})=>{var _t,bt;let g=(0,y.useRef)(null),A=(0,y.useRef)(!1),l=ne(V,m=>m.instances[e]),h=l==null?void 0:l.app.app_id,T=l==null?void 0:l.app.manifest_url,_=l==null?void 0:l.context,b=l==null?void 0:l.url_params,[f,L]=(0,y.useState)(()=>h?R(h):null),[G,$]=(0,y.useState)(!1),[Se,ce]=(0,y.useState)(0),[w,S]=(0,y.useState)(0),[z,v]=(0,y.useState)(!1),D=(0,y.useRef)(null),re=m=>{D.current&&clearTimeout(D.current),D.current=setTimeout(()=>{D.current=null,v(!0)},m)};(0,y.useEffect)(()=>()=>{D.current&&clearTimeout(D.current)},[]),(0,y.useEffect)(()=>{if(!h||!t&&f)return;let m=!0;return $(!1),(async()=>{let M=R(h),q=M?await se(M):!1;if(!m||(L(q?Q=>!Q||Q.version!==M.version||Q.permissions.join(",")!==M.permissions.join(",")?M:Q:null),__DEV__&&Date.now()-Un>1e4&&(Un=Date.now(),await tt()),!m))return;let le=await Ne(h),Ae=le!==void 0?le:T?await hn(h,T):R(h);if(m){if(!Ae){$(!0);return}L(Q=>Q!=null?Q:Ae)}})(),()=>{m=!1}},[t,h,T,Se]),(0,y.useEffect)(()=>An(e,m=>g.current?(g.current.postMessage(m),!0):!1),[e]);let B=ne(P,m=>{let M=h?m.downloads[h]:void 0;return(M==null?void 0:M.status)==="installed"?M.version:void 0});(0,y.useEffect)(()=>{if(t||!h||!f)return;let m=R(h);if(!m||m.version===f.version)return;let M=!0;return se(m).then(q=>{!M||!q||(J(`webview:${e}`,"\u0111\u1ED5i bundle (\u1EA9n)",f.version,"\u2192",m.version),L(m))}),()=>{M=!1}},[t,h,B,f==null?void 0:f.version]);let C=ne(P,m=>{var M;return h&&(M=m.apply_ticks[h])!=null?M:0});(0,y.useEffect)(()=>{if(!C||!h)return;let m=R(h);if(!m||m.version===(f==null?void 0:f.version))return;let M=!0;return se(m).then(q=>{!M||!q||(J(`webview:${e}`,"c\u1EADp nh\u1EADt",f==null?void 0:f.version,"\u2192",m.version),v(!1),L(m))}),()=>{M=!1}},[C]),(0,y.useEffect)(()=>{var q;let m=(q=k().keep_alive)==null?void 0:q.idle_close_ms;if(t||!m||m<=0)return;let M=setTimeout(()=>{Ye(e)},m);return()=>clearTimeout(M)},[t,e]),(0,y.useEffect)(()=>{i>0&&($(!1),v(!1),S(m=>m+1),ce(m=>m+1))},[i]);let H=(0,y.useRef)(t);(0,y.useEffect)(()=>{var m;H.current!==t&&(H.current=t,A.current&&((m=g.current)==null||m.injectJavaScript(rn(t?"resumed":"paused"))))},[t]);let pe=`${(_t=f==null?void 0:f.version)!=null?_t:"none"}:${(bt=f==null?void 0:f.permissions.join(","))!=null?bt:""}:${w}`,he=(0,y.useMemo)(()=>JSON.stringify([_!=null?_:{},b!=null?b:{}]),[_,b]),ie=(0,y.useMemo)(()=>{var m;return pn(b!=null?b:{},(m=f==null?void 0:f.permissions)!=null?m:[])},[he,f==null?void 0:f.permissions]),nt=(0,y.useMemo)(()=>an(_!=null?_:{},ie)+tn()+(E.Platform.OS==="android"?nn():"")+(k().debug?en():""),[ie]),oe=(0,y.useRef)(null),Ue=(0,y.useRef)(null);(0,y.useEffect)(()=>{var M,q,le;if(!f)return;if(Ue.current!==pe){Ue.current=pe,oe.current=he;return}if(oe.current===he)return;let m=((q=JSON.parse((M=oe.current)!=null?M:"[]")[0])!=null?q:{}).org_id;if(oe.current=he,m===(_==null?void 0:_.org_id)&&A.current){v(!1),re(1500),(le=g.current)==null||le.injectJavaScript(on(_!=null?_:{},ie));return}v(!1),S(Ae=>Ae+1)},[he,f,pe]),(0,y.useEffect)(()=>(t||(te(e),ye(e)),()=>{te(e),ye(e)}),[t,e,pe,i]),(0,y.useEffect)(()=>{let m=E.AppState.addEventListener("change",M=>{M==="background"&&!Jt()&&te(e)});return()=>m.remove()},[e]);let Fe=(0,y.useCallback)(async m=>{var q,le,Ae,Q,rt;let M=Gt(m.nativeEvent.data);if(!M){if(h&&(p!=null&&p.onWebEvent))try{Promise.resolve(p.onWebEvent(m.nativeEvent.data,{app_id:h,instance_id:e})).catch(I=>{console.warn("[miniapp] onWebEvent l\u1ED7i",h,I)})}catch(I){console.warn("[miniapp] onWebEvent l\u1ED7i",h,I)}return}if(M.method==="log"){let{level:I,text:F}=M;J(`web:${e}`,I!=null?I:"log",F!=null?F:"");return}if(M.method==="pong"){D.current||v(!0);return}if(M.method==="touchAtTop"){o.emit(!!M.at_top);return}if(M.method==="contextApplied"){D.current&&clearTimeout(D.current),D.current=null,v(!0);return}if(M.method==="ready"){A.current=!0,v(!0);let I=(q=V.getState().instances[e])==null?void 0:q.context;I&&((le=g.current)==null||le.injectJavaScript(ut(I)));return}try{let I=await ln(M,{getHostData:()=>{var F,W;return(W=(F=V.getState().instances[e])==null?void 0:F.host_data)!=null?W:{}},getPermissions:()=>{var F,W;return h?(W=(F=R(h))==null?void 0:F.permissions)!=null?W:[]:[]},getContext:()=>{var F,W;return(W=(F=V.getState().instances[e])==null?void 0:F.context)!=null?W:{}},is_dark:r,close:be,app_id:h!=null?h:"",instance_id:e,options:p,emit:(F,W)=>{var xt;(xt=g.current)==null||xt.injectJavaScript(Zt(F,W))},isActive:()=>V.getState().active_key===e&&E.AppState.currentState!=="background"});M.id&&((Ae=g.current)==null||Ae.injectJavaScript(Qt(M.id,I)))}catch(I){if(!M.id)return;let F=I==null?void 0:I.code,W=I instanceof u?I:new u(typeof F=="string"?F:"HOST_ERROR",String((Q=I==null?void 0:I.message)!=null?Q:I));(rt=g.current)==null||rt.injectJavaScript(Xt(M.id,W))}},[e,r,h,o,p]),qn=(0,y.useCallback)(()=>{$(!1),S(m=>m+1),ce(m=>m+1)},[]);return(0,O.jsxs)(E.View,{style:[E.StyleSheet.absoluteFill,a&&{backgroundColor:r?"#09090B":"#FFFFFF"},!n&&Y.behind],pointerEvents:t?"auto":"none",children:[f?(0,O.jsx)($n.default,{ref:g,source:{uri:f.entry_uri},originWhitelist:["*"],allowingReadAccessToURL:`file://${s?mt():f.dir}`,allowFileAccess:!0,allowFileAccessFromFileURLs:!0,allowUniversalAccessFromFileURLs:!0,injectedJavaScriptBeforeContentLoaded:nt,onMessage:Fe,bounces:!1,overScrollMode:"never",onLoadStart:m=>{te(e),ye(e),J(`webview:${e}`,"load start",vt(m.nativeEvent.url)),A.current=!1,v(!1)},onError:m=>{te(e),ye(e),J(`webview:${e}`,"load error",vt(m.nativeEvent.url),m.nativeEvent.description),$(!0),v(!1)},onLoadEnd:m=>{let M=m.nativeEvent.url;J(`webview:${e}`,"load end",vt(M)),h&&(d==null||d({app_id:h,instance_id:e,url:M})),re(1500)},onContentProcessDidTerminate:()=>{te(e),ye(e),A.current=!1,v(!1),S(m=>m+1)},onRenderProcessGone:()=>(te(e),ye(e),A.current=!1,v(!1),S(m=>m+1),!0),style:Y.webview},pe):null,l&&(0,O.jsx)(Ir,{visible:!f||!z,interactive:G,children:(0,O.jsx)(kr,{splash:c,app:l.app,is_dark:r,error:G,has_bundle:!!f,retry:qn})})]})}),kr=y.default.memo(({splash:e,app:t,is_dark:n,error:r,has_bundle:i,retry:o})=>{let c=e,p=Ze(t.app_id),a=r?"error":!i&&(p==null?void 0:p.status)==="downloading"?"downloading":"loading";return(0,O.jsx)(c,{app:t,is_dark:n,status:a,progress:a==="downloading"?p==null?void 0:p.progress:void 0,retry:o})}),Ir=({visible:e,interactive:t,children:n})=>{let r=(0,y.useRef)(new E.Animated.Value(e?1:0)).current,[i,o]=(0,y.useState)(e);return(0,y.useEffect)(()=>{if(e){o(!0),r.setValue(1);return}let c=E.Animated.timing(r,{toValue:0,duration:180,useNativeDriver:!0});return c.start(({finished:p})=>{p&&o(!1)}),()=>c.stop()},[e,r]),i?(0,O.jsx)(E.Animated.View,{style:[E.StyleSheet.absoluteFill,{opacity:r}],pointerEvents:t?"auto":"none",children:n}):null},St=({app:e,is_dark:t,status:n,progress:r,retry:i})=>{let o=t?"#FAFAFA":"#18181B";return(0,O.jsxs)(E.View,{style:[Y.splash,{backgroundColor:t?"#09090B":"#FFFFFF"}],children:[(0,O.jsx)(E.View,{style:[Y.splash_icon,{backgroundColor:t?"#18181B":"#F4F4F5"}],children:e.icon?(0,O.jsx)(E.Image,{source:{uri:e.icon},style:Y.splash_icon_image}):(0,O.jsx)(E.Text,{style:Y.splash_letter,children:(e.name||"?").slice(0,1).toUpperCase()})}),(0,O.jsx)(E.Text,{style:[Y.splash_name,{color:o}],children:e.name}),n==="error"?(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)(E.Text,{style:Y.splash_hint,children:"Kh\xF4ng t\u1EA3i \u0111\u01B0\u1EE3c mini app"}),(0,O.jsx)(E.TouchableOpacity,{activeOpacity:.7,style:[Y.retry_button,{backgroundColor:t?"#27272A":"#F4F4F5"}],onPress:i,children:(0,O.jsx)(E.Text,{style:[Y.retry_text,{color:o}],children:"Th\u1EED l\u1EA1i"})})]}):(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)(E.ActivityIndicator,{style:Y.splash_spinner,color:t?"#A1A1AA":"#71717A"}),n==="downloading"&&(0,O.jsxs)(E.Text,{style:Y.splash_hint,children:["\u0110ang t\u1EA3i mini app",r?` ${Math.round(r*100)}%`:"\u2026"]})]})]})},Fn=(e,t)=>{let n=(0,y.useRef)(t),r=(0,y.useRef)(!1);__DEV__&&!r.current&&n.current!==t&&(r.current=!0,console.warn(`[miniapp] MiniAppHost prop "${e}" \u0111\u1ED5i gi\u1EEFa c\xE1c l\u1EA7n render \u2192 m\u1ECDi WebView b\u1ECB mount l\u1EA1i. Khai b\xE1o component b\xEAn ngo\xE0i render.`))},Lr=({container:e,splash:t=St,is_dark:n=!1,bridge:r,close_on_back:i=!0,opaque_background:o=!0,allow_embedded_miniapps:c=!1,onWebLoadEnd:p})=>{Fn("container",e),Fn("splash",t);let a=e,s=ne(V,f=>f.active_key),d=(0,y.useRef)(s);s&&(d.current=s);let g=ne(V,f=>Object.keys(f.instances).join("|")),A=ne(V,f=>{var L;return f.active_key?(L=f.instances[f.active_key])==null?void 0:L.app.name:void 0}),l=(0,y.useMemo)(()=>g?g.split("|"):[],[g]),[h,T]=(0,y.useState)({}),_=(0,y.useRef)(Tr()).current;(0,y.useEffect)(()=>{if(!s||!i)return;let f=E.BackHandler.addEventListener("hardwareBackPress",()=>(be(),!0));return()=>f.remove()},[s,i]);let b=(0,y.useCallback)(()=>{let f=V.getState().active_key;f&&T(L=>({...L,[f]:(L[f]||0)+1}))},[]);return l.length?(0,O.jsx)(a,{visible:!!s,title:A!=null?A:"",is_dark:n,close:be,reload:b,subscribeWebAtTop:_.subscribe,children:l.map(f=>(0,O.jsx)(Cr,{instance_key:f,is_active:s===f,is_front:(s!=null?s:d.current)===f,is_dark:n,reload_tick:h[f]||0,web_at_top:_,splash:t,bridge:r,opaque_background:o,allow_embedded_miniapps:c,onWebLoadEnd:p},f))}):null},Y=E.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"}}),Bn=y.default.memo(Lr);0&&(module.exports={DefaultMiniAppSplash,MINIAPP_PLATFORM_URL,MiniAppHost,MiniAppHostError,closeMiniApp,configureMiniApp,createMmkvStorage,createReactNativeBiometrics,createRnfsFileSystem,ensureMiniApp,getLocalMiniApp,getMiniAppCatalog,getMiniAppCatalogEntry,getMiniAppStatuses,getMiniAppUpdate,installBundledMiniApp,onMiniAppEvent,openMiniApp,pauseMiniApp,pauseMiniAppDownloads,preloadMiniApp,releaseSpeechFor,restoreMiniApp,resumeMiniApp,resumeMiniAppDownloads,sendEventToWeb,syncMiniAppCatalog,uninstallMiniApp,updateMiniApp,uploadToUrl,useMiniAppDownload,useMiniAppDownloadsPaused});
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- var Ye="https://retion-miniapp-platform.vercel.app",de=null,vt=new Set,vn=e=>{de=e,vt.forEach(t=>t())},R=()=>{if(!de)throw new Error("[miniapp] Ch\u01B0a g\u1ECDi configureMiniApp()");return de},_t=e=>{vt.add(e),de&&e()},j=(...e)=>{de!=null&&de.debug&&console.log("[miniapp]",...e)};var _n=(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(i=>i.map(s=>s.name)).catch(()=>[]),sha256:n=>e.hash(n,"sha256"),unzip:async(n,i)=>{await t(n,i)},download:({url:n,to_file:i,onProgress:s})=>{let{jobId:o,promise:c}=e.downloadFile({fromUrl:n,toFile:i,progressInterval:250,begin:()=>{},progress:({bytesWritten:a,contentLength:r})=>s==null?void 0:s(a,r)});return{promise:c.then(({statusCode:a})=>({status:a})),cancel:()=>e.stopDownload(o)}}}),bn=e=>({getString:t=>e.getString(t),setString:(t,n)=>e.set(t,n)});import mt,{useCallback as gt,useEffect as q,useMemo as We,useRef as G,useState as he}from"react";import{AppState as gn,ActivityIndicator as wi,Animated as ut,BackHandler as yi,Image as Mi,StyleSheet as ht,Text as Re,TouchableOpacity as vi,View as ft}from"react-native";import _i from"react-native-webview";import{Linking as Bt,Platform as Vn}from"react-native";var bt=e=>({getAvailability:()=>e.isSensorAvailable(),authenticate:({reason:t,cancelButtonText:n})=>e.simplePrompt({promptMessage:t,cancelButtonText:n,fallbackPromptMessage:""})}),Ce,Ge=()=>(Ce||(Ce=import("react-native-biometrics").then(({default:e})=>bt(new e({allowDeviceCredentials:!1}))).catch(e=>{throw Ce=void 0,new d("NOT_SUPPORTED",`Biometric native module unavailable: ${e instanceof Error?e.message:String(e)}`)})),Ce);import{PermissionsAndroid as ge,Platform as Sn}from"react-native";var St=e=>{var n,i,s;if(e!==void 0&&(e===null||typeof e!="object"||Array.isArray(e)))throw new d("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 d("INVALID_PARAMS","enableHighAccuracy ph\u1EA3i l\xE0 boolean");for(let[o,c,a]of[["timeout",1,6e4],["maximumAge",0,864e5]]){let r=t[o];if(r!==void 0&&(typeof r!="number"||!Number.isFinite(r)||r<c||r>a))throw new d("INVALID_PARAMS",`${o} ph\u1EA3i n\u1EB1m trong kho\u1EA3ng ${c}\u2013${a} ms`)}return{enableHighAccuracy:(n=t.enableHighAccuracy)!=null?n:!1,timeout:(i=t.timeout)!=null?i:15e3,maximumAge:(s=t.maximumAge)!=null?s:0}},xt=(e,t=()=>!0)=>new Promise((n,i)=>{let s=!1,o=(r,l)=>{s||(s=!0,clearTimeout(c),r?i(r):n(l))},c=setTimeout(()=>o(new d("TIMEOUT","H\u1EBFt th\u1EDDi gian ch\u1EDD c\u1EA5p quy\u1EC1n/l\u1EA5y v\u1ECB tr\xED")),12e4+e.timeout),a=()=>s?!1:t()?!0:(o(new d("CANCELLED","Mini app kh\xF4ng c\xF2n ho\u1EA1t \u0111\u1ED9ng")),!1);(async()=>{if(!a())return;let r;try{r=(await import("@react-native-community/geolocation")).default}catch{throw new d("NOT_SUPPORTED","Ch\u01B0a c\xF3 module v\u1ECB tr\xED trong b\u1EA3n native")}if(a()){if(Sn.OS==="android"){let l=ge.PERMISSIONS.ACCESS_FINE_LOCATION,u=ge.PERMISSIONS.ACCESS_COARSE_LOCATION,p=await ge.check(l);if(!a())return;let h=p||await ge.check(u);if(!a())return;if(!p&&!h){let A=await ge.requestMultiple([l,u]);if(!a())return;if(A[l]!==ge.RESULTS.GRANTED&&A[u]!==ge.RESULTS.GRANTED)throw new d("PERMISSION_DENIED","Ch\u01B0a c\u1EA5p quy\u1EC1n truy c\u1EADp v\u1ECB tr\xED")}}a()&&r.getCurrentPosition(l=>{a()&&o(void 0,l)},l=>{var p;if(!a())return;let u=(p={1:"PERMISSION_DENIED",2:"POSITION_UNAVAILABLE",3:"TIMEOUT"}[l.code])!=null?p:"LOCATION_ERROR";o(new d(u,l.message))},e)}})().catch(r=>o(r))});import{Platform as xn}from"react-native";var Qe=20,Et=20,Ot=/^[a-z][a-z0-9_-]{0,31}$/,En=/^(\.[\w-]{1,16}|[\w.+-]+\/(\*|[\w.+-]+))$/,Pn=["low","medium","high"],se=e=>!!e&&typeof e=="object"&&!Array.isArray(e),I=e=>new d("INVALID_PARAMS",e),Me=(e,t,n)=>typeof e=="number"&&Number.isInteger(e)&&e>=t&&e<=n,Pt=(e,t)=>{if(e===void 0)return{};if(!se(e)||Object.keys(e).length>Et||Object.values(e).some(n=>typeof n!="string"))throw I(`${t} ph\u1EA3i l\xE0 object chu\u1ED7i (t\u1ED1i \u0111a ${Et} key)`);return e},Tt=e=>{var n,i,s,o;if(e!==void 0&&!se(e))throw I("Tu\u1EF3 ch\u1ECDn upload ph\u1EA3i l\xE0 object");let t=e!=null?e:{};if(t.source!==void 0&&(typeof t.source!="string"||!Ot.test(t.source)))throw I("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(c=>typeof c!="string"||!En.test(c))))throw I("accept ph\u1EA3i l\xE0 m\u1EA3ng mime (image/*, application/pdf) ho\u1EB7c \u0111u\xF4i (.docx)");if(t.max_count!==void 0&&!Me(t.max_count,1,Qe))throw I(`max_count ph\u1EA3i l\xE0 s\u1ED1 nguy\xEAn 1\u2013${Qe}`);if(t.max_size!==void 0&&!Me(t.max_size,1,Number.MAX_SAFE_INTEGER))throw I("max_size ph\u1EA3i l\xE0 s\u1ED1 byte > 0");if(t.concurrency!==void 0&&!Me(t.concurrency,1,5))throw I("concurrency ph\u1EA3i l\xE0 s\u1ED1 nguy\xEAn 1\u20135");return{source:(n=t.source)!=null?n:"library",accept:((i=t.accept)!=null?i:[]).map(c=>c.toLowerCase()),max_count:(s=t.max_count)!=null?s:1,max_size:t.max_size,process:Rn(t.process),target:On(t.upload),concurrency:(o=t.concurrency)!=null?o:3}},Rn=e=>{if(e===void 0)return{};if(!se(e))throw I("process ph\u1EA3i l\xE0 object");let t={};if(e.image!==void 0){let n=e.image;if(!se(n))throw I("process.image ph\u1EA3i l\xE0 object");for(let i of["max_width","max_height"])if(n[i]!==void 0&&!Me(n[i],1,1e4))throw I(`process.image.${i} 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 I("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(!se(n))throw I("process.video ph\u1EA3i l\xE0 object");if(n.max_duration!==void 0&&!Me(n.max_duration,1,3600))throw I("process.video.max_duration ph\u1EA3i l\xE0 s\u1ED1 gi\xE2y 1\u20133600");if(n.quality!==void 0&&!Pn.includes(n.quality))throw I("process.video.quality ph\u1EA3i l\xE0 low | medium | high");t.video={max_duration:n.max_duration,quality:n.quality}}return t},On=e=>{var n,i,s,o;if(e===void 0)return{target:"host",params:{}};if(!se(e))throw I("upload ph\u1EA3i l\xE0 object");let t=(n=e.target)!=null?n:"host";if(typeof t!="string"||!Ot.test(t))throw I("upload.target ph\u1EA3i l\xE0 t\xEAn \u0111\xEDch, vd host | url");if(t!=="url"){if(e.params!==void 0&&!se(e.params))throw I("upload.params ph\u1EA3i l\xE0 object");return{target:t,params:(i=e.params)!=null?i:{}}}if(typeof e.url!="string"||!/^https:\/\//i.test(e.url))throw I("upload.url ph\u1EA3i l\xE0 https");for(let c of["field_name","url_field"])if(e[c]!==void 0&&(typeof e[c]!="string"||!e[c]))throw I(`upload.${c} ph\u1EA3i l\xE0 chu\u1ED7i`);return{target:"url",url:e.url,headers:Pt(e.headers,"upload.headers"),form_data:Pt(e.form_data,"upload.form_data"),field_name:(s=e.field_name)!=null?s:"file",url_field:(o=e.url_field)!=null?o:"url"}},kt=e=>{let t=e.lastIndexOf(".");return t>0?e.slice(t).toLowerCase():""},Tn=(e,t)=>{if(!t.length)return!0;let n=e.mime_type.toLowerCase(),i=kt(e.name);return t.some(s=>s==="*/*"?!0:s.startsWith(".")?s===i:s.endsWith("/*")?n.startsWith(s.slice(0,-1)):n===s)},kn=e=>{let t=e.length>0&&e.every(i=>i.startsWith("image/")),n=e.length>0&&e.every(i=>i.startsWith("video/"));return t?"image":n?"video":"mixed"},ye,Cn=()=>(ye!=null||(ye=import("react-native-image-picker").catch(e=>{throw ye=void 0,new d("NOT_SUPPORTED",`Ch\u01B0a c\xF3 module ch\u1ECDn \u1EA3nh trong b\u1EA3n native: ${e instanceof Error?e.message:String(e)}`)})),ye),Rt=e=>async({accept:t,max_count:n,process:i})=>{var r,l,u,p,h,A,w,T,x;let s=await Cn(),o=kn(t),c={mediaType:o==="image"?"photo":o,maxWidth:(r=i.image)==null?void 0:r.max_width,maxHeight:(l=i.image)==null?void 0:l.max_height,quality:(p=(u=i.image)==null?void 0:u.quality)!=null?p:.8,videoQuality:(A=(h=i.video)==null?void 0:h.quality)!=null?A:"medium",durationLimit:(w=i.video)==null?void 0:w.max_duration,assetRepresentationMode:"compatible"},a=e==="camera"?await s.launchCamera({...c,saveToPhotos:!1}):await s.launchImageLibrary({...c,selectionLimit:n});if(a.didCancel)return[];if(a.errorCode){let b=a.errorCode==="permission"?"PERMISSION_DENIED":a.errorCode==="camera_unavailable"?"NOT_SUPPORTED":"HOST_ERROR";throw new d(b,(T=a.errorMessage)!=null?T:a.errorCode)}return((x=a.assets)!=null?x:[]).filter(b=>b.uri).map((b,m)=>{var k,z,U;return{uri:b.uri,name:(k=b.fileName)!=null?k:`file_${m+1}`,mime_type:(z=b.type)!=null?z:"application/octet-stream",size:b.fileSize,width:b.width,height:b.height,duration:b.duration,processed:!((U=b.type)!=null&&U.startsWith("video/"))||xn.OS==="ios"}})},In={"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"},Ln={".pdf":"pdf",".txt":"plainText",".csv":"csv",".json":"json",".zip":"zip",".doc":"doc",".docx":"docx",".xls":"xls",".xlsx":"xlsx",".ppt":"ppt",".pptx":"pptx"},Dn=e=>async({accept:t,max_count:n})=>{var o,c,a,r;let i=t.map(l=>{var u;return(u=In[l])!=null?u:Ln[l]}),s=!t.length||i.some(l=>!l||!e.types[l])?e.types.allFiles:[...new Set(i)].flatMap(l=>e.types[l]);try{return(await e.pick({type:s,allowMultiSelection:n>1,mode:"import"})).filter(u=>u.uri&&!u.error).map((u,p)=>{var h,A,w;return{uri:u.uri,name:(h=u.name)!=null?h:`file_${p+1}`,mime_type:(A=u.type)!=null?A:"application/octet-stream",size:(w=u.size)!=null?w:void 0}})}catch(l){let u=l==null?void 0:l.code;if(u===((c=(o=e.errorCodes)==null?void 0:o.OPERATION_CANCELED)!=null?c:"OPERATION_CANCELED"))return[];throw u===((r=(a=e.errorCodes)==null?void 0:a.IN_PROGRESS)!=null?r:"ASYNC_OP_IN_PROGRESS")?new d("BUSY","\u0110ang m\u1EDF tr\xECnh ch\u1ECDn file kh\xE1c"):l}},Nn={library:Rt("library"),camera:Rt("camera")},Un=(e,t)=>t.split(".").reduce((n,i)=>se(n)?n[i]:void 0,e),Ct=({file:e,target:t,onProgress:n,signal:i})=>new Promise((s,o)=>{if(t.target!=="url"||!("url"in t)){o(new d("INVALID_PARAMS","Thi\u1EBFu upload.url"));return}let c=t;if(i.aborted){o(new d("CANCELLED","\u0110\xE3 hu\u1EF7 upload"));return}let a=new XMLHttpRequest,r=new FormData;Object.entries(c.form_data).forEach(([p,h])=>r.append(p,h)),r.append(c.field_name,{uri:e.uri,name:e.name,type:e.mime_type});let l=()=>a.abort();i.addEventListener("abort",l);let u=p=>{i.removeEventListener("abort",l),p()};a.open("POST",c.url),Object.entries(c.headers).forEach(([p,h])=>a.setRequestHeader(p,h)),a.upload.onprogress=p=>n(p.loaded,p.total||e.size||0),a.onload=()=>u(()=>{let p=a.responseText;try{p=JSON.parse(a.responseText)}catch{}if(a.status<200||a.status>=300){o(new d("UPLOAD_FAILED",`HTTP ${a.status}`));return}let h=Un(p,c.url_field);if(typeof h!="string"||!h){o(new d("UPLOAD_FAILED",`Response kh\xF4ng c\xF3 "${c.url_field}"`));return}s({url:h,response:p})}),a.onerror=()=>u(()=>o(new d("UPLOAD_FAILED","L\u1ED7i m\u1EA1ng khi upload"))),a.onabort=()=>u(()=>o(new d("CANCELLED","\u0110\xE3 hu\u1EF7 upload"))),a.send(r)}),It=e=>{var i,s;let t={...Nn};for(let[o,c]of Object.entries((i=e==null?void 0:e.sources)!=null?i:{}))c?t[o]=c:delete t[o];let n={url:Ct};for(let[o,c]of Object.entries((s=e==null?void 0:e.targets)!=null?s:{}))o!=="url"&&c&&(n[o]=c);return{sources:t,targets:n}},Lt=e=>{let{sources:t,targets:n}=It(e);return{sources:Object.keys(t),targets:Object.keys(n),max_count:Qe}},Le=new Map,Dt=(e,t)=>`${e}:${t}`,Fn=0,Nt=(e,t)=>{var n;typeof t=="string"&&((n=Le.get(Dt(e,t)))==null||n.abort())},fe=e=>{for(let[t,n]of Le)t.startsWith(`${e}:`)&&n.abort()},Ie=()=>new d("CANCELLED","\u0110\xE3 hu\u1EF7 upload"),$n=(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)}},Ut=async(e,t)=>{var r;let{sources:n,targets:i}=It(t.config),s=n[e.source];if(!s)throw new d("NOT_SUPPORTED",`\u1EE8ng d\u1EE5ng ch\u01B0a h\u1ED7 tr\u1EE3 ngu\u1ED3n "${e.source}"`);let o=i[e.target.target];if(!o)throw new d("NOT_SUPPORTED",`\u1EE8ng d\u1EE5ng ch\u01B0a h\u1ED7 tr\u1EE3 \u0111\xEDch upload "${e.target.target}"`);let c=new AbortController,a=Dt(t.instance_id,(r=t.task_id)!=null?r:`auto-${++Fn}`);Le.set(a,c);try{return await Bn(e,t,s,o,c.signal)}finally{Le.delete(a)}},Bn=async(e,{task_id:t,config:n,emit:i,exclusivePick:s=r=>r()},o,c,a)=>{var z,U;let r=(await s(()=>o({accept:e.accept,max_count:e.max_count,process:e.process}))).slice(0,e.max_count);if(a.aborted)throw Ie();if(!r.length)throw new d("CANCELLED","Ng\u01B0\u1EDDi d\xF9ng kh\xF4ng ch\u1ECDn file");let l=[],u=r.filter(E=>Tn(E,e.accept)?!0:(l.push({name:E.name,code:"INVALID_FILE",message:`Kh\xF4ng cho ph\xE9p \u0111\u1ECBnh d\u1EA1ng ${E.mime_type||kt(E.name)}`}),!1)),p=u.map(()=>0),h=u.map(E=>{var f;return(f=E.size)!=null?f:0}),A=0,w=0,T=(E=!1)=>{if(!i||!t)return;let f=Date.now();if(!E&&f-w<200)return;w=f;let y=h.reduce((D,C)=>D+C,0),v=p.reduce((D,C)=>D+C,0);i("upload.progress",{task_id:t,loaded:v,total:y,percent:y?Math.min(100,Math.round(v/y*100)):0,done_count:A,count:u.length})},x=[],b=0,m=async()=>{var E,f;for(;b<u.length;){let y=b++,v=u[y];try{if(a.aborted)throw Ie();let D=v.mime_type.startsWith("image/")?"image":v.mime_type.startsWith("video/")?"video":void 0,C=D&&!v.processed?(E=n==null?void 0:n.processors)==null?void 0:E[D]:void 0;if(C&&(v=await C(v,e.process),h[y]=(f=v.size)!=null?f:h[y],a.aborted))throw Ie();if(e.max_size&&v.size&&v.size>e.max_size)throw new d("FILE_TOO_LARGE",`File ${v.size} byte v\u01B0\u1EE3t gi\u1EDBi h\u1EA1n ${e.max_size}`);let V=(Te,re)=>{p[y]=Te,re&&(h[y]=re),T()},ie=await c({file:v,target:e.target,onProgress:V,signal:a});if(typeof(ie==null?void 0:ie.url)!="string"||!ie.url)throw new d("UPLOAD_FAILED","Upload kh\xF4ng tr\u1EA3 url");let{url:ze,...pe}=ie;x[y]={url:ze,name:v.name,mime_type:v.mime_type,size:v.size,width:v.width,height:v.height,duration:v.duration,...Object.keys(pe).length?{response:"response"in pe?pe.response:pe}:{}},p[y]=h[y]}catch(D){l.push($n(u[y].name,D))}finally{A++,T(!0)}}};if(await Promise.all(Array.from({length:Math.min(e.concurrency,u.length)},m)),a.aborted)throw Ie();let k=x.filter(E=>!!E);if(!k.length){let E=l[0];throw new d((z=E==null?void 0:E.code)!=null?z:"UPLOAD_FAILED",(U=E==null?void 0:E.message)!=null?U:"Kh\xF4ng upload \u0111\u01B0\u1EE3c file n\xE0o")}return{files:k,failed:l}};import{Platform as qn}from"react-native";var Z,Xe=e=>{var t;if(Z===e&&(Z=void 0,e.subscriptions.forEach(n=>n.remove()),e.started&&qn.OS==="ios"))try{(t=e.native)==null||t.setAudioSessionActiveIOS(!1,{notifyOthersOnDeactivation:!0})}catch{}},Ft=async(e,t,n,i=()=>!0)=>{var o,c,a,r,l;if(Z)throw new d("BUSY","Micro \u0111ang \u0111\u01B0\u1EE3c mini app kh\xE1c s\u1EED d\u1EE5ng");if(!i())throw new d("CANCELLED","Mini app kh\xF4ng c\xF2n ho\u1EA1t \u0111\u1ED9ng");let s={owner:e,emit:n,cancelled:!1,started:!1,subscriptions:[]};Z=s;try{let u;try{u=await import("expo-speech-recognition")}catch{throw new d("NOT_SUPPORTED","Ch\u01B0a c\xF3 module nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i trong b\u1EA3n native")}let p=u.ExpoSpeechRecognitionModule;if(s.native=p,s.cancelled||!i())throw new d("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");let h=await p.requestPermissionsAsync();if(s.cancelled||!i())throw new d("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");if(!h.granted)throw new d("PERMISSION_DENIED","Ch\u01B0a c\u1EA5p quy\u1EC1n micro / nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i");if(await p.getStateAsync()!=="inactive")throw new d("BUSY","Nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i \u0111ang \u0111\u01B0\u1EE3c t\xEDnh n\u0103ng kh\xE1c s\u1EED d\u1EE5ng");if(s.cancelled||!i())throw new d("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");s.subscriptions.push(p.addListener("result",A=>{var w,T;Z!==s||s.cancelled||n(A.isFinal?"speech.final":"speech.partial",{...A,text:(T=(w=A.results[0])==null?void 0:w.transcript)!=null?T:""})}),p.addListener("error",A=>{Z===s&&!s.cancelled&&n("speech.error",{...A,code:A.error})}),p.addListener("end",()=>{Z===s&&(Xe(s),n("speech.end"))})),s.started=!0,p.start({lang:(o=t.lang)!=null?o:"vi-VN",continuous:(c=t.continuous)!=null?c:!0,interimResults:(a=t.interimResults)!=null?a:!0,addsPunctuation:(r=t.addsPunctuation)!=null?r:!0,requiresOnDeviceRecognition:(l=t.requiresOnDeviceRecognition)!=null?l:!1,iosCategory:{category:u.AVAudioSessionCategory.playAndRecord,categoryOptions:[u.AVAudioSessionCategoryOptions.defaultToSpeaker,u.AVAudioSessionCategoryOptions.allowBluetooth],mode:u.AVAudioSessionMode.measurement}})}catch(u){throw Xe(s),u}},$t=e=>{let t=Z;if(!(!t||t.owner!==e)){if(!t.started){t.cancelled=!0;return}t.native.stop()}},ee=e=>{let t=Z;if(!(!t||t.owner!==e||t.cancelled)&&(t.cancelled=!0,t.started))try{t.native.abort()}catch{Xe(t)}};var Ne=1,d=class extends Error{constructor(n,i){super(i);this.code=n}},qt=e=>{try{let t=JSON.parse(e);return(t==null?void 0:t.__retion)===Ne&&typeof t.method=="string"?t:null}catch{return null}},_e=e=>`window.__RETION_MINIAPP__ && window.__RETION_MINIAPP__.receive(${JSON.stringify(e)}); true;`,Vt=(e,t)=>_e({id:e,result:t}),jt=(e,t)=>_e({id:e,error:{code:t.code,message:t.message}}),Ht=(e,t)=>_e({event:e,data:t}),et=e=>_e({event:"context",data:e});var Wt=()=>`(function () {
1
+ var et="https://retion-miniapp-platform.vercel.app",he=null,Et=new Set,Tn=e=>{he=e,Et.forEach(t=>t())},O=()=>{if(!he)throw new Error("[miniapp] Ch\u01B0a g\u1ECDi configureMiniApp()");return he},Pt=e=>{Et.add(e),he&&e()},W=(...e)=>{he!=null&&he.debug&&console.log("[miniapp]",...e)};var Cn=(e,t)=>({document_dir:e.DocumentDirectoryPath,cache_dir:e.CachesDirectoryPath,exists:n=>e.exists(n),mkdir:n=>e.mkdir(n),remove:n=>e.unlink(n).catch(()=>{}),listDir:n=>e.readDir(n).then(r=>r.map(i=>i.name)).catch(()=>[]),sha256:n=>e.hash(n,"sha256"),unzip:async(n,r)=>{await t(n,r)},download:({url:n,to_file:r,onProgress:i})=>{let{jobId:o,promise:c}=e.downloadFile({fromUrl:n,toFile:r,progressInterval:250,begin:()=>{},progress:({bytesWritten:p,contentLength:a})=>i==null?void 0:i(p,a)});return{promise:c.then(({statusCode:p})=>({status:p})),cancel:()=>e.stopDownload(o)}}}),kn=e=>({getString:t=>e.getString(t),setString:(t,n)=>e.set(t,n)});import vt,{useCallback as yt,useEffect as V,useMemo as Qe,useRef as Z,useState as Me}from"react";import{AppState as bn,ActivityIndicator as Ir,Animated as At,BackHandler as Lr,Image as Dr,Platform as Nr,StyleSheet as St,Text as Le,TouchableOpacity as Ur,View as Mt}from"react-native";import Fr from"react-native-webview";import{Linking as Gt,Platform as rr}from"react-native";var Rt=e=>({getAvailability:()=>e.isSensorAvailable(),authenticate:({reason:t,cancelButtonText:n})=>e.simplePrompt({promptMessage:t,cancelButtonText:n,fallbackPromptMessage:""})}),Fe,tt=()=>(Fe||(Fe=import("react-native-biometrics").then(({default:e})=>Rt(new e({allowDeviceCredentials:!1}))).catch(e=>{throw Fe=void 0,new u("NOT_SUPPORTED",`Biometric native module unavailable: ${e instanceof Error?e.message:String(e)}`)})),Fe);import{PermissionsAndroid as Ae,Platform as In}from"react-native";var Ot=e=>{var n,r,i;if(e!==void 0&&(e===null||typeof e!="object"||Array.isArray(e)))throw new u("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 u("INVALID_PARAMS","enableHighAccuracy ph\u1EA3i l\xE0 boolean");for(let[o,c,p]of[["timeout",1,6e4],["maximumAge",0,864e5]]){let a=t[o];if(a!==void 0&&(typeof a!="number"||!Number.isFinite(a)||a<c||a>p))throw new u("INVALID_PARAMS",`${o} ph\u1EA3i n\u1EB1m trong kho\u1EA3ng ${c}\u2013${p} ms`)}return{enableHighAccuracy:(n=t.enableHighAccuracy)!=null?n:!1,timeout:(r=t.timeout)!=null?r:15e3,maximumAge:(i=t.maximumAge)!=null?i:0}},Tt=(e,t=()=>!0)=>new Promise((n,r)=>{let i=!1,o=(a,s)=>{i||(i=!0,clearTimeout(c),a?r(a):n(s))},c=setTimeout(()=>o(new u("TIMEOUT","H\u1EBFt th\u1EDDi gian ch\u1EDD c\u1EA5p quy\u1EC1n/l\u1EA5y v\u1ECB tr\xED")),12e4+e.timeout),p=()=>i?!1:t()?!0:(o(new u("CANCELLED","Mini app kh\xF4ng c\xF2n ho\u1EA1t \u0111\u1ED9ng")),!1);(async()=>{if(!p())return;let a;try{a=(await import("@react-native-community/geolocation")).default}catch{throw new u("NOT_SUPPORTED","Ch\u01B0a c\xF3 module v\u1ECB tr\xED trong b\u1EA3n native")}if(p()){if(In.OS==="android"){let s=Ae.PERMISSIONS.ACCESS_FINE_LOCATION,d=Ae.PERMISSIONS.ACCESS_COARSE_LOCATION,g=await Ae.check(s);if(!p())return;let A=g||await Ae.check(d);if(!p())return;if(!g&&!A){let l=await Ae.requestMultiple([s,d]);if(!p())return;if(l[s]!==Ae.RESULTS.GRANTED&&l[d]!==Ae.RESULTS.GRANTED)throw new u("PERMISSION_DENIED","Ch\u01B0a c\u1EA5p quy\u1EC1n truy c\u1EADp v\u1ECB tr\xED")}}p()&&a.getCurrentPosition(s=>{p()&&o(void 0,s)},s=>{var g;if(!p())return;let d=(g={1:"PERMISSION_DENIED",2:"POSITION_UNAVAILABLE",3:"TIMEOUT"}[s.code])!=null?g:"LOCATION_ERROR";o(new u(d,s.message))},e)}})().catch(a=>o(a))});import{Platform as Lt}from"react-native";var nt=20,Ct=20,Dt=/^[a-z][a-z0-9_-]{0,31}$/,Ln=/^(\.[\w-]{1,16}|[\w.+-]+\/(\*|[\w.+-]+))$/,Dn=["low","medium","high"],le=e=>!!e&&typeof e=="object"&&!Array.isArray(e),I=e=>new u("INVALID_PARAMS",e),Ee=(e,t,n)=>typeof e=="number"&&Number.isInteger(e)&&e>=t&&e<=n,kt=(e,t)=>{if(e===void 0)return{};if(!le(e)||Object.keys(e).length>Ct||Object.values(e).some(n=>typeof n!="string"))throw I(`${t} ph\u1EA3i l\xE0 object chu\u1ED7i (t\u1ED1i \u0111a ${Ct} key)`);return e},Nt=e=>{var n,r,i,o;if(e!==void 0&&!le(e))throw I("Tu\u1EF3 ch\u1ECDn upload ph\u1EA3i l\xE0 object");let t=e!=null?e:{};if(t.source!==void 0&&(typeof t.source!="string"||!Dt.test(t.source)))throw I("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(c=>typeof c!="string"||!Ln.test(c))))throw I("accept ph\u1EA3i l\xE0 m\u1EA3ng mime (image/*, application/pdf) ho\u1EB7c \u0111u\xF4i (.docx)");if(t.max_count!==void 0&&!Ee(t.max_count,1,nt))throw I(`max_count ph\u1EA3i l\xE0 s\u1ED1 nguy\xEAn 1\u2013${nt}`);if(t.max_size!==void 0&&!Ee(t.max_size,1,Number.MAX_SAFE_INTEGER))throw I("max_size ph\u1EA3i l\xE0 s\u1ED1 byte > 0");if(t.concurrency!==void 0&&!Ee(t.concurrency,1,5))throw I("concurrency ph\u1EA3i l\xE0 s\u1ED1 nguy\xEAn 1\u20135");return{source:(n=t.source)!=null?n:"library",accept:((r=t.accept)!=null?r:[]).map(c=>c.toLowerCase()),max_count:(i=t.max_count)!=null?i:1,max_size:t.max_size,process:Nn(t.process),target:Un(t.upload),concurrency:(o=t.concurrency)!=null?o:3}},Nn=e=>{if(e===void 0)return{};if(!le(e))throw I("process ph\u1EA3i l\xE0 object");let t={};if(e.image!==void 0){let n=e.image;if(!le(n))throw I("process.image ph\u1EA3i l\xE0 object");for(let r of["max_width","max_height"])if(n[r]!==void 0&&!Ee(n[r],1,1e4))throw I(`process.image.${r} 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 I("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(!le(n))throw I("process.video ph\u1EA3i l\xE0 object");if(n.max_duration!==void 0&&!Ee(n.max_duration,1,3600))throw I("process.video.max_duration ph\u1EA3i l\xE0 s\u1ED1 gi\xE2y 1\u20133600");if(n.quality!==void 0&&!Dn.includes(n.quality))throw I("process.video.quality ph\u1EA3i l\xE0 low | medium | high");t.video={max_duration:n.max_duration,quality:n.quality}}return t},Un=e=>{var n,r,i,o;if(e===void 0)return{target:"host",params:{}};if(!le(e))throw I("upload ph\u1EA3i l\xE0 object");let t=(n=e.target)!=null?n:"host";if(typeof t!="string"||!Dt.test(t))throw I("upload.target ph\u1EA3i l\xE0 t\xEAn \u0111\xEDch, vd host | url");if(t!=="url"){if(e.params!==void 0&&!le(e.params))throw I("upload.params ph\u1EA3i l\xE0 object");return{target:t,params:(r=e.params)!=null?r:{}}}if(typeof e.url!="string"||!/^https:\/\//i.test(e.url))throw I("upload.url ph\u1EA3i l\xE0 https");for(let c of["field_name","url_field"])if(e[c]!==void 0&&(typeof e[c]!="string"||!e[c]))throw I(`upload.${c} ph\u1EA3i l\xE0 chu\u1ED7i`);return{target:"url",url:e.url,headers:kt(e.headers,"upload.headers"),form_data:kt(e.form_data,"upload.form_data"),field_name:(i=e.field_name)!=null?i:"file",url_field:(o=e.url_field)!=null?o:"url"}},Ut=e=>{let t=e.lastIndexOf(".");return t>0?e.slice(t).toLowerCase():""},Fn=(e,t)=>{if(!t.length)return!0;let n=e.mime_type.toLowerCase(),r=Ut(e.name);return t.some(i=>i==="*/*"?!0:i.startsWith(".")?i===r:i.endsWith("/*")?n.startsWith(i.slice(0,-1)):n===i)},$n=e=>{let t=e.length>0&&e.every(r=>r.startsWith("image/")),n=e.length>0&&e.every(r=>r.startsWith("video/"));return t?"image":n?"video":"mixed"},_e,Bn=()=>(_e!=null||(_e=import("react-native-image-picker").catch(e=>{throw _e=void 0,new u("NOT_SUPPORTED",`Ch\u01B0a c\xF3 module ch\u1ECDn \u1EA3nh trong b\u1EA3n native: ${e instanceof Error?e.message:String(e)}`)})),_e),It=e=>async({accept:t,max_count:n,process:r})=>{var a,s,d,g,A,l,h,E,S;let i=await Bn(),o=$n(t),c={mediaType:o==="image"?"photo":o,maxWidth:(a=r.image)==null?void 0:a.max_width,maxHeight:(s=r.image)==null?void 0:s.max_height,quality:(g=(d=r.image)==null?void 0:d.quality)!=null?g:.8,videoQuality:(l=(A=r.video)==null?void 0:A.quality)!=null?l:"medium",durationLimit:(h=r.video)==null?void 0:h.max_duration,assetRepresentationMode:"compatible"},p=e==="camera"?await i.launchCamera({...c,saveToPhotos:!1}):await i.launchImageLibrary({...c,selectionLimit:n});if(p.didCancel)return[];if(p.errorCode){let _=p.errorCode==="permission"?"PERMISSION_DENIED":p.errorCode==="camera_unavailable"?"NOT_SUPPORTED":"HOST_ERROR";throw new u(_,(E=p.errorMessage)!=null?E:p.errorCode)}return((S=p.assets)!=null?S:[]).filter(_=>_.uri).map((_,f)=>{var C,Y,U;return{uri:_.uri,name:(C=_.fileName)!=null?C:`file_${f+1}`,mime_type:(Y=_.type)!=null?Y:"application/octet-stream",size:_.fileSize,width:_.width,height:_.height,duration:_.duration,processed:!((U=_.type)!=null&&U.startsWith("video/"))||Lt.OS==="ios"}})},qn={"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"},Vn={".pdf":"pdf",".txt":"plainText",".csv":"csv",".json":"json",".zip":"zip",".doc":"doc",".docx":"docx",".xls":"xls",".xlsx":"xlsx",".ppt":"ppt",".pptx":"pptx"},jn=e=>async({accept:t,max_count:n})=>{var o,c,p,a;let r=t.map(s=>{var d;return(d=qn[s])!=null?d:Vn[s]}),i=!t.length||r.some(s=>!s||!e.types[s])?e.types.allFiles:[...new Set(r)].flatMap(s=>e.types[s]);try{let d=(await e.pick({type:i,allowMultiSelection:n>1,mode:"import"})).filter(l=>l.uri&&!l.error).map((l,h)=>{var E,S,_;return{uri:l.uri,name:(E=l.name)!=null?E:`file_${h+1}`,mime_type:(S=l.type)!=null?S:"application/octet-stream",size:(_=l.size)!=null?_:void 0}});if(Lt.OS!=="android"||!e.keepLocalCopy||!d.some(l=>l.uri.startsWith("content://")))return d;let g=await e.keepLocalCopy({files:d.map(l=>({uri:l.uri,fileName:l.name})),destination:"cachesDirectory"}),A=new Map(g.map(l=>[l.sourceUri,l.status==="success"?l.localUri:void 0]));return d.map(l=>{var h;return{...l,uri:(h=A.get(l.uri))!=null?h:l.uri}})}catch(s){let d=s==null?void 0:s.code;if(d===((c=(o=e.errorCodes)==null?void 0:o.OPERATION_CANCELED)!=null?c:"OPERATION_CANCELED"))return[];throw d===((a=(p=e.errorCodes)==null?void 0:p.IN_PROGRESS)!=null?a:"ASYNC_OP_IN_PROGRESS")?new u("BUSY","\u0110ang m\u1EDF tr\xECnh ch\u1ECDn file kh\xE1c"):s}},be,zn=async e=>(be!=null||(be=import("@react-native-documents/picker").then(t=>jn(t)).catch(t=>{throw be=void 0,new u("NOT_SUPPORTED",`Ch\u01B0a c\xF3 module ch\u1ECDn file trong b\u1EA3n native: ${t instanceof Error?t.message:String(t)}`)})),(await be)(e)),Hn={library:It("library"),camera:It("camera"),document:zn},xe,Ft=()=>(xe!=null||(xe=import("react-native-compressor").catch(()=>(xe=void 0,null))),xe),$t=async(e,t,n)=>{try{return Number(await e.getFileSize(t))||n}catch{return n}},Wn=new Set(["image/jpeg","image/jpg","image/heic","image/heif","image/webp"]),Jn={low:640,medium:1280,high:1920},Kn=async(e,{image:t})=>{var r;if(!t||!Wn.has(e.mime_type.toLowerCase()))return e;let n=await Ft();if(!n)return e;try{let i=await n.Image.compress(e.uri,{compressionMethod:"manual",maxWidth:t.max_width,maxHeight:t.max_height,quality:(r=t.quality)!=null?r:.8,output:"jpg"});return{...e,uri:i,mime_type:"image/jpeg",name:e.name.replace(/\.[^.]+$/,"")+".jpg",size:await $t(n,i,e.size),processed:!0}}catch{return e}},Yn=async(e,{video:t})=>{var r;let n=await Ft();if(!n)return e;try{let i=await n.Video.compress(e.uri,{compressionMethod:"auto",maxSize:Jn[(r=t==null?void 0:t.quality)!=null?r:"medium"],minimumFileSizeForCompress:2});return{...e,uri:i,mime_type:"video/mp4",size:await $t(n,i,e.size),processed:!0}}catch{return e}},Gn={image:Kn,video:Yn},Qn=(e,t)=>t.split(".").reduce((n,r)=>le(n)?n[r]:void 0,e),Bt=({file:e,target:t,onProgress:n,signal:r})=>new Promise((i,o)=>{if(t.target!=="url"||!("url"in t)){o(new u("INVALID_PARAMS","Thi\u1EBFu upload.url"));return}let c=t;if(r.aborted){o(new u("CANCELLED","\u0110\xE3 hu\u1EF7 upload"));return}let p=new XMLHttpRequest,a=new FormData;Object.entries(c.form_data).forEach(([g,A])=>a.append(g,A)),a.append(c.field_name,{uri:e.uri,name:e.name,type:e.mime_type});let s=()=>p.abort();r.addEventListener("abort",s);let d=g=>{r.removeEventListener("abort",s),g()};p.open("POST",c.url),Object.entries(c.headers).forEach(([g,A])=>p.setRequestHeader(g,A)),p.upload.onprogress=g=>n(g.loaded,g.total||e.size||0),p.onload=()=>d(()=>{let g=p.responseText;try{g=JSON.parse(p.responseText)}catch{}if(p.status<200||p.status>=300){o(new u("UPLOAD_FAILED",`HTTP ${p.status}`));return}let A=Qn(g,c.url_field);if(typeof A!="string"||!A){o(new u("UPLOAD_FAILED",`Response kh\xF4ng c\xF3 "${c.url_field}"`));return}i({url:A,response:g})}),p.onerror=()=>d(()=>o(new u("UPLOAD_FAILED","L\u1ED7i m\u1EA1ng khi upload"))),p.onabort=()=>d(()=>o(new u("CANCELLED","\u0110\xE3 hu\u1EF7 upload"))),p.send(a)}),qt=e=>{var r,i;let t={...Hn};for(let[o,c]of Object.entries((r=e==null?void 0:e.sources)!=null?r:{}))c?t[o]=c:delete t[o];let n={url:Bt};for(let[o,c]of Object.entries((i=e==null?void 0:e.targets)!=null?i:{}))o!=="url"&&c&&(n[o]=c);return{sources:t,targets:n}},Vt=e=>{let{sources:t,targets:n}=qt(e);return{sources:Object.keys(t),targets:Object.keys(n),max_count:nt}},Be=new Map,jt=(e,t)=>`${e}:${t}`,Xn=0,zt=(e,t)=>{var n;typeof t=="string"&&((n=Be.get(jt(e,t)))==null||n.abort())},we=e=>{for(let[t,n]of Be)t.startsWith(`${e}:`)&&n.abort()},$e=()=>new u("CANCELLED","\u0110\xE3 hu\u1EF7 upload"),Zn=(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)}},Ht=async(e,t)=>{var a;let{sources:n,targets:r}=qt(t.config),i=n[e.source];if(!i)throw new u("NOT_SUPPORTED",`\u1EE8ng d\u1EE5ng ch\u01B0a h\u1ED7 tr\u1EE3 ngu\u1ED3n "${e.source}"`);let o=r[e.target.target];if(!o)throw new u("NOT_SUPPORTED",`\u1EE8ng d\u1EE5ng ch\u01B0a h\u1ED7 tr\u1EE3 \u0111\xEDch upload "${e.target.target}"`);let c=new AbortController,p=jt(t.instance_id,(a=t.task_id)!=null?a:`auto-${++Xn}`);Be.set(p,c);try{return await er(e,t,i,o,c.signal)}finally{Be.delete(p)}},er=async(e,{instance_id:t,app_id:n,getContext:r,task_id:i,config:o,emit:c,exclusivePick:p=g=>g()},a,s,d)=>{var w,v,j;let g={app_id:n!=null?n:"",instance_id:t,context:{...(w=r==null?void 0:r())!=null?w:{}}},A=(await p(()=>a({accept:e.accept,max_count:e.max_count,process:e.process,caller:g}))).slice(0,e.max_count);if(d.aborted)throw $e();if(!A.length)throw new u("CANCELLED","Ng\u01B0\u1EDDi d\xF9ng kh\xF4ng ch\u1ECDn file");let l=[],h=A.filter(M=>Fn(M,e.accept)?!0:(l.push({name:M.name,code:"INVALID_FILE",message:`Kh\xF4ng cho ph\xE9p \u0111\u1ECBnh d\u1EA1ng ${M.mime_type||Ut(M.name)}`}),!1)),E=h.map(()=>0),S=h.map(M=>{var k;return(k=M.size)!=null?k:0}),_=0,f=0,C=(M=!1)=>{if(!c||!i)return;let k=Date.now();if(!M&&k-f<200)return;f=k;let te=S.reduce((R,z)=>R+z,0),F=E.reduce((R,z)=>R+z,0);c("upload.progress",{task_id:i,loaded:F,total:te,percent:te?Math.min(100,Math.round(F/te*100)):0,done_count:_,count:h.length})},Y=[],U=0,ve=async()=>{var M,k,te;for(;U<h.length;){let F=U++,R=h[F];try{if(d.aborted)throw $e();let z=R.mime_type.startsWith("image/")?"image":R.mime_type.startsWith("video/")?"video":void 0,ce=z&&!R.processed?(k=(M=o==null?void 0:o.processors)==null?void 0:M[z])!=null?k:Gn[z]:void 0;if(ce&&(R=await ce(R,e.process),S[F]=(te=R.size)!=null?te:S[F],d.aborted))throw $e();if(e.max_size&&R.size&&R.size>e.max_size)throw new u("FILE_TOO_LARGE",`File ${R.size} byte v\u01B0\u1EE3t gi\u1EDBi h\u1EA1n ${e.max_size}`);let me=(Ne,Ue)=>{E[F]=Ne,Ue&&(S[F]=Ue),C()},ne=await s({file:R,target:e.target,onProgress:me,signal:d,caller:g});if(typeof(ne==null?void 0:ne.url)!="string"||!ne.url)throw new u("UPLOAD_FAILED","Upload kh\xF4ng tr\u1EA3 url");let{url:Xe,...re}=ne;Y[F]={url:Xe,name:R.name,mime_type:R.mime_type,size:R.size,width:R.width,height:R.height,duration:R.duration,...Object.keys(re).length?{response:"response"in re?re.response:re}:{}},E[F]=S[F]}catch(z){l.push(Zn(h[F].name,z))}finally{_++,C(!0)}}};if(await Promise.all(Array.from({length:Math.min(e.concurrency,h.length)},ve)),d.aborted)throw $e();let ae=Y.filter(M=>!!M);if(!ae.length){let M=l[0];throw new u((v=M==null?void 0:M.code)!=null?v:"UPLOAD_FAILED",(j=M==null?void 0:M.message)!=null?j:"Kh\xF4ng upload \u0111\u01B0\u1EE3c file n\xE0o")}return{files:ae,failed:l}};import{AppState as Wt,Platform as it}from"react-native";var J,Jt=()=>it.OS==="android"&&!!(J!=null&&J.requesting_permission),tr=1500,nr=()=>new Promise(e=>{if(it.OS!=="android"||Wt.currentState==="active"){e();return}let t=()=>{clearTimeout(n),r.remove(),e()},n=setTimeout(t,tr),r=Wt.addEventListener("change",i=>{i==="active"&&t()})}),rt=e=>{var t;if(J===e&&(J=void 0,e.subscriptions.forEach(n=>n.remove()),e.started&&it.OS==="ios"))try{(t=e.native)==null||t.setAudioSessionActiveIOS(!1,{notifyOthersOnDeactivation:!0})}catch{}},Kt=async(e,t,n,r=()=>!0)=>{var o,c,p,a,s;if(J)throw new u("BUSY","Micro \u0111ang \u0111\u01B0\u1EE3c mini app kh\xE1c s\u1EED d\u1EE5ng");if(!r())throw new u("CANCELLED","Mini app kh\xF4ng c\xF2n ho\u1EA1t \u0111\u1ED9ng");let i={owner:e,emit:n,cancelled:!1,started:!1,subscriptions:[]};J=i;try{let d;try{d=await import("expo-speech-recognition")}catch{throw new u("NOT_SUPPORTED","Ch\u01B0a c\xF3 module nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i trong b\u1EA3n native")}let g=d.ExpoSpeechRecognitionModule;if(i.native=g,i.cancelled||!r())throw new u("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");i.requesting_permission=!0;let A;try{A=await g.requestPermissionsAsync()}finally{i.requesting_permission=!1}if(await nr(),i.cancelled||!r())throw new u("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");if(!A.granted)throw new u("PERMISSION_DENIED","Ch\u01B0a c\u1EA5p quy\u1EC1n micro / nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i");if(await g.getStateAsync()!=="inactive")throw new u("BUSY","Nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i \u0111ang \u0111\u01B0\u1EE3c t\xEDnh n\u0103ng kh\xE1c s\u1EED d\u1EE5ng");if(i.cancelled||!r())throw new u("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");i.subscriptions.push(g.addListener("result",l=>{var h,E;J!==i||i.cancelled||n(l.isFinal?"speech.final":"speech.partial",{...l,text:(E=(h=l.results[0])==null?void 0:h.transcript)!=null?E:""})}),g.addListener("error",l=>{J===i&&!i.cancelled&&n("speech.error",{...l,code:l.error})}),g.addListener("end",()=>{J===i&&(rt(i),n("speech.end"))})),i.started=!0,g.start({lang:(o=t.lang)!=null?o:"vi-VN",continuous:(c=t.continuous)!=null?c:!0,interimResults:(p=t.interimResults)!=null?p:!0,addsPunctuation:(a=t.addsPunctuation)!=null?a:!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 rt(i),d}},Yt=e=>{let t=J;if(!(!t||t.owner!==e)){if(!t.started){t.cancelled=!0;return}t.native.stop()}},ie=e=>{let t=J;if(!(!t||t.owner!==e||t.cancelled)&&(t.cancelled=!0,t.started))try{t.native.abort()}catch{rt(t)}};var Ve=1,u=class extends Error{constructor(n,r){super(r);this.code=n}},Qt=e=>{try{let t=JSON.parse(e);return(t==null?void 0:t.__retion)===Ve&&typeof t.method=="string"?t:null}catch{return null}},Re=e=>`window.__RETION_MINIAPP__ && window.__RETION_MINIAPP__.receive(${JSON.stringify(e)}); true;`,Xt=(e,t)=>Re({id:e,result:t}),Zt=(e,t)=>Re({id:e,error:{code:t.code,message:t.message}}),en=(e,t)=>Re({event:e,data:t}),st=e=>Re({event:"context",data:e});var tn=()=>`(function () {
2
2
  var post = function (level, args) {
3
3
  try {
4
4
  var parts = [];
@@ -8,7 +8,7 @@ var Ye="https://retion-miniapp-platform.vercel.app",de=null,vt=new Set,vn=e=>{de
8
8
  else if (typeof a === 'object') { try { parts.push(JSON.stringify(a).slice(0, 800)); } catch (e) { parts.push(String(a)); } }
9
9
  else { parts.push(String(a)); }
10
10
  }
11
- window.ReactNativeWebView && window.ReactNativeWebView.postMessage(JSON.stringify({ __retion: ${Ne}, method: 'log', level: level, text: parts.join(' ') }));
11
+ window.ReactNativeWebView && window.ReactNativeWebView.postMessage(JSON.stringify({ __retion: ${Ve}, method: 'log', level: level, text: parts.join(' ') }));
12
12
  } catch (e) {}
13
13
  };
14
14
  ['log', 'info', 'warn', 'error'].forEach(function (level) {
@@ -19,7 +19,7 @@ var Ye="https://retion-miniapp-platform.vercel.app",de=null,vt=new Set,vn=e=>{de
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;`,zt=()=>`(function () {
22
+ })(); true;`,nn=()=>`(function () {
23
23
  function atTop(el) {
24
24
  for (var n = el; n && n !== document.documentElement; n = n.parentElement) {
25
25
  if (n.scrollTop > 0) { return false; }
@@ -30,7 +30,7 @@ var Ye="https://retion-miniapp-platform.vercel.app",de=null,vt=new Set,vn=e=>{de
30
30
  function report(at_top) {
31
31
  if (at_top === last) { return; }
32
32
  last = at_top;
33
- window.ReactNativeWebView && window.ReactNativeWebView.postMessage(JSON.stringify({ __retion: ${Ne}, method: 'touchAtTop', at_top: at_top }));
33
+ window.ReactNativeWebView && window.ReactNativeWebView.postMessage(JSON.stringify({ __retion: ${Ve}, method: 'touchAtTop', at_top: at_top }));
34
34
  }
35
35
  document.addEventListener('touchstart', function (e) { report(atTop(e.target)); }, { capture: true, passive: true });
36
36
  // Cu\u1ED9n r\u1EDDi \u0111\u1EA7u trang \u2192 b\xE1o ngay, kh\xF4ng \u0111\u1EE3i l\u1EA7n ch\u1EA1m sau (tr\xE1nh host d\xF9ng gi\xE1 tr\u1ECB c\u0169 "\u0111ang \u1EDF \u0111\u1EA7u").
@@ -38,8 +38,29 @@ var Ye="https://retion-miniapp-platform.vercel.app",de=null,vt=new Set,vn=e=>{de
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;`,Jt=e=>_e({event:e}),Kt=(e,t)=>{let n=Yt(t);return`try { history.replaceState(history.state, '', location.pathname + ${JSON.stringify(n?`?${n}`:"")} + location.hash); } catch (e) {}
42
- ${et(e)}`},Yt=e=>Object.entries(e).filter(([,t])=>t!=null&&t!=="").map(([t,n])=>`${encodeURIComponent(t)}=${encodeURIComponent(String(n))}`).join("&"),Gt=(e,t={})=>{let n=Yt(t);return`window.__RETION_MINIAPP_HOST__ = { protocol: ${Ne} };
41
+ })(); true;`,rn=()=>`(function () {
42
+ if (window.__retionSafeAreaFrozen) { return; }
43
+ window.__retionSafeAreaFrozen = true;
44
+ var max = {};
45
+ var orig = window.getComputedStyle;
46
+ window.getComputedStyle = function (el, pseudo) {
47
+ var style = orig.call(this, el, pseudo);
48
+ var m = el && el.style && /env\\(safe-area-inset-(top|right|bottom|left)\\)/.exec(el.style.cssText || '');
49
+ if (!m) { return style; }
50
+ var prop = 'padding-' + m[1];
51
+ var value = parseFloat(style.getPropertyValue(prop)) || 0;
52
+ if (!(prop in max) || value > max[prop]) { max[prop] = value; }
53
+ var frozen = max[prop] + 'px';
54
+ return new Proxy(style, {
55
+ get: function (t, k) {
56
+ if (k === 'getPropertyValue') { return function (p) { return p === prop ? frozen : t.getPropertyValue(p); }; }
57
+ var v = t[k];
58
+ return typeof v === 'function' ? v.bind(t) : v;
59
+ },
60
+ });
61
+ };
62
+ })(); true;`,on=e=>Re({event:e}),sn=(e,t)=>{let n=an(t);return`try { history.replaceState(history.state, '', location.pathname + ${JSON.stringify(n?`?${n}`:"")} + location.hash); } catch (e) {}
63
+ ${st(e)}`},an=e=>Object.entries(e).filter(([,t])=>t!=null&&t!=="").map(([t,n])=>`${encodeURIComponent(t)}=${encodeURIComponent(String(n))}`).join("&"),cn=(e,t={})=>{let n=an(t);return`window.__RETION_MINIAPP_HOST__ = { protocol: ${Ve} };
43
64
  window.__RETION_MINIAPP_CONTEXT__ = ${JSON.stringify(e)};
44
65
  ${n?`try { history.replaceState(history.state, '', location.pathname + '?' + ${JSON.stringify(n)} + location.hash); } catch (e) {}`:""}
45
- true;`},Qt={partner:"partner_token",chatbox:"chatbox_token"},Xt=(e,t)=>{let n={...e};for(let i of Object.values(Qt))t.includes(i)||delete n[i];return n},Ze=new Set,ve=async(e,t)=>{if(Ze.has(e))throw new d("BUSY",`${e} \u0111ang ch\u1EA1y \u2014 ch\u1EDD l\u01B0\u1EE3t tr\u01B0\u1EDBc xong`);Ze.add(e);try{return await t()}finally{Ze.delete(e)}},jn=new Set(["selection","impactLight","impactMedium","impactHeavy","rigid","soft","notificationSuccess","notificationWarning","notificationError"]),De=(e,t)=>{if(typeof e!="string"||!e)throw new d("INVALID_PARAMS",`Thi\u1EBFu ${t}`);return e},Zt=async({method:e,params:t},{getHostData:n,getPermissions:i,is_dark:s,close:o,app_id:c,instance_id:a,options:r,emit:l,isActive:u})=>{var w,T,x,b,m,k,z,U,E;let p=r==null?void 0:r.handlers,h={app_id:c,instance_id:a,close:o},A=()=>new d("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF \u1EE9ng d\u1EE5ng n\xE0y`);switch(e){case"getCurrentLocation":{let f=St(t);return ve(e,()=>xt(f,u))}case"speech.start":{if(!l)throw A();let f={};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 d("INVALID_PARAMS","lang ph\u1EA3i l\xE0 m\xE3 ng\xF4n ng\u1EEF nh\u01B0 vi-VN");f.lang=t.lang}for(let y of["continuous","interimResults","addsPunctuation","requiresOnDeviceRecognition"])if((t==null?void 0:t[y])!==void 0){if(typeof t[y]!="boolean")throw new d("INVALID_PARAMS",`${y} ph\u1EA3i l\xE0 boolean`);f[y]=t[y]}return Ft(a,f,l,u)}case"speech.stop":return $t(a);case"uploadFiles":{let{task_id:f,...y}=t!=null?t:{};if(f!==void 0&&(typeof f!="string"||!f))throw new d("INVALID_PARAMS","task_id ph\u1EA3i l\xE0 chu\u1ED7i");return Ut(Tt(y),{instance_id:a,task_id:f,config:r==null?void 0:r.upload,emit:l,exclusivePick:v=>ve("uploadFiles.pick",v)})}case"uploadFiles.cancel":Nt(a,t==null?void 0:t.task_id);return;case"getUploadCapabilities":return Lt(r==null?void 0:r.upload);case"getBiometricAvailability":return((w=r==null?void 0:r.biometrics)!=null?w:await Ge()).getAvailability();case"authenticateBiometric":{let f=De(t==null?void 0:t.reason,"reason").trim();if(!f||f.length>200)throw new d("INVALID_PARAMS","reason must contain 1\u2013200 characters");let y=t==null?void 0:t.cancelButtonText;if(y!==void 0&&(typeof y!="string"||!y.trim()||y.length>80))throw new d("INVALID_PARAMS","Invalid cancelButtonText");return ve(e,async()=>{var D;return((D=r==null?void 0:r.biometrics)!=null?D:await Ge()).authenticate({reason:f,cancelButtonText:y})})}case"requestPayment":{let f=p==null?void 0:p.requestPayment;if(!f)throw A();let y=t==null?void 0:t.amount;if(typeof y!="number"||!Number.isFinite(y)||y<=0)throw new d("INVALID_PARAMS","amount ph\u1EA3i l\xE0 s\u1ED1 > 0");let v={...t,amount:y,currency:De(t==null?void 0:t.currency,"currency")};return ve(e,()=>f(v,h))}case"printImage":{let f=p==null?void 0:p.printImage;if(!f)throw A();let y=De(t==null?void 0:t.image,"image");await ve(e,()=>f({image:y},h));return}case"openScreen":if(!(p!=null&&p.openScreen))throw A();await p.openScreen({screen:De(t==null?void 0:t.screen,"screen"),params:t==null?void 0:t.params},h);return;case"closeApp":o();return;case"openWebview":{let f=String((T=t==null?void 0:t.url)!=null?T:"");if(!/^https?:\/\//i.test(f))throw new d("INVALID_PARAMS","url ph\u1EA3i l\xE0 http(s)");await(r!=null&&r.openUrl?r.openUrl(f):Bt.openURL(f));return}case"openLink":{let f=String((x=t==null?void 0:t.url)!=null?x:"").trim();if(!/^[a-z][a-z0-9+.-]*:/i.test(f)||/^(javascript|file|data|about|blob):/i.test(f))throw new d("INVALID_PARAMS","url kh\xF4ng h\u1EE3p l\u1EC7");try{await(r!=null&&r.openUrl?r.openUrl(f):Bt.openURL(f))}catch(y){throw new d("NOT_SUPPORTED",String((m=(b=y==null?void 0:y.message)!=null?b:y)!=null?m:"Kh\xF4ng m\u1EDF \u0111\u01B0\u1EE3c link"))}return}case"showToast":(z=r==null?void 0:r.showToast)==null||z.call(r,String((k=t==null?void 0:t.message)!=null?k:""));return;case"haptic":{let f=jn.has(t==null?void 0:t.type)?t.type:"selection";(U=r==null?void 0:r.haptic)==null||U.call(r,f);return}case"getSystemInfo":return{platform:Vn.OS==="ios"?"ios":"android",appVersion:(E=r==null?void 0:r.app_version)!=null?E:"",theme:s?"dark":"light"};case"getAccessToken":{let f=n().access_token;if(!f)throw new d("HOST_ERROR","Mini app ch\u01B0a c\xF3 token cho page n\xE0y");return f}case"getToken":{let f=t==null?void 0:t.type;if(f==="access"){let D=n().access_token;if(!D)throw new d("HOST_ERROR","Mini app ch\u01B0a c\xF3 token cho page n\xE0y");return D}if(f!=="partner"&&f!=="chatbox")throw new d("HOST_ERROR",`Lo\u1EA1i token kh\xF4ng h\u1EE3p l\u1EC7: ${String(f)}`);let y=Qt[f];if(!i().includes(y))throw new d("PERMISSION_DENIED",`Mini app ch\u01B0a \u0111\u01B0\u1EE3c c\u1EA5p quy\u1EC1n ${y} (Console \u2192 Quy\u1EC1n l\u1EA5y token)`);let v=f==="partner"?n().partner_token:n().chatbox_token;if(!v)throw new d("HOST_ERROR",`Kh\xF4ng c\xF3 ${y}`);return v}case"getUserInfo":{let f=n().user;if(!f)throw new d("HOST_ERROR","Kh\xF4ng l\u1EA5y \u0111\u01B0\u1EE3c th\xF4ng tin nh\xE2n vi\xEAn");return f}case"getPageInfo":{let f=n().page;if(!f)throw new d("HOST_ERROR","Kh\xF4ng l\u1EA5y \u0111\u01B0\u1EE3c th\xF4ng tin page");return f}case"sendMessage":case"insertText":throw new d("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF phi\xEAn b\u1EA3n app n\xE0y`);default:throw new d("NOT_SUPPORTED",`API kh\xF4ng t\u1ED3n t\u1EA1i: ${e}`)}};var nt=e=>`bundle:${e}`,it=()=>`${R().file_system.document_dir}/miniapps`,rt=it,ot=(e,t,n="index.html",i=!1,s=[])=>{let o=`${rt()}/${e}/${t}`;return{app_id:e,version:t,dir:o,entry_uri:`file://${o}/${n}`,context_update:i,permissions:s}},tt=e=>{var t;R().storage.setString(nt(e.app_id),JSON.stringify({version:e.version,entry:e.entry,context_update:!!e.context_update,permissions:(t=e.permissions)!=null?t:[]}))},Hn=(e,t)=>/^https?:\/\//.test(t)?t:`${e.replace(/[^/]*$/,"")}${t}`,P=e=>{let t=R().storage.getString(nt(e));if(!t)return null;try{let{version:n,entry:i,context_update:s,permissions:o}=JSON.parse(t);return ot(e,n,i,!!s,Array.isArray(o)?o:[])}catch{return null}},te=e=>R().file_system.exists(e.entry_uri.replace("file://","")),st=async e=>{let t=P(e.app_id);return(t==null?void 0:t.version)===e.version&&await te(t)},tn=async(e,t)=>{let n=R().file_system,i=`${rt()}/${e}`,s=await n.listDir(i).catch(()=>[]);await Promise.all(s.filter(o=>!t.includes(o)).map(o=>n.remove(`${i}/${o}`).catch(()=>{})))},nn=async e=>{var t;await((t=Se[e])==null?void 0:t.catch(()=>{})),R().storage.setString(nt(e),""),await R().file_system.remove(`${rt()}/${e}`).catch(()=>{})},Ae=class extends Error{constructor(){super("cancelled"),this.name="MiniAppInstallCancelled"}},Se={},rn=(e,t)=>{var o;let i=((o=Se[e])!=null?o:Promise.resolve()).catch(()=>{}).then(t),s=i.catch(()=>{});return Se[e]=s,s.then(()=>{Se[e]===s&&delete Se[e]}),i},Wn=(e,t)=>{var s,o;let n=e.split(".").map(c=>parseInt(c,10)||0),i=t.split(".").map(c=>parseInt(c,10)||0);for(let c=0;c<Math.max(n.length,i.length);c++){let a=((s=n[c])!=null?s:0)-((o=i[c])!=null?o:0);if(a)return a}return 0},zn=({manifest:e,zip_path:t})=>rn(e.app_id,async()=>{var o;let n=R().file_system,i=P(e.app_id);if(i&&Wn(i.version,e.version)>=0&&await te(i))return i;if(e.sha256&&n.sha256&&await n.sha256(t)!==e.sha256)throw new Error("sha256 mismatch");let s=ot(e.app_id,e.version,e.entry,!!e.context_update,(o=e.permissions)!=null?o:[]);return await n.remove(s.dir).catch(()=>{}),await n.mkdir(s.dir),await n.unzip(t,s.dir),tt(e),j("\u0111\xE3 c\xE0i b\u1EA3n \u0111\xF3ng s\u1EB5n",e.app_id,e.version),tn(e.app_id,[e.version,i==null?void 0:i.version].filter(Boolean)),s}),at=(e,{base_url:t,onProgress:n}={})=>{let i=R().file_system,s=null,o=!1,c=`${i.cache_dir}/${e.app_id}-${e.version}.zip`,a=()=>{if(o)throw new Ae},r=async()=>{var p;a();let l=P(e.app_id);if((l==null?void 0:l.version)===e.version&&await i.exists(l.dir))return tt(e),P(e.app_id);a();let u=i.download({url:t?Hn(t,e.bundle_url):e.bundle_url,to_file:c,onProgress:(h,A)=>{var T;let w=A>0?A:(T=e.size)!=null?T:0;w>0&&(n==null||n(Math.min(1,h/w)))}});s=u;try{let{status:h}=await u.promise;if(a(),h!==200)throw new Error(`bundle ${h}`);if(e.sha256)if(i.sha256){if(await i.sha256(c)!==e.sha256)throw new Error("sha256 mismatch")}else j("b\u1ECF qua ki\u1EC3m tra sha256 (file_system kh\xF4ng c\xF3 sha256)",e.app_id);a();let A=ot(e.app_id,e.version,e.entry,!!e.context_update,(p=e.permissions)!=null?p:[]);return await i.remove(A.dir).catch(()=>{}),await i.mkdir(A.dir),await i.unzip(c,A.dir),tt(e),tn(e.app_id,[e.version,l==null?void 0:l.version].filter(Boolean)),A}catch(h){throw o?new Ae:h}finally{s=null,i.remove(c).catch(()=>{})}};return{promise:rn(e.app_id,r),cancel:()=>{o=!0,s==null||s.cancel()}}},be={},Jn=__DEV__?0:60*1e3,en={},on=(e,t)=>{var i,s;let n=P(e);return n&&Date.now()-((i=en[t])!=null?i:0)<Jn?Promise.resolve(n):((s=be[e])!=null||(be[e]=(async()=>{let o=await fetch(t,{headers:{"Cache-Control":"no-cache"}});if(!o.ok)throw new Error(`manifest ${o.status}`);let c=await o.json(),a=await at(c,{base_url:t}).promise;return en[t]=Date.now(),a})().catch(o=>(console.warn("[miniapp] sync failed",e,o==null?void 0:o.message),P(e))).finally(()=>{be[e]=void 0})),be[e])};var Ue=new Map,sn=(e,t)=>(Ue.set(e,t),()=>{Ue.get(e)===t&&Ue.delete(e)}),Kn=(e,t)=>{let n=Ue.get(e);return n?n(t):!1};import{useRef as Yn,useSyncExternalStore as Gn}from"react";var Fe=e=>{let t=e,n=new Set;return{getState:()=>t,setState:i=>{let s=typeof i=="function"?i(t):i;t={...t,...s},n.forEach(o=>o())},subscribe:i=>(n.add(i),()=>{n.delete(i)})}},Q=(e,t,n=Object.is)=>{let i=Yn(null),s=()=>{let o=e.getState(),c=i.current;if(c&&c.state===o&&c.selector===t)return c.value;let a=t(o),r=c&&n(c.value,a)?c.value:a;return i.current={state:o,selector:t,value:r},r};return Gn(e.subscribe,s)};var H=Fe({active_key:null,instances:{}}),an=({app:e,instance_id:t,context:n={},url_params:i={},host_data:s={}},o)=>{var a;let c=(a=R().keep_alive)==null?void 0:a.max_webviews;H.setState(r=>{let l=t!=null?t:e.app_id,u={...r.instances,[l]:{key:l,app:e,context:n,url_params:i,host_data:s,last_used_at:Date.now()}},p=Object.keys(u);return c&&c>0&&p.length>c&&p.filter(h=>h!==l).sort((h,A)=>u[h].last_used_at-u[A].last_used_at).slice(0,p.length-c).forEach(h=>{delete u[h]}),o?{active_key:l,instances:u}:{instances:u}})},Qn=e=>an(e,!0),Xn=e=>an(e,!1),xe=()=>H.setState({active_key:null}),$e=e=>{H.setState(t=>{if(t.active_key===e||!t.instances[e])return{};let n={...t.instances};return delete n[e],{instances:n}})};var cn="catalog",Zn="paused_apps",ei="removed_apps",ti=10*1e3,ni=2,ii=3e3,ri=()=>{var e;try{return JSON.parse((e=R().storage.getString(cn))!=null?e:"{}")}catch{return{}}},S=Fe({catalog:{},downloads:{},pause_reasons:[],updates:{},apply_ticks:{}}),ln=e=>{var t;return!!((t=R().manual_update)!=null&&t.includes(e))},Ve=new Set,pn=e=>{let t=new Set,n=()=>R().storage.setString(e,JSON.stringify([...t]));return{has:i=>t.has(i),values:()=>[...t],add:i=>t.has(i)?!1:(t.add(i),n(),!0),delete:i=>t.delete(i)?(n(),!0):!1,load:()=>{var i;t.clear();try{let s=JSON.parse((i=R().storage.getString(e))!=null?i:"[]");Array.isArray(s)&&s.forEach(o=>{typeof o=="string"&&t.add(o)})}catch{}}}},Y=pn(Zn),le=pn(ei);_t(()=>{Y.load(),le.load();let e=ri(),t={};Object.keys(e).filter(n=>!le.has(n)).forEach(n=>{let i=P(n);i?t[n]={status:"installed",progress:1,version:i.version,has_local:!0}:Y.has(n)&&(t[n]={status:"paused",progress:0,version:e[n].version,has_local:!1})}),S.setState({catalog:e,downloads:t})});var lt=e=>Q(S,t=>e?t.downloads[e]:void 0),oi=()=>Q(S,e=>e.pause_reasons.length>0),K=(...e)=>j("queue",...e),L=[],ne={},_=null,Be=new Set,me={},ct=new Set,ae=e=>{ct.forEach(t=>{try{t(e)}catch(n){console.warn("[miniapp-queue] event listener error",n==null?void 0:n.message)}})},si=e=>(ct.add(e),()=>{ct.delete(e)}),ai=()=>S.getState().downloads,B=(e,t)=>{let n=!!P(e),i=S.getState().downloads[e],s=t.status==="downloading"&&n?"updating":t.status,o={...i!=null?i:{status:"queued",progress:0},...t,...s?{status:s}:{},has_local:n};S.setState(c=>({downloads:{...c.downloads,[e]:o}})),(i==null?void 0:i.status)!==o.status||(i==null?void 0:i.version)!==o.version||(i==null?void 0:i.has_local)!==o.has_local?ae({type:"status_change",app_id:e,state:o}):i.progress!==o.progress&&ae({type:"progress",app_id:e,progress:o.progress,version:o.version})},qe=(e,t)=>{var n;(n=me[e])==null||n.forEach(i=>i(t)),delete me[e]},ci=()=>S.getState().pause_reasons.length>0,ce=e=>{var a;if(_)return;let t=e?L.indexOf(e):ci()?-1:L.findIndex(r=>!Y.has(r));if(t<0||t>=L.length)return;let[n]=L.splice(t,1),i=S.getState().catalog[n];if(!i){qe(n,P(n)),ce();return}let s=Date.now();ne[n]=((a=ne[n])!=null?a:0)+1,B(n,{status:"downloading",progress:0,version:i.version,error:void 0});let o=0,c=at(i,{onProgress:r=>{let l=Math.floor(r*100);l!==o&&(o=l,B(n,{progress:l/100,version:i.version}))}});_={app_id:n,handle:c,forced:!!e},K("start",n,i.version,e?"(forced)":""),c.promise.then(r=>{K("installed",n,i.version,`${Date.now()-s}ms`),B(n,{status:"installed",progress:1,version:i.version}),qe(n,r)}).catch(r=>{var u;if(r instanceof Ae){if(Be.has(n))return;K("paused",n),ne[n]-=1,L.unshift(n),B(n,{status:Y.has(n)?"paused":"queued",progress:0,version:i.version});return}let l=String((u=r==null?void 0:r.message)!=null?u:r);if(console.warn("[miniapp-queue] failed",n,l),ne[n]<ni){B(n,{status:"queued",progress:0,version:i.version,error:l}),setTimeout(()=>{var p;L.includes(n)||(_==null?void 0:_.app_id)===n||(L.push(n),ce((p=me[n])!=null&&p.length?n:void 0))},ii);return}B(n,{status:"failed",progress:0,version:i.version,error:l}),qe(n,P(n))}).finally(()=>{_=null;let r=L.find(l=>{var u;return(u=me[l])==null?void 0:u.length});ce(r)})},je=(e,{front:t=!1}={})=>{if((_==null?void 0:_.app_id)===e)return;let n=L.indexOf(e);if(n>=0){if(!t)return;L.splice(n,1)}t?L.unshift(e):L.push(e)},li=async e=>{let{host_id:t,client_token:n}=R(),i=new AbortController,s=setTimeout(()=>i.abort(),ti);try{let o=`${Ye}/api/hosts/${encodeURIComponent(t)}/miniapps?channel=${e}`,c=await fetch(o,{headers:{Authorization:`Bearer ${n}`,"Cache-Control":"no-cache"},signal:i.signal});if(!c.ok)throw new Error(`host list ${e} ${c.status}`);return(await c.json()).apps.map(r=>({...r,channel:e}))}finally{clearTimeout(s)}},Ee=null,pt=()=>(Ee!=null||(Ee=(async()=>{var t;let e=Date.now();try{let n=await Promise.all(R().channels.map(li)),i={};[...n].reverse().flat().forEach(r=>{i[r.app_id]=r});let s=Object.keys(S.getState().catalog).filter(r=>!i[r]);R().storage.setString(cn,JSON.stringify(i)),S.setState({catalog:i}),await Promise.all(s.map(r=>un(r,{by_user:!1}))),s.forEach(r=>le.delete(r));let o=Object.keys(i).filter(r=>!le.has(r)),c=[],a={};for(let r of o.map(l=>i[l])){if(await st(r)){B(r.app_id,{status:"installed",progress:1,version:r.version});continue}let l=P(r.app_id);if(ln(r.app_id)&&!Ve.has(r.app_id)&&l&&await te(l)){B(r.app_id,{status:"installed",progress:1,version:l.version}),a[r.app_id]={app_id:r.app_id,current_version:l.version,next_version:r.version};continue}c.push(r)}return S.setState({updates:a}),c.forEach(r=>{ne[r.app_id]=0,B(r.app_id,{status:Y.has(r.app_id)?"paused":"queued",progress:0,version:r.version,error:void 0}),je(r.app_id)}),K("catalog",o.length,"apps, outdated",c.map(r=>r.app_id),"removed",s,`${Date.now()-e}ms`),ae({type:"sync_complete",app_ids:o,removed:s}),Object.values(a).forEach(r=>ae({type:"update_available",...r})),ce(),{ok:!0,app_ids:o,removed:s}}catch(n){let i=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",i),ae({type:"sync_failed",error:i}),{ok:!1,error:i}}finally{Ee=null}})()),Ee),un=async(e,{by_user:t})=>{var s,o,c,a;if(t&&le.add(e),Be.has(e))return;Be.add(e),Y.delete(e);let n=L.indexOf(e);n>=0&&L.splice(n,1),(_==null?void 0:_.app_id)===e&&_.handle.cancel();let i=(a=(c=(s=S.getState().downloads[e])==null?void 0:s.version)!=null?c:(o=P(e))==null?void 0:o.version)!=null?a:"";B(e,{status:"uninstalling",progress:0,version:i}),await nn(e),$e(e),S.setState(r=>{let l={...r.downloads};return delete l[e],{downloads:l}}),delete ne[e],Be.delete(e),qe(e,null),K("uninstalled",e,t?"(user)":"(not in list)"),ae({type:"uninstalled",app_id:e})},pi=e=>un(e,{by_user:!0}),ui=e=>{let t=Pe(e);return t?(le.delete(e),(_==null?void 0:_.app_id)===e||L.includes(e)||(ne[e]=0,B(e,{status:Y.has(e)?"paused":"queued",progress:0,version:t.version,error:void 0}),je(e),ce(),K("restore",e)),!0):!1},di=e=>{if(Y.has(e))return;if(Y.add(e),K("pause app",e),(_==null?void 0:_.app_id)===e&&!_.forced){_.handle.cancel();return}let t=S.getState().downloads[e];L.includes(e)&&t&&B(e,{status:"paused",progress:0,version:t.version})},gi=e=>{if(!Y.delete(e))return;K("resume app",e);let t=S.getState().downloads[e];(t==null?void 0:t.status)==="paused"&&!L.includes(e)&&Pe(e)&&(ne[e]=0,je(e)),L.includes(e)&&t&&B(e,{status:"queued",progress:0,version:t.version}),ce()},fi=e=>{let{pause_reasons:t}=S.getState();t.includes(e)||(S.setState({pause_reasons:[...t,e]}),K("pause",e),t.length===0&&ae({type:"pause_change",paused:!0,reasons:[e]}),_&&!_.forced&&_.handle.cancel())},mi=e=>{let{pause_reasons:t}=S.getState();if(!t.includes(e))return;let n=t.filter(i=>i!==e);S.setState({pause_reasons:n}),K("resume",e),n.length===0&&ae({type:"pause_change",paused:!1,reasons:n}),ce()},dn=e=>S.getState().updates[e],hi=async e=>{var n,i;let t=dn(e);Ve.add(e);try{let s=await He(e),o=(i=t==null?void 0:t.next_version)!=null?i:(n=Pe(e))==null?void 0:n.version;return!s||!o||s.version!==o?!1:(S.setState(c=>{var r;let a={...c.updates};return delete a[e],{updates:a,apply_ticks:{...c.apply_ticks,[e]:((r=c.apply_ticks[e])!=null?r:0)+1}}}),K("updated",e,t==null?void 0:t.current_version,"\u2192",s.version),!0)}finally{Ve.delete(e)}},Ai=()=>Object.values(S.getState().catalog).map(e=>({...e,installed:!!P(e.app_id),removed_by_user:le.has(e.app_id)})),Pe=e=>S.getState().catalog[e],He=async e=>{let t=Pe(e);if(!t)return;if(Y.delete(e),le.delete(e),await st(t))return P(e);let n=P(e);if(ln(e)&&!Ve.has(e)&&n&&await te(n))return n;let i=new Promise(s=>{var o;((o=me[e])!=null?o:me[e]=[]).push(s)});return(_==null?void 0:_.app_id)===e?_.forced=!0:(ne[e]=0,je(e,{front:!0}),_&&!_.forced?_.handle.cancel():ce(e)),i};import{Fragment as hn,jsx as N,jsxs as Oe}from"react/jsx-runtime";var dt=e=>(e!=null?e:"").replace(/\?[^#]*/,""),fn=0,bi=()=>{let e=new Set;return{emit:t=>e.forEach(n=>n(t)),subscribe:t=>(e.add(t),()=>{e.delete(t)})}},Si=mt.memo(({instance_key:e,is_active:t,is_front:n,is_dark:i,reload_tick:s,web_at_top:o,splash:c,bridge:a,opaque_background:r,allow_embedded_miniapps:l,onWebLoadEnd:u})=>{var wt,yt;let p=G(null),h=G(!1),A=Q(H,g=>g.instances[e]),w=A==null?void 0:A.app.app_id,T=A==null?void 0:A.app.manifest_url,x=A==null?void 0:A.context,b=A==null?void 0:A.url_params,[m,k]=he(()=>w?P(w):null),[z,U]=he(!1),[E,f]=he(0),[y,v]=he(0),[D,C]=he(!1),V=G(null),ie=g=>{V.current&&clearTimeout(V.current),V.current=setTimeout(()=>{V.current=null,C(!0)},g)};q(()=>()=>{V.current&&clearTimeout(V.current)},[]),q(()=>{if(!w||!t&&m)return;let g=!0;return U(!1),(async()=>{let M=P(w),F=M?await te(M):!1;if(!g||(k(F?J=>!J||J.version!==M.version||J.permissions.join(",")!==M.permissions.join(",")?M:J:null),__DEV__&&Date.now()-fn>1e4&&(fn=Date.now(),await pt()),!g))return;let oe=await He(w),ue=oe!==void 0?oe:T?await on(w,T):P(w);if(g){if(!ue){U(!0);return}k(J=>J!=null?J:ue)}})(),()=>{g=!1}},[t,w,T,E]),q(()=>sn(e,g=>p.current?(p.current.postMessage(g),!0):!1),[e]);let ze=Q(S,g=>{let M=w?g.downloads[w]:void 0;return(M==null?void 0:M.status)==="installed"?M.version:void 0});q(()=>{if(t||!w||!m)return;let g=P(w);if(!g||g.version===m.version)return;let M=!0;return te(g).then(F=>{!M||!F||(j(`webview:${e}`,"\u0111\u1ED5i bundle (\u1EA9n)",m.version,"\u2192",g.version),k(g))}),()=>{M=!1}},[t,w,ze,m==null?void 0:m.version]);let pe=Q(S,g=>{var M;return w&&(M=g.apply_ticks[w])!=null?M:0});q(()=>{if(!pe||!w)return;let g=P(w);if(!g||g.version===(m==null?void 0:m.version))return;let M=!0;return te(g).then(F=>{!M||!F||(j(`webview:${e}`,"c\u1EADp nh\u1EADt",m==null?void 0:m.version,"\u2192",g.version),C(!1),k(g))}),()=>{M=!1}},[pe]),q(()=>{var F;let g=(F=R().keep_alive)==null?void 0:F.idle_close_ms;if(t||!g||g<=0)return;let M=setTimeout(()=>{$e(e)},g);return()=>clearTimeout(M)},[t,e]),q(()=>{s>0&&(U(!1),C(!1),v(g=>g+1),f(g=>g+1))},[s]);let Te=G(t);q(()=>{var g;Te.current!==t&&(Te.current=t,h.current&&((g=p.current)==null||g.injectJavaScript(Jt(t?"resumed":"paused"))))},[t]);let re=`${(wt=m==null?void 0:m.version)!=null?wt:"none"}:${(yt=m==null?void 0:m.permissions.join(","))!=null?yt:""}:${y}`,we=We(()=>JSON.stringify([x!=null?x:{},b!=null?b:{}]),[x,b]),Je=We(()=>{var g;return Xt(b!=null?b:{},(g=m==null?void 0:m.permissions)!=null?g:[])},[we,m==null?void 0:m.permissions]),wn=We(()=>Gt(x!=null?x:{},Je)+zt()+(R().debug?Wt():""),[Je]),ke=G(null),At=G(null);q(()=>{var M,F,oe;if(!m)return;if(At.current!==re){At.current=re,ke.current=we;return}if(ke.current===we)return;let g=((F=JSON.parse((M=ke.current)!=null?M:"[]")[0])!=null?F:{}).org_id;if(ke.current=we,g===(x==null?void 0:x.org_id)&&h.current){C(!1),ie(1500),(oe=p.current)==null||oe.injectJavaScript(Kt(x!=null?x:{},Je));return}C(!1),v(ue=>ue+1)},[we,m,re]),q(()=>(t||(ee(e),fe(e)),()=>{ee(e),fe(e)}),[t,e,re,s]),q(()=>{let g=gn.addEventListener("change",M=>{M==="background"&&ee(e)});return()=>g.remove()},[e]);let yn=gt(async g=>{var F,oe,ue,J,Ke;let M=qt(g.nativeEvent.data);if(!M){if(w&&(a!=null&&a.onWebEvent))try{Promise.resolve(a.onWebEvent(g.nativeEvent.data,{app_id:w,instance_id:e})).catch(O=>{console.warn("[miniapp] onWebEvent l\u1ED7i",w,O)})}catch(O){console.warn("[miniapp] onWebEvent l\u1ED7i",w,O)}return}if(M.method==="log"){let{level:O,text:$}=M;j(`web:${e}`,O!=null?O:"log",$!=null?$:"");return}if(M.method==="pong"){V.current||C(!0);return}if(M.method==="touchAtTop"){o.emit(!!M.at_top);return}if(M.method==="contextApplied"){V.current&&clearTimeout(V.current),V.current=null,C(!0);return}if(M.method==="ready"){h.current=!0,C(!0);let O=(F=H.getState().instances[e])==null?void 0:F.context;O&&((oe=p.current)==null||oe.injectJavaScript(et(O)));return}try{let O=await Zt(M,{getHostData:()=>{var $,X;return(X=($=H.getState().instances[e])==null?void 0:$.host_data)!=null?X:{}},getPermissions:()=>{var $,X;return w?(X=($=P(w))==null?void 0:$.permissions)!=null?X:[]:[]},is_dark:i,close:xe,app_id:w!=null?w:"",instance_id:e,options:a,emit:($,X)=>{var Mt;(Mt=p.current)==null||Mt.injectJavaScript(Ht($,X))},isActive:()=>H.getState().active_key===e&&gn.currentState!=="background"});M.id&&((ue=p.current)==null||ue.injectJavaScript(Vt(M.id,O)))}catch(O){if(!M.id)return;let $=O==null?void 0:O.code,X=O instanceof d?O:new d(typeof $=="string"?$:"HOST_ERROR",String((J=O==null?void 0:O.message)!=null?J:O));(Ke=p.current)==null||Ke.injectJavaScript(jt(M.id,X))}},[e,i,w,o,a]),Mn=gt(()=>{U(!1),v(g=>g+1),f(g=>g+1)},[]);return Oe(ft,{style:[ht.absoluteFill,r&&{backgroundColor:i?"#09090B":"#FFFFFF"},!n&&W.behind],pointerEvents:t?"auto":"none",children:[m?N(_i,{ref:p,source:{uri:m.entry_uri},originWhitelist:["*"],allowingReadAccessToURL:`file://${l?it():m.dir}`,allowFileAccess:!0,allowFileAccessFromFileURLs:!0,allowUniversalAccessFromFileURLs:!0,injectedJavaScriptBeforeContentLoaded:wn,onMessage:yn,bounces:!1,overScrollMode:"never",onLoadStart:g=>{ee(e),fe(e),j(`webview:${e}`,"load start",dt(g.nativeEvent.url)),h.current=!1,C(!1)},onError:g=>{ee(e),fe(e),j(`webview:${e}`,"load error",dt(g.nativeEvent.url),g.nativeEvent.description),U(!0),C(!1)},onLoadEnd:g=>{let M=g.nativeEvent.url;j(`webview:${e}`,"load end",dt(M)),w&&(u==null||u({app_id:w,instance_id:e,url:M})),ie(1500)},onContentProcessDidTerminate:()=>{ee(e),fe(e),h.current=!1,C(!1),v(g=>g+1)},onRenderProcessGone:()=>(ee(e),fe(e),h.current=!1,C(!1),v(g=>g+1),!0),style:W.webview},re):null,A&&N(Ei,{visible:!m||!D,interactive:z,children:N(xi,{splash:c,app:A.app,is_dark:i,error:z,has_bundle:!!m,retry:Mn})})]})}),xi=mt.memo(({splash:e,app:t,is_dark:n,error:i,has_bundle:s,retry:o})=>{let c=e,a=lt(t.app_id),r=i?"error":!s&&(a==null?void 0:a.status)==="downloading"?"downloading":"loading";return N(c,{app:t,is_dark:n,status:r,progress:r==="downloading"?a==null?void 0:a.progress:void 0,retry:o})}),Ei=({visible:e,interactive:t,children:n})=>{let i=G(new ut.Value(e?1:0)).current,[s,o]=he(e);return q(()=>{if(e){o(!0),i.setValue(1);return}let c=ut.timing(i,{toValue:0,duration:180,useNativeDriver:!0});return c.start(({finished:a})=>{a&&o(!1)}),()=>c.stop()},[e,i]),s?N(ut.View,{style:[ht.absoluteFill,{opacity:i}],pointerEvents:t?"auto":"none",children:n}):null},An=({app:e,is_dark:t,status:n,progress:i,retry:s})=>{let o=t?"#FAFAFA":"#18181B";return Oe(ft,{style:[W.splash,{backgroundColor:t?"#09090B":"#FFFFFF"}],children:[N(ft,{style:[W.splash_icon,{backgroundColor:t?"#18181B":"#F4F4F5"}],children:e.icon?N(Mi,{source:{uri:e.icon},style:W.splash_icon_image}):N(Re,{style:W.splash_letter,children:(e.name||"?").slice(0,1).toUpperCase()})}),N(Re,{style:[W.splash_name,{color:o}],children:e.name}),n==="error"?Oe(hn,{children:[N(Re,{style:W.splash_hint,children:"Kh\xF4ng t\u1EA3i \u0111\u01B0\u1EE3c mini app"}),N(vi,{activeOpacity:.7,style:[W.retry_button,{backgroundColor:t?"#27272A":"#F4F4F5"}],onPress:s,children:N(Re,{style:[W.retry_text,{color:o}],children:"Th\u1EED l\u1EA1i"})})]}):Oe(hn,{children:[N(wi,{style:W.splash_spinner,color:t?"#A1A1AA":"#71717A"}),n==="downloading"&&Oe(Re,{style:W.splash_hint,children:["\u0110ang t\u1EA3i mini app",i?` ${Math.round(i*100)}%`:"\u2026"]})]})]})},mn=(e,t)=>{let n=G(t),i=G(!1);__DEV__&&!i.current&&n.current!==t&&(i.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.`))},Pi=({container:e,splash:t=An,is_dark:n=!1,bridge:i,close_on_back:s=!0,opaque_background:o=!0,allow_embedded_miniapps:c=!1,onWebLoadEnd:a})=>{mn("container",e),mn("splash",t);let r=e,l=Q(H,m=>m.active_key),u=G(l);l&&(u.current=l);let p=Q(H,m=>Object.keys(m.instances).join("|")),h=Q(H,m=>{var k;return m.active_key?(k=m.instances[m.active_key])==null?void 0:k.app.name:void 0}),A=We(()=>p?p.split("|"):[],[p]),[w,T]=he({}),x=G(bi()).current;q(()=>{if(!l||!s)return;let m=yi.addEventListener("hardwareBackPress",()=>(xe(),!0));return()=>m.remove()},[l,s]);let b=gt(()=>{let m=H.getState().active_key;m&&T(k=>({...k,[m]:(k[m]||0)+1}))},[]);return A.length?N(r,{visible:!!l,title:h!=null?h:"",is_dark:n,close:xe,reload:b,subscribeWebAtTop:x.subscribe,children:A.map(m=>N(Si,{instance_key:m,is_active:l===m,is_front:(l!=null?l:u.current)===m,is_dark:n,reload_tick:w[m]||0,web_at_top:x,splash:t,bridge:i,opaque_background:o,allow_embedded_miniapps:c,onWebLoadEnd:a},m))}):null},W=ht.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"}}),Ri=mt.memo(Pi);export{An as DefaultMiniAppSplash,Ye as MINIAPP_PLATFORM_URL,Ri as MiniAppHost,d as MiniAppHostError,xe as closeMiniApp,vn as configureMiniApp,Dn as createDocumentPickerSource,bn as createMmkvStorage,bt as createReactNativeBiometrics,_n as createRnfsFileSystem,He as ensureMiniApp,P as getLocalMiniApp,Ai as getMiniAppCatalog,Pe as getMiniAppCatalogEntry,ai as getMiniAppStatuses,dn as getMiniAppUpdate,zn as installBundledMiniApp,si as onMiniAppEvent,Qn as openMiniApp,di as pauseMiniApp,fi as pauseMiniAppDownloads,Xn as preloadMiniApp,ee as releaseSpeechFor,ui as restoreMiniApp,gi as resumeMiniApp,mi as resumeMiniAppDownloads,Kn as sendEventToWeb,pt as syncMiniAppCatalog,pi as uninstallMiniApp,hi as updateMiniApp,Ct as uploadToUrl,lt as useMiniAppDownload,oi as useMiniAppDownloadsPaused};
66
+ true;`},pn={partner:"partner_token",chatbox:"chatbox_token"},ln=(e,t)=>{let n={...e};for(let r of Object.values(pn))t.includes(r)||delete n[r];return n},ot=new Set,Pe=async(e,t)=>{if(ot.has(e))throw new u("BUSY",`${e} \u0111ang ch\u1EA1y \u2014 ch\u1EDD l\u01B0\u1EE3t tr\u01B0\u1EDBc xong`);ot.add(e);try{return await t()}finally{ot.delete(e)}},ir=new Set(["selection","impactLight","impactMedium","impactHeavy","rigid","soft","notificationSuccess","notificationWarning","notificationError"]),qe=(e,t)=>{if(typeof e!="string"||!e)throw new u("INVALID_PARAMS",`Thi\u1EBFu ${t}`);return e},un=async({method:e,params:t},{getHostData:n,getPermissions:r,getContext:i,is_dark:o,close:c,app_id:p,instance_id:a,options:s,emit:d,isActive:g})=>{var E,S,_,f,C,Y,U,ve,ae;let A=s==null?void 0:s.handlers,l={app_id:p,instance_id:a,close:c},h=()=>new u("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF \u1EE9ng d\u1EE5ng n\xE0y`);switch(e){case"getCurrentLocation":{let w=Ot(t);return Pe(e,()=>Tt(w,g))}case"speech.start":{if(!d)throw h();let w={};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 u("INVALID_PARAMS","lang ph\u1EA3i l\xE0 m\xE3 ng\xF4n ng\u1EEF nh\u01B0 vi-VN");w.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 u("INVALID_PARAMS",`${v} ph\u1EA3i l\xE0 boolean`);w[v]=t[v]}return Kt(a,w,d,g)}case"speech.stop":return Yt(a);case"uploadFiles":{let{task_id:w,...v}=t!=null?t:{};if(w!==void 0&&(typeof w!="string"||!w))throw new u("INVALID_PARAMS","task_id ph\u1EA3i l\xE0 chu\u1ED7i");return Ht(Nt(v),{instance_id:a,app_id:p,getContext:i,task_id:w,config:s==null?void 0:s.upload,emit:d,exclusivePick:j=>Pe("uploadFiles.pick",j)})}case"uploadFiles.cancel":zt(a,t==null?void 0:t.task_id);return;case"getUploadCapabilities":return Vt(s==null?void 0:s.upload);case"getBiometricAvailability":return((E=s==null?void 0:s.biometrics)!=null?E:await tt()).getAvailability();case"authenticateBiometric":{let w=qe(t==null?void 0:t.reason,"reason").trim();if(!w||w.length>200)throw new u("INVALID_PARAMS","reason must contain 1\u2013200 characters");let v=t==null?void 0:t.cancelButtonText;if(v!==void 0&&(typeof v!="string"||!v.trim()||v.length>80))throw new u("INVALID_PARAMS","Invalid cancelButtonText");return Pe(e,async()=>{var M;return((M=s==null?void 0:s.biometrics)!=null?M:await tt()).authenticate({reason:w,cancelButtonText:v})})}case"requestPayment":{let w=A==null?void 0:A.requestPayment;if(!w)throw h();let v=t==null?void 0:t.amount;if(typeof v!="number"||!Number.isFinite(v)||v<=0)throw new u("INVALID_PARAMS","amount ph\u1EA3i l\xE0 s\u1ED1 > 0");let j={...t,amount:v,currency:qe(t==null?void 0:t.currency,"currency")};return Pe(e,()=>w(j,l))}case"printImage":{let w=A==null?void 0:A.printImage;if(!w)throw h();let v=qe(t==null?void 0:t.image,"image");await Pe(e,()=>w({image:v},l));return}case"openScreen":if(!(A!=null&&A.openScreen))throw h();await A.openScreen({screen:qe(t==null?void 0:t.screen,"screen"),params:t==null?void 0:t.params},l);return;case"closeApp":c();return;case"openWebview":{let w=String((S=t==null?void 0:t.url)!=null?S:"");if(!/^https?:\/\//i.test(w))throw new u("INVALID_PARAMS","url ph\u1EA3i l\xE0 http(s)");await(s!=null&&s.openUrl?s.openUrl(w):Gt.openURL(w));return}case"openLink":{let w=String((_=t==null?void 0:t.url)!=null?_:"").trim();if(!/^[a-z][a-z0-9+.-]*:/i.test(w)||/^(javascript|file|data|about|blob):/i.test(w))throw new u("INVALID_PARAMS","url kh\xF4ng h\u1EE3p l\u1EC7");try{await(s!=null&&s.openUrl?s.openUrl(w):Gt.openURL(w))}catch(v){throw new u("NOT_SUPPORTED",String((C=(f=v==null?void 0:v.message)!=null?f:v)!=null?C:"Kh\xF4ng m\u1EDF \u0111\u01B0\u1EE3c link"))}return}case"showToast":(U=s==null?void 0:s.showToast)==null||U.call(s,String((Y=t==null?void 0:t.message)!=null?Y:""));return;case"haptic":{let w=ir.has(t==null?void 0:t.type)?t.type:"selection";(ve=s==null?void 0:s.haptic)==null||ve.call(s,w);return}case"getSystemInfo":return{platform:rr.OS==="ios"?"ios":"android",appVersion:(ae=s==null?void 0:s.app_version)!=null?ae:"",theme:o?"dark":"light"};case"getAccessToken":{let w=n().access_token;if(!w)throw new u("HOST_ERROR","Mini app ch\u01B0a c\xF3 token cho page n\xE0y");return w}case"getToken":{let w=t==null?void 0:t.type;if(w==="access"){let M=n().access_token;if(!M)throw new u("HOST_ERROR","Mini app ch\u01B0a c\xF3 token cho page n\xE0y");return M}if(w!=="partner"&&w!=="chatbox")throw new u("HOST_ERROR",`Lo\u1EA1i token kh\xF4ng h\u1EE3p l\u1EC7: ${String(w)}`);let v=pn[w];if(!r().includes(v))throw new u("PERMISSION_DENIED",`Mini app ch\u01B0a \u0111\u01B0\u1EE3c c\u1EA5p quy\u1EC1n ${v} (Console \u2192 Quy\u1EC1n l\u1EA5y token)`);let j=w==="partner"?n().partner_token:n().chatbox_token;if(!j)throw new u("HOST_ERROR",`Kh\xF4ng c\xF3 ${v}`);return j}case"getUserInfo":{let w=n().user;if(!w)throw new u("HOST_ERROR","Kh\xF4ng l\u1EA5y \u0111\u01B0\u1EE3c th\xF4ng tin nh\xE2n vi\xEAn");return w}case"getPageInfo":{let w=n().page;if(!w)throw new u("HOST_ERROR","Kh\xF4ng l\u1EA5y \u0111\u01B0\u1EE3c th\xF4ng tin page");return w}case"sendMessage":case"insertText":throw new u("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF phi\xEAn b\u1EA3n app n\xE0y`);default:throw new u("NOT_SUPPORTED",`API kh\xF4ng t\u1ED3n t\u1EA1i: ${e}`)}};var ct=e=>`bundle:${e}`,pt=()=>`${O().file_system.document_dir}/miniapps`,lt=pt,ut=(e,t,n="index.html",r=!1,i=[])=>{let o=`${lt()}/${e}/${t}`;return{app_id:e,version:t,dir:o,entry_uri:`file://${o}/${n}`,context_update:r,permissions:i}},at=e=>{var t;O().storage.setString(ct(e.app_id),JSON.stringify({version:e.version,entry:e.entry,context_update:!!e.context_update,permissions:(t=e.permissions)!=null?t:[]}))},or=(e,t)=>/^https?:\/\//.test(t)?t:`${e.replace(/[^/]*$/,"")}${t}`,P=e=>{let t=O().storage.getString(ct(e));if(!t)return null;try{let{version:n,entry:r,context_update:i,permissions:o}=JSON.parse(t);return ut(e,n,r,!!i,Array.isArray(o)?o:[])}catch{return null}},oe=e=>O().file_system.exists(e.entry_uri.replace("file://","")),dt=async e=>{let t=P(e.app_id);return(t==null?void 0:t.version)===e.version&&await oe(t)},gn=async(e,t)=>{let n=O().file_system,r=`${lt()}/${e}`,i=await n.listDir(r).catch(()=>[]);await Promise.all(i.filter(o=>!t.includes(o)).map(o=>n.remove(`${r}/${o}`).catch(()=>{})))},mn=async e=>{var t;await((t=Te[e])==null?void 0:t.catch(()=>{})),O().storage.setString(ct(e),""),await O().file_system.remove(`${lt()}/${e}`).catch(()=>{})},Se=class extends Error{constructor(){super("cancelled"),this.name="MiniAppInstallCancelled"}},Te={},fn=(e,t)=>{var o;let r=((o=Te[e])!=null?o:Promise.resolve()).catch(()=>{}).then(t),i=r.catch(()=>{});return Te[e]=i,i.then(()=>{Te[e]===i&&delete Te[e]}),r},sr=(e,t)=>{var i,o;let n=e.split(".").map(c=>parseInt(c,10)||0),r=t.split(".").map(c=>parseInt(c,10)||0);for(let c=0;c<Math.max(n.length,r.length);c++){let p=((i=n[c])!=null?i:0)-((o=r[c])!=null?o:0);if(p)return p}return 0},ar=({manifest:e,zip_path:t})=>fn(e.app_id,async()=>{var o;let n=O().file_system,r=P(e.app_id);if(r&&sr(r.version,e.version)>=0&&await oe(r))return r;if(e.sha256&&n.sha256&&await n.sha256(t)!==e.sha256)throw new Error("sha256 mismatch");let i=ut(e.app_id,e.version,e.entry,!!e.context_update,(o=e.permissions)!=null?o:[]);return await n.remove(i.dir).catch(()=>{}),await n.mkdir(i.dir),await n.unzip(t,i.dir),at(e),W("\u0111\xE3 c\xE0i b\u1EA3n \u0111\xF3ng s\u1EB5n",e.app_id,e.version),gn(e.app_id,[e.version,r==null?void 0:r.version].filter(Boolean)),i}),gt=(e,{base_url:t,onProgress:n}={})=>{let r=O().file_system,i=null,o=!1,c=`${r.cache_dir}/${e.app_id}-${e.version}.zip`,p=()=>{if(o)throw new Se},a=async()=>{var g;p();let s=P(e.app_id);if((s==null?void 0:s.version)===e.version&&await r.exists(s.dir))return at(e),P(e.app_id);p();let d=r.download({url:t?or(t,e.bundle_url):e.bundle_url,to_file:c,onProgress:(A,l)=>{var E;let h=l>0?l:(E=e.size)!=null?E:0;h>0&&(n==null||n(Math.min(1,A/h)))}});i=d;try{let{status:A}=await d.promise;if(p(),A!==200)throw new Error(`bundle ${A}`);if(e.sha256)if(r.sha256){if(await r.sha256(c)!==e.sha256)throw new Error("sha256 mismatch")}else W("b\u1ECF qua ki\u1EC3m tra sha256 (file_system kh\xF4ng c\xF3 sha256)",e.app_id);p();let l=ut(e.app_id,e.version,e.entry,!!e.context_update,(g=e.permissions)!=null?g:[]);return await r.remove(l.dir).catch(()=>{}),await r.mkdir(l.dir),await r.unzip(c,l.dir),at(e),gn(e.app_id,[e.version,s==null?void 0:s.version].filter(Boolean)),l}catch(A){throw o?new Se:A}finally{i=null,r.remove(c).catch(()=>{})}};return{promise:fn(e.app_id,a),cancel:()=>{o=!0,i==null||i.cancel()}}},Oe={},cr=__DEV__?0:60*1e3,dn={},hn=(e,t)=>{var r,i;let n=P(e);return n&&Date.now()-((r=dn[t])!=null?r:0)<cr?Promise.resolve(n):((i=Oe[e])!=null||(Oe[e]=(async()=>{let o=await fetch(t,{headers:{"Cache-Control":"no-cache"}});if(!o.ok)throw new Error(`manifest ${o.status}`);let c=await o.json(),p=await gt(c,{base_url:t}).promise;return dn[t]=Date.now(),p})().catch(o=>(console.warn("[miniapp] sync failed",e,o==null?void 0:o.message),P(e))).finally(()=>{Oe[e]=void 0})),Oe[e])};var je=new Map,An=(e,t)=>(je.set(e,t),()=>{je.get(e)===t&&je.delete(e)}),pr=(e,t)=>{let n=je.get(e);return n?n(t):!1};import{useRef as lr,useSyncExternalStore as ur}from"react";var ze=e=>{let t=e,n=new Set;return{getState:()=>t,setState:r=>{let i=typeof r=="function"?r(t):r;t={...t,...i},n.forEach(o=>o())},subscribe:r=>(n.add(r),()=>{n.delete(r)})}},ee=(e,t,n=Object.is)=>{let r=lr(null),i=()=>{let o=e.getState(),c=r.current;if(c&&c.state===o&&c.selector===t)return c.value;let p=t(o),a=c&&n(c.value,p)?c.value:p;return r.current={state:o,selector:t,value:a},a};return ur(e.subscribe,i)};var B=ze({active_key:null,instances:{}}),wn=({app:e,instance_id:t,context:n={},url_params:r={},host_data:i={}},o)=>{var p;let c=(p=O().keep_alive)==null?void 0:p.max_webviews;B.setState(a=>{let s=t!=null?t:e.app_id,d={...a.instances,[s]:{key:s,app:e,context:n,url_params:r,host_data:i,last_used_at:Date.now()}},g=Object.keys(d);return c&&c>0&&g.length>c&&g.filter(A=>A!==s).sort((A,l)=>d[A].last_used_at-d[l].last_used_at).slice(0,g.length-c).forEach(A=>{delete d[A]}),o?{active_key:s,instances:d}:{instances:d}})},dr=e=>wn(e,!0),gr=e=>wn(e,!1),Ce=()=>B.setState({active_key:null}),He=e=>{B.setState(t=>{if(t.active_key===e||!t.instances[e])return{};let n={...t.instances};return delete n[e],{instances:n}})};var yn="catalog",mr="paused_apps",fr="removed_apps",hr=10*1e3,Ar=2,wr=3e3,yr=()=>{var e;try{return JSON.parse((e=O().storage.getString(yn))!=null?e:"{}")}catch{return{}}},x=ze({catalog:{},downloads:{},pause_reasons:[],updates:{},apply_ticks:{}}),Mn=e=>{var t;return!!((t=O().manual_update)!=null&&t.includes(e))},Ke=new Set,vn=e=>{let t=new Set,n=()=>O().storage.setString(e,JSON.stringify([...t]));return{has:r=>t.has(r),values:()=>[...t],add:r=>t.has(r)?!1:(t.add(r),n(),!0),delete:r=>t.delete(r)?(n(),!0):!1,load:()=>{var r;t.clear();try{let i=JSON.parse((r=O().storage.getString(e))!=null?r:"[]");Array.isArray(i)&&i.forEach(o=>{typeof o=="string"&&t.add(o)})}catch{}}}},X=vn(mr),ge=vn(fr);Pt(()=>{X.load(),ge.load();let e=yr(),t={};Object.keys(e).filter(n=>!ge.has(n)).forEach(n=>{let r=P(n);r?t[n]={status:"installed",progress:1,version:r.version,has_local:!0}:X.has(n)&&(t[n]={status:"paused",progress:0,version:e[n].version,has_local:!1})}),x.setState({catalog:e,downloads:t})});var ft=e=>ee(x,t=>e?t.downloads[e]:void 0),Mr=()=>ee(x,e=>e.pause_reasons.length>0),Q=(...e)=>W("queue",...e),L=[],se={},b=null,We=new Set,ye={},mt=new Set,ue=e=>{mt.forEach(t=>{try{t(e)}catch(n){console.warn("[miniapp-queue] event listener error",n==null?void 0:n.message)}})},vr=e=>(mt.add(e),()=>{mt.delete(e)}),Sr=()=>x.getState().downloads,q=(e,t)=>{let n=!!P(e),r=x.getState().downloads[e],i=t.status==="downloading"&&n?"updating":t.status,o={...r!=null?r:{status:"queued",progress:0},...t,...i?{status:i}:{},has_local:n};x.setState(c=>({downloads:{...c.downloads,[e]:o}})),(r==null?void 0:r.status)!==o.status||(r==null?void 0:r.version)!==o.version||(r==null?void 0:r.has_local)!==o.has_local?ue({type:"status_change",app_id:e,state:o}):r.progress!==o.progress&&ue({type:"progress",app_id:e,progress:o.progress,version:o.version})},Je=(e,t)=>{var n;(n=ye[e])==null||n.forEach(r=>r(t)),delete ye[e]},_r=()=>x.getState().pause_reasons.length>0,de=e=>{var p;if(b)return;let t=e?L.indexOf(e):_r()?-1:L.findIndex(a=>!X.has(a));if(t<0||t>=L.length)return;let[n]=L.splice(t,1),r=x.getState().catalog[n];if(!r){Je(n,P(n)),de();return}let i=Date.now();se[n]=((p=se[n])!=null?p:0)+1,q(n,{status:"downloading",progress:0,version:r.version,error:void 0});let o=0,c=gt(r,{onProgress:a=>{let s=Math.floor(a*100);s!==o&&(o=s,q(n,{progress:s/100,version:r.version}))}});b={app_id:n,handle:c,forced:!!e},Q("start",n,r.version,e?"(forced)":""),c.promise.then(a=>{Q("installed",n,r.version,`${Date.now()-i}ms`),q(n,{status:"installed",progress:1,version:r.version}),Je(n,a)}).catch(a=>{var d;if(a instanceof Se){if(We.has(n))return;Q("paused",n),se[n]-=1,L.unshift(n),q(n,{status:X.has(n)?"paused":"queued",progress:0,version:r.version});return}let s=String((d=a==null?void 0:a.message)!=null?d:a);if(console.warn("[miniapp-queue] failed",n,s),se[n]<Ar){q(n,{status:"queued",progress:0,version:r.version,error:s}),setTimeout(()=>{var g;L.includes(n)||(b==null?void 0:b.app_id)===n||(L.push(n),de((g=ye[n])!=null&&g.length?n:void 0))},wr);return}q(n,{status:"failed",progress:0,version:r.version,error:s}),Je(n,P(n))}).finally(()=>{b=null;let a=L.find(s=>{var d;return(d=ye[s])==null?void 0:d.length});de(a)})},Ye=(e,{front:t=!1}={})=>{if((b==null?void 0:b.app_id)===e)return;let n=L.indexOf(e);if(n>=0){if(!t)return;L.splice(n,1)}t?L.unshift(e):L.push(e)},br=async e=>{let{host_id:t,client_token:n}=O(),r=new AbortController,i=setTimeout(()=>r.abort(),hr);try{let o=`${et}/api/hosts/${encodeURIComponent(t)}/miniapps?channel=${e}`,c=await fetch(o,{headers:{Authorization:`Bearer ${n}`,"Cache-Control":"no-cache"},signal:r.signal});if(!c.ok)throw new Error(`host list ${e} ${c.status}`);return(await c.json()).apps.map(a=>({...a,channel:e}))}finally{clearTimeout(i)}},ke=null,ht=()=>(ke!=null||(ke=(async()=>{var t;let e=Date.now();try{let n=await Promise.all(O().channels.map(br)),r={};[...n].reverse().flat().forEach(a=>{r[a.app_id]=a});let i=Object.keys(x.getState().catalog).filter(a=>!r[a]);O().storage.setString(yn,JSON.stringify(r)),x.setState({catalog:r}),await Promise.all(i.map(a=>Sn(a,{by_user:!1}))),i.forEach(a=>ge.delete(a));let o=Object.keys(r).filter(a=>!ge.has(a)),c=[],p={};for(let a of o.map(s=>r[s])){if(await dt(a)){q(a.app_id,{status:"installed",progress:1,version:a.version});continue}let s=P(a.app_id);if(Mn(a.app_id)&&!Ke.has(a.app_id)&&s&&await oe(s)){q(a.app_id,{status:"installed",progress:1,version:s.version}),p[a.app_id]={app_id:a.app_id,current_version:s.version,next_version:a.version};continue}c.push(a)}return x.setState({updates:p}),c.forEach(a=>{se[a.app_id]=0,q(a.app_id,{status:X.has(a.app_id)?"paused":"queued",progress:0,version:a.version,error:void 0}),Ye(a.app_id)}),Q("catalog",o.length,"apps, outdated",c.map(a=>a.app_id),"removed",i,`${Date.now()-e}ms`),ue({type:"sync_complete",app_ids:o,removed:i}),Object.values(p).forEach(a=>ue({type:"update_available",...a})),de(),{ok:!0,app_ids:o,removed:i}}catch(n){let r=String((n==null?void 0:n.name)==="AbortError"?"timeout":(t=n==null?void 0:n.message)!=null?t:n);return console.warn("[miniapp-queue] sync catalog failed",r),ue({type:"sync_failed",error:r}),{ok:!1,error:r}}finally{ke=null}})()),ke),Sn=async(e,{by_user:t})=>{var i,o,c,p;if(t&&ge.add(e),We.has(e))return;We.add(e),X.delete(e);let n=L.indexOf(e);n>=0&&L.splice(n,1),(b==null?void 0:b.app_id)===e&&b.handle.cancel();let r=(p=(c=(i=x.getState().downloads[e])==null?void 0:i.version)!=null?c:(o=P(e))==null?void 0:o.version)!=null?p:"";q(e,{status:"uninstalling",progress:0,version:r}),await mn(e),He(e),x.setState(a=>{let s={...a.downloads};return delete s[e],{downloads:s}}),delete se[e],We.delete(e),Je(e,null),Q("uninstalled",e,t?"(user)":"(not in list)"),ue({type:"uninstalled",app_id:e})},xr=e=>Sn(e,{by_user:!0}),Er=e=>{let t=Ie(e);return t?(ge.delete(e),(b==null?void 0:b.app_id)===e||L.includes(e)||(se[e]=0,q(e,{status:X.has(e)?"paused":"queued",progress:0,version:t.version,error:void 0}),Ye(e),de(),Q("restore",e)),!0):!1},Pr=e=>{if(X.has(e))return;if(X.add(e),Q("pause app",e),(b==null?void 0:b.app_id)===e&&!b.forced){b.handle.cancel();return}let t=x.getState().downloads[e];L.includes(e)&&t&&q(e,{status:"paused",progress:0,version:t.version})},Rr=e=>{if(!X.delete(e))return;Q("resume app",e);let t=x.getState().downloads[e];(t==null?void 0:t.status)==="paused"&&!L.includes(e)&&Ie(e)&&(se[e]=0,Ye(e)),L.includes(e)&&t&&q(e,{status:"queued",progress:0,version:t.version}),de()},Or=e=>{let{pause_reasons:t}=x.getState();t.includes(e)||(x.setState({pause_reasons:[...t,e]}),Q("pause",e),t.length===0&&ue({type:"pause_change",paused:!0,reasons:[e]}),b&&!b.forced&&b.handle.cancel())},Tr=e=>{let{pause_reasons:t}=x.getState();if(!t.includes(e))return;let n=t.filter(r=>r!==e);x.setState({pause_reasons:n}),Q("resume",e),n.length===0&&ue({type:"pause_change",paused:!1,reasons:n}),de()},_n=e=>x.getState().updates[e],Cr=async e=>{var n,r;let t=_n(e);Ke.add(e);try{let i=await Ge(e),o=(r=t==null?void 0:t.next_version)!=null?r:(n=Ie(e))==null?void 0:n.version;return!i||!o||i.version!==o?!1:(x.setState(c=>{var a;let p={...c.updates};return delete p[e],{updates:p,apply_ticks:{...c.apply_ticks,[e]:((a=c.apply_ticks[e])!=null?a:0)+1}}}),Q("updated",e,t==null?void 0:t.current_version,"\u2192",i.version),!0)}finally{Ke.delete(e)}},kr=()=>Object.values(x.getState().catalog).map(e=>({...e,installed:!!P(e.app_id),removed_by_user:ge.has(e.app_id)})),Ie=e=>x.getState().catalog[e],Ge=async e=>{let t=Ie(e);if(!t)return;if(X.delete(e),ge.delete(e),await dt(t))return P(e);let n=P(e);if(Mn(e)&&!Ke.has(e)&&n&&await oe(n))return n;let r=new Promise(i=>{var o;((o=ye[e])!=null?o:ye[e]=[]).push(i)});return(b==null?void 0:b.app_id)===e?b.forced=!0:(se[e]=0,Ye(e,{front:!0}),b&&!b.forced?b.handle.cancel():de(e)),r};import{Fragment as Pn,jsx as N,jsxs as De}from"react/jsx-runtime";var wt=e=>(e!=null?e:"").replace(/\?[^#]*/,""),xn=0,$r=()=>{let e=new Set;return{emit:t=>e.forEach(n=>n(t)),subscribe:t=>(e.add(t),()=>{e.delete(t)})}},Br=vt.memo(({instance_key:e,is_active:t,is_front:n,is_dark:r,reload_tick:i,web_at_top:o,splash:c,bridge:p,opaque_background:a,allow_embedded_miniapps:s,onWebLoadEnd:d})=>{var _t,bt;let g=Z(null),A=Z(!1),l=ee(B,m=>m.instances[e]),h=l==null?void 0:l.app.app_id,E=l==null?void 0:l.app.manifest_url,S=l==null?void 0:l.context,_=l==null?void 0:l.url_params,[f,C]=Me(()=>h?P(h):null),[Y,U]=Me(!1),[ve,ae]=Me(0),[w,v]=Me(0),[j,M]=Me(!1),k=Z(null),te=m=>{k.current&&clearTimeout(k.current),k.current=setTimeout(()=>{k.current=null,M(!0)},m)};V(()=>()=>{k.current&&clearTimeout(k.current)},[]),V(()=>{if(!h||!t&&f)return;let m=!0;return U(!1),(async()=>{let y=P(h),$=y?await oe(y):!1;if(!m||(C($?G=>!G||G.version!==y.version||G.permissions.join(",")!==y.permissions.join(",")?y:G:null),__DEV__&&Date.now()-xn>1e4&&(xn=Date.now(),await ht()),!m))return;let pe=await Ge(h),fe=pe!==void 0?pe:E?await hn(h,E):P(h);if(m){if(!fe){U(!0);return}C(G=>G!=null?G:fe)}})(),()=>{m=!1}},[t,h,E,ve]),V(()=>An(e,m=>g.current?(g.current.postMessage(m),!0):!1),[e]);let F=ee(x,m=>{let y=h?m.downloads[h]:void 0;return(y==null?void 0:y.status)==="installed"?y.version:void 0});V(()=>{if(t||!h||!f)return;let m=P(h);if(!m||m.version===f.version)return;let y=!0;return oe(m).then($=>{!y||!$||(W(`webview:${e}`,"\u0111\u1ED5i bundle (\u1EA9n)",f.version,"\u2192",m.version),C(m))}),()=>{y=!1}},[t,h,F,f==null?void 0:f.version]);let R=ee(x,m=>{var y;return h&&(y=m.apply_ticks[h])!=null?y:0});V(()=>{if(!R||!h)return;let m=P(h);if(!m||m.version===(f==null?void 0:f.version))return;let y=!0;return oe(m).then($=>{!y||!$||(W(`webview:${e}`,"c\u1EADp nh\u1EADt",f==null?void 0:f.version,"\u2192",m.version),M(!1),C(m))}),()=>{y=!1}},[R]),V(()=>{var $;let m=($=O().keep_alive)==null?void 0:$.idle_close_ms;if(t||!m||m<=0)return;let y=setTimeout(()=>{He(e)},m);return()=>clearTimeout(y)},[t,e]),V(()=>{i>0&&(U(!1),M(!1),v(m=>m+1),ae(m=>m+1))},[i]);let z=Z(t);V(()=>{var m;z.current!==t&&(z.current=t,A.current&&((m=g.current)==null||m.injectJavaScript(on(t?"resumed":"paused"))))},[t]);let ce=`${(_t=f==null?void 0:f.version)!=null?_t:"none"}:${(bt=f==null?void 0:f.permissions.join(","))!=null?bt:""}:${w}`,me=Qe(()=>JSON.stringify([S!=null?S:{},_!=null?_:{}]),[S,_]),ne=Qe(()=>{var m;return ln(_!=null?_:{},(m=f==null?void 0:f.permissions)!=null?m:[])},[me,f==null?void 0:f.permissions]),Xe=Qe(()=>cn(S!=null?S:{},ne)+nn()+(Nr.OS==="android"?rn():"")+(O().debug?tn():""),[ne]),re=Z(null),Ne=Z(null);V(()=>{var y,$,pe;if(!f)return;if(Ne.current!==ce){Ne.current=ce,re.current=me;return}if(re.current===me)return;let m=(($=JSON.parse((y=re.current)!=null?y:"[]")[0])!=null?$:{}).org_id;if(re.current=me,m===(S==null?void 0:S.org_id)&&A.current){M(!1),te(1500),(pe=g.current)==null||pe.injectJavaScript(sn(S!=null?S:{},ne));return}M(!1),v(fe=>fe+1)},[me,f,ce]),V(()=>(t||(ie(e),we(e)),()=>{ie(e),we(e)}),[t,e,ce,i]),V(()=>{let m=bn.addEventListener("change",y=>{y==="background"&&!Jt()&&ie(e)});return()=>m.remove()},[e]);let Ue=yt(async m=>{var $,pe,fe,G,Ze;let y=Qt(m.nativeEvent.data);if(!y){if(h&&(p!=null&&p.onWebEvent))try{Promise.resolve(p.onWebEvent(m.nativeEvent.data,{app_id:h,instance_id:e})).catch(T=>{console.warn("[miniapp] onWebEvent l\u1ED7i",h,T)})}catch(T){console.warn("[miniapp] onWebEvent l\u1ED7i",h,T)}return}if(y.method==="log"){let{level:T,text:D}=y;W(`web:${e}`,T!=null?T:"log",D!=null?D:"");return}if(y.method==="pong"){k.current||M(!0);return}if(y.method==="touchAtTop"){o.emit(!!y.at_top);return}if(y.method==="contextApplied"){k.current&&clearTimeout(k.current),k.current=null,M(!0);return}if(y.method==="ready"){A.current=!0,M(!0);let T=($=B.getState().instances[e])==null?void 0:$.context;T&&((pe=g.current)==null||pe.injectJavaScript(st(T)));return}try{let T=await un(y,{getHostData:()=>{var D,H;return(H=(D=B.getState().instances[e])==null?void 0:D.host_data)!=null?H:{}},getPermissions:()=>{var D,H;return h?(H=(D=P(h))==null?void 0:D.permissions)!=null?H:[]:[]},getContext:()=>{var D,H;return(H=(D=B.getState().instances[e])==null?void 0:D.context)!=null?H:{}},is_dark:r,close:Ce,app_id:h!=null?h:"",instance_id:e,options:p,emit:(D,H)=>{var xt;(xt=g.current)==null||xt.injectJavaScript(en(D,H))},isActive:()=>B.getState().active_key===e&&bn.currentState!=="background"});y.id&&((fe=g.current)==null||fe.injectJavaScript(Xt(y.id,T)))}catch(T){if(!y.id)return;let D=T==null?void 0:T.code,H=T instanceof u?T:new u(typeof D=="string"?D:"HOST_ERROR",String((G=T==null?void 0:T.message)!=null?G:T));(Ze=g.current)==null||Ze.injectJavaScript(Zt(y.id,H))}},[e,r,h,o,p]),On=yt(()=>{U(!1),v(m=>m+1),ae(m=>m+1)},[]);return De(Mt,{style:[St.absoluteFill,a&&{backgroundColor:r?"#09090B":"#FFFFFF"},!n&&K.behind],pointerEvents:t?"auto":"none",children:[f?N(Fr,{ref:g,source:{uri:f.entry_uri},originWhitelist:["*"],allowingReadAccessToURL:`file://${s?pt():f.dir}`,allowFileAccess:!0,allowFileAccessFromFileURLs:!0,allowUniversalAccessFromFileURLs:!0,injectedJavaScriptBeforeContentLoaded:Xe,onMessage:Ue,bounces:!1,overScrollMode:"never",onLoadStart:m=>{ie(e),we(e),W(`webview:${e}`,"load start",wt(m.nativeEvent.url)),A.current=!1,M(!1)},onError:m=>{ie(e),we(e),W(`webview:${e}`,"load error",wt(m.nativeEvent.url),m.nativeEvent.description),U(!0),M(!1)},onLoadEnd:m=>{let y=m.nativeEvent.url;W(`webview:${e}`,"load end",wt(y)),h&&(d==null||d({app_id:h,instance_id:e,url:y})),te(1500)},onContentProcessDidTerminate:()=>{ie(e),we(e),A.current=!1,M(!1),v(m=>m+1)},onRenderProcessGone:()=>(ie(e),we(e),A.current=!1,M(!1),v(m=>m+1),!0),style:K.webview},ce):null,l&&N(Vr,{visible:!f||!j,interactive:Y,children:N(qr,{splash:c,app:l.app,is_dark:r,error:Y,has_bundle:!!f,retry:On})})]})}),qr=vt.memo(({splash:e,app:t,is_dark:n,error:r,has_bundle:i,retry:o})=>{let c=e,p=ft(t.app_id),a=r?"error":!i&&(p==null?void 0:p.status)==="downloading"?"downloading":"loading";return N(c,{app:t,is_dark:n,status:a,progress:a==="downloading"?p==null?void 0:p.progress:void 0,retry:o})}),Vr=({visible:e,interactive:t,children:n})=>{let r=Z(new At.Value(e?1:0)).current,[i,o]=Me(e);return V(()=>{if(e){o(!0),r.setValue(1);return}let c=At.timing(r,{toValue:0,duration:180,useNativeDriver:!0});return c.start(({finished:p})=>{p&&o(!1)}),()=>c.stop()},[e,r]),i?N(At.View,{style:[St.absoluteFill,{opacity:r}],pointerEvents:t?"auto":"none",children:n}):null},Rn=({app:e,is_dark:t,status:n,progress:r,retry:i})=>{let o=t?"#FAFAFA":"#18181B";return De(Mt,{style:[K.splash,{backgroundColor:t?"#09090B":"#FFFFFF"}],children:[N(Mt,{style:[K.splash_icon,{backgroundColor:t?"#18181B":"#F4F4F5"}],children:e.icon?N(Dr,{source:{uri:e.icon},style:K.splash_icon_image}):N(Le,{style:K.splash_letter,children:(e.name||"?").slice(0,1).toUpperCase()})}),N(Le,{style:[K.splash_name,{color:o}],children:e.name}),n==="error"?De(Pn,{children:[N(Le,{style:K.splash_hint,children:"Kh\xF4ng t\u1EA3i \u0111\u01B0\u1EE3c mini app"}),N(Ur,{activeOpacity:.7,style:[K.retry_button,{backgroundColor:t?"#27272A":"#F4F4F5"}],onPress:i,children:N(Le,{style:[K.retry_text,{color:o}],children:"Th\u1EED l\u1EA1i"})})]}):De(Pn,{children:[N(Ir,{style:K.splash_spinner,color:t?"#A1A1AA":"#71717A"}),n==="downloading"&&De(Le,{style:K.splash_hint,children:["\u0110ang t\u1EA3i mini app",r?` ${Math.round(r*100)}%`:"\u2026"]})]})]})},En=(e,t)=>{let n=Z(t),r=Z(!1);__DEV__&&!r.current&&n.current!==t&&(r.current=!0,console.warn(`[miniapp] MiniAppHost prop "${e}" \u0111\u1ED5i gi\u1EEFa c\xE1c l\u1EA7n render \u2192 m\u1ECDi WebView b\u1ECB mount l\u1EA1i. Khai b\xE1o component b\xEAn ngo\xE0i render.`))},jr=({container:e,splash:t=Rn,is_dark:n=!1,bridge:r,close_on_back:i=!0,opaque_background:o=!0,allow_embedded_miniapps:c=!1,onWebLoadEnd:p})=>{En("container",e),En("splash",t);let a=e,s=ee(B,f=>f.active_key),d=Z(s);s&&(d.current=s);let g=ee(B,f=>Object.keys(f.instances).join("|")),A=ee(B,f=>{var C;return f.active_key?(C=f.instances[f.active_key])==null?void 0:C.app.name:void 0}),l=Qe(()=>g?g.split("|"):[],[g]),[h,E]=Me({}),S=Z($r()).current;V(()=>{if(!s||!i)return;let f=Lr.addEventListener("hardwareBackPress",()=>(Ce(),!0));return()=>f.remove()},[s,i]);let _=yt(()=>{let f=B.getState().active_key;f&&E(C=>({...C,[f]:(C[f]||0)+1}))},[]);return l.length?N(a,{visible:!!s,title:A!=null?A:"",is_dark:n,close:Ce,reload:_,subscribeWebAtTop:S.subscribe,children:l.map(f=>N(Br,{instance_key:f,is_active:s===f,is_front:(s!=null?s:d.current)===f,is_dark:n,reload_tick:h[f]||0,web_at_top:S,splash:t,bridge:r,opaque_background:o,allow_embedded_miniapps:c,onWebLoadEnd:p},f))}):null},K=St.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"}}),zr=vt.memo(jr);export{Rn as DefaultMiniAppSplash,et as MINIAPP_PLATFORM_URL,zr as MiniAppHost,u as MiniAppHostError,Ce as closeMiniApp,Tn as configureMiniApp,kn as createMmkvStorage,Rt as createReactNativeBiometrics,Cn as createRnfsFileSystem,Ge as ensureMiniApp,P as getLocalMiniApp,kr as getMiniAppCatalog,Ie as getMiniAppCatalogEntry,Sr as getMiniAppStatuses,_n as getMiniAppUpdate,ar as installBundledMiniApp,vr as onMiniAppEvent,dr as openMiniApp,Pr as pauseMiniApp,Or as pauseMiniAppDownloads,gr as preloadMiniApp,ie as releaseSpeechFor,Er as restoreMiniApp,Rr as resumeMiniApp,Tr as resumeMiniAppDownloads,pr as sendEventToWeb,ht as syncMiniAppCatalog,xr as uninstallMiniApp,Cr as updateMiniApp,Bt as uploadToUrl,ft as useMiniAppDownload,Mr as useMiniAppDownloadsPaused};
@@ -551,7 +551,7 @@ Mount **1 lần** ở gốc app, không unmount.
551
551
  | `container` | ✓ | Layout bao ngoài — nhận `MiniAppContainerProps` |
552
552
  | `splash` | | Màn che lúc khởi động / đang tải / lỗi — nhận `MiniAppSplashProps`. Mặc định có sẵn |
553
553
  | `is_dark` | | Theme, mặc định `false` |
554
- | `bridge` | | `{ handlers, upload, showToast, haptic, openUrl, app_version, onWebEvent }` — `openUrl` dùng cho `openWebview` / `openLink`; `upload` cấu hình nguồn / nén / đích cho `uploadFiles` (xem [Upload file](#upload-file-uploadfiles)) |
554
+ | `bridge` | | `{ handlers, upload, showToast, haptic, openUrl, app_version, onWebEvent }` — `openUrl` dùng cho `openWebview` / `openLink`; `upload` tuỳ chọn: chỉ cần khai báo đích `host` (API upload của app) cho `uploadFiles` (xem [Upload file](#upload-file-uploadfiles)) |
555
555
  | `close_on_back` | | Nút Back (Android) đóng mini app. Mặc định `true`; `false` khi mini app là nội dung chính của màn / tab |
556
556
  | `opaque_background` | | Tô nền đặc (trắng / `#09090B` theo `is_dark`) dưới mỗi WebView → web không tô nền không lộ mini app chạy ngầm phía sau. Mặc định `true`; `false` để nền trong suốt (container tự lo nền) |
557
557
  | `allow_embedded_miniapps` | | Mini app được nhúng mini app khác bằng iframe nạp bản trong máy (`getLocalMiniApp(app_id).entry_uri`) — vd Sảnh mở app con offline. iOS cho WebView đọc cả thư mục `miniapps/`. Mặc định `false` |
@@ -613,7 +613,7 @@ Mount **1 lần** ở gốc app, không unmount.
613
613
 
614
614
  ## Tích hợp API native
615
615
 
616
- Phần này hướng dẫn **Face ID / Touch ID**, **speech-to-text**, **vị trí hiện tại**, **upload file** và các API native do app chủ cung cấp. App chủ dùng `@retion-miniapp/react-native@0.10.0`; web dùng `@retion-miniapp/sdk@0.8.0` trở lên (upload file cần cả hai bản 0.10.0). Package tự xử lý các tính năng này qua bridge chung, không phụ thuộc Chat SDK và không cần gắn handler riêng.
616
+ Phần này hướng dẫn **Face ID / Touch ID**, **speech-to-text**, **vị trí hiện tại**, **upload file** và các API native do app chủ cung cấp. App chủ dùng `@retion-miniapp/react-native@0.10.1`; web dùng `@retion-miniapp/sdk@0.8.0` trở lên (upload file cần cả hai bản 0.10.0). Package tự xử lý các tính năng này qua bridge chung, không phụ thuộc Chat SDK và không cần gắn handler riêng.
617
617
 
618
618
  ### Thiết lập app chủ
619
619
 
@@ -680,7 +680,7 @@ Android: kiểm tra manifest sau khi hợp nhất có cấu hình tương đươ
680
680
  </queries>
681
681
  ```
682
682
 
683
- Nếu CLI chỉ dò dependency trực tiếp, bổ sung liên kết biometric, geolocation và image-picker vào `react-native.config.js`, giữ các cấu hình khác:
683
+ Nếu CLI chỉ dò dependency trực tiếp, bổ sung liên kết biometric, geolocation, image-picker, document picker và compressor vào `react-native.config.js`, giữ các cấu hình khác:
684
684
 
685
685
  ```js
686
686
  const path = require('path');
@@ -701,11 +701,21 @@ module.exports = {
701
701
  paths: [path.dirname(require.resolve('@retion-miniapp/react-native/package.json'))],
702
702
  })),
703
703
  },
704
+ '@react-native-documents/picker': {
705
+ root: path.dirname(require.resolve('@react-native-documents/picker/package.json', {
706
+ paths: [path.dirname(require.resolve('@retion-miniapp/react-native/package.json'))],
707
+ })),
708
+ },
709
+ 'react-native-compressor': {
710
+ root: path.dirname(require.resolve('react-native-compressor/package.json', {
711
+ paths: [path.dirname(require.resolve('@retion-miniapp/react-native/package.json'))],
712
+ })),
713
+ },
704
714
  },
705
715
  };
706
716
  ```
707
717
 
708
- Expo ≥52 là yêu cầu khai báo, không đảm bảo mọi tổ hợp native đã được kiểm tra. Package ghim biometric **3.0.1**, speech **1.1.1**, geolocation **3.4.0** và image-picker **8.2.1**. Không cài nhiều phiên bản native khác nhau; không xoá dependency trực tiếp nếu tính năng khác của app còn dùng. Với Expo 57, giữ bản vá `expo-speech-recognition@1.1.1` đang dùng trong Retion để sửa kiểu resolver Swift trước khi build.
718
+ Expo ≥52 là yêu cầu khai báo, không đảm bảo mọi tổ hợp native đã được kiểm tra. Package ghim biometric **3.0.1**, speech **1.1.1**, geolocation **3.4.0**, image-picker **8.2.1**, document picker **12.0.2** và compressor **1.13.0**. Không cài nhiều phiên bản native khác nhau; không xoá dependency trực tiếp nếu tính năng khác của app còn dùng. Với Expo 57, giữ bản vá `expo-speech-recognition@1.1.1` đang dùng trong Retion để sửa kiểu resolver Swift trước khi build.
709
719
 
710
720
  Cài package/plugin không sửa binary đã cài. Nếu thiếu module hoặc quyền, phải build/cài lại; OTA và reload không bổ sung native. Nếu binary đã đủ module/quyền tương thích, thay đổi JavaScript có thể chỉ cần reload.
711
721
 
@@ -901,60 +911,30 @@ const { files, failed } = await uploadFiles({
901
911
 
902
912
  `target: 'url'` chỉ nhận https, gửi multipart POST và đọc link ở `url_field` (dạng `a.b.c`) trong JSON trả về.
903
913
 
904
- **App chủ** — cấu hình qua `bridge.upload`:
914
+ **App chủ: không cần cấu hình.** Cài package, build lại native là có ngay:
905
915
 
906
- ```tsx
907
- import * as DocumentPicker from '@react-native-documents/picker';
908
- import { createDocumentPickerSource } from '@retion-miniapp/react-native';
916
+ | Có sẵn | Thư viện (package tự cài) |
917
+ | --- | --- |
918
+ | Nguồn `library`, `camera` | `react-native-image-picker` 8.2.1 |
919
+ | Nguồn `document` (mọi loại file: Files, iCloud, Drive…) | `@react-native-documents/picker` 12.0.2. Android tự copy `content://` ra file cục bộ |
920
+ | Nén ảnh (khi web truyền `process.image`, bỏ qua PNG/GIF) và nén video (luôn, mặc định `medium`) | `react-native-compressor` 1.13.0. Nén lỗi → upload bản gốc |
921
+ | Đích `url` (server của mini app) | Có sẵn |
909
922
 
923
+ **Chỉ một thứ do app quyết định: đích `host`.** Đây là API upload của chính app (domain, token, storage riêng), package không đoán được. App không khai báo thì web gọi `target: 'host'` nhận `NOT_SUPPORTED` và dùng `target: 'url'`. Muốn bật thì truyền một hàm upload, thường tái dùng hàm upload sẵn có của app:
924
+
925
+ ```tsx
910
926
  <MiniAppHost bridge={{ upload: {
911
- sources: {
912
- // Có sẵn: library, camera (react-native-image-picker 8.2.1). Ghi đè theo tên, hoặc null để tắt.
913
- document: createDocumentPickerSource(DocumentPicker), // mọi loại file
914
- library: async ({ accept, max_count, process }) => [/* UI gallery riêng của app */],
915
- },
916
- processors: {
917
- // Chạy cho file nguồn chưa tự nén (processed !== true), vd react-native-compressor.
918
- image: async (file, { image }) => ({ ...file, uri: compressedUri, size }),
919
- video: async (file, { video }) => ({ ...file, uri: compressedUri, size }),
920
- },
921
927
  targets: {
922
- // Đích 'url' có sẵn, không ghi đè được.
923
- host: async ({ file, target, onProgress, signal }) => ({ url: 'https://cdn/...' }),
928
+ host: async ({ file, onProgress, signal, caller }) => {
929
+ // file: { uri, name, mime_type, size? } — đã nén; caller.context: context lúc openMiniApp (vd page_id)
930
+ const url = await myAppUpload(file, caller.context.page_id, onProgress, signal);
931
+ return { url }; // trường thêm → web nhận trong response
932
+ },
924
933
  },
925
934
  } }} />
926
935
  ```
927
936
 
928
- **Type phía app chủ** (export từ `@retion-miniapp/react-native`)
929
-
930
- `MiniAppUploadOptions`: giá trị của `bridge.upload`
931
-
932
- | Prop | Type | Mô tả |
933
- | --- | --- | --- |
934
- | `sources` | `Record<string, MiniAppUploadSource \| null>` | Thêm / ghi đè nguồn theo tên. Có sẵn `library`, `camera`; `null` để tắt một nguồn có sẵn |
935
- | `processors` | `{ image?: MiniAppUploadProcessor; video?: MiniAppUploadProcessor }` | Nén file mà nguồn chưa tự nén (`processed !== true`) |
936
- | `targets` | `Record<string, MiniAppUploader>` | Đích upload theo tên, vd `host`. Có sẵn `url`, không ghi đè được |
937
-
938
- | Type | Chữ ký / dạng |
939
- | --- | --- |
940
- | `MiniAppUploadSource` | `(request: MiniAppUploadSourceRequest) => Promise<MiniAppPickedFile[]>`. Người dùng huỷ → trả `[]` |
941
- | `MiniAppUploadSourceRequest` | `{ accept: string[]; max_count: number; process: MiniAppUploadProcessOptions }` |
942
- | `MiniAppUploadProcessor` | `(file: MiniAppPickedFile, options: MiniAppUploadProcessOptions) => Promise<MiniAppPickedFile>` |
943
- | `MiniAppUploadProcessOptions` | `{ image?: { max_width?, max_height?, quality? }; video?: { max_duration?, quality? } }` |
944
- | `MiniAppPickedFile` | `{ uri: string; name: string; mime_type: string; size?: number; width?: number; height?: number; duration?: number; processed?: boolean }` |
945
- | `MiniAppUploader` | `(request: MiniAppUploadRequest) => Promise<{ url: string; [key: string]: unknown }>`. Trường thêm → web nhận trong `response` |
946
- | `MiniAppUploadRequest` | `{ file: MiniAppPickedFile; target: MiniAppUploadTarget; onProgress: (loaded, total) => void; signal: AbortSignal }` |
947
- | `MiniAppUploadTarget` | `{ target: string; params: Record<string, unknown> }` hoặc `MiniAppUrlUploadTarget` |
948
- | `MiniAppUrlUploadTarget` | `{ target: 'url'; url; headers; form_data; field_name; url_field }` |
949
-
950
- | Hàm | Mô tả |
951
- | --- | --- |
952
- | `createDocumentPickerSource(DocumentPicker)` | Nguồn mọi loại file từ `@react-native-documents/picker` (app tự cài). Map `accept` sang loại của picker; `accept` lạ → mở toàn bộ file rồi lọc lại |
953
- | `uploadToUrl` | Uploader multipart dùng cho đích `url`; dùng lại được trong uploader riêng |
954
-
955
- - Nguồn: `(request: { accept, max_count, process }) => Promise<PickedFile[]>`, huỷ trả `[]`. Lõi tự lọc lại theo `accept` sau khi chọn, nên nguồn chỉ cần dùng `accept` làm gợi ý.
956
- - `react-native-image-picker` đã nén ảnh (và video trên iOS) nên bỏ qua processor; video Android vẫn qua `processors.video` nếu có.
957
- - `max_size` kiểm tra sau khi xử lý.
937
+ `bridge.upload` còn cho ghi đè nếu thật sự cần (không bắt buộc): `sources` (thay / thêm nguồn theo tên, `null` để tắt), `processors` (`image` / `video`, thay bộ nén có sẵn).
958
938
 
959
939
  Plugin Expo thêm `NSPhotoLibraryUsageDescription` / `NSCameraUsageDescription` (tuỳ chỉnh qua `photoLibraryPermission`, `cameraPermission`). Upload không bị huỷ khi app xuống nền (picker hệ thống làm app vào background); chỉ huỷ khi đóng / reload mini app.
960
940
 
@@ -1,6 +1,6 @@
1
1
  ## Tích hợp API native
2
2
 
3
- Phần này hướng dẫn **Face ID / Touch ID**, **speech-to-text**, **vị trí hiện tại**, **upload file** và các API native do app chủ cung cấp. App chủ dùng `@retion-miniapp/react-native@0.10.0`; web dùng `@retion-miniapp/sdk@0.8.0` trở lên (upload cần cả hai bản 0.10.0). Package tự xử lý các tính năng này qua bridge chung, không phụ thuộc Chat SDK và không cần gắn handler riêng.
3
+ Phần này hướng dẫn **Face ID / Touch ID**, **speech-to-text**, **vị trí hiện tại**, **upload file** và các API native do app chủ cung cấp. App chủ dùng `@retion-miniapp/react-native@0.10.1`; web dùng `@retion-miniapp/sdk@0.8.0` trở lên (upload cần cả hai bản 0.10.0). Package tự xử lý các tính năng này qua bridge chung, không phụ thuộc Chat SDK và không cần gắn handler riêng.
4
4
 
5
5
  ### Thiết lập app chủ
6
6
 
@@ -61,7 +61,7 @@ Android: kiểm tra manifest sau khi hợp nhất có cấu hình tương đươ
61
61
  </queries>
62
62
  ```
63
63
 
64
- Nếu CLI chỉ dò dependency trực tiếp, bổ sung liên kết biometric, geolocation và image-picker vào `react-native.config.js`, giữ các cấu hình khác:
64
+ Nếu CLI chỉ dò dependency trực tiếp, bổ sung liên kết biometric, geolocation, image-picker, document picker và compressor vào `react-native.config.js`, giữ các cấu hình khác:
65
65
 
66
66
  ```js
67
67
  const path = require('path');
@@ -82,11 +82,21 @@ module.exports = {
82
82
  paths: [path.dirname(require.resolve('@retion-miniapp/react-native/package.json'))],
83
83
  })),
84
84
  },
85
+ '@react-native-documents/picker': {
86
+ root: path.dirname(require.resolve('@react-native-documents/picker/package.json', {
87
+ paths: [path.dirname(require.resolve('@retion-miniapp/react-native/package.json'))],
88
+ })),
89
+ },
90
+ 'react-native-compressor': {
91
+ root: path.dirname(require.resolve('react-native-compressor/package.json', {
92
+ paths: [path.dirname(require.resolve('@retion-miniapp/react-native/package.json'))],
93
+ })),
94
+ },
85
95
  },
86
96
  };
87
97
  ```
88
98
 
89
- Expo ≥52 là yêu cầu khai báo, không đảm bảo mọi tổ hợp native đã được kiểm tra. Package ghim biometric **3.0.1**, speech **1.1.1**, geolocation **3.4.0** và image-picker **8.2.1**. Không cài nhiều phiên bản native khác nhau; không xoá dependency trực tiếp nếu tính năng khác của app còn dùng. Với Expo 57, giữ bản vá `expo-speech-recognition@1.1.1` đang dùng trong Retion để sửa kiểu resolver Swift trước khi build.
99
+ Expo ≥52 là yêu cầu khai báo, không đảm bảo mọi tổ hợp native đã được kiểm tra. Package ghim biometric **3.0.1**, speech **1.1.1**, geolocation **3.4.0**, image-picker **8.2.1**, document picker **12.0.2** và compressor **1.13.0**. Không cài nhiều phiên bản native khác nhau; không xoá dependency trực tiếp nếu tính năng khác của app còn dùng. Với Expo 57, giữ bản vá `expo-speech-recognition@1.1.1` đang dùng trong Retion để sửa kiểu resolver Swift trước khi build.
90
100
 
91
101
  Cài package/plugin không sửa binary đã cài. Nếu thiếu module hoặc quyền, phải build/cài lại; OTA và reload không bổ sung native. Nếu binary đã đủ module/quyền tương thích, thay đổi JavaScript có thể chỉ cần reload.
92
102
 
@@ -414,59 +424,29 @@ const { files, failed } = await uploadFiles({
414
424
 
415
425
  `target: 'url'` chỉ nhận https, gửi multipart POST và đọc link ở `url_field` (dạng `a.b.c`) trong JSON trả về.
416
426
 
417
- **App chủ** — cấu hình qua `bridge.upload`:
427
+ **App chủ: không cần cấu hình.** Cài package, build lại native là có ngay:
418
428
 
419
- ```tsx
420
- import * as DocumentPicker from '@react-native-documents/picker';
421
- import { createDocumentPickerSource } from '@retion-miniapp/react-native';
429
+ | Có sẵn | Thư viện (package tự cài) |
430
+ | --- | --- |
431
+ | Nguồn `library`, `camera` | `react-native-image-picker` 8.2.1 |
432
+ | Nguồn `document` (mọi loại file: Files, iCloud, Drive…) | `@react-native-documents/picker` 12.0.2. Android tự copy `content://` ra file cục bộ |
433
+ | Nén ảnh (khi web truyền `process.image`, bỏ qua PNG/GIF) và nén video (luôn, mặc định `medium`) | `react-native-compressor` 1.13.0. Nén lỗi → upload bản gốc |
434
+ | Đích `url` (server của mini app) | Có sẵn |
422
435
 
436
+ **Chỉ một thứ do app quyết định: đích `host`.** Đây là API upload của chính app (domain, token, storage riêng), package không đoán được. App không khai báo thì web gọi `target: 'host'` nhận `NOT_SUPPORTED` và dùng `target: 'url'`. Muốn bật thì truyền một hàm upload, thường tái dùng hàm upload sẵn có của app:
437
+
438
+ ```tsx
423
439
  <MiniAppHost bridge={{ upload: {
424
- sources: {
425
- // Có sẵn: library, camera (react-native-image-picker 8.2.1). Ghi đè theo tên, hoặc null để tắt.
426
- document: createDocumentPickerSource(DocumentPicker), // mọi loại file
427
- library: async ({ accept, max_count, process }) => [/* UI gallery riêng của app */],
428
- },
429
- processors: {
430
- // Chạy cho file nguồn chưa tự nén (processed !== true), vd react-native-compressor.
431
- image: async (file, { image }) => ({ ...file, uri: compressedUri, size }),
432
- video: async (file, { video }) => ({ ...file, uri: compressedUri, size }),
433
- },
434
440
  targets: {
435
- // Đích 'url' có sẵn, không ghi đè được.
436
- host: async ({ file, target, onProgress, signal }) => ({ url: 'https://cdn/...' }),
441
+ host: async ({ file, onProgress, signal, caller }) => {
442
+ // file: { uri, name, mime_type, size? } — đã nén; caller.context: context lúc openMiniApp (vd page_id)
443
+ const url = await myAppUpload(file, caller.context.page_id, onProgress, signal);
444
+ return { url }; // trường thêm → web nhận trong response
445
+ },
437
446
  },
438
447
  } }} />
439
448
  ```
440
449
 
441
- **Type phía app chủ** (export từ `@retion-miniapp/react-native`)
442
-
443
- `MiniAppUploadOptions`: giá trị của `bridge.upload`
444
-
445
- | Prop | Type | Mô tả |
446
- | --- | --- | --- |
447
- | `sources` | `Record<string, MiniAppUploadSource \| null>` | Thêm / ghi đè nguồn theo tên. Có sẵn `library`, `camera`; `null` để tắt một nguồn có sẵn |
448
- | `processors` | `{ image?: MiniAppUploadProcessor; video?: MiniAppUploadProcessor }` | Nén file mà nguồn chưa tự nén (`processed !== true`) |
449
- | `targets` | `Record<string, MiniAppUploader>` | Đích upload theo tên, vd `host`. Có sẵn `url`, không ghi đè được |
450
-
451
- | Type | Chữ ký / dạng |
452
- | --- | --- |
453
- | `MiniAppUploadSource` | `(request: MiniAppUploadSourceRequest) => Promise<MiniAppPickedFile[]>`. Người dùng huỷ → trả `[]` |
454
- | `MiniAppUploadSourceRequest` | `{ accept: string[]; max_count: number; process: MiniAppUploadProcessOptions }` |
455
- | `MiniAppUploadProcessor` | `(file: MiniAppPickedFile, options: MiniAppUploadProcessOptions) => Promise<MiniAppPickedFile>` |
456
- | `MiniAppUploadProcessOptions` | `{ image?: { max_width?, max_height?, quality? }; video?: { max_duration?, quality? } }` |
457
- | `MiniAppPickedFile` | `{ uri: string; name: string; mime_type: string; size?: number; width?: number; height?: number; duration?: number; processed?: boolean }` |
458
- | `MiniAppUploader` | `(request: MiniAppUploadRequest) => Promise<{ url: string; [key: string]: unknown }>`. Trường thêm → web nhận trong `response` |
459
- | `MiniAppUploadRequest` | `{ file: MiniAppPickedFile; target: MiniAppUploadTarget; onProgress: (loaded, total) => void; signal: AbortSignal }` |
460
- | `MiniAppUploadTarget` | `{ target: string; params: Record<string, unknown> }` hoặc `MiniAppUrlUploadTarget` |
461
- | `MiniAppUrlUploadTarget` | `{ target: 'url'; url; headers; form_data; field_name; url_field }` |
462
-
463
- | Hàm | Mô tả |
464
- | --- | --- |
465
- | `createDocumentPickerSource(DocumentPicker)` | Nguồn mọi loại file từ `@react-native-documents/picker` (app tự cài). Map `accept` sang loại của picker; `accept` lạ → mở toàn bộ file rồi lọc lại |
466
- | `uploadToUrl` | Uploader multipart dùng cho đích `url`; dùng lại được trong uploader riêng |
467
-
468
- - Nguồn: `(request: { accept, max_count, process }) => Promise<PickedFile[]>`, huỷ trả `[]`. Lõi tự lọc lại theo `accept` sau khi chọn, nên nguồn chỉ cần dùng `accept` làm gợi ý.
469
- - `react-native-image-picker` đã nén ảnh (và video trên iOS) nên bỏ qua processor; video Android vẫn qua `processors.video` nếu có.
470
- - `max_size` kiểm tra sau khi xử lý.
450
+ `bridge.upload` còn cho ghi đè nếu thật sự cần (không bắt buộc): `sources` (thay / thêm nguồn theo tên, `null` để tắt), `processors` (`image` / `video`, thay bộ nén có sẵn).
471
451
 
472
452
  Plugin Expo thêm `NSPhotoLibraryUsageDescription` / `NSCameraUsageDescription` (tuỳ chỉnh qua `photoLibraryPermission`, `cameraPermission`). Upload không bị huỷ khi app xuống nền (picker hệ thống làm app vào background); chỉ huỷ khi đóng / reload mini app.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@retion-miniapp/react-native",
3
- "version": "0.10.0",
3
+ "version": "0.10.2",
4
4
  "description": "React Native host for Retion Mini Apps with built-in biometric authentication",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -89,8 +89,10 @@
89
89
  },
90
90
  "dependencies": {
91
91
  "@react-native-community/geolocation": "3.4.0",
92
+ "@react-native-documents/picker": "12.0.2",
92
93
  "expo-speech-recognition": "1.1.1",
93
94
  "react-native-biometrics": "3.0.1",
95
+ "react-native-compressor": "1.13.0",
94
96
  "react-native-image-picker": "8.2.1"
95
97
  }
96
98
  }