@capgo/capacitor-updater 7.51.23 → 7.53.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.
Files changed (29) hide show
  1. package/CapgoCapacitorUpdater.podspec +0 -3
  2. package/Package.swift +3 -11
  3. package/README.md +201 -66
  4. package/android/build.gradle +2 -3
  5. package/android/src/main/java/ee/forgr/capacitor_updater/CapacitorUpdaterPlugin.java +593 -176
  6. package/android/src/main/java/ee/forgr/capacitor_updater/CapgoUpdater.java +775 -162
  7. package/android/src/main/java/ee/forgr/capacitor_updater/CryptoCipher.java +2 -1
  8. package/android/src/main/java/ee/forgr/capacitor_updater/DelayUpdateUtils.java +226 -106
  9. package/android/src/main/java/ee/forgr/capacitor_updater/DownloadService.java +107 -30
  10. package/android/src/main/java/ee/forgr/capacitor_updater/HeadlessUpdateWorker.java +325 -0
  11. package/android/src/main/java/ee/forgr/capacitor_updater/Logger.java +63 -4
  12. package/android/src/main/java/ee/forgr/capacitor_updater/NativeUpdatePrompt.java +303 -0
  13. package/android/src/main/java/ee/forgr/capacitor_updater/Version.java +306 -0
  14. package/dist/docs.json +394 -27
  15. package/dist/esm/definitions.d.ts +220 -7
  16. package/dist/esm/definitions.js.map +1 -1
  17. package/ios/Sources/CapacitorUpdaterPlugin/AES.swift +104 -52
  18. package/ios/Sources/CapacitorUpdaterPlugin/CapacitorUpdaterPlugin.swift +472 -144
  19. package/ios/Sources/CapacitorUpdaterPlugin/CapgoSemanticVersion.swift +162 -0
  20. package/ios/Sources/CapacitorUpdaterPlugin/CapgoUpdater.swift +392 -82
  21. package/ios/Sources/CapacitorUpdaterPlugin/CryptoCipher.swift +2 -1
  22. package/ios/Sources/CapacitorUpdaterPlugin/DelayUpdateUtils.swift +204 -93
  23. package/ios/Sources/CapacitorUpdaterPlugin/Logger.swift +75 -5
  24. package/ios/Sources/CapacitorUpdaterPlugin/NativeUpdatePrompt.swift +183 -0
  25. package/ios/Sources/CapacitorUpdaterPlugin/RedirectPolicyDelegate.swift +53 -0
  26. package/ios/Sources/CapacitorUpdaterPlugin/ShakeMenu.swift +5 -2
  27. package/ios/Sources/CapacitorUpdaterPlugin/ZipArchiveReader.swift +247 -0
  28. package/ios/Sources/CapacitorUpdaterPlugin/ZipCentralDirectory.swift +280 -0
  29. package/package.json +7 -3
@@ -8,7 +8,6 @@ import Foundation
8
8
  import Capacitor
9
9
  import UIKit
10
10
  import WebKit
11
- import Version
12
11
 
13
12
  /**
14
13
  * Please read the Capacitor iOS Plugin Development Guide
@@ -96,11 +95,18 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
96
95
  deinit {
97
96
  implementation.shutdown()
98
97
  }
99
- private let pluginVersion: String = "7.51.23"
98
+ private let pluginVersion: String = "7.53.0"
100
99
  private let launchStartedAtMs = Int64(Date().timeIntervalSince1970 * 1000)
101
100
  static let updateUrlDefault = "https://plugin.capgo.app/updates"
102
101
  static let statsUrlDefault = "https://plugin.capgo.app/stats"
103
102
  static let channelUrlDefault = "https://plugin.capgo.app/channel_self"
103
+ // Stats action for a failed update check (offline, timeout, unreadable response, 429 block).
104
+ // Nothing was downloaded, so it is reported apart from download_fail.
105
+ static let updateCheckErrorAction = "update_check_error"
106
+ // Single listener that receives every plugin event as { type, data }.
107
+ static let updaterEvent = "updaterEvent"
108
+ // Deprecated alias emitted next to breakingAvailable; not forwarded to avoid duplicates.
109
+ static let deprecatedMajorAvailableEvent = "majorAvailable"
104
110
  static let autoUpdateModeOff = "off"
105
111
  static let autoUpdateModeBackground = "atBackground"
106
112
  static let autoUpdateModeInstall = "atInstall"
@@ -147,14 +153,19 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
147
153
  // Note: DELAY_CONDITION_PREFERENCES is now defined in DelayUpdateUtils.DELAY_CONDITION_PREFERENCES
148
154
  private var updateUrl = ""
149
155
  private var backgroundTaskID: UIBackgroundTaskIdentifier = UIBackgroundTaskIdentifier.invalid
150
- private var currentVersionNative: Version = "0.0.0"
156
+ private var currentVersionNative = CapgoSemanticVersion(major: 0, minor: 0, patch: 0)
151
157
  private var currentBuildVersion: String = "0"
152
158
  private var autoUpdate = false
153
159
  private var autoUpdateMode = CapacitorUpdaterPlugin.autoUpdateModeOff
154
160
  private var launchStartReported = false
155
161
  private var launchReadyReported = false
162
+ private var launchTimeoutReported = false
163
+ private let launchReportLock = NSLock()
156
164
  private var appReadyTimeout = 10000
157
165
  private var appReadyCheck: DispatchWorkItem?
166
+ // Between appMovedToBackground and appMovedToForeground (main thread). A suspended page cannot
167
+ // call notifyAppReady, so the rollback check waits for the fresh one armed by the next foreground.
168
+ private var appInBackground = false
158
169
  private var resetWhenUpdate = true
159
170
  private var directUpdate = false
160
171
  private var directUpdateMode: String = "false"
@@ -219,10 +230,15 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
219
230
  // Best-effort flag: set before we expect notifyAppReady (load/reload).
220
231
  // No lock — never held across waits; a rare race only mis-times one wait.
221
232
  private var pendingNotifyAppReady = false
233
+ // Armed only after a reload. The next document stamps this generation into notifyAppReady.
234
+ // A call from the previous page has no matching generation and must not mark the new bundle successful.
235
+ private var readyGuardArmed = false
236
+ private var readyGeneration = 0
222
237
  private let semaphoreWaitTestingLock = NSLock()
223
238
  private var didEnterSemaphoreWaitForTesting = false
224
239
 
225
240
  private var delayUpdateUtils: DelayUpdateUtils!
241
+ private var nativeUpdatePromptCoordinator: NativeUpdatePromptCoordinator?
226
242
 
227
243
  override public func load() {
228
244
  let disableJSLogging = getConfig().getBoolean("disableJSLogging", false)
@@ -242,6 +258,16 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
242
258
  #endif
243
259
 
244
260
  self.semaphoreUp()
261
+ // A silent push or background fetch launches the app straight into the background:
262
+ // no didEnterBackground is posted, so read the state once. Otherwise the notifyAppReady
263
+ // check would roll back a bundle whose page cannot run before the user opens the app.
264
+ if Thread.isMainThread {
265
+ self.appInBackground = UIApplication.shared.applicationState == .background
266
+ } else {
267
+ DispatchQueue.main.sync {
268
+ self.appInBackground = UIApplication.shared.applicationState == .background
269
+ }
270
+ }
245
271
  // Use DeviceIdHelper to get or create device ID that persists across reinstalls
246
272
  self.implementation.deviceID = DeviceIdHelper.getOrCreateDeviceId()
247
273
  persistCustomId = getConfig().getBoolean("persistCustomId", false)
@@ -264,7 +290,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
264
290
  fatalError("Cannot get version name")
265
291
  }
266
292
  do {
267
- currentVersionNative = try Version(versionName)
293
+ currentVersionNative = try CapgoSemanticVersion(versionName)
268
294
  } catch {
269
295
  logger.error("Cannot parse versionName \(versionName)")
270
296
  }
@@ -288,6 +314,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
288
314
  configureAutoUpdateModeFromConfig()
289
315
  appReadyTimeout = max(1000, getConfig().getInt("appReadyTimeout", 10000)) // Minimum 1 second
290
316
  implementation.timeout = Double(getConfig().getInt("responseTimeout", 20))
317
+ implementation.allowHttpsToHttpRedirect = getConfig().getBoolean("allowHttpsToHttpRedirect", false)
291
318
  resetWhenUpdate = getConfig().getBoolean("resetWhenUpdate", true)
292
319
  shakeMenuEnabled = getConfig().getBoolean("shakeMenu", false)
293
320
  shakeChannelSelectorEnabled = getConfig().getBoolean("allowShakeChannelSelector", false)
@@ -303,21 +330,13 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
303
330
  ?? shakeChannelSelectorEnabled
304
331
  }
305
332
  syncShakeMenuGestureRecognizer()
333
+ nativeUpdatePromptCoordinator = NativeUpdatePromptCoordinator(plugin: self)
306
334
  periodCheckDelay = Self.normalizedPeriodCheckDelaySeconds(getConfig().getInt("periodCheckDelay", 0))
307
335
 
308
336
  implementation.setPublicKey(getConfig().getString("publicKey") ?? "")
309
337
  implementation.notifyDownloadRaw = notifyDownload
310
338
  implementation.notifyListeners = { [weak self] eventName, data in
311
- let emit = {
312
- self?.notifyListeners(eventName, data: data)
313
- }
314
- if Thread.isMainThread {
315
- emit()
316
- } else {
317
- DispatchQueue.main.async {
318
- emit()
319
- }
320
- }
339
+ self?.notifyListenersOnMain(eventName, data: data)
321
340
  }
322
341
  implementation.pluginVersion = self.pluginVersion
323
342
 
@@ -416,19 +435,10 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
416
435
  state?.exists != true || (!defaultChannelPersistenceDisabled && state?.isReadable != true) {
417
436
  _ = self.persistDefaultChannelStateFromDefaults()
418
437
  }
419
- self.reportAppLaunchStart()
420
- self.implementation.autoReset()
421
- let appHealthTracker = AppHealthTracker(implementation: self.implementation)
422
- self.appHealthTracker = appHealthTracker
423
- appHealthTracker.reportPreviousUncleanForegroundExit()
424
- appHealthTracker.startSession()
425
-
426
- // Check if app was recently installed/updated BEFORE cleanup updates the stored native build version.
427
- self.wasRecentlyInstalledOrUpdated = self.checkIfRecentlyInstalledOrUpdated()
428
- if nativeBuildVersionChanged {
429
- self.clearPreviewSessionForNativeBuildChange()
430
- }
431
- self.leavePreviewSessionForLaunchURLIfNeeded()
438
+ let didResetCurrentBundle = self.resetStartupBundleAndReportAppLaunchStart(
439
+ resetWhenUpdate: resetWhenUpdate,
440
+ nativeBuildVersionChanged: nativeBuildVersionChanged
441
+ )
432
442
 
433
443
  // Downloads (including shake-menu / CapgoUpdater entry points) wait on this gate.
434
444
  self.implementation.beforeDownload = { [weak self] in
@@ -436,11 +446,6 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
436
446
  }
437
447
  // Always run async cleanup: delete obsolete bundles on native update (when enabled)
438
448
  // and sweep orphan directories every launch. Must not block app startup.
439
- if !resetWhenUpdate {
440
- UserDefaults.standard.set(self.currentBuildVersion, forKey: "LatestNativeBuildVersion")
441
- UserDefaults.standard.synchronize()
442
- }
443
- let didResetCurrentBundle = resetWhenUpdate ? self.resetCurrentBundleForNativeBuildChangeIfNeeded() : false
444
449
  self.cleanupObsoleteVersions(
445
450
  resetWhenUpdate: resetWhenUpdate,
446
451
  didResetCurrentBundle: didResetCurrentBundle
@@ -464,7 +469,9 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
464
469
  // This handles cases where the app was killed (willTerminateNotification is not reliable for system kills)
465
470
  self.delayUpdateUtils.checkCancelDelay(source: .killed)
466
471
 
467
- self.appMovedToForeground()
472
+ if !self.appInBackground {
473
+ self.appMovedToForeground()
474
+ }
468
475
  self.checkForUpdateAfterDelay()
469
476
  self.showPreviewSessionNoticeIfNeeded()
470
477
  }
@@ -1044,6 +1051,33 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
1044
1051
  return true
1045
1052
  }
1046
1053
 
1054
+ @discardableResult
1055
+ private func resetStartupBundleAndReportAppLaunchStart(
1056
+ resetWhenUpdate: Bool,
1057
+ nativeBuildVersionChanged: Bool
1058
+ ) -> Bool {
1059
+ self.implementation.autoReset()
1060
+ let appHealthTracker = AppHealthTracker(implementation: self.implementation)
1061
+ self.appHealthTracker = appHealthTracker
1062
+ appHealthTracker.reportPreviousUncleanForegroundExit()
1063
+ appHealthTracker.startSession()
1064
+
1065
+ // Check if app was recently installed/updated BEFORE cleanup updates the stored native build version.
1066
+ self.wasRecentlyInstalledOrUpdated = self.checkIfRecentlyInstalledOrUpdated()
1067
+ if nativeBuildVersionChanged {
1068
+ self.clearPreviewSessionForNativeBuildChange()
1069
+ }
1070
+ self.leavePreviewSessionForLaunchURLIfNeeded()
1071
+
1072
+ if !resetWhenUpdate {
1073
+ UserDefaults.standard.set(self.currentBuildVersion, forKey: "LatestNativeBuildVersion")
1074
+ UserDefaults.standard.synchronize()
1075
+ }
1076
+ let didResetCurrentBundle = resetWhenUpdate ? self.resetCurrentBundleForNativeBuildChangeIfNeeded() : false
1077
+ self.reportAppLaunchStart()
1078
+ return didResetCurrentBundle
1079
+ }
1080
+
1047
1081
  private func cleanupObsoleteVersions(resetWhenUpdate: Bool = true, didResetCurrentBundle: Bool = false) {
1048
1082
  // Enter before publishing incomplete state so waiters cannot hit an empty group.
1049
1083
  self.cleanupStateLock.lock()
@@ -1244,9 +1278,34 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
1244
1278
  call.keepAlive = true
1245
1279
  }
1246
1280
 
1247
- private func notifyListenersOnMain(_ eventName: String, data: JSObject) {
1281
+ static func updateCheckErrorMetadata(error: String, statusCode: Int) -> [String: String] {
1282
+ var metadata = ["error": error.isEmpty ? "unknown" : error]
1283
+ if statusCode > 0 {
1284
+ metadata["status_code"] = String(statusCode)
1285
+ }
1286
+ return metadata
1287
+ }
1288
+
1289
+ static func updaterEventPayload(eventName: String, data: [String: Any]?) -> [String: Any] {
1290
+ return ["type": eventName, "data": data ?? [:]]
1291
+ }
1292
+
1293
+ static func shouldForwardToUpdaterEvent(_ eventName: String) -> Bool {
1294
+ return eventName != updaterEvent && eventName != deprecatedMajorAvailableEvent
1295
+ }
1296
+
1297
+ /// CAPPlugin's listener storage is not thread-safe (ionic-team/capacitor#8157), so every
1298
+ /// event this plugin emits goes through the main thread. Calls already on main stay synchronous.
1299
+ private func notifyListenersOnMain(_ eventName: String, data: [String: Any]?, retainUntilConsumed: Bool = false) {
1248
1300
  let notify = {
1249
- self.notifyListeners(eventName, data: data)
1301
+ self.notifyListeners(eventName, data: data, retainUntilConsumed: retainUntilConsumed)
1302
+ if CapacitorUpdaterPlugin.shouldForwardToUpdaterEvent(eventName) {
1303
+ self.notifyListeners(
1304
+ CapacitorUpdaterPlugin.updaterEvent,
1305
+ data: CapacitorUpdaterPlugin.updaterEventPayload(eventName: eventName, data: data),
1306
+ retainUntilConsumed: retainUntilConsumed
1307
+ )
1308
+ }
1250
1309
  }
1251
1310
 
1252
1311
  if Thread.isMainThread {
@@ -1630,7 +1689,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
1630
1689
  if let manifestEntries = manifestEntries {
1631
1690
  next = try self.implementation.downloadManifest(manifest: manifestEntries, version: version, sessionKey: sessionKey)
1632
1691
  } else {
1633
- next = try self.implementation.download(url: url, version: version, sessionKey: sessionKey)
1692
+ next = try self.implementation.downloadVerified(url: url, version: version, sessionKey: sessionKey, expectedChecksum: rawChecksum)
1634
1693
  }
1635
1694
 
1636
1695
  if manifestEntries == nil {
@@ -1718,6 +1777,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
1718
1777
  self.logger.error("Cannot get capBridge")
1719
1778
  return false
1720
1779
  }
1780
+ self.armReadyGuard(webView: vc.webView)
1721
1781
  if self.keepUrlPathAfterReload {
1722
1782
  if let currentURL = vc.webView?.url {
1723
1783
  capBridge.setServerBasePath(dest.path)
@@ -1769,7 +1829,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
1769
1829
  return false
1770
1830
  }
1771
1831
  self.checkAppReady()
1772
- self.notifyListeners("appReloaded", data: [:])
1832
+ self.notifyListenersOnMain("appReloaded", data: [:])
1773
1833
  return true
1774
1834
  }
1775
1835
 
@@ -1792,7 +1852,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
1792
1852
  return false
1793
1853
  }
1794
1854
  self.checkAppReady()
1795
- self.notifyListeners("appReloaded", data: [:])
1855
+ self.notifyListenersOnMain("appReloaded", data: [:])
1796
1856
  return true
1797
1857
  }
1798
1858
 
@@ -1909,7 +1969,11 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
1909
1969
  if !res {
1910
1970
  logger.info("Bundle successfully set to: \(id) ")
1911
1971
  call.reject("Update failed, id \(id) doesn't exist")
1912
- } else if self.previewSessionEnabled {
1972
+ return
1973
+ }
1974
+ // The bundle is now active: it must not stay reported as the pending next bundle.
1975
+ self.implementation.clearNextBundleIfCurrent()
1976
+ if self.previewSessionEnabled {
1913
1977
  let bundle = self.implementation.getBundleInfo(id: id)
1914
1978
  _ = self.recordPreviewBundle(bundle)
1915
1979
  if !self.reloadWithoutWaitingForAppReady() {
@@ -2707,12 +2771,12 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
2707
2771
  var response: URLResponse?
2708
2772
  var responseError: Error?
2709
2773
 
2710
- URLSession.shared.dataTask(with: request) { data, urlResponse, error in
2774
+ self.implementation.startRawDataTask(request) { data, urlResponse, error in
2711
2775
  responseData = data
2712
2776
  response = urlResponse
2713
2777
  responseError = error
2714
2778
  semaphore.signal()
2715
- }.resume()
2779
+ }
2716
2780
 
2717
2781
  if semaphore.wait(timeout: .now() + 60) == .timedOut {
2718
2782
  throw makePreviewError("Preview payload request timed out")
@@ -3003,8 +3067,13 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
3003
3067
  logger.error("Error no url or wrong format")
3004
3068
  return "unavailable"
3005
3069
  }
3070
+ // The TS contract only knows queued / already_running / unavailable.
3006
3071
  if self.shouldBlockAutoUpdateForPreviewSession() {
3007
- return "preview_session"
3072
+ return "unavailable"
3073
+ }
3074
+ if !self._isAutoUpdateEnabled() {
3075
+ logger.info("Auto update is disabled, update check not triggered")
3076
+ return "unavailable"
3008
3077
  }
3009
3078
  if self.isDownloadStuckOrTimedOut() {
3010
3079
  logger.info("Download already in progress, skipping duplicate download request")
@@ -3027,11 +3096,16 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
3027
3096
  self.saveCallForAsyncHandling(call)
3028
3097
  DispatchQueue.global(qos: .utility).async {
3029
3098
  let configDefaultChannel = self.getConfig().getString("defaultChannel", "")!
3030
- let res = self.implementation.unsetChannel(defaultChannelKey: self.defaultChannelDefaultsKey, configDefaultChannel: configDefaultChannel)
3099
+ let res = self.implementation.unsetChannel(
3100
+ defaultChannelKey: self.defaultChannelDefaultsKey,
3101
+ configDefaultChannel: configDefaultChannel,
3102
+ allowSetDefaultChannel: self.allowSetDefaultChannel
3103
+ )
3031
3104
  if res.error != "" {
3032
- self.rejectCall(call, message: res.error, code: "UNSETCHANNEL_FAILED", data: [
3033
- "message": res.error,
3034
- "error": res.error.contains("Channel URL") ? "missing_config" : "request_failed"
3105
+ let message = res.message.isEmpty ? res.error : res.message
3106
+ self.rejectCall(call, message: message, code: "UNSETCHANNEL_FAILED", data: [
3107
+ "message": message,
3108
+ "error": res.error
3035
3109
  ])
3036
3110
  } else {
3037
3111
  guard self.persistDefaultChannelStateFromDefaults() else {
@@ -3079,9 +3153,20 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
3079
3153
  "message": res.error
3080
3154
  ])
3081
3155
  }
3082
- self.rejectCall(call, message: res.error, code: "SETCHANNEL_FAILED", data: [
3083
- "message": res.error,
3084
- "error": res.error.contains("Channel URL") ? "missing_config" : (res.error.contains("cannot_update_via_private_channel") || res.error.contains("channel_self_set_not_allowed")) ? "channel_private" : "request_failed"
3156
+ let message = res.message.isEmpty ? res.error : res.message
3157
+ let errorCode: String
3158
+ if res.error == "disabled_by_config" {
3159
+ errorCode = res.error
3160
+ } else if res.error.contains("cannot_update_via_private_channel") || res.error.contains("channel_self_set_not_allowed") {
3161
+ errorCode = "channel_private"
3162
+ } else if res.error.contains("Channel URL") {
3163
+ errorCode = "missing_config"
3164
+ } else {
3165
+ errorCode = "request_failed"
3166
+ }
3167
+ self.rejectCall(call, message: message, code: "SETCHANNEL_FAILED", data: [
3168
+ "message": message,
3169
+ "error": errorCode
3085
3170
  ])
3086
3171
  } else {
3087
3172
  guard self.persistDefaultChannelStateFromDefaults() else {
@@ -3274,11 +3359,10 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
3274
3359
  }
3275
3360
 
3276
3361
  private func reportAppLaunchReady(_ bundle: BundleInfo) {
3277
- guard !self.implementation.statsUrl.isEmpty, !launchReadyReported else {
3362
+ guard !self.implementation.statsUrl.isEmpty, self.claimLaunchReport(timeout: false) else {
3278
3363
  return
3279
3364
  }
3280
3365
 
3281
- launchReadyReported = true
3282
3366
  let duration = max(0, Int64(Date().timeIntervalSince1970 * 1000) - launchStartedAtMs)
3283
3367
  self.implementation.sendStats(
3284
3368
  action: "app_launch_ready",
@@ -3292,8 +3376,23 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
3292
3376
  )
3293
3377
  }
3294
3378
 
3379
+ /// The launch outcome is reported once: either ready or timeout, never both, never twice.
3380
+ private func claimLaunchReport(timeout: Bool) -> Bool {
3381
+ launchReportLock.lock()
3382
+ defer { launchReportLock.unlock() }
3383
+ if launchReadyReported || launchTimeoutReported {
3384
+ return false
3385
+ }
3386
+ if timeout {
3387
+ launchTimeoutReported = true
3388
+ } else {
3389
+ launchReadyReported = true
3390
+ }
3391
+ return true
3392
+ }
3393
+
3295
3394
  private func reportAppLaunchTimeout(_ bundle: BundleInfo) {
3296
- guard !self.implementation.statsUrl.isEmpty else {
3395
+ guard !self.implementation.statsUrl.isEmpty, self.claimLaunchReport(timeout: true) else {
3297
3396
  return
3298
3397
  }
3299
3398
 
@@ -3311,7 +3410,65 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
3311
3410
  )
3312
3411
  }
3313
3412
 
3413
+ static func shouldAcceptReadyCall(guardArmed: Bool, expectedGeneration: Int, reportedGeneration: Int?) -> Bool {
3414
+ if !guardArmed {
3415
+ return true
3416
+ }
3417
+ guard let reportedGeneration else {
3418
+ return false
3419
+ }
3420
+ return reportedGeneration == expectedGeneration
3421
+ }
3422
+
3423
+ static func readyGenerationScript(_ generation: Int) -> String {
3424
+ // Wrap Capacitor.nativePromise, not the plugin proxy. registerPlugin's get trap
3425
+ // ignores assignments to notifyAppReady. Each document keeps its own generation.
3426
+ return "(function(){window.__CAPGO_READY_GEN=\(generation);if(window.__capgoReadyBridge)return;function arm(){var cap=window.Capacitor;if(!cap||typeof cap.nativePromise!=='function'||cap.__capgoNativePromise)return false;var orig=cap.nativePromise.bind(cap);cap.nativePromise=function(pluginName,methodName,options){if(pluginName==='CapacitorUpdater'&&methodName==='notifyAppReady'){var next={};if(options&&typeof options==='object'){for(var k in options){if(Object.prototype.hasOwnProperty.call(options,k))next[k]=options[k];}}next.loadGeneration=window.__CAPGO_READY_GEN;options=next;}return orig(pluginName,methodName,options);};cap.__capgoNativePromise=true;window.__capgoReadyBridge=true;return true;}if(!arm()){var n=0;var t=setInterval(function(){if(arm()||++n>100)clearInterval(t);},20);}})();"
3427
+ }
3428
+
3429
+ private func armReadyGuard(webView: WKWebView?) {
3430
+ let generation = self.readyGeneration + 1
3431
+ guard let webView else {
3432
+ logger.warn("Cannot stamp notifyAppReady generation without a webview")
3433
+ self.readyGuardArmed = false
3434
+ return
3435
+ }
3436
+ let userScript = WKUserScript(
3437
+ source: CapacitorUpdaterPlugin.readyGenerationScript(generation),
3438
+ injectionTime: .atDocumentStart,
3439
+ forMainFrameOnly: true
3440
+ )
3441
+ webView.configuration.userContentController.addUserScript(userScript)
3442
+ self.readyGeneration = generation
3443
+ self.readyGuardArmed = true
3444
+ }
3445
+
3446
+ private func reportedReadyGeneration(_ call: CAPPluginCall) -> Int? {
3447
+ if let generation = call.getInt("loadGeneration") {
3448
+ return generation
3449
+ }
3450
+ // The bridge often boxes JS numbers as NSNumber, which getInt does not cast.
3451
+ if let number = call.getValue("loadGeneration") as? NSNumber {
3452
+ return number.intValue
3453
+ }
3454
+ return nil
3455
+ }
3456
+
3457
+ private func acceptsReadyCall(_ call: CAPPluginCall) -> Bool {
3458
+ let reported = self.readyGuardArmed ? self.reportedReadyGeneration(call) : nil
3459
+ return CapacitorUpdaterPlugin.shouldAcceptReadyCall(
3460
+ guardArmed: self.readyGuardArmed,
3461
+ expectedGeneration: self.readyGeneration,
3462
+ reportedGeneration: reported
3463
+ )
3464
+ }
3465
+
3314
3466
  @objc func notifyAppReady(_ call: CAPPluginCall) {
3467
+ if !self.acceptsReadyCall(call) {
3468
+ logger.info("Ignoring notifyAppReady from a page that is no longer current")
3469
+ call.resolve(["bundle": self.implementation.getCurrentBundle().toJSON()])
3470
+ return
3471
+ }
3315
3472
  self.semaphoreDown()
3316
3473
  let bundle = self.implementation.getCurrentBundle()
3317
3474
  self.implementation.setSuccess(bundle: bundle, autoDeletePrevious: self.autoDeletePrevious)
@@ -3330,7 +3487,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
3330
3487
  return
3331
3488
  }
3332
3489
 
3333
- // Handle background conditions with empty value (set to "0")
3490
+ var conditionsPayload: Any = delayConditionList
3334
3491
  if var modifiableList = delayConditionList as? [[String: Any]] {
3335
3492
  for i in 0..<modifiableList.count {
3336
3493
  if let kind = modifiableList[i]["kind"] as? String,
@@ -3340,20 +3497,33 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
3340
3497
  modifiableList[i]["value"] = "0"
3341
3498
  }
3342
3499
  }
3343
- let delayConditions: String = toJson(object: modifiableList)
3344
- if delayUpdateUtils.setMultiDelay(delayConditions: delayConditions) {
3345
- call.resolve()
3346
- } else {
3347
- call.reject("Failed to delay update")
3500
+ conditionsPayload = modifiableList
3501
+ }
3502
+
3503
+ let delayConditions: String = toJson(object: conditionsPayload)
3504
+ let previousConditions = UserDefaults.standard.string(
3505
+ forKey: DelayUpdateUtils.DELAY_CONDITION_PREFERENCES
3506
+ ) ?? "[]"
3507
+ let previousMode = delayUpdateUtils.getConditionMode()
3508
+ guard delayUpdateUtils.setMultiDelay(delayConditions: delayConditions) else {
3509
+ if !delayUpdateUtils.setMultiDelay(delayConditions: previousConditions) {
3510
+ logger.error("Failed to restore previous delay conditions after setMultiDelay failure")
3348
3511
  }
3349
- } else {
3350
- let delayConditions: String = toJson(object: delayConditionList)
3351
- if delayUpdateUtils.setMultiDelay(delayConditions: delayConditions) {
3352
- call.resolve()
3353
- } else {
3354
- call.reject("Failed to delay update")
3512
+ call.reject("Failed to delay update")
3513
+ return
3514
+ }
3515
+ let conditionMode = call.getString("conditionMode") ?? DelayUpdateUtils.DELAY_CONDITION_MODE_AND
3516
+ guard delayUpdateUtils.setConditionMode(conditionMode) else {
3517
+ if !delayUpdateUtils.setMultiDelay(delayConditions: previousConditions) {
3518
+ logger.error("Failed to restore previous delay conditions after setConditionMode failure")
3355
3519
  }
3520
+ if !delayUpdateUtils.setConditionMode(previousMode) {
3521
+ logger.error("Failed to restore previous delay condition mode after setConditionMode failure")
3522
+ }
3523
+ call.reject("Failed to delay update")
3524
+ return
3356
3525
  }
3526
+ call.resolve()
3357
3527
  }
3358
3528
 
3359
3529
  // Note: _setMultiDelay and _cancelDelay methods have been moved to DelayUpdateUtils class
@@ -3419,7 +3589,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
3419
3589
  if BundleStatus.SUCCESS.storedValue != current.getStatus() {
3420
3590
  logger.error("notifyAppReady was not called, roll back current bundle: \(current.toString())")
3421
3591
  logger.error("Did you forget to call 'notifyAppReady()' in your Capacitor App code?")
3422
- self.notifyListeners("updateFailed", data: [
3592
+ self.notifyListenersOnMain("updateFailed", data: [
3423
3593
  "bundle": current.toJSON()
3424
3594
  ])
3425
3595
  self.persistLastFailedBundle(current)
@@ -3451,8 +3621,14 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
3451
3621
  }
3452
3622
 
3453
3623
  func DeferredNotifyAppReadyCheck() {
3454
- self.checkRevert()
3455
3624
  self.appReadyCheck = nil
3625
+ // A suspended app can resume with this timer already expired, before willEnterForeground
3626
+ // re-arms it: its page could not run yet, so wait for the check of the next foreground.
3627
+ if self.appInBackground {
3628
+ logger.info("App is in background, notifyAppReady check deferred to the next foreground")
3629
+ return
3630
+ }
3631
+ self.checkRevert()
3456
3632
  }
3457
3633
 
3458
3634
  func endBackGroundTask() {
@@ -3461,7 +3637,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
3461
3637
  }
3462
3638
 
3463
3639
  private func notifyBundleSet(_ bundle: BundleInfo) {
3464
- self.notifyListeners("set", data: ["bundle": bundle.toJSON()], retainUntilConsumed: true)
3640
+ self.notifyListenersOnMain("set", data: ["bundle": bundle.toJSON()], retainUntilConsumed: true)
3465
3641
  }
3466
3642
 
3467
3643
  func sendReadyToJs(current: BundleInfo, msg: String) {
@@ -3473,7 +3649,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
3473
3649
  if self.consumePendingNotifyAppReady() {
3474
3650
  self.semaphoreWait(waitTime: self.appReadyTimeout)
3475
3651
  }
3476
- self.notifyListeners("appReady", data: ["bundle": current.toJSON(), "status": msg], retainUntilConsumed: true)
3652
+ self.notifyListenersOnMain("appReady", data: ["bundle": current.toJSON(), "status": msg], retainUntilConsumed: true)
3477
3653
 
3478
3654
  // Auto hide splashscreen if enabled
3479
3655
  // We show it on background when conditions are met, so we should hide it on foreground regardless of update outcome
@@ -4181,6 +4357,10 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4181
4357
  self.updateUrl = updateUrl
4182
4358
  }
4183
4359
 
4360
+ func notifyListenersOnMainForTesting(_ eventName: String, data: [String: Any]?, retainUntilConsumed: Bool) {
4361
+ self.notifyListenersOnMain(eventName, data: data, retainUntilConsumed: retainUntilConsumed)
4362
+ }
4363
+
4184
4364
  func downloadBundleForTesting(
4185
4365
  urlString: String,
4186
4366
  version: String,
@@ -4208,10 +4388,28 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4208
4388
  self.currentBuildVersion = currentBuildVersion
4209
4389
  }
4210
4390
 
4391
+ func resetStartupBundleAndReportAppLaunchStartForTesting(
4392
+ resetWhenUpdate: Bool,
4393
+ nativeBuildVersionChanged: Bool
4394
+ ) -> Bool {
4395
+ self.resetStartupBundleAndReportAppLaunchStart(
4396
+ resetWhenUpdate: resetWhenUpdate,
4397
+ nativeBuildVersionChanged: nativeBuildVersionChanged
4398
+ )
4399
+ }
4400
+
4401
+ func reportAppLaunchStartForTesting() {
4402
+ self.reportAppLaunchStart()
4403
+ }
4404
+
4211
4405
  func setAppReadyTimeoutForTesting(_ timeout: Int) {
4212
4406
  self.appReadyTimeout = timeout
4213
4407
  }
4214
4408
 
4409
+ func setDelayUpdateUtilsForTesting(_ delayUpdateUtils: DelayUpdateUtils) {
4410
+ self.delayUpdateUtils = delayUpdateUtils
4411
+ }
4412
+
4215
4413
  func armPendingNotifyAppReadyForTesting() {
4216
4414
  pendingNotifyAppReady = true
4217
4415
  }
@@ -4249,16 +4447,12 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4249
4447
  return
4250
4448
  }
4251
4449
  let payload: [String: Any] = ["version": version]
4252
- self.notifyListeners("breakingAvailable", data: payload)
4253
- self.notifyListeners("majorAvailable", data: payload)
4450
+ self.notifyListenersOnMain("breakingAvailable", data: payload)
4451
+ self.notifyListenersOnMain("majorAvailable", data: payload)
4254
4452
  }
4255
4453
 
4256
4454
  private func shouldNotifyBreakingEvents(response: AppVersion) -> Bool {
4257
- if response.breaking == true {
4258
- return true
4259
- }
4260
-
4261
- return response.error == "disable_auto_update_to_major" || response.message == "store_update_required"
4455
+ NativeUpdatePromptCoordinator.isNativeStoreUpdateBlock(response: response)
4262
4456
  }
4263
4457
 
4264
4458
  private func notifyBreakingEventsIfNeeded(response: AppVersion, version: String) {
@@ -4266,6 +4460,51 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4266
4460
  let eventVersion = version.isEmpty ? self.implementation.getCurrentBundle().getVersionName() : version
4267
4461
  self.notifyBreakingEvents(version: eventVersion)
4268
4462
  }
4463
+ self.nativeUpdatePromptCoordinator?.maybeShowForUpdateBlock(response: response)
4464
+ }
4465
+
4466
+ func currentBuildVersionForNativeUpdatePrompt() -> String {
4467
+ currentBuildVersion
4468
+ }
4469
+
4470
+ func openAppStoreFromNativeUpdatePrompt() {
4471
+ let bundleId = implementation.appId
4472
+ let lookupUrl = "https://itunes.apple.com/lookup?bundleId=\(bundleId)"
4473
+ DispatchQueue.global(qos: .background).async {
4474
+ guard let url = URL(string: lookupUrl) else {
4475
+ self.logger.error("Invalid App Store lookup URL from native update prompt")
4476
+ return
4477
+ }
4478
+
4479
+ let task = URLSession.shared.dataTask(with: url) { data, _, error in
4480
+ if let error = error {
4481
+ self.logger.error("App Store lookup from native update prompt failed: \(error.localizedDescription)")
4482
+ return
4483
+ }
4484
+
4485
+ guard let data = data,
4486
+ let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
4487
+ let results = json["results"] as? [[String: Any]],
4488
+ let appInfo = results.first,
4489
+ let trackId = appInfo["trackId"] as? Int else {
4490
+ self.logger.error("App Store lookup from native update prompt did not return a trackId for bundleId \(bundleId)")
4491
+ return
4492
+ }
4493
+
4494
+ self.openAppStorePageFromNativeUpdatePrompt(urlString: "https://apps.apple.com/app/id\(trackId)")
4495
+ }
4496
+ task.resume()
4497
+ }
4498
+ }
4499
+
4500
+ private func openAppStorePageFromNativeUpdatePrompt(urlString: String) {
4501
+ guard let url = URL(string: urlString) else {
4502
+ logger.error("Invalid App Store URL from native update prompt")
4503
+ return
4504
+ }
4505
+ DispatchQueue.main.async {
4506
+ UIApplication.shared.open(url, options: [:], completionHandler: nil)
4507
+ }
4269
4508
  }
4270
4509
 
4271
4510
  static func normalizedUpdateResponseKind(kind: String?) -> String {
@@ -4279,26 +4518,25 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4279
4518
  Self.normalizedUpdateResponseKind(kind: kind)
4280
4519
  }
4281
4520
 
4282
- private func endBackgroundDownloadAfterLatestError(
4521
+ /// Emits `updateCheckResult` for an error / kind response and logs it.
4522
+ @discardableResult
4523
+ private func notifyUpdateCheckResult(
4283
4524
  backendError: String,
4284
4525
  res: AppVersion,
4285
- current: BundleInfo,
4286
- plannedDirectUpdate: Bool
4287
- ) {
4288
- let statusCode = res.statusCode
4526
+ current: BundleInfo
4527
+ ) -> (kind: String, message: String, latestVersionName: String) {
4289
4528
  let responseKind = self.updateResponseKind(kind: res.kind)
4290
4529
  let responseMessage = res.message?.isEmpty == false ? res.message : nil
4291
4530
  let message = responseMessage ?? (backendError.isEmpty ? "server did not provide a message" : backendError)
4292
4531
  let latestVersionName = res.version.isEmpty ? current.getVersionName() : res.version
4293
- self.notifyListeners("updateCheckResult", data: [
4532
+ self.notifyListenersOnMain("updateCheckResult", data: [
4294
4533
  "kind": responseKind,
4295
4534
  "error": backendError,
4296
4535
  "message": message,
4297
- "statusCode": statusCode,
4536
+ "statusCode": res.statusCode,
4298
4537
  "version": latestVersionName,
4299
4538
  "bundle": current.toJSON()
4300
4539
  ])
4301
- self.notifyBreakingEventsIfNeeded(response: res, version: res.version)
4302
4540
 
4303
4541
  if responseKind == "up_to_date" {
4304
4542
  self.logger.info("No new version available")
@@ -4307,15 +4545,39 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4307
4545
  } else {
4308
4546
  self.logger.error("getLatest failed with error: \(backendError)")
4309
4547
  }
4548
+ return (responseKind, message, latestVersionName)
4549
+ }
4550
+
4551
+ private func endBackgroundDownloadAfterLatestError(
4552
+ backendError: String,
4553
+ res: AppVersion,
4554
+ current: BundleInfo,
4555
+ plannedDirectUpdate: Bool
4556
+ ) {
4557
+ let (responseKind, message, latestVersionName) = self.notifyUpdateCheckResult(
4558
+ backendError: backendError,
4559
+ res: res,
4560
+ current: current
4561
+ )
4562
+ self.notifyBreakingEventsIfNeeded(response: res, version: res.version)
4310
4563
 
4311
4564
  let isFailure = responseKind == "failed"
4565
+ if isFailure {
4566
+ // The check itself failed: nothing was downloaded, so report it apart from download_fail.
4567
+ self.implementation.sendStats(
4568
+ action: CapacitorUpdaterPlugin.updateCheckErrorAction,
4569
+ versionName: current.getVersionName(),
4570
+ oldVersionName: "",
4571
+ metadata: CapacitorUpdaterPlugin.updateCheckErrorMetadata(error: backendError, statusCode: res.statusCode)
4572
+ )
4573
+ }
4312
4574
  self.endBackGroundTaskWithNotif(
4313
4575
  msg: message,
4314
4576
  latestVersionName: latestVersionName,
4315
4577
  current: current,
4316
4578
  error: isFailure,
4317
4579
  plannedDirectUpdate: plannedDirectUpdate,
4318
- sendStats: isFailure
4580
+ sendStats: false
4319
4581
  )
4320
4582
  }
4321
4583
 
@@ -4343,10 +4605,10 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4343
4605
  if sendStats {
4344
4606
  self.implementation.sendStats(action: failureAction, versionName: current.getVersionName())
4345
4607
  }
4346
- self.notifyListeners(failureEvent, data: ["version": latestVersionName])
4608
+ self.notifyListenersOnMain(failureEvent, data: ["version": latestVersionName])
4347
4609
  }
4348
4610
  if notifyNoNeedUpdate {
4349
- self.notifyListeners("noNeedUpdate", data: ["bundle": current.toJSON()])
4611
+ self.notifyListenersOnMain("noNeedUpdate", data: ["bundle": current.toJSON()])
4350
4612
  }
4351
4613
  self.sendReadyToJs(current: current, msg: msg)
4352
4614
  logger.info("endBackGroundTaskWithNotif \(msg) current: \(current.getVersionName()) latestVersionName: \(latestVersionName)")
@@ -4388,7 +4650,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4388
4650
  DispatchQueue.global(qos: .userInitiated).async(execute: work)
4389
4651
  }
4390
4652
 
4391
- private func beginDownloadBackgroundTask() {
4653
+ func beginDownloadBackgroundTask() {
4392
4654
  let registerTask = {
4393
4655
  self.backgroundTaskID = UIApplication.shared.beginBackgroundTask(withName: "Finish Download Tasks") {
4394
4656
  self.endBackGroundTask()
@@ -4503,7 +4765,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4503
4765
  let builtinUpdateAvailable = !current.isBuiltin()
4504
4766
  if builtinUpdateAvailable {
4505
4767
  let builtinBundle = self.implementation.getBundleInfo(id: BundleInfo.ID_BUILTIN)
4506
- self.notifyListeners("updateAvailable", data: ["bundle": builtinBundle.toJSON()], retainUntilConsumed: true)
4768
+ self.notifyListenersOnMain("updateAvailable", data: ["bundle": builtinBundle.toJSON()], retainUntilConsumed: true)
4507
4769
  }
4508
4770
  self.endBackGroundTaskWithNotif(
4509
4771
  msg: "Latest version is builtin, autoUpdate onlyDownload",
@@ -4571,7 +4833,14 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4571
4833
  )
4572
4834
  return
4573
4835
  }
4574
- nextImpl = try self.implementation.download(url: downloadUrl, version: latestVersionName, sessionKey: sessionKey, link: res.link, comment: res.comment)
4836
+ nextImpl = try self.implementation.downloadVerified(
4837
+ url: downloadUrl,
4838
+ version: latestVersionName,
4839
+ sessionKey: sessionKey,
4840
+ expectedChecksum: res.checksum,
4841
+ link: res.link,
4842
+ comment: res.comment
4843
+ )
4575
4844
  }
4576
4845
  }
4577
4846
  guard let next = nextImpl else {
@@ -4628,11 +4897,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4628
4897
  let directUpdateAllowed = plannedDirectUpdate && !self.autoSplashscreenTimedOut
4629
4898
  if directUpdateAllowed {
4630
4899
  let delayUpdatePreferences = UserDefaults.standard.string(forKey: DelayUpdateUtils.DELAY_CONDITION_PREFERENCES) ?? "[]"
4631
- let delayConditionList: [DelayCondition] = self.fromJsonArr(json: delayUpdatePreferences).map { obj -> DelayCondition in
4632
- let kind: String = obj.value(forKey: "kind") as! String
4633
- let value: String? = obj.value(forKey: "value") as? String
4634
- return DelayCondition(kind: kind, value: value)
4635
- }
4900
+ let delayConditionList = DelayUpdateUtils.parseDelayConditions(json: delayUpdatePreferences)
4636
4901
  if !delayConditionList.isEmpty {
4637
4902
  self.logger.info("Update delayed until delay conditions met")
4638
4903
  self.endBackGroundTaskWithNotif(
@@ -4654,7 +4919,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4654
4919
  plannedDirectUpdate: plannedDirectUpdate
4655
4920
  )
4656
4921
  } else if self.queueBundleForNextBackgroundInstall(next) {
4657
- self.notifyListeners("updateAvailable", data: ["bundle": next.toJSON()])
4922
+ self.notifyListenersOnMain("updateAvailable", data: ["bundle": next.toJSON()])
4658
4923
  self.endBackGroundTaskWithNotif(
4659
4924
  msg: "Direct update reload failed, update will install next background",
4660
4925
  latestVersionName: latestVersionName,
@@ -4675,11 +4940,12 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4675
4940
  self.logger.info("Direct update skipped because splashscreen timeout occurred. Update will install on next app background.")
4676
4941
  }
4677
4942
  if self.queueBundleForNextBackgroundInstall(next) {
4678
- self.notifyListeners("updateAvailable", data: ["bundle": next.toJSON()])
4943
+ self.notifyListenersOnMain("updateAvailable", data: ["bundle": next.toJSON()])
4944
+ let installed = self.installNextIfInBackground()
4679
4945
  self.endBackGroundTaskWithNotif(
4680
- msg: "update downloaded, will install next background",
4946
+ msg: installed ? "update downloaded and installed in background" : "update downloaded, will install next background",
4681
4947
  latestVersionName: latestVersionName,
4682
- current: current,
4948
+ current: self.implementation.getCurrentBundle(),
4683
4949
  error: false,
4684
4950
  plannedDirectUpdate: plannedDirectUpdate
4685
4951
  )
@@ -4693,7 +4959,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4693
4959
  }
4694
4960
  } else {
4695
4961
  self.logger.info("autoUpdate is set to onlyDownload, downloaded update will not be set as next bundle")
4696
- self.notifyListeners("updateAvailable", data: ["bundle": next.toJSON()], retainUntilConsumed: true)
4962
+ self.notifyListenersOnMain("updateAvailable", data: ["bundle": next.toJSON()], retainUntilConsumed: true)
4697
4963
  self.endBackGroundTaskWithNotif(
4698
4964
  msg: "update downloaded, autoUpdate onlyDownload",
4699
4965
  latestVersionName: latestVersionName,
@@ -4708,7 +4974,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4708
4974
  self.logger.error("Error downloading file \(error.localizedDescription)")
4709
4975
  let current: BundleInfo = self.implementation.getCurrentBundle()
4710
4976
  self.endBackGroundTaskWithNotif(
4711
- msg: "Error downloading file",
4977
+ msg: (error as? ObjectSavableError) == .checksum ? "Error checksum" : "Error downloading file",
4712
4978
  latestVersionName: latestVersionName,
4713
4979
  current: current,
4714
4980
  plannedDirectUpdate: plannedDirectUpdate
@@ -4729,33 +4995,85 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4729
4995
  }
4730
4996
  }
4731
4997
 
4732
- private func installNext() {
4733
- if self.shouldBlockAutoUpdateForPreviewSession() {
4998
+ /// A download that finishes while the app is in the background (silent push,
4999
+ /// background fetch, cold background launch) would otherwise wait for the next
5000
+ /// didEnterBackground, which a background launch never posts, so the user would
5001
+ /// open the old bundle. Install now; the notifyAppReady check stays deferred
5002
+ /// until the app reaches the foreground.
5003
+ @discardableResult
5004
+ func installNextIfInBackground() -> Bool {
5005
+ let install = {
5006
+ self.appInBackground && self.shouldInstallQueuedBundleWhileInBackground() && self.installNext()
5007
+ }
5008
+ if Thread.isMainThread {
5009
+ return install()
5010
+ }
5011
+ return DispatchQueue.main.sync(execute: install)
5012
+ }
5013
+
5014
+ /// Immediate background install applies to deferred (`atBackground`) updates only.
5015
+ /// Direct-update modes retry from `appMovedToForeground` when a reload failed earlier.
5016
+ private func shouldInstallQueuedBundleWhileInBackground() -> Bool {
5017
+ autoUpdateMode == Self.autoUpdateModeBackground
5018
+ }
5019
+
5020
+ /// Direct-update modes queue `next` when an immediate reload fails; retry once the app is active again.
5021
+ private func shouldInstallQueuedBundleOnForeground() -> Bool {
5022
+ switch directUpdateMode {
5023
+ case Self.autoUpdateModeAlways, Self.autoUpdateModeLaunch:
5024
+ return true
5025
+ default:
5026
+ return false
5027
+ }
5028
+ }
5029
+
5030
+ private func installQueuedBundleOnForegroundIfNeeded() {
5031
+ guard shouldInstallQueuedBundleOnForeground() else {
4734
5032
  return
4735
5033
  }
4736
- let delayUpdatePreferences = UserDefaults.standard.string(forKey: DelayUpdateUtils.DELAY_CONDITION_PREFERENCES) ?? "[]"
4737
- let delayConditionList: [DelayCondition] = fromJsonArr(json: delayUpdatePreferences).map { obj -> DelayCondition in
4738
- let kind: String = obj.value(forKey: "kind") as! String
4739
- let value: String? = obj.value(forKey: "value") as? String
4740
- return DelayCondition(kind: kind, value: value)
5034
+ let current = self.implementation.getCurrentBundle()
5035
+ guard let next = self.implementation.getNextBundle(),
5036
+ !next.isErrorStatus(),
5037
+ next.getVersionName() != current.getVersionName() else {
5038
+ return
5039
+ }
5040
+ _ = self.installNext()
5041
+ }
5042
+
5043
+ /// Returns true when the next bundle became the active WebView bundle.
5044
+ @discardableResult
5045
+ private func installNext() -> Bool {
5046
+ if self.shouldBlockAutoUpdateForPreviewSession() {
5047
+ return false
4741
5048
  }
5049
+ let delayUpdatePreferences = UserDefaults.standard.string(forKey: DelayUpdateUtils.DELAY_CONDITION_PREFERENCES) ?? "[]"
5050
+ let delayConditionList = DelayUpdateUtils.parseDelayConditions(json: delayUpdatePreferences)
4742
5051
  if !delayConditionList.isEmpty {
4743
5052
  logger.info("Update delayed until delay conditions met")
4744
- return
5053
+ return false
4745
5054
  }
4746
5055
  let current: BundleInfo = self.implementation.getCurrentBundle()
4747
5056
  let next: BundleInfo? = self.implementation.getNextBundle()
4748
5057
 
4749
5058
  if next != nil && !next!.isErrorStatus() && next!.getVersionName() != current.getVersionName() {
4750
5059
  logger.info("Next bundle is: \(next!.toString())")
4751
- if self.implementation.set(bundle: next!) && self._reload() {
4752
- logger.info("Updated to bundle: \(next!.toString())")
4753
- self.notifyBundleSet(next!)
4754
- _ = self.implementation.setNextBundle(next: Optional<String>.none)
4755
- } else {
5060
+ let resetState = self.implementation.captureResetState()
5061
+ guard self.implementation.set(bundle: next!) else {
4756
5062
  logger.error("Update to bundle: \(next!.toString()) Failed!")
5063
+ return false
5064
+ }
5065
+ guard self._reload() else {
5066
+ // Built-in `set` may reset fallback/next; restore the full pre-install state for retry.
5067
+ self.implementation.restoreResetState(resetState)
5068
+ logger.error("Update to bundle: \(next!.toString()) Failed! Reload failed, keeping it as next")
5069
+ return false
4757
5070
  }
5071
+ logger.info("Updated to bundle: \(next!.toString())")
5072
+ self.notifyBundleSet(next!)
5073
+ _ = self.implementation.setNextBundle(next: Optional<String>.none)
5074
+ return true
4758
5075
  }
5076
+ return false
4759
5077
  }
4760
5078
 
4761
5079
  @objc private func toJson(object: Any) -> String {
@@ -4765,18 +5083,8 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4765
5083
  return String(data: data, encoding: String.Encoding.utf8) ?? ""
4766
5084
  }
4767
5085
 
4768
- @objc private func fromJsonArr(json: String) -> [NSObject] {
4769
- guard let jsonData = json.data(using: .utf8) else {
4770
- return []
4771
- }
4772
- let object = try? JSONSerialization.jsonObject(
4773
- with: jsonData,
4774
- options: .mutableContainers
4775
- ) as? [NSObject]
4776
- return object ?? []
4777
- }
4778
-
4779
5086
  @objc func appMovedToForeground() {
5087
+ self.appInBackground = false
4780
5088
  appHealthTracker?.markForeground(true)
4781
5089
  let current: BundleInfo = self.implementation.getCurrentBundle()
4782
5090
  self.implementation.sendStats(action: "app_moved_to_foreground", versionName: current.getVersionName())
@@ -4786,6 +5094,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4786
5094
  backgroundWork!.cancel()
4787
5095
  logger.info("Background Timer Task canceled, Activity resumed before timer completes")
4788
5096
  }
5097
+ self.installQueuedBundleOnForegroundIfNeeded()
4789
5098
  if self._isAutoUpdateEnabled() {
4790
5099
  // Check if download is already in progress (with timeout protection)
4791
5100
  if !isDownloadStuckOrTimedOut() {
@@ -4824,30 +5133,43 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4824
5133
  return
4825
5134
  }
4826
5135
  DispatchQueue.global(qos: .utility).async {
4827
- if self.shouldBlockAutoUpdateForPreviewSession() {
4828
- return
4829
- }
4830
- let res = self.implementation.getLatest(url: url, channel: nil)
4831
- let current = self.implementation.getCurrentBundle()
4832
- if self.shouldBlockAutoUpdateForPreviewSession() {
4833
- return
4834
- }
4835
-
4836
- if res.version != current.getVersionName() {
4837
- self.logger.info("New version found: \(res.version)")
4838
- // Check if download is already in progress (with timeout protection)
4839
- if !self.isDownloadStuckOrTimedOut() {
4840
- self.backgroundDownload()
4841
- } else {
4842
- self.logger.info("Download already in progress, skipping duplicate download request")
4843
- }
4844
- }
5136
+ self.runPeriodicUpdateCheck(url: url)
4845
5137
  }
4846
5138
  }
4847
5139
  RunLoop.current.add(periodicUpdateTimer!, forMode: .default)
4848
5140
  }
4849
5141
 
5142
+ func runPeriodicUpdateCheck(url: URL) {
5143
+ if self.shouldBlockAutoUpdateForPreviewSession() {
5144
+ return
5145
+ }
5146
+ let res = self.implementation.getLatest(url: url, channel: nil)
5147
+ let current = self.implementation.getCurrentBundle()
5148
+ if self.shouldBlockAutoUpdateForPreviewSession() {
5149
+ return
5150
+ }
5151
+
5152
+ // Error / kind responses carry no downloadable bundle: report them, like Android.
5153
+ let backendError = res.error ?? ""
5154
+ let backendKind = res.kind ?? ""
5155
+ if !backendError.isEmpty || !backendKind.isEmpty {
5156
+ self.notifyUpdateCheckResult(backendError: backendError, res: res, current: current)
5157
+ return
5158
+ }
5159
+
5160
+ if !res.version.isEmpty && res.version != current.getVersionName() {
5161
+ self.logger.info("New version found: \(res.version)")
5162
+ // Check if download is already in progress (with timeout protection)
5163
+ if !self.isDownloadStuckOrTimedOut() {
5164
+ self.backgroundDownload()
5165
+ } else {
5166
+ self.logger.info("Download already in progress, skipping duplicate download request")
5167
+ }
5168
+ }
5169
+ }
5170
+
4850
5171
  @objc func appMovedToBackground() {
5172
+ self.appInBackground = true
4851
5173
  // Reset timeout flag at start of each background cycle
4852
5174
  self.autoSplashscreenTimedOut = false
4853
5175
  appHealthTracker?.markForeground(false)
@@ -4888,6 +5210,8 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4888
5210
  }
4889
5211
 
4890
5212
  @objc func getNextBundle(_ call: CAPPluginCall) {
5213
+ // Heals a next bundle left stored after it was activated (set() did not clear it before).
5214
+ self.implementation.clearNextBundleIfCurrent()
4891
5215
  let bundle = self.implementation.getNextBundle()
4892
5216
  if bundle == nil || bundle?.isUnknown() == true {
4893
5217
  call.resolve()
@@ -5038,8 +5362,8 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
5038
5362
  // Determine update availability by comparing versions
5039
5363
  if let availableVersion = availableVersion {
5040
5364
  do {
5041
- let currentVer = try Version(currentVersionName)
5042
- let availableVer = try Version(availableVersion)
5365
+ let currentVer = try CapgoSemanticVersion(currentVersionName)
5366
+ let availableVer = try CapgoSemanticVersion(availableVersion)
5043
5367
  if availableVer > currentVer {
5044
5368
  result["updateAvailability"] = AppUpdateAvailability.updateAvailable.rawValue
5045
5369
  } else {
@@ -5067,6 +5391,10 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
5067
5391
  }
5068
5392
 
5069
5393
  self.resolveCall(call, data: result)
5394
+ if let availability = result["updateAvailability"] as? Int,
5395
+ availability == AppUpdateAvailability.updateAvailable.rawValue {
5396
+ self.nativeUpdatePromptCoordinator?.maybeShowForStoreUpdateAvailable()
5397
+ }
5070
5398
  } catch {
5071
5399
  self.logger.error("Failed to parse App Store response: \(error.localizedDescription)")
5072
5400
  self.rejectCall(call, message: "Failed to parse App Store response: \(error.localizedDescription)")