@retion-miniapp/react-native 0.9.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,11 +1,11 @@
1
1
  # Retion Mini App cho React Native
2
2
 
3
- Package chạy mini app web trong app React Native: tải bundle, lưu cục bộ, quản lý WebView và cung cấp API native qua bridge chung. Từ **0.8.0**, Face ID / Touch ID và nhận dạng giọng nói được xử lý trong package; app chủ không cần gắn handler riêng cho các API này.
3
+ Package chạy mini app web trong app React Native: tải bundle, lưu cục bộ, quản lý WebView và cung cấp API native qua bridge chung. Từ **0.8.0**, Face ID / Touch ID và nhận dạng giọng nói (từ **0.9.0** thêm vị trí hiện tại, từ **0.10.0** thêm upload file) được xử lý trong package; app chủ không cần gắn handler riêng cho các API này.
4
4
 
5
5
  ## Đọc theo thứ tự
6
6
 
7
7
  1. [Cài đặt, cấu hình và mở mini app](docs/MINIAPP_README.md).
8
- 2. [Tích hợp API native: Face ID / Touch ID và speech-to-text](docs/NATIVE_APIS.md).
8
+ 2. [Tích hợp API native: Face ID / Touch ID, speech-to-text, vị trí hiện tại và upload file](docs/NATIVE_APIS.md).
9
9
  3. [Nhận dạng giọng nói: quyền, hoạt động, API và quản lý phiên](docs/SPEECH.md).
10
10
  4. [Face ID / Touch ID: quyền, API và kết quả native](docs/BIOMETRICS.md).
11
11
 
@@ -14,7 +14,7 @@ Package chạy mini app web trong app React Native: tải bundle, lưu cục b
14
14
  | Thành phần | Trách nhiệm |
15
15
  | --- | --- |
16
16
  | App chủ | Cài package, cấu hình quyền và liên kết native, build ứng dụng, cấu hình dữ liệu mini app và mount `MiniAppHost` |
17
- | Mini App React Native | Tải/chạy mini app; thực hiện xác thực sinh trắc học, xin quyền speech, quản lý micro và chuyển kết quả/event về đúng WebView |
17
+ | Mini App React Native | Tải/chạy mini app; thực hiện xác thực sinh trắc học, lấy vị trí, chọn và upload file, xin quyền speech/vị trí, quản lý micro và chuyển kết quả/event về đúng WebView |
18
18
  | Web SDK `@retion-miniapp/sdk` | Cung cấp API Promise và đăng ký event cho mini app web |
19
19
  | Mini app web | Gọi API khi người dùng thao tác, kiểm tra kết quả/lỗi và cập nhật giao diện |
20
20
 
@@ -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.8.1 + Web SDK 0.8.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.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.
26
26
 
27
- Package tự cài `react-native-biometrics@3.0.1` và `expo-speech-recognition@1.1.1`. 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` 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).
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/app.plugin.js CHANGED
@@ -10,6 +10,12 @@ module.exports = function withMiniApp(config, options = {}) {
10
10
  config.modResults.NSLocationWhenInUseUsageDescription = options.locationPermission
11
11
  || config.modResults.NSLocationWhenInUseUsageDescription
12
12
  || 'Allow this app to access your location while you use it.';
13
+ config.modResults.NSPhotoLibraryUsageDescription = options.photoLibraryPermission
14
+ || config.modResults.NSPhotoLibraryUsageDescription
15
+ || 'Allow this app to access your photos to upload them.';
16
+ config.modResults.NSCameraUsageDescription = options.cameraPermission
17
+ || config.modResults.NSCameraUsageDescription
18
+ || 'Allow this app to use the camera to take photos and videos to upload.';
13
19
  return config;
14
20
  });
15
21
  config = withSpeechRecognition(config, {
package/dist/index.d.mts CHANGED
@@ -155,6 +155,81 @@ interface MiniAppNativeHandlers {
155
155
  params?: Record<string, unknown>;
156
156
  }, context: MiniAppHandlerContext) => Promise<void> | void;
157
157
  }
158
+ interface MiniAppUploadProcessOptions {
159
+ image?: {
160
+ max_width?: number;
161
+ max_height?: number; /** (0, 1]. */
162
+ quality?: number;
163
+ };
164
+ video?: {
165
+ max_duration?: number;
166
+ quality?: 'low' | 'medium' | 'high';
167
+ };
168
+ }
169
+ /** File đã chọn trong máy — chỉ host thấy, không gửi xuống web. */
170
+ interface MiniAppPickedFile {
171
+ uri: string;
172
+ name: string;
173
+ mime_type: string;
174
+ /** Byte. */
175
+ size?: number;
176
+ width?: number;
177
+ height?: number;
178
+ /** Giây (video). */
179
+ duration?: number;
180
+ /** Nguồn đã tự nén theo `process` → bỏ qua processors. */
181
+ processed?: boolean;
182
+ }
183
+ interface MiniAppUploadSourceRequest {
184
+ /** 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
+ accept: string[];
186
+ max_count: number;
187
+ process: MiniAppUploadProcessOptions;
188
+ }
189
+ /** Nguồn lấy file (UI chọn). Người dùng huỷ → trả []. */
190
+ type MiniAppUploadSource = (request: MiniAppUploadSourceRequest) => Promise<MiniAppPickedFile[]>;
191
+ /** Xử lý 1 file (vd nén bằng react-native-compressor), trả file mới. */
192
+ type MiniAppUploadProcessor = (file: MiniAppPickedFile, options: MiniAppUploadProcessOptions) => Promise<MiniAppPickedFile>;
193
+ /** Server của mini app: multipart POST, lấy link ở `url_field` (dạng a.b.c) của JSON trả về. */
194
+ interface MiniAppUrlUploadTarget {
195
+ target: 'url';
196
+ url: string;
197
+ headers: Record<string, string>;
198
+ form_data: Record<string, string>;
199
+ field_name: string;
200
+ url_field: string;
201
+ }
202
+ type MiniAppUploadTarget =
203
+ /** Đích app đăng ký (vd 'host') — `params` web truyền thêm, uploader tự hiểu. */
204
+ {
205
+ target: string;
206
+ params: Record<string, unknown>;
207
+ } | MiniAppUrlUploadTarget;
208
+ interface MiniAppUploadRequest {
209
+ file: MiniAppPickedFile;
210
+ target: MiniAppUploadTarget;
211
+ onProgress: (loaded: number, total: number) => void;
212
+ /** Web huỷ / đóng mini app → abort; uploader nên dừng request. */
213
+ signal: AbortSignal;
214
+ }
215
+ /** Upload 1 file, trả link (+ trường thêm → web nhận trong `response`). */
216
+ type MiniAppUploader = (request: MiniAppUploadRequest) => Promise<{
217
+ url: string;
218
+ [key: string]: unknown;
219
+ }>;
220
+ /**
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.
223
+ */
224
+ interface MiniAppUploadOptions {
225
+ sources?: Record<string, MiniAppUploadSource | null>;
226
+ processors?: {
227
+ image?: MiniAppUploadProcessor;
228
+ video?: MiniAppUploadProcessor;
229
+ };
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. */
231
+ targets?: Record<string, MiniAppUploader>;
232
+ }
158
233
  /** Kiểu rung web gửi qua haptic() — trùng tên trigger của react-native-haptic-feedback. */
159
234
  type MiniAppHapticType = 'selection' | 'impactLight' | 'impactMedium' | 'impactHeavy' | 'rigid' | 'soft' | 'notificationSuccess' | 'notificationWarning' | 'notificationError';
160
235
  /** Hành vi bridge phụ thuộc ứng dụng. */
@@ -171,6 +246,8 @@ interface MiniAppBridgeOptions {
171
246
  app_version?: string;
172
247
  /** Chức năng native web gọi qua SDK: thanh toán, in, mở màn hình. */
173
248
  handlers?: MiniAppNativeHandlers;
249
+ /** uploadFiles: nguồn chọn file, xử lý, đích upload. */
250
+ upload?: MiniAppUploadOptions;
174
251
  /**
175
252
  * Web → app: event riêng của web (không qua @retion-miniapp/sdk), web gửi bằng
176
253
  * `window.ReactNativeWebView.postMessage(...)`. `data` là chuỗi gốc web gửi. Gửi lại web bằng sendEventToWeb().
@@ -569,4 +646,58 @@ interface LocationResult {
569
646
  timestamp: number;
570
647
  }
571
648
 
572
- 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 MiniAppSplashProps, type MiniAppStorage, type MiniAppSyncResult, type MiniAppUpdate, type OpenMiniAppArgs, type ReactNativeBiometricsLike, type SpeechOptions, closeMiniApp, configureMiniApp, createMmkvStorage, createReactNativeBiometrics, createRnfsFileSystem, ensureMiniApp, getLocalMiniApp, getMiniAppCatalog, getMiniAppCatalogEntry, getMiniAppStatuses, getMiniAppUpdate, installBundledMiniApp, onMiniAppEvent, openMiniApp, pauseMiniApp, pauseMiniAppDownloads, preloadMiniApp, releaseSpeechFor, restoreMiniApp, resumeMiniApp, resumeMiniAppDownloads, sendEventToWeb, syncMiniAppCatalog, uninstallMiniApp, updateMiniApp, useMiniAppDownload, useMiniAppDownloadsPaused };
649
+ interface UploadedFile {
650
+ url: string;
651
+ name: string;
652
+ mime_type: string;
653
+ size?: number;
654
+ width?: number;
655
+ height?: number;
656
+ duration?: number;
657
+ /** Body JSON server trả về (target url) / dữ liệu thêm uploader của app trả. */
658
+ response?: unknown;
659
+ }
660
+ interface UploadFilesResult {
661
+ files: UploadedFile[];
662
+ failed: {
663
+ name: string;
664
+ code: string;
665
+ message: string;
666
+ }[];
667
+ }
668
+ interface UploadCapabilities {
669
+ sources: string[];
670
+ targets: string[];
671
+ max_count: number;
672
+ }
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
+ /** 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
+ declare const uploadToUrl: MiniAppUploader;
702
+
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 };
package/dist/index.d.ts CHANGED
@@ -155,6 +155,81 @@ interface MiniAppNativeHandlers {
155
155
  params?: Record<string, unknown>;
156
156
  }, context: MiniAppHandlerContext) => Promise<void> | void;
157
157
  }
158
+ interface MiniAppUploadProcessOptions {
159
+ image?: {
160
+ max_width?: number;
161
+ max_height?: number; /** (0, 1]. */
162
+ quality?: number;
163
+ };
164
+ video?: {
165
+ max_duration?: number;
166
+ quality?: 'low' | 'medium' | 'high';
167
+ };
168
+ }
169
+ /** File đã chọn trong máy — chỉ host thấy, không gửi xuống web. */
170
+ interface MiniAppPickedFile {
171
+ uri: string;
172
+ name: string;
173
+ mime_type: string;
174
+ /** Byte. */
175
+ size?: number;
176
+ width?: number;
177
+ height?: number;
178
+ /** Giây (video). */
179
+ duration?: number;
180
+ /** Nguồn đã tự nén theo `process` → bỏ qua processors. */
181
+ processed?: boolean;
182
+ }
183
+ interface MiniAppUploadSourceRequest {
184
+ /** 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
+ accept: string[];
186
+ max_count: number;
187
+ process: MiniAppUploadProcessOptions;
188
+ }
189
+ /** Nguồn lấy file (UI chọn). Người dùng huỷ → trả []. */
190
+ type MiniAppUploadSource = (request: MiniAppUploadSourceRequest) => Promise<MiniAppPickedFile[]>;
191
+ /** Xử lý 1 file (vd nén bằng react-native-compressor), trả file mới. */
192
+ type MiniAppUploadProcessor = (file: MiniAppPickedFile, options: MiniAppUploadProcessOptions) => Promise<MiniAppPickedFile>;
193
+ /** Server của mini app: multipart POST, lấy link ở `url_field` (dạng a.b.c) của JSON trả về. */
194
+ interface MiniAppUrlUploadTarget {
195
+ target: 'url';
196
+ url: string;
197
+ headers: Record<string, string>;
198
+ form_data: Record<string, string>;
199
+ field_name: string;
200
+ url_field: string;
201
+ }
202
+ type MiniAppUploadTarget =
203
+ /** Đích app đăng ký (vd 'host') — `params` web truyền thêm, uploader tự hiểu. */
204
+ {
205
+ target: string;
206
+ params: Record<string, unknown>;
207
+ } | MiniAppUrlUploadTarget;
208
+ interface MiniAppUploadRequest {
209
+ file: MiniAppPickedFile;
210
+ target: MiniAppUploadTarget;
211
+ onProgress: (loaded: number, total: number) => void;
212
+ /** Web huỷ / đóng mini app → abort; uploader nên dừng request. */
213
+ signal: AbortSignal;
214
+ }
215
+ /** Upload 1 file, trả link (+ trường thêm → web nhận trong `response`). */
216
+ type MiniAppUploader = (request: MiniAppUploadRequest) => Promise<{
217
+ url: string;
218
+ [key: string]: unknown;
219
+ }>;
220
+ /**
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.
223
+ */
224
+ interface MiniAppUploadOptions {
225
+ sources?: Record<string, MiniAppUploadSource | null>;
226
+ processors?: {
227
+ image?: MiniAppUploadProcessor;
228
+ video?: MiniAppUploadProcessor;
229
+ };
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. */
231
+ targets?: Record<string, MiniAppUploader>;
232
+ }
158
233
  /** Kiểu rung web gửi qua haptic() — trùng tên trigger của react-native-haptic-feedback. */
159
234
  type MiniAppHapticType = 'selection' | 'impactLight' | 'impactMedium' | 'impactHeavy' | 'rigid' | 'soft' | 'notificationSuccess' | 'notificationWarning' | 'notificationError';
160
235
  /** Hành vi bridge phụ thuộc ứng dụng. */
@@ -171,6 +246,8 @@ interface MiniAppBridgeOptions {
171
246
  app_version?: string;
172
247
  /** Chức năng native web gọi qua SDK: thanh toán, in, mở màn hình. */
173
248
  handlers?: MiniAppNativeHandlers;
249
+ /** uploadFiles: nguồn chọn file, xử lý, đích upload. */
250
+ upload?: MiniAppUploadOptions;
174
251
  /**
175
252
  * Web → app: event riêng của web (không qua @retion-miniapp/sdk), web gửi bằng
176
253
  * `window.ReactNativeWebView.postMessage(...)`. `data` là chuỗi gốc web gửi. Gửi lại web bằng sendEventToWeb().
@@ -569,4 +646,58 @@ interface LocationResult {
569
646
  timestamp: number;
570
647
  }
571
648
 
572
- 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 MiniAppSplashProps, type MiniAppStorage, type MiniAppSyncResult, type MiniAppUpdate, type OpenMiniAppArgs, type ReactNativeBiometricsLike, type SpeechOptions, closeMiniApp, configureMiniApp, createMmkvStorage, createReactNativeBiometrics, createRnfsFileSystem, ensureMiniApp, getLocalMiniApp, getMiniAppCatalog, getMiniAppCatalogEntry, getMiniAppStatuses, getMiniAppUpdate, installBundledMiniApp, onMiniAppEvent, openMiniApp, pauseMiniApp, pauseMiniAppDownloads, preloadMiniApp, releaseSpeechFor, restoreMiniApp, resumeMiniApp, resumeMiniAppDownloads, sendEventToWeb, syncMiniAppCatalog, uninstallMiniApp, updateMiniApp, useMiniAppDownload, useMiniAppDownloadsPaused };
649
+ interface UploadedFile {
650
+ url: string;
651
+ name: string;
652
+ mime_type: string;
653
+ size?: number;
654
+ width?: number;
655
+ height?: number;
656
+ duration?: number;
657
+ /** Body JSON server trả về (target url) / dữ liệu thêm uploader của app trả. */
658
+ response?: unknown;
659
+ }
660
+ interface UploadFilesResult {
661
+ files: UploadedFile[];
662
+ failed: {
663
+ name: string;
664
+ code: string;
665
+ message: string;
666
+ }[];
667
+ }
668
+ interface UploadCapabilities {
669
+ sources: string[];
670
+ targets: string[];
671
+ max_count: number;
672
+ }
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
+ /** 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
+ declare const uploadToUrl: MiniAppUploader;
702
+
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 };
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var hn=Object.create;var be=Object.defineProperty;var mn=Object.getOwnPropertyDescriptor;var An=Object.getOwnPropertyNames;var wn=Object.getPrototypeOf,yn=Object.prototype.hasOwnProperty;var Mn=(e,t)=>{for(var n in t)be(e,n,{get:t[n],enumerable:!0})},lt=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of An(t))!yn.call(e,o)&&o!==n&&be(e,o,{get:()=>t[o],enumerable:!(r=mn(t,o))||r.enumerable});return e};var fe=(e,t,n)=>(n=e!=null?hn(wn(e)):{},lt(t||!e||!e.__esModule?be(n,"default",{value:e,enumerable:!0}):n,e)),vn=e=>lt(be({},"__esModule",{value:!0}),e);var Vn={};Mn(Vn,{DefaultMiniAppSplash:()=>nt,MINIAPP_PLATFORM_URL:()=>_e,MiniAppHost:()=>ln,MiniAppHostError:()=>g,closeMiniApp:()=>pe,configureMiniApp:()=>dt,createMmkvStorage:()=>ht,createReactNativeBiometrics:()=>Ue,createRnfsFileSystem:()=>ft,ensureMiniApp:()=>Me,getLocalMiniApp:()=>x,getMiniAppCatalog:()=>sn,getMiniAppCatalogEntry:()=>le,getMiniAppStatuses:()=>Gt,getMiniAppUpdate:()=>et,installBundledMiniApp:()=>$t,onMiniAppEvent:()=>Yt,openMiniApp:()=>qt,pauseMiniApp:()=>en,pauseMiniAppDownloads:()=>nn,preloadMiniApp:()=>Ht,releaseSpeechFor:()=>z,restoreMiniApp:()=>Zt,resumeMiniApp:()=>tn,resumeMiniAppDownloads:()=>rn,sendEventToWeb:()=>Ut,syncMiniAppCatalog:()=>$e,uninstallMiniApp:()=>Xt,updateMiniApp:()=>on,useMiniAppDownload:()=>Ne,useMiniAppDownloadsPaused:()=>Kt});module.exports=vn(Vn);var _e="https://retion-miniapp-platform.vercel.app",se=null,ut=new Set,dt=e=>{se=e,ut.forEach(t=>t())},R=()=>{if(!se)throw new Error("[miniapp] Ch\u01B0a g\u1ECDi configureMiniApp()");return se},gt=e=>{ut.add(e),se&&e()},$=(...e)=>{se!=null&&se.debug&&console.log("[miniapp]",...e)};var ft=(e,t)=>({document_dir:e.DocumentDirectoryPath,cache_dir:e.CachesDirectoryPath,exists:n=>e.exists(n),mkdir:n=>e.mkdir(n),remove:n=>e.unlink(n).catch(()=>{}),listDir:n=>e.readDir(n).then(r=>r.map(o=>o.name)).catch(()=>[]),sha256:n=>e.hash(n,"sha256"),unzip:async(n,r)=>{await t(n,r)},download:({url:n,to_file:r,onProgress:o})=>{let{jobId:s,promise:a}=e.downloadFile({fromUrl:n,toFile:r,progressInterval:250,begin:()=>{},progress:({bytesWritten:c,contentLength:i})=>o==null?void 0:o(c,i)});return{promise:a.then(({statusCode:c})=>({status:c})),cancel:()=>e.stopDownload(s)}}}),ht=e=>({getString:t=>e.getString(t),setString:(t,n)=>e.set(t,n)});var f=fe(require("react")),b=require("react-native"),pn=fe(require("react-native-webview"));var he=require("react-native");var Ue=e=>({getAvailability:()=>e.isSensorAvailable(),authenticate:({reason:t,cancelButtonText:n})=>e.simplePrompt({promptMessage:t,cancelButtonText:n,fallbackPromptMessage:""})}),xe,Je=()=>(xe||(xe=import("react-native-biometrics").then(({default:e})=>Ue(new e({allowDeviceCredentials:!1}))).catch(e=>{throw xe=void 0,new g("NOT_SUPPORTED",`Biometric native module unavailable: ${e instanceof Error?e.message:String(e)}`)})),xe);var W=require("react-native");var mt=e=>{var n,r,o;if(e!==void 0&&(e===null||typeof e!="object"||Array.isArray(e)))throw new g("INVALID_PARAMS","Tu\u1EF3 ch\u1ECDn v\u1ECB tr\xED ph\u1EA3i l\xE0 object");let t=e!=null?e:{};if(t.enableHighAccuracy!==void 0&&typeof t.enableHighAccuracy!="boolean")throw new g("INVALID_PARAMS","enableHighAccuracy ph\u1EA3i l\xE0 boolean");for(let[s,a,c]of[["timeout",1,6e4],["maximumAge",0,864e5]]){let i=t[s];if(i!==void 0&&(typeof i!="number"||!Number.isFinite(i)||i<a||i>c))throw new g("INVALID_PARAMS",`${s} ph\u1EA3i n\u1EB1m trong kho\u1EA3ng ${a}\u2013${c} ms`)}return{enableHighAccuracy:(n=t.enableHighAccuracy)!=null?n:!1,timeout:(r=t.timeout)!=null?r:15e3,maximumAge:(o=t.maximumAge)!=null?o:0}},At=(e,t=()=>!0)=>new Promise((n,r)=>{let o=!1,s=(i,p)=>{o||(o=!0,clearTimeout(a),i?r(i):n(p))},a=setTimeout(()=>s(new g("TIMEOUT","H\u1EBFt th\u1EDDi gian ch\u1EDD c\u1EA5p quy\u1EC1n/l\u1EA5y v\u1ECB tr\xED")),12e4+e.timeout),c=()=>o?!1:t()?!0:(s(new g("CANCELLED","Mini app kh\xF4ng c\xF2n ho\u1EA1t \u0111\u1ED9ng")),!1);(async()=>{if(!c())return;let i;try{i=(await import("@react-native-community/geolocation")).default}catch{throw new g("NOT_SUPPORTED","Ch\u01B0a c\xF3 module v\u1ECB tr\xED trong b\u1EA3n native")}if(c()){if(W.Platform.OS==="android"){let p=W.PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,y=W.PermissionsAndroid.PERMISSIONS.ACCESS_COARSE_LOCATION,d=await W.PermissionsAndroid.check(p);if(!c())return;let M=d||await W.PermissionsAndroid.check(y);if(!c())return;if(!d&&!M){let A=await W.PermissionsAndroid.requestMultiple([p,y]);if(!c())return;if(A[p]!==W.PermissionsAndroid.RESULTS.GRANTED&&A[y]!==W.PermissionsAndroid.RESULTS.GRANTED)throw new g("PERMISSION_DENIED","Ch\u01B0a c\u1EA5p quy\u1EC1n truy c\u1EADp v\u1ECB tr\xED")}}c()&&i.getCurrentPosition(p=>{c()&&s(void 0,p)},p=>{var d;if(!c())return;let y=(d={1:"PERMISSION_DENIED",2:"POSITION_UNAVAILABLE",3:"TIMEOUT"}[p.code])!=null?d:"LOCATION_ERROR";s(new g(y,p.message))},e)}})().catch(i=>s(i))});var wt=require("react-native");var G,qe=e=>{var t;if(G===e&&(G=void 0,e.subscriptions.forEach(n=>n.remove()),e.started&&wt.Platform.OS==="ios"))try{(t=e.native)==null||t.setAudioSessionActiveIOS(!1,{notifyOthersOnDeactivation:!0})}catch{}},yt=async(e,t,n,r=()=>!0)=>{var s,a,c,i,p;if(G)throw new g("BUSY","Micro \u0111ang \u0111\u01B0\u1EE3c mini app kh\xE1c s\u1EED d\u1EE5ng");if(!r())throw new g("CANCELLED","Mini app kh\xF4ng c\xF2n ho\u1EA1t \u0111\u1ED9ng");let o={owner:e,emit:n,cancelled:!1,started:!1,subscriptions:[]};G=o;try{let y;try{y=await import("expo-speech-recognition")}catch{throw new g("NOT_SUPPORTED","Ch\u01B0a c\xF3 module nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i trong b\u1EA3n native")}let d=y.ExpoSpeechRecognitionModule;if(o.native=d,o.cancelled||!r())throw new g("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");let M=await d.requestPermissionsAsync();if(o.cancelled||!r())throw new g("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");if(!M.granted)throw new g("PERMISSION_DENIED","Ch\u01B0a c\u1EA5p quy\u1EC1n micro / nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i");if(await d.getStateAsync()!=="inactive")throw new g("BUSY","Nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i \u0111ang \u0111\u01B0\u1EE3c t\xEDnh n\u0103ng kh\xE1c s\u1EED d\u1EE5ng");if(o.cancelled||!r())throw new g("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");o.subscriptions.push(d.addListener("result",A=>{var w,C;G!==o||o.cancelled||n(A.isFinal?"speech.final":"speech.partial",{...A,text:(C=(w=A.results[0])==null?void 0:w.transcript)!=null?C:""})}),d.addListener("error",A=>{G===o&&!o.cancelled&&n("speech.error",{...A,code:A.error})}),d.addListener("end",()=>{G===o&&(qe(o),n("speech.end"))})),o.started=!0,d.start({lang:(s=t.lang)!=null?s:"vi-VN",continuous:(a=t.continuous)!=null?a:!0,interimResults:(c=t.interimResults)!=null?c:!0,addsPunctuation:(i=t.addsPunctuation)!=null?i:!0,requiresOnDeviceRecognition:(p=t.requiresOnDeviceRecognition)!=null?p:!1,iosCategory:{category:y.AVAudioSessionCategory.playAndRecord,categoryOptions:[y.AVAudioSessionCategoryOptions.defaultToSpeaker,y.AVAudioSessionCategoryOptions.allowBluetooth],mode:y.AVAudioSessionMode.measurement}})}catch(y){throw qe(o),y}},Mt=e=>{let t=G;if(!(!t||t.owner!==e)){if(!t.started){t.cancelled=!0;return}t.native.stop()}},z=e=>{let t=G;if(!(!t||t.owner!==e||t.cancelled)&&(t.cancelled=!0,t.started))try{t.native.abort()}catch{qe(t)}};var Pe=1,g=class extends Error{constructor(n,r){super(r);this.code=n}},vt=e=>{try{let t=JSON.parse(e);return(t==null?void 0:t.__retion)===Pe&&typeof t.method=="string"?t:null}catch{return null}},me=e=>`window.__RETION_MINIAPP__ && window.__RETION_MINIAPP__.receive(${JSON.stringify(e)}); true;`,St=(e,t)=>me({id:e,result:t}),bt=(e,t)=>me({id:e,error:{code:t.code,message:t.message}}),_t=(e,t)=>me({event:e,data:t}),je=e=>me({event:"context",data:e});var xt=()=>`(function () {
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 () {
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: ${Pe}, method: 'log', level: level, text: parts.join(' ') }));
11
+ window.ReactNativeWebView && window.ReactNativeWebView.postMessage(JSON.stringify({ __retion: ${Fe}, 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;`,Et=()=>`(function () {
22
+ })(); true;`,Yt=()=>`(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: ${Pe}, method: 'touchAtTop', at_top: at_top }));
33
+ window.ReactNativeWebView && window.ReactNativeWebView.postMessage(JSON.stringify({ __retion: ${Fe}, method: 'touchAtTop', at_top: at_top }));
34
34
  }
35
35
  document.addEventListener('touchstart', function (e) { report(atTop(e.target)); }, { capture: true, passive: true });
36
36
  // Cu\u1ED9n r\u1EDDi \u0111\u1EA7u trang \u2192 b\xE1o ngay, kh\xF4ng \u0111\u1EE3i l\u1EA7n ch\u1EA1m sau (tr\xE1nh host d\xF9ng gi\xE1 tr\u1ECB c\u0169 "\u0111ang \u1EDF \u0111\u1EA7u").
@@ -38,8 +38,8 @@
38
38
  var el = e.target === document ? document.documentElement : e.target;
39
39
  if (el && el.scrollTop > 0) { report(false); }
40
40
  }, { capture: true, passive: true });
41
- })(); true;`,Rt=e=>me({event:e}),Pt=(e,t)=>{let n=Tt(t);return`try { history.replaceState(history.state, '', location.pathname + ${JSON.stringify(n?`?${n}`:"")} + location.hash); } catch (e) {}
42
- ${je(e)}`},Tt=e=>Object.entries(e).filter(([,t])=>t!=null&&t!=="").map(([t,n])=>`${encodeURIComponent(t)}=${encodeURIComponent(String(n))}`).join("&"),Ot=(e,t={})=>{let n=Tt(t);return`window.__RETION_MINIAPP_HOST__ = { protocol: ${Pe} };
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} };
43
43
  window.__RETION_MINIAPP_CONTEXT__ = ${JSON.stringify(e)};
44
44
  ${n?`try { history.replaceState(history.state, '', location.pathname + '?' + ${JSON.stringify(n)} + location.hash); } catch (e) {}`:""}
45
- true;`},Ct={partner:"partner_token",chatbox:"chatbox_token"},It=(e,t)=>{let n={...e};for(let r of Object.values(Ct))t.includes(r)||delete n[r];return n},He=new Set,Ee=async(e,t)=>{if(He.has(e))throw new g("BUSY",`${e} \u0111ang ch\u1EA1y \u2014 ch\u1EDD l\u01B0\u1EE3t tr\u01B0\u1EDBc xong`);He.add(e);try{return await t()}finally{He.delete(e)}},Sn=new Set(["selection","impactLight","impactMedium","impactHeavy","rigid","soft","notificationSuccess","notificationWarning","notificationError"]),Re=(e,t)=>{if(typeof e!="string"||!e)throw new g("INVALID_PARAMS",`Thi\u1EBFu ${t}`);return e},Lt=async({method:e,params:t},{getHostData:n,getPermissions:r,is_dark:o,close:s,app_id:a,instance_id:c,options:i,emit:p,isActive:y})=>{var w,C,T,N,u,I,ue,Z,ve;let d=i==null?void 0:i.handlers,M={app_id:a,instance_id:c,close:s},A=()=>new g("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF \u1EE9ng d\u1EE5ng n\xE0y`);switch(e){case"getCurrentLocation":{let h=mt(t);return Ee(e,()=>At(h,y))}case"speech.start":{if(!p)throw A();let h={};if((t==null?void 0:t.lang)!==void 0){if(typeof t.lang!="string"||!/^[a-zA-Z]{2,8}(-[a-zA-Z0-9]{1,8})*$/.test(t.lang))throw new g("INVALID_PARAMS","lang ph\u1EA3i l\xE0 m\xE3 ng\xF4n ng\u1EEF nh\u01B0 vi-VN");h.lang=t.lang}for(let S of["continuous","interimResults","addsPunctuation","requiresOnDeviceRecognition"])if((t==null?void 0:t[S])!==void 0){if(typeof t[S]!="boolean")throw new g("INVALID_PARAMS",`${S} ph\u1EA3i l\xE0 boolean`);h[S]=t[S]}return yt(c,h,p,y)}case"speech.stop":return Mt(c);case"getBiometricAvailability":return((w=i==null?void 0:i.biometrics)!=null?w:await Je()).getAvailability();case"authenticateBiometric":{let h=Re(t==null?void 0:t.reason,"reason").trim();if(!h||h.length>200)throw new g("INVALID_PARAMS","reason must contain 1\u2013200 characters");let S=t==null?void 0:t.cancelButtonText;if(S!==void 0&&(typeof S!="string"||!S.trim()||S.length>80))throw new g("INVALID_PARAMS","Invalid cancelButtonText");return Ee(e,async()=>{var ie;return((ie=i==null?void 0:i.biometrics)!=null?ie:await Je()).authenticate({reason:h,cancelButtonText:S})})}case"requestPayment":{let h=d==null?void 0:d.requestPayment;if(!h)throw A();let S=t==null?void 0:t.amount;if(typeof S!="number"||!Number.isFinite(S)||S<=0)throw new g("INVALID_PARAMS","amount ph\u1EA3i l\xE0 s\u1ED1 > 0");let U={...t,amount:S,currency:Re(t==null?void 0:t.currency,"currency")};return Ee(e,()=>h(U,M))}case"printImage":{let h=d==null?void 0:d.printImage;if(!h)throw A();let S=Re(t==null?void 0:t.image,"image");await Ee(e,()=>h({image:S},M));return}case"openScreen":if(!(d!=null&&d.openScreen))throw A();await d.openScreen({screen:Re(t==null?void 0:t.screen,"screen"),params:t==null?void 0:t.params},M);return;case"closeApp":s();return;case"openWebview":{let h=String((C=t==null?void 0:t.url)!=null?C:"");if(!/^https?:\/\//i.test(h))throw new g("INVALID_PARAMS","url ph\u1EA3i l\xE0 http(s)");await(i!=null&&i.openUrl?i.openUrl(h):he.Linking.openURL(h));return}case"openLink":{let h=String((T=t==null?void 0:t.url)!=null?T:"").trim();if(!/^[a-z][a-z0-9+.-]*:/i.test(h)||/^(javascript|file|data|about|blob):/i.test(h))throw new g("INVALID_PARAMS","url kh\xF4ng h\u1EE3p l\u1EC7");try{await(i!=null&&i.openUrl?i.openUrl(h):he.Linking.openURL(h))}catch(S){throw new g("NOT_SUPPORTED",String((u=(N=S==null?void 0:S.message)!=null?N:S)!=null?u:"Kh\xF4ng m\u1EDF \u0111\u01B0\u1EE3c link"))}return}case"showToast":(ue=i==null?void 0:i.showToast)==null||ue.call(i,String((I=t==null?void 0:t.message)!=null?I:""));return;case"haptic":{let h=Sn.has(t==null?void 0:t.type)?t.type:"selection";(Z=i==null?void 0:i.haptic)==null||Z.call(i,h);return}case"getSystemInfo":return{platform:he.Platform.OS==="ios"?"ios":"android",appVersion:(ve=i==null?void 0:i.app_version)!=null?ve:"",theme:o?"dark":"light"};case"getAccessToken":{let h=n().access_token;if(!h)throw new g("HOST_ERROR","Mini app ch\u01B0a c\xF3 token cho page n\xE0y");return h}case"getToken":{let h=t==null?void 0:t.type;if(h==="access"){let ie=n().access_token;if(!ie)throw new g("HOST_ERROR","Mini app ch\u01B0a c\xF3 token cho page n\xE0y");return ie}if(h!=="partner"&&h!=="chatbox")throw new g("HOST_ERROR",`Lo\u1EA1i token kh\xF4ng h\u1EE3p l\u1EC7: ${String(h)}`);let S=Ct[h];if(!r().includes(S))throw new g("PERMISSION_DENIED",`Mini app ch\u01B0a \u0111\u01B0\u1EE3c c\u1EA5p quy\u1EC1n ${S} (Console \u2192 Quy\u1EC1n l\u1EA5y token)`);let U=h==="partner"?n().partner_token:n().chatbox_token;if(!U)throw new g("HOST_ERROR",`Kh\xF4ng c\xF3 ${S}`);return U}case"getUserInfo":{let h=n().user;if(!h)throw new g("HOST_ERROR","Kh\xF4ng l\u1EA5y \u0111\u01B0\u1EE3c th\xF4ng tin nh\xE2n vi\xEAn");return h}case"getPageInfo":{let h=n().page;if(!h)throw new g("HOST_ERROR","Kh\xF4ng l\u1EA5y \u0111\u01B0\u1EE3c th\xF4ng tin page");return h}case"sendMessage":case"insertText":throw new g("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF phi\xEAn b\u1EA3n app n\xE0y`);default:throw new g("NOT_SUPPORTED",`API kh\xF4ng t\u1ED3n t\u1EA1i: ${e}`)}};var ze=e=>`bundle:${e}`,Ke=()=>`${R().file_system.document_dir}/miniapps`,Ye=Ke,Ge=(e,t,n="index.html",r=!1,o=[])=>{let s=`${Ye()}/${e}/${t}`;return{app_id:e,version:t,dir:s,entry_uri:`file://${s}/${n}`,context_update:r,permissions:o}},We=e=>{var t;R().storage.setString(ze(e.app_id),JSON.stringify({version:e.version,entry:e.entry,context_update:!!e.context_update,permissions:(t=e.permissions)!=null?t:[]}))},bn=(e,t)=>/^https?:\/\//.test(t)?t:`${e.replace(/[^/]*$/,"")}${t}`,x=e=>{let t=R().storage.getString(ze(e));if(!t)return null;try{let{version:n,entry:r,context_update:o,permissions:s}=JSON.parse(t);return Ge(e,n,r,!!o,Array.isArray(s)?s:[])}catch{return null}},Q=e=>R().file_system.exists(e.entry_uri.replace("file://","")),Qe=async e=>{let t=x(e.app_id);return(t==null?void 0:t.version)===e.version&&await Q(t)},Dt=async(e,t)=>{let n=R().file_system,r=`${Ye()}/${e}`,o=await n.listDir(r).catch(()=>[]);await Promise.all(o.filter(s=>!t.includes(s)).map(s=>n.remove(`${r}/${s}`).catch(()=>{})))},Nt=async e=>{var t;await((t=we[e])==null?void 0:t.catch(()=>{})),R().storage.setString(ze(e),""),await R().file_system.remove(`${Ye()}/${e}`).catch(()=>{})},ce=class extends Error{constructor(){super("cancelled"),this.name="MiniAppInstallCancelled"}},we={},Bt=(e,t)=>{var s;let r=((s=we[e])!=null?s:Promise.resolve()).catch(()=>{}).then(t),o=r.catch(()=>{});return we[e]=o,o.then(()=>{we[e]===o&&delete we[e]}),r},_n=(e,t)=>{var o,s;let n=e.split(".").map(a=>parseInt(a,10)||0),r=t.split(".").map(a=>parseInt(a,10)||0);for(let a=0;a<Math.max(n.length,r.length);a++){let c=((o=n[a])!=null?o:0)-((s=r[a])!=null?s:0);if(c)return c}return 0},$t=({manifest:e,zip_path:t})=>Bt(e.app_id,async()=>{var s;let n=R().file_system,r=x(e.app_id);if(r&&_n(r.version,e.version)>=0&&await Q(r))return r;if(e.sha256&&n.sha256&&await n.sha256(t)!==e.sha256)throw new Error("sha256 mismatch");let o=Ge(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),We(e),$("\u0111\xE3 c\xE0i b\u1EA3n \u0111\xF3ng s\u1EB5n",e.app_id,e.version),Dt(e.app_id,[e.version,r==null?void 0:r.version].filter(Boolean)),o}),Xe=(e,{base_url:t,onProgress:n}={})=>{let r=R().file_system,o=null,s=!1,a=`${r.cache_dir}/${e.app_id}-${e.version}.zip`,c=()=>{if(s)throw new ce},i=async()=>{var d;c();let p=x(e.app_id);if((p==null?void 0:p.version)===e.version&&await r.exists(p.dir))return We(e),x(e.app_id);c();let y=r.download({url:t?bn(t,e.bundle_url):e.bundle_url,to_file:a,onProgress:(M,A)=>{var C;let w=A>0?A:(C=e.size)!=null?C:0;w>0&&(n==null||n(Math.min(1,M/w)))}});o=y;try{let{status:M}=await y.promise;if(c(),M!==200)throw new Error(`bundle ${M}`);if(e.sha256)if(r.sha256){if(await r.sha256(a)!==e.sha256)throw new Error("sha256 mismatch")}else $("b\u1ECF qua ki\u1EC3m tra sha256 (file_system kh\xF4ng c\xF3 sha256)",e.app_id);c();let A=Ge(e.app_id,e.version,e.entry,!!e.context_update,(d=e.permissions)!=null?d:[]);return await r.remove(A.dir).catch(()=>{}),await r.mkdir(A.dir),await r.unzip(a,A.dir),We(e),Dt(e.app_id,[e.version,p==null?void 0:p.version].filter(Boolean)),A}catch(M){throw s?new ce:M}finally{o=null,r.remove(a).catch(()=>{})}};return{promise:Bt(e.app_id,i),cancel:()=>{s=!0,o==null||o.cancel()}}},Ae={},xn=__DEV__?0:60*1e3,kt={},Vt=(e,t)=>{var r,o;let n=x(e);return n&&Date.now()-((r=kt[t])!=null?r:0)<xn?Promise.resolve(n):((o=Ae[e])!=null||(Ae[e]=(async()=>{let s=await fetch(t,{headers:{"Cache-Control":"no-cache"}});if(!s.ok)throw new Error(`manifest ${s.status}`);let a=await s.json(),c=await Xe(a,{base_url:t}).promise;return kt[t]=Date.now(),c})().catch(s=>(console.warn("[miniapp] sync failed",e,s==null?void 0:s.message),x(e))).finally(()=>{Ae[e]=void 0})),Ae[e])};var Te=new Map,Ft=(e,t)=>(Te.set(e,t),()=>{Te.get(e)===t&&Te.delete(e)}),Ut=(e,t)=>{let n=Te.get(e);return n?n(t):!1};var Oe=require("react"),Ce=e=>{let t=e,n=new Set;return{getState:()=>t,setState:r=>{let o=typeof r=="function"?r(t):r;t={...t,...o},n.forEach(s=>s())},subscribe:r=>(n.add(r),()=>{n.delete(r)})}},K=(e,t,n=Object.is)=>{let r=(0,Oe.useRef)(null),o=()=>{let s=e.getState(),a=r.current;if(a&&a.state===s&&a.selector===t)return a.value;let c=t(s),i=a&&n(a.value,c)?a.value:c;return r.current={state:s,selector:t,value:i},i};return(0,Oe.useSyncExternalStore)(e.subscribe,o)};var V=Ce({active_key:null,instances:{}}),Jt=({app:e,instance_id:t,context:n={},url_params:r={},host_data:o={}},s)=>{var c;let a=(c=R().keep_alive)==null?void 0:c.max_webviews;V.setState(i=>{let p=t!=null?t:e.app_id,y={...i.instances,[p]:{key:p,app:e,context:n,url_params:r,host_data:o,last_used_at:Date.now()}},d=Object.keys(y);return a&&a>0&&d.length>a&&d.filter(M=>M!==p).sort((M,A)=>y[M].last_used_at-y[A].last_used_at).slice(0,d.length-a).forEach(M=>{delete y[M]}),s?{active_key:p,instances:y}:{instances:y}})},qt=e=>Jt(e,!0),Ht=e=>Jt(e,!1),pe=()=>V.setState({active_key:null}),Ie=e=>{V.setState(t=>{if(t.active_key===e||!t.instances[e])return{};let n={...t.instances};return delete n[e],{instances:n}})};var jt="catalog",En="paused_apps",Rn="removed_apps",Pn=10*1e3,Tn=2,On=3e3,Cn=()=>{var e;try{return JSON.parse((e=R().storage.getString(jt))!=null?e:"{}")}catch{return{}}},_=Ce({catalog:{},downloads:{},pause_reasons:[],updates:{},apply_ticks:{}}),Wt=e=>{var t;return!!((t=R().manual_update)!=null&&t.includes(e))},De=new Set,zt=e=>{let t=new Set,n=()=>R().storage.setString(e,JSON.stringify([...t]));return{has:r=>t.has(r),values:()=>[...t],add:r=>t.has(r)?!1:(t.add(r),n(),!0),delete:r=>t.delete(r)?(n(),!0):!1,load:()=>{var r;t.clear();try{let o=JSON.parse((r=R().storage.getString(e))!=null?r:"[]");Array.isArray(o)&&o.forEach(s=>{typeof s=="string"&&t.add(s)})}catch{}}}},H=zt(En),re=zt(Rn);gt(()=>{H.load(),re.load();let e=Cn(),t={};Object.keys(e).filter(n=>!re.has(n)).forEach(n=>{let r=x(n);r?t[n]={status:"installed",progress:1,version:r.version,has_local:!0}:H.has(n)&&(t[n]={status:"paused",progress:0,version:e[n].version,has_local:!1})}),_.setState({catalog:e,downloads:t})});var Ne=e=>K(_,t=>e?t.downloads[e]:void 0),Kt=()=>K(_,e=>e.pause_reasons.length>0),q=(...e)=>$("queue",...e),O=[],X={},v=null,Le=new Set,ae={},Ze=new Set,te=e=>{Ze.forEach(t=>{try{t(e)}catch(n){console.warn("[miniapp-queue] event listener error",n==null?void 0:n.message)}})},Yt=e=>(Ze.add(e),()=>{Ze.delete(e)}),Gt=()=>_.getState().downloads,D=(e,t)=>{let n=!!x(e),r=_.getState().downloads[e],o=t.status==="downloading"&&n?"updating":t.status,s={...r!=null?r:{status:"queued",progress:0},...t,...o?{status:o}:{},has_local:n};_.setState(a=>({downloads:{...a.downloads,[e]:s}})),(r==null?void 0:r.status)!==s.status||(r==null?void 0:r.version)!==s.version||(r==null?void 0:r.has_local)!==s.has_local?te({type:"status_change",app_id:e,state:s}):r.progress!==s.progress&&te({type:"progress",app_id:e,progress:s.progress,version:s.version})},ke=(e,t)=>{var n;(n=ae[e])==null||n.forEach(r=>r(t)),delete ae[e]},In=()=>_.getState().pause_reasons.length>0,ne=e=>{var c;if(v)return;let t=e?O.indexOf(e):In()?-1:O.findIndex(i=>!H.has(i));if(t<0||t>=O.length)return;let[n]=O.splice(t,1),r=_.getState().catalog[n];if(!r){ke(n,x(n)),ne();return}let o=Date.now();X[n]=((c=X[n])!=null?c:0)+1,D(n,{status:"downloading",progress:0,version:r.version,error:void 0});let s=0,a=Xe(r,{onProgress:i=>{let p=Math.floor(i*100);p!==s&&(s=p,D(n,{progress:p/100,version:r.version}))}});v={app_id:n,handle:a,forced:!!e},q("start",n,r.version,e?"(forced)":""),a.promise.then(i=>{q("installed",n,r.version,`${Date.now()-o}ms`),D(n,{status:"installed",progress:1,version:r.version}),ke(n,i)}).catch(i=>{var y;if(i instanceof ce){if(Le.has(n))return;q("paused",n),X[n]-=1,O.unshift(n),D(n,{status:H.has(n)?"paused":"queued",progress:0,version:r.version});return}let p=String((y=i==null?void 0:i.message)!=null?y:i);if(console.warn("[miniapp-queue] failed",n,p),X[n]<Tn){D(n,{status:"queued",progress:0,version:r.version,error:p}),setTimeout(()=>{var d;O.includes(n)||(v==null?void 0:v.app_id)===n||(O.push(n),ne((d=ae[n])!=null&&d.length?n:void 0))},On);return}D(n,{status:"failed",progress:0,version:r.version,error:p}),ke(n,x(n))}).finally(()=>{v=null;let i=O.find(p=>{var y;return(y=ae[p])==null?void 0:y.length});ne(i)})},Be=(e,{front:t=!1}={})=>{if((v==null?void 0:v.app_id)===e)return;let n=O.indexOf(e);if(n>=0){if(!t)return;O.splice(n,1)}t?O.unshift(e):O.push(e)},Ln=async e=>{let{host_id:t,client_token:n}=R(),r=new AbortController,o=setTimeout(()=>r.abort(),Pn);try{let s=`${_e}/api/hosts/${encodeURIComponent(t)}/miniapps?channel=${e}`,a=await fetch(s,{headers:{Authorization:`Bearer ${n}`,"Cache-Control":"no-cache"},signal:r.signal});if(!a.ok)throw new Error(`host list ${e} ${a.status}`);return(await a.json()).apps.map(i=>({...i,channel:e}))}finally{clearTimeout(o)}},ye=null,$e=()=>(ye!=null||(ye=(async()=>{var t;let e=Date.now();try{let n=await Promise.all(R().channels.map(Ln)),r={};[...n].reverse().flat().forEach(i=>{r[i.app_id]=i});let o=Object.keys(_.getState().catalog).filter(i=>!r[i]);R().storage.setString(jt,JSON.stringify(r)),_.setState({catalog:r}),await Promise.all(o.map(i=>Qt(i,{by_user:!1}))),o.forEach(i=>re.delete(i));let s=Object.keys(r).filter(i=>!re.has(i)),a=[],c={};for(let i of s.map(p=>r[p])){if(await Qe(i)){D(i.app_id,{status:"installed",progress:1,version:i.version});continue}let p=x(i.app_id);if(Wt(i.app_id)&&!De.has(i.app_id)&&p&&await Q(p)){D(i.app_id,{status:"installed",progress:1,version:p.version}),c[i.app_id]={app_id:i.app_id,current_version:p.version,next_version:i.version};continue}a.push(i)}return _.setState({updates:c}),a.forEach(i=>{X[i.app_id]=0,D(i.app_id,{status:H.has(i.app_id)?"paused":"queued",progress:0,version:i.version,error:void 0}),Be(i.app_id)}),q("catalog",s.length,"apps, outdated",a.map(i=>i.app_id),"removed",o,`${Date.now()-e}ms`),te({type:"sync_complete",app_ids:s,removed:o}),Object.values(c).forEach(i=>te({type:"update_available",...i})),ne(),{ok:!0,app_ids:s,removed:o}}catch(n){let r=String((n==null?void 0:n.name)==="AbortError"?"timeout":(t=n==null?void 0:n.message)!=null?t:n);return console.warn("[miniapp-queue] sync catalog failed",r),te({type:"sync_failed",error:r}),{ok:!1,error:r}}finally{ye=null}})()),ye),Qt=async(e,{by_user:t})=>{var o,s,a,c;if(t&&re.add(e),Le.has(e))return;Le.add(e),H.delete(e);let n=O.indexOf(e);n>=0&&O.splice(n,1),(v==null?void 0:v.app_id)===e&&v.handle.cancel();let r=(c=(a=(o=_.getState().downloads[e])==null?void 0:o.version)!=null?a:(s=x(e))==null?void 0:s.version)!=null?c:"";D(e,{status:"uninstalling",progress:0,version:r}),await Nt(e),Ie(e),_.setState(i=>{let p={...i.downloads};return delete p[e],{downloads:p}}),delete X[e],Le.delete(e),ke(e,null),q("uninstalled",e,t?"(user)":"(not in list)"),te({type:"uninstalled",app_id:e})},Xt=e=>Qt(e,{by_user:!0}),Zt=e=>{let t=le(e);return t?(re.delete(e),(v==null?void 0:v.app_id)===e||O.includes(e)||(X[e]=0,D(e,{status:H.has(e)?"paused":"queued",progress:0,version:t.version,error:void 0}),Be(e),ne(),q("restore",e)),!0):!1},en=e=>{if(H.has(e))return;if(H.add(e),q("pause app",e),(v==null?void 0:v.app_id)===e&&!v.forced){v.handle.cancel();return}let t=_.getState().downloads[e];O.includes(e)&&t&&D(e,{status:"paused",progress:0,version:t.version})},tn=e=>{if(!H.delete(e))return;q("resume app",e);let t=_.getState().downloads[e];(t==null?void 0:t.status)==="paused"&&!O.includes(e)&&le(e)&&(X[e]=0,Be(e)),O.includes(e)&&t&&D(e,{status:"queued",progress:0,version:t.version}),ne()},nn=e=>{let{pause_reasons:t}=_.getState();t.includes(e)||(_.setState({pause_reasons:[...t,e]}),q("pause",e),t.length===0&&te({type:"pause_change",paused:!0,reasons:[e]}),v&&!v.forced&&v.handle.cancel())},rn=e=>{let{pause_reasons:t}=_.getState();if(!t.includes(e))return;let n=t.filter(r=>r!==e);_.setState({pause_reasons:n}),q("resume",e),n.length===0&&te({type:"pause_change",paused:!1,reasons:n}),ne()},et=e=>_.getState().updates[e],on=async e=>{var n,r;let t=et(e);De.add(e);try{let o=await Me(e),s=(r=t==null?void 0:t.next_version)!=null?r:(n=le(e))==null?void 0:n.version;return!o||!s||o.version!==s?!1:(_.setState(a=>{var i;let c={...a.updates};return delete c[e],{updates:c,apply_ticks:{...a.apply_ticks,[e]:((i=a.apply_ticks[e])!=null?i:0)+1}}}),q("updated",e,t==null?void 0:t.current_version,"\u2192",o.version),!0)}finally{De.delete(e)}},sn=()=>Object.values(_.getState().catalog).map(e=>({...e,installed:!!x(e.app_id),removed_by_user:re.has(e.app_id)})),le=e=>_.getState().catalog[e],Me=async e=>{let t=le(e);if(!t)return;if(H.delete(e),re.delete(e),await Qe(t))return x(e);let n=x(e);if(Wt(e)&&!De.has(e)&&n&&await Q(n))return n;let r=new Promise(o=>{var s;((s=ae[e])!=null?s:ae[e]=[]).push(o)});return(v==null?void 0:v.app_id)===e?v.forced=!0:(X[e]=0,Be(e,{front:!0}),v&&!v.forced?v.handle.cancel():ne(e)),r};var E=require("react/jsx-runtime"),tt=e=>(e!=null?e:"").replace(/\?[^#]*/,""),an=0,kn=()=>{let e=new Set;return{emit:t=>e.forEach(n=>n(t)),subscribe:t=>(e.add(t),()=>{e.delete(t)})}},Dn=f.default.memo(({instance_key:e,is_active:t,is_front:n,is_dark:r,reload_tick:o,web_at_top:s,splash:a,bridge:c,opaque_background:i,allow_embedded_miniapps:p,onWebLoadEnd:y})=>{var at,ct;let d=(0,f.useRef)(null),M=(0,f.useRef)(!1),A=K(V,l=>l.instances[e]),w=A==null?void 0:A.app.app_id,C=A==null?void 0:A.app.manifest_url,T=A==null?void 0:A.context,N=A==null?void 0:A.url_params,[u,I]=(0,f.useState)(()=>w?x(w):null),[ue,Z]=(0,f.useState)(!1),[ve,h]=(0,f.useState)(0),[S,U]=(0,f.useState)(0),[ie,B]=(0,f.useState)(!1),j=(0,f.useRef)(null),rt=l=>{j.current&&clearTimeout(j.current),j.current=setTimeout(()=>{j.current=null,B(!0)},l)};(0,f.useEffect)(()=>()=>{j.current&&clearTimeout(j.current)},[]),(0,f.useEffect)(()=>{if(!w||!t&&u)return;let l=!0;return Z(!1),(async()=>{let m=x(w),L=m?await Q(m):!1;if(!l||(I(L?J=>!J||J.version!==m.version||J.permissions.join(",")!==m.permissions.join(",")?m:J:null),__DEV__&&Date.now()-an>1e4&&(an=Date.now(),await $e()),!l))return;let ee=await Me(w),oe=ee!==void 0?ee:C?await Vt(w,C):x(w);if(l){if(!oe){Z(!0);return}I(J=>J!=null?J:oe)}})(),()=>{l=!1}},[t,w,C,ve]),(0,f.useEffect)(()=>Ft(e,l=>d.current?(d.current.postMessage(l),!0):!1),[e]);let un=K(_,l=>{let m=w?l.downloads[w]:void 0;return(m==null?void 0:m.status)==="installed"?m.version:void 0});(0,f.useEffect)(()=>{if(t||!w||!u)return;let l=x(w);if(!l||l.version===u.version)return;let m=!0;return Q(l).then(L=>{!m||!L||($(`webview:${e}`,"\u0111\u1ED5i bundle (\u1EA9n)",u.version,"\u2192",l.version),I(l))}),()=>{m=!1}},[t,w,un,u==null?void 0:u.version]);let it=K(_,l=>{var m;return w&&(m=l.apply_ticks[w])!=null?m:0});(0,f.useEffect)(()=>{if(!it||!w)return;let l=x(w);if(!l||l.version===(u==null?void 0:u.version))return;let m=!0;return Q(l).then(L=>{!m||!L||($(`webview:${e}`,"c\u1EADp nh\u1EADt",u==null?void 0:u.version,"\u2192",l.version),B(!1),I(l))}),()=>{m=!1}},[it]),(0,f.useEffect)(()=>{var L;let l=(L=R().keep_alive)==null?void 0:L.idle_close_ms;if(t||!l||l<=0)return;let m=setTimeout(()=>{Ie(e)},l);return()=>clearTimeout(m)},[t,e]),(0,f.useEffect)(()=>{o>0&&(Z(!1),B(!1),U(l=>l+1),h(l=>l+1))},[o]);let ot=(0,f.useRef)(t);(0,f.useEffect)(()=>{var l;ot.current!==t&&(ot.current=t,M.current&&((l=d.current)==null||l.injectJavaScript(Rt(t?"resumed":"paused"))))},[t]);let de=`${(at=u==null?void 0:u.version)!=null?at:"none"}:${(ct=u==null?void 0:u.permissions.join(","))!=null?ct:""}:${S}`,ge=(0,f.useMemo)(()=>JSON.stringify([T!=null?T:{},N!=null?N:{}]),[T,N]),Ve=(0,f.useMemo)(()=>{var l;return It(N!=null?N:{},(l=u==null?void 0:u.permissions)!=null?l:[])},[ge,u==null?void 0:u.permissions]),dn=(0,f.useMemo)(()=>Ot(T!=null?T:{},Ve)+Et()+(R().debug?xt():""),[Ve]),Se=(0,f.useRef)(null),st=(0,f.useRef)(null);(0,f.useEffect)(()=>{var m,L,ee;if(!u)return;if(st.current!==de){st.current=de,Se.current=ge;return}if(Se.current===ge)return;let l=((L=JSON.parse((m=Se.current)!=null?m:"[]")[0])!=null?L:{}).org_id;if(Se.current=ge,l===(T==null?void 0:T.org_id)&&M.current){B(!1),rt(1500),(ee=d.current)==null||ee.injectJavaScript(Pt(T!=null?T:{},Ve));return}B(!1),U(oe=>oe+1)},[ge,u,de]),(0,f.useEffect)(()=>(t||z(e),()=>z(e)),[t,e,de,o]),(0,f.useEffect)(()=>{let l=b.AppState.addEventListener("change",m=>{m==="background"&&z(e)});return()=>l.remove()},[e]);let gn=(0,f.useCallback)(async l=>{var L,ee,oe,J,Fe;let m=vt(l.nativeEvent.data);if(!m){if(w&&(c!=null&&c.onWebEvent))try{Promise.resolve(c.onWebEvent(l.nativeEvent.data,{app_id:w,instance_id:e})).catch(P=>{console.warn("[miniapp] onWebEvent l\u1ED7i",w,P)})}catch(P){console.warn("[miniapp] onWebEvent l\u1ED7i",w,P)}return}if(m.method==="log"){let{level:P,text:k}=m;$(`web:${e}`,P!=null?P:"log",k!=null?k:"");return}if(m.method==="pong"){j.current||B(!0);return}if(m.method==="touchAtTop"){s.emit(!!m.at_top);return}if(m.method==="contextApplied"){j.current&&clearTimeout(j.current),j.current=null,B(!0);return}if(m.method==="ready"){M.current=!0,B(!0);let P=(L=V.getState().instances[e])==null?void 0:L.context;P&&((ee=d.current)==null||ee.injectJavaScript(je(P)));return}try{let P=await Lt(m,{getHostData:()=>{var k,Y;return(Y=(k=V.getState().instances[e])==null?void 0:k.host_data)!=null?Y:{}},getPermissions:()=>{var k,Y;return w?(Y=(k=x(w))==null?void 0:k.permissions)!=null?Y:[]:[]},is_dark:r,close:pe,app_id:w!=null?w:"",instance_id:e,options:c,emit:(k,Y)=>{var pt;(pt=d.current)==null||pt.injectJavaScript(_t(k,Y))},isActive:()=>V.getState().active_key===e&&b.AppState.currentState!=="background"});m.id&&((oe=d.current)==null||oe.injectJavaScript(St(m.id,P)))}catch(P){if(!m.id)return;let k=P==null?void 0:P.code,Y=P instanceof g?P:new g(typeof k=="string"?k:"HOST_ERROR",String((J=P==null?void 0:P.message)!=null?J:P));(Fe=d.current)==null||Fe.injectJavaScript(bt(m.id,Y))}},[e,r,w,s,c]),fn=(0,f.useCallback)(()=>{Z(!1),U(l=>l+1),h(l=>l+1)},[]);return(0,E.jsxs)(b.View,{style:[b.StyleSheet.absoluteFill,i&&{backgroundColor:r?"#09090B":"#FFFFFF"},!n&&F.behind],pointerEvents:t?"auto":"none",children:[u?(0,E.jsx)(pn.default,{ref:d,source:{uri:u.entry_uri},originWhitelist:["*"],allowingReadAccessToURL:`file://${p?Ke():u.dir}`,allowFileAccess:!0,allowFileAccessFromFileURLs:!0,allowUniversalAccessFromFileURLs:!0,injectedJavaScriptBeforeContentLoaded:dn,onMessage:gn,bounces:!1,overScrollMode:"never",onLoadStart:l=>{z(e),$(`webview:${e}`,"load start",tt(l.nativeEvent.url)),M.current=!1,B(!1)},onError:l=>{z(e),$(`webview:${e}`,"load error",tt(l.nativeEvent.url),l.nativeEvent.description),Z(!0),B(!1)},onLoadEnd:l=>{let m=l.nativeEvent.url;$(`webview:${e}`,"load end",tt(m)),w&&(y==null||y({app_id:w,instance_id:e,url:m})),rt(1500)},onContentProcessDidTerminate:()=>{z(e),M.current=!1,B(!1),U(l=>l+1)},onRenderProcessGone:()=>(z(e),M.current=!1,B(!1),U(l=>l+1),!0),style:F.webview},de):null,A&&(0,E.jsx)(Bn,{visible:!u||!ie,interactive:ue,children:(0,E.jsx)(Nn,{splash:a,app:A.app,is_dark:r,error:ue,has_bundle:!!u,retry:fn})})]})}),Nn=f.default.memo(({splash:e,app:t,is_dark:n,error:r,has_bundle:o,retry:s})=>{let a=e,c=Ne(t.app_id),i=r?"error":!o&&(c==null?void 0:c.status)==="downloading"?"downloading":"loading";return(0,E.jsx)(a,{app:t,is_dark:n,status:i,progress:i==="downloading"?c==null?void 0:c.progress:void 0,retry:s})}),Bn=({visible:e,interactive:t,children:n})=>{let r=(0,f.useRef)(new b.Animated.Value(e?1:0)).current,[o,s]=(0,f.useState)(e);return(0,f.useEffect)(()=>{if(e){s(!0),r.setValue(1);return}let a=b.Animated.timing(r,{toValue:0,duration:180,useNativeDriver:!0});return a.start(({finished:c})=>{c&&s(!1)}),()=>a.stop()},[e,r]),o?(0,E.jsx)(b.Animated.View,{style:[b.StyleSheet.absoluteFill,{opacity:r}],pointerEvents:t?"auto":"none",children:n}):null},nt=({app:e,is_dark:t,status:n,progress:r,retry:o})=>{let s=t?"#FAFAFA":"#18181B";return(0,E.jsxs)(b.View,{style:[F.splash,{backgroundColor:t?"#09090B":"#FFFFFF"}],children:[(0,E.jsx)(b.View,{style:[F.splash_icon,{backgroundColor:t?"#18181B":"#F4F4F5"}],children:e.icon?(0,E.jsx)(b.Image,{source:{uri:e.icon},style:F.splash_icon_image}):(0,E.jsx)(b.Text,{style:F.splash_letter,children:(e.name||"?").slice(0,1).toUpperCase()})}),(0,E.jsx)(b.Text,{style:[F.splash_name,{color:s}],children:e.name}),n==="error"?(0,E.jsxs)(E.Fragment,{children:[(0,E.jsx)(b.Text,{style:F.splash_hint,children:"Kh\xF4ng t\u1EA3i \u0111\u01B0\u1EE3c mini app"}),(0,E.jsx)(b.TouchableOpacity,{activeOpacity:.7,style:[F.retry_button,{backgroundColor:t?"#27272A":"#F4F4F5"}],onPress:o,children:(0,E.jsx)(b.Text,{style:[F.retry_text,{color:s}],children:"Th\u1EED l\u1EA1i"})})]}):(0,E.jsxs)(E.Fragment,{children:[(0,E.jsx)(b.ActivityIndicator,{style:F.splash_spinner,color:t?"#A1A1AA":"#71717A"}),n==="downloading"&&(0,E.jsxs)(b.Text,{style:F.splash_hint,children:["\u0110ang t\u1EA3i mini app",r?` ${Math.round(r*100)}%`:"\u2026"]})]})]})},cn=(e,t)=>{let n=(0,f.useRef)(t),r=(0,f.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.`))},$n=({container:e,splash:t=nt,is_dark:n=!1,bridge:r,close_on_back:o=!0,opaque_background:s=!0,allow_embedded_miniapps:a=!1,onWebLoadEnd:c})=>{cn("container",e),cn("splash",t);let i=e,p=K(V,u=>u.active_key),y=(0,f.useRef)(p);p&&(y.current=p);let d=K(V,u=>Object.keys(u.instances).join("|")),M=K(V,u=>{var I;return u.active_key?(I=u.instances[u.active_key])==null?void 0:I.app.name:void 0}),A=(0,f.useMemo)(()=>d?d.split("|"):[],[d]),[w,C]=(0,f.useState)({}),T=(0,f.useRef)(kn()).current;(0,f.useEffect)(()=>{if(!p||!o)return;let u=b.BackHandler.addEventListener("hardwareBackPress",()=>(pe(),!0));return()=>u.remove()},[p,o]);let N=(0,f.useCallback)(()=>{let u=V.getState().active_key;u&&C(I=>({...I,[u]:(I[u]||0)+1}))},[]);return A.length?(0,E.jsx)(i,{visible:!!p,title:M!=null?M:"",is_dark:n,close:pe,reload:N,subscribeWebAtTop:T.subscribe,children:A.map(u=>(0,E.jsx)(Dn,{instance_key:u,is_active:p===u,is_front:(p!=null?p:y.current)===u,is_dark:n,reload_tick:w[u]||0,web_at_top:T,splash:t,bridge:r,opaque_background:s,allow_embedded_miniapps:a,onWebLoadEnd:c},u))}):null},F=b.StyleSheet.create({webview:{flex:1,backgroundColor:"transparent"},behind:{zIndex:-1},splash:{flex:1,alignItems:"center",justifyContent:"center",gap:12},splash_icon:{width:72,height:72,borderRadius:20,alignItems:"center",justifyContent:"center",overflow:"hidden"},splash_icon_image:{width:72,height:72},splash_letter:{fontSize:28,fontWeight:"700",color:"#1D4ED8"},splash_name:{fontSize:16,fontWeight:"600"},splash_hint:{color:"#71717A"},splash_spinner:{marginTop:8},retry_button:{marginTop:4,paddingHorizontal:20,paddingVertical:10,borderRadius:999},retry_text:{fontWeight:"600"}}),ln=f.default.memo($n);0&&(module.exports={DefaultMiniAppSplash,MINIAPP_PLATFORM_URL,MiniAppHost,MiniAppHostError,closeMiniApp,configureMiniApp,createMmkvStorage,createReactNativeBiometrics,createRnfsFileSystem,ensureMiniApp,getLocalMiniApp,getMiniAppCatalog,getMiniAppCatalogEntry,getMiniAppStatuses,getMiniAppUpdate,installBundledMiniApp,onMiniAppEvent,openMiniApp,pauseMiniApp,pauseMiniAppDownloads,preloadMiniApp,releaseSpeechFor,restoreMiniApp,resumeMiniApp,resumeMiniAppDownloads,sendEventToWeb,syncMiniAppCatalog,uninstallMiniApp,updateMiniApp,useMiniAppDownload,useMiniAppDownloadsPaused});
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});