import { App } from '@capacitor/app' import { Capacitor } from '@capacitor/core' import { CapacitorUpdater, type BundleInfo } from '@capgo/capacitor-updater' import { ElNotification } from 'element-plus' import { translate } from '../i18n' import http from '../api/http' interface AppUpdateCheckResponse { available: boolean version?: string nativeVersion: string platform: 'Android' | 'Ios' channel: 'Production' | 'Staging' downloadUrl?: string releaseNotes?: string fileSize?: number sha256?: string publishedAt?: string } const updateChannel = import.meta.env.VITE_APP_UPDATE_CHANNEL?.trim() || 'production' let checkInProgress: Promise | undefined let updatePromptVisible = false function absoluteApiUrl(relativePath: string) { const configuredBase = String(http.defaults.baseURL ?? '/api') const publicBase = import.meta.env.VITE_PUBLIC_BASE_URL?.trim() || window.location.origin const apiBase = new URL( configuredBase.endsWith('/') ? configuredBase : `${configuredBase}/`, publicBase, ) return new URL(relativePath, apiBase).toString() } async function checkForAppUpdate() { if (checkInProgress) return checkInProgress if (!navigator.onLine) return checkInProgress = (async () => { try { const platform = Capacitor.getPlatform() if (platform !== 'android' && platform !== 'ios') return const [current, builtin, next] = await Promise.all([ CapacitorUpdater.current(), CapacitorUpdater.getBuiltinVersion(), CapacitorUpdater.getNextBundle(), ]) const currentVersion = current.bundle.id === 'builtin' ? builtin.version : current.bundle.version const { data } = await http.get( '/app-updates/latest', { params: { platform, channel: updateChannel, nativeVersion: current.native, currentVersion, }, // Update discovery is deliberately public. Do not delay startup for a // token refresh or send a stale Authorization header to this endpoint. skipAuthSession: true, timeout: 15000, }, ) if ( !data.available || !data.version || !data.downloadUrl || !data.sha256 || data.version === currentVersion || next?.version === data.version ) { return } const downloaded = await CapacitorUpdater.download({ url: absoluteApiUrl(data.downloadUrl), version: data.version, checksum: data.sha256, }) await CapacitorUpdater.next({ id: downloaded.id }) ElNotification({ title: translate('updates.readyTitle', { version: data.version }), message: (data.releaseNotes ? translate('updates.releaseNotes', { notes: data.releaseNotes }) : translate('updates.readyMessage')), type: 'success', duration: 0, onClick: () => void applyDownloadedUpdate(downloaded), }) } catch (error) { // OTA failure must never stop users from entering the bundled application. console.warn('[app-update] update check failed', error) } finally { checkInProgress = undefined } })() return checkInProgress } async function applyDownloadedUpdate(bundle: BundleInfo) { if (updatePromptVisible) return updatePromptVisible = true try { await ElNotification.closeAll() // `set` replaces the WebView bundle and immediately reloads, so ask for a // deliberate confirmation instead of interrupting unsaved form input. await import('element-plus').then(({ ElMessageBox }) => ElMessageBox.confirm( translate('updates.applyMessage'), translate('updates.applyTitle'), { confirmButtonText: translate('updates.applyNow'), cancelButtonText: translate('updates.later'), type: 'info', }, ), ) await CapacitorUpdater.set({ id: bundle.id }) } catch { // Choosing "later" is safe: next() has already queued this bundle for // activation when the app backgrounds or is launched again. } finally { updatePromptVisible = false } } export async function initializeAppUpdates() { if (!Capacitor.isNativePlatform()) return try { // Confirm the bundle before any network request. If a newly installed // bundle cannot reach this point, the native plugin rolls it back. await CapacitorUpdater.notifyAppReady() } catch (error) { // Do not let a native-plugin error prevent the bundled app from starting. console.warn('[app-update] bundle readiness confirmation failed', error) } // Every cold start checks the latest public release immediately. A bundle // downloaded here is activated when the app is next launched. void checkForAppUpdate() // Keep the native app aligned with the PWA behavior: returning to the app // is another opportunity to discover a newly deployed web bundle. The // single-flight guard prevents duplicate cold-start/foreground requests. void App.addListener('appStateChange', ({ isActive }) => { if (isActive) void checkForAppUpdate() }) window.addEventListener('online', () => void checkForAppUpdate()) }