@capgo/capacitor-updater 6.51.23 → 6.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 = "6.51.23"
98
+ private let pluginVersion: String = "6.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 {
@@ -1628,7 +1687,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
1628
1687
  if let manifestEntries = manifestEntries {
1629
1688
  next = try self.implementation.downloadManifest(manifest: manifestEntries, version: version, sessionKey: sessionKey)
1630
1689
  } else {
1631
- next = try self.implementation.download(url: url, version: version, sessionKey: sessionKey)
1690
+ next = try self.implementation.downloadVerified(url: url, version: version, sessionKey: sessionKey, expectedChecksum: rawChecksum)
1632
1691
  }
1633
1692
 
1634
1693
  if manifestEntries == nil {
@@ -1716,6 +1775,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
1716
1775
  self.logger.error("Cannot get capBridge")
1717
1776
  return false
1718
1777
  }
1778
+ self.armReadyGuard(webView: vc.webView)
1719
1779
  if self.keepUrlPathAfterReload {
1720
1780
  if let currentURL = vc.webView?.url {
1721
1781
  capBridge.setServerBasePath(dest.path)
@@ -1767,7 +1827,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
1767
1827
  return false
1768
1828
  }
1769
1829
  self.checkAppReady()
1770
- self.notifyListeners("appReloaded", data: [:])
1830
+ self.notifyListenersOnMain("appReloaded", data: [:])
1771
1831
  return true
1772
1832
  }
1773
1833
 
@@ -1790,7 +1850,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
1790
1850
  return false
1791
1851
  }
1792
1852
  self.checkAppReady()
1793
- self.notifyListeners("appReloaded", data: [:])
1853
+ self.notifyListenersOnMain("appReloaded", data: [:])
1794
1854
  return true
1795
1855
  }
1796
1856
 
@@ -1907,7 +1967,11 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
1907
1967
  if !res {
1908
1968
  logger.info("Bundle successfully set to: \(id) ")
1909
1969
  call.reject("Update failed, id \(id) doesn't exist")
1910
- } else if self.previewSessionEnabled {
1970
+ return
1971
+ }
1972
+ // The bundle is now active: it must not stay reported as the pending next bundle.
1973
+ self.implementation.clearNextBundleIfCurrent()
1974
+ if self.previewSessionEnabled {
1911
1975
  let bundle = self.implementation.getBundleInfo(id: id)
1912
1976
  _ = self.recordPreviewBundle(bundle)
1913
1977
  if !self.reloadWithoutWaitingForAppReady() {
@@ -2705,12 +2769,12 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
2705
2769
  var response: URLResponse?
2706
2770
  var responseError: Error?
2707
2771
 
2708
- URLSession.shared.dataTask(with: request) { data, urlResponse, error in
2772
+ self.implementation.startRawDataTask(request) { data, urlResponse, error in
2709
2773
  responseData = data
2710
2774
  response = urlResponse
2711
2775
  responseError = error
2712
2776
  semaphore.signal()
2713
- }.resume()
2777
+ }
2714
2778
 
2715
2779
  if semaphore.wait(timeout: .now() + 60) == .timedOut {
2716
2780
  throw makePreviewError("Preview payload request timed out")
@@ -3001,8 +3065,13 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
3001
3065
  logger.error("Error no url or wrong format")
3002
3066
  return "unavailable"
3003
3067
  }
3068
+ // The TS contract only knows queued / already_running / unavailable.
3004
3069
  if self.shouldBlockAutoUpdateForPreviewSession() {
3005
- return "preview_session"
3070
+ return "unavailable"
3071
+ }
3072
+ if !self._isAutoUpdateEnabled() {
3073
+ logger.info("Auto update is disabled, update check not triggered")
3074
+ return "unavailable"
3006
3075
  }
3007
3076
  if self.isDownloadStuckOrTimedOut() {
3008
3077
  logger.info("Download already in progress, skipping duplicate download request")
@@ -3025,11 +3094,16 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
3025
3094
  self.saveCallForAsyncHandling(call)
3026
3095
  DispatchQueue.global(qos: .utility).async {
3027
3096
  let configDefaultChannel = self.getConfig().getString("defaultChannel", "")!
3028
- let res = self.implementation.unsetChannel(defaultChannelKey: self.defaultChannelDefaultsKey, configDefaultChannel: configDefaultChannel)
3097
+ let res = self.implementation.unsetChannel(
3098
+ defaultChannelKey: self.defaultChannelDefaultsKey,
3099
+ configDefaultChannel: configDefaultChannel,
3100
+ allowSetDefaultChannel: self.allowSetDefaultChannel
3101
+ )
3029
3102
  if res.error != "" {
3030
- self.rejectCall(call, message: res.error, code: "UNSETCHANNEL_FAILED", data: [
3031
- "message": res.error,
3032
- "error": res.error.contains("Channel URL") ? "missing_config" : "request_failed"
3103
+ let message = res.message.isEmpty ? res.error : res.message
3104
+ self.rejectCall(call, message: message, code: "UNSETCHANNEL_FAILED", data: [
3105
+ "message": message,
3106
+ "error": res.error
3033
3107
  ])
3034
3108
  } else {
3035
3109
  guard self.persistDefaultChannelStateFromDefaults() else {
@@ -3077,9 +3151,20 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
3077
3151
  "message": res.error
3078
3152
  ])
3079
3153
  }
3080
- self.rejectCall(call, message: res.error, code: "SETCHANNEL_FAILED", data: [
3081
- "message": res.error,
3082
- "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"
3154
+ let message = res.message.isEmpty ? res.error : res.message
3155
+ let errorCode: String
3156
+ if res.error == "disabled_by_config" {
3157
+ errorCode = res.error
3158
+ } else if res.error.contains("cannot_update_via_private_channel") || res.error.contains("channel_self_set_not_allowed") {
3159
+ errorCode = "channel_private"
3160
+ } else if res.error.contains("Channel URL") {
3161
+ errorCode = "missing_config"
3162
+ } else {
3163
+ errorCode = "request_failed"
3164
+ }
3165
+ self.rejectCall(call, message: message, code: "SETCHANNEL_FAILED", data: [
3166
+ "message": message,
3167
+ "error": errorCode
3083
3168
  ])
3084
3169
  } else {
3085
3170
  guard self.persistDefaultChannelStateFromDefaults() else {
@@ -3272,11 +3357,10 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
3272
3357
  }
3273
3358
 
3274
3359
  private func reportAppLaunchReady(_ bundle: BundleInfo) {
3275
- guard !self.implementation.statsUrl.isEmpty, !launchReadyReported else {
3360
+ guard !self.implementation.statsUrl.isEmpty, self.claimLaunchReport(timeout: false) else {
3276
3361
  return
3277
3362
  }
3278
3363
 
3279
- launchReadyReported = true
3280
3364
  let duration = max(0, Int64(Date().timeIntervalSince1970 * 1000) - launchStartedAtMs)
3281
3365
  self.implementation.sendStats(
3282
3366
  action: "app_launch_ready",
@@ -3290,8 +3374,23 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
3290
3374
  )
3291
3375
  }
3292
3376
 
3377
+ /// The launch outcome is reported once: either ready or timeout, never both, never twice.
3378
+ private func claimLaunchReport(timeout: Bool) -> Bool {
3379
+ launchReportLock.lock()
3380
+ defer { launchReportLock.unlock() }
3381
+ if launchReadyReported || launchTimeoutReported {
3382
+ return false
3383
+ }
3384
+ if timeout {
3385
+ launchTimeoutReported = true
3386
+ } else {
3387
+ launchReadyReported = true
3388
+ }
3389
+ return true
3390
+ }
3391
+
3293
3392
  private func reportAppLaunchTimeout(_ bundle: BundleInfo) {
3294
- guard !self.implementation.statsUrl.isEmpty else {
3393
+ guard !self.implementation.statsUrl.isEmpty, self.claimLaunchReport(timeout: true) else {
3295
3394
  return
3296
3395
  }
3297
3396
 
@@ -3309,7 +3408,65 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
3309
3408
  )
3310
3409
  }
3311
3410
 
3411
+ static func shouldAcceptReadyCall(guardArmed: Bool, expectedGeneration: Int, reportedGeneration: Int?) -> Bool {
3412
+ if !guardArmed {
3413
+ return true
3414
+ }
3415
+ guard let reportedGeneration else {
3416
+ return false
3417
+ }
3418
+ return reportedGeneration == expectedGeneration
3419
+ }
3420
+
3421
+ static func readyGenerationScript(_ generation: Int) -> String {
3422
+ // Wrap Capacitor.nativePromise, not the plugin proxy. registerPlugin's get trap
3423
+ // ignores assignments to notifyAppReady. Each document keeps its own generation.
3424
+ 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);}})();"
3425
+ }
3426
+
3427
+ private func armReadyGuard(webView: WKWebView?) {
3428
+ let generation = self.readyGeneration + 1
3429
+ guard let webView else {
3430
+ logger.warn("Cannot stamp notifyAppReady generation without a webview")
3431
+ self.readyGuardArmed = false
3432
+ return
3433
+ }
3434
+ let userScript = WKUserScript(
3435
+ source: CapacitorUpdaterPlugin.readyGenerationScript(generation),
3436
+ injectionTime: .atDocumentStart,
3437
+ forMainFrameOnly: true
3438
+ )
3439
+ webView.configuration.userContentController.addUserScript(userScript)
3440
+ self.readyGeneration = generation
3441
+ self.readyGuardArmed = true
3442
+ }
3443
+
3444
+ private func reportedReadyGeneration(_ call: CAPPluginCall) -> Int? {
3445
+ if let generation = call.getInt("loadGeneration") {
3446
+ return generation
3447
+ }
3448
+ // The bridge often boxes JS numbers as NSNumber, which getInt does not cast.
3449
+ if let number = call.getValue("loadGeneration") as? NSNumber {
3450
+ return number.intValue
3451
+ }
3452
+ return nil
3453
+ }
3454
+
3455
+ private func acceptsReadyCall(_ call: CAPPluginCall) -> Bool {
3456
+ let reported = self.readyGuardArmed ? self.reportedReadyGeneration(call) : nil
3457
+ return CapacitorUpdaterPlugin.shouldAcceptReadyCall(
3458
+ guardArmed: self.readyGuardArmed,
3459
+ expectedGeneration: self.readyGeneration,
3460
+ reportedGeneration: reported
3461
+ )
3462
+ }
3463
+
3312
3464
  @objc func notifyAppReady(_ call: CAPPluginCall) {
3465
+ if !self.acceptsReadyCall(call) {
3466
+ logger.info("Ignoring notifyAppReady from a page that is no longer current")
3467
+ call.resolve(["bundle": self.implementation.getCurrentBundle().toJSON()])
3468
+ return
3469
+ }
3313
3470
  self.semaphoreDown()
3314
3471
  let bundle = self.implementation.getCurrentBundle()
3315
3472
  self.implementation.setSuccess(bundle: bundle, autoDeletePrevious: self.autoDeletePrevious)
@@ -3328,7 +3485,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
3328
3485
  return
3329
3486
  }
3330
3487
 
3331
- // Handle background conditions with empty value (set to "0")
3488
+ var conditionsPayload: Any = delayConditionList
3332
3489
  if var modifiableList = delayConditionList as? [[String: Any]] {
3333
3490
  for i in 0..<modifiableList.count {
3334
3491
  if let kind = modifiableList[i]["kind"] as? String,
@@ -3338,20 +3495,33 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
3338
3495
  modifiableList[i]["value"] = "0"
3339
3496
  }
3340
3497
  }
3341
- let delayConditions: String = toJson(object: modifiableList)
3342
- if delayUpdateUtils.setMultiDelay(delayConditions: delayConditions) {
3343
- call.resolve()
3344
- } else {
3345
- call.reject("Failed to delay update")
3498
+ conditionsPayload = modifiableList
3499
+ }
3500
+
3501
+ let delayConditions: String = toJson(object: conditionsPayload)
3502
+ let previousConditions = UserDefaults.standard.string(
3503
+ forKey: DelayUpdateUtils.DELAY_CONDITION_PREFERENCES
3504
+ ) ?? "[]"
3505
+ let previousMode = delayUpdateUtils.getConditionMode()
3506
+ guard delayUpdateUtils.setMultiDelay(delayConditions: delayConditions) else {
3507
+ if !delayUpdateUtils.setMultiDelay(delayConditions: previousConditions) {
3508
+ logger.error("Failed to restore previous delay conditions after setMultiDelay failure")
3346
3509
  }
3347
- } else {
3348
- let delayConditions: String = toJson(object: delayConditionList)
3349
- if delayUpdateUtils.setMultiDelay(delayConditions: delayConditions) {
3350
- call.resolve()
3351
- } else {
3352
- call.reject("Failed to delay update")
3510
+ call.reject("Failed to delay update")
3511
+ return
3512
+ }
3513
+ let conditionMode = call.getString("conditionMode") ?? DelayUpdateUtils.DELAY_CONDITION_MODE_AND
3514
+ guard delayUpdateUtils.setConditionMode(conditionMode) else {
3515
+ if !delayUpdateUtils.setMultiDelay(delayConditions: previousConditions) {
3516
+ logger.error("Failed to restore previous delay conditions after setConditionMode failure")
3353
3517
  }
3518
+ if !delayUpdateUtils.setConditionMode(previousMode) {
3519
+ logger.error("Failed to restore previous delay condition mode after setConditionMode failure")
3520
+ }
3521
+ call.reject("Failed to delay update")
3522
+ return
3354
3523
  }
3524
+ call.resolve()
3355
3525
  }
3356
3526
 
3357
3527
  // Note: _setMultiDelay and _cancelDelay methods have been moved to DelayUpdateUtils class
@@ -3417,7 +3587,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
3417
3587
  if BundleStatus.SUCCESS.storedValue != current.getStatus() {
3418
3588
  logger.error("notifyAppReady was not called, roll back current bundle: \(current.toString())")
3419
3589
  logger.error("Did you forget to call 'notifyAppReady()' in your Capacitor App code?")
3420
- self.notifyListeners("updateFailed", data: [
3590
+ self.notifyListenersOnMain("updateFailed", data: [
3421
3591
  "bundle": current.toJSON()
3422
3592
  ])
3423
3593
  self.persistLastFailedBundle(current)
@@ -3449,8 +3619,14 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
3449
3619
  }
3450
3620
 
3451
3621
  func DeferredNotifyAppReadyCheck() {
3452
- self.checkRevert()
3453
3622
  self.appReadyCheck = nil
3623
+ // A suspended app can resume with this timer already expired, before willEnterForeground
3624
+ // re-arms it: its page could not run yet, so wait for the check of the next foreground.
3625
+ if self.appInBackground {
3626
+ logger.info("App is in background, notifyAppReady check deferred to the next foreground")
3627
+ return
3628
+ }
3629
+ self.checkRevert()
3454
3630
  }
3455
3631
 
3456
3632
  func endBackGroundTask() {
@@ -3459,7 +3635,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
3459
3635
  }
3460
3636
 
3461
3637
  private func notifyBundleSet(_ bundle: BundleInfo) {
3462
- self.notifyListeners("set", data: ["bundle": bundle.toJSON()], retainUntilConsumed: true)
3638
+ self.notifyListenersOnMain("set", data: ["bundle": bundle.toJSON()], retainUntilConsumed: true)
3463
3639
  }
3464
3640
 
3465
3641
  func sendReadyToJs(current: BundleInfo, msg: String) {
@@ -3471,7 +3647,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
3471
3647
  if self.consumePendingNotifyAppReady() {
3472
3648
  self.semaphoreWait(waitTime: self.appReadyTimeout)
3473
3649
  }
3474
- self.notifyListeners("appReady", data: ["bundle": current.toJSON(), "status": msg], retainUntilConsumed: true)
3650
+ self.notifyListenersOnMain("appReady", data: ["bundle": current.toJSON(), "status": msg], retainUntilConsumed: true)
3475
3651
 
3476
3652
  // Auto hide splashscreen if enabled
3477
3653
  // We show it on background when conditions are met, so we should hide it on foreground regardless of update outcome
@@ -4204,6 +4380,10 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4204
4380
  self.updateUrl = updateUrl
4205
4381
  }
4206
4382
 
4383
+ func notifyListenersOnMainForTesting(_ eventName: String, data: [String: Any]?, retainUntilConsumed: Bool) {
4384
+ self.notifyListenersOnMain(eventName, data: data, retainUntilConsumed: retainUntilConsumed)
4385
+ }
4386
+
4207
4387
  func downloadBundleForTesting(
4208
4388
  urlString: String,
4209
4389
  version: String,
@@ -4231,10 +4411,28 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4231
4411
  self.currentBuildVersion = currentBuildVersion
4232
4412
  }
4233
4413
 
4414
+ func resetStartupBundleAndReportAppLaunchStartForTesting(
4415
+ resetWhenUpdate: Bool,
4416
+ nativeBuildVersionChanged: Bool
4417
+ ) -> Bool {
4418
+ self.resetStartupBundleAndReportAppLaunchStart(
4419
+ resetWhenUpdate: resetWhenUpdate,
4420
+ nativeBuildVersionChanged: nativeBuildVersionChanged
4421
+ )
4422
+ }
4423
+
4424
+ func reportAppLaunchStartForTesting() {
4425
+ self.reportAppLaunchStart()
4426
+ }
4427
+
4234
4428
  func setAppReadyTimeoutForTesting(_ timeout: Int) {
4235
4429
  self.appReadyTimeout = timeout
4236
4430
  }
4237
4431
 
4432
+ func setDelayUpdateUtilsForTesting(_ delayUpdateUtils: DelayUpdateUtils) {
4433
+ self.delayUpdateUtils = delayUpdateUtils
4434
+ }
4435
+
4238
4436
  func armPendingNotifyAppReadyForTesting() {
4239
4437
  pendingNotifyAppReady = true
4240
4438
  }
@@ -4272,16 +4470,12 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4272
4470
  return
4273
4471
  }
4274
4472
  let payload: [String: Any] = ["version": version]
4275
- self.notifyListeners("breakingAvailable", data: payload)
4276
- self.notifyListeners("majorAvailable", data: payload)
4473
+ self.notifyListenersOnMain("breakingAvailable", data: payload)
4474
+ self.notifyListenersOnMain("majorAvailable", data: payload)
4277
4475
  }
4278
4476
 
4279
4477
  private func shouldNotifyBreakingEvents(response: AppVersion) -> Bool {
4280
- if response.breaking == true {
4281
- return true
4282
- }
4283
-
4284
- return response.error == "disable_auto_update_to_major" || response.message == "store_update_required"
4478
+ NativeUpdatePromptCoordinator.isNativeStoreUpdateBlock(response: response)
4285
4479
  }
4286
4480
 
4287
4481
  private func notifyBreakingEventsIfNeeded(response: AppVersion, version: String) {
@@ -4289,6 +4483,51 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4289
4483
  let eventVersion = version.isEmpty ? self.implementation.getCurrentBundle().getVersionName() : version
4290
4484
  self.notifyBreakingEvents(version: eventVersion)
4291
4485
  }
4486
+ self.nativeUpdatePromptCoordinator?.maybeShowForUpdateBlock(response: response)
4487
+ }
4488
+
4489
+ func currentBuildVersionForNativeUpdatePrompt() -> String {
4490
+ currentBuildVersion
4491
+ }
4492
+
4493
+ func openAppStoreFromNativeUpdatePrompt() {
4494
+ let bundleId = implementation.appId
4495
+ let lookupUrl = "https://itunes.apple.com/lookup?bundleId=\(bundleId)"
4496
+ DispatchQueue.global(qos: .background).async {
4497
+ guard let url = URL(string: lookupUrl) else {
4498
+ self.logger.error("Invalid App Store lookup URL from native update prompt")
4499
+ return
4500
+ }
4501
+
4502
+ let task = URLSession.shared.dataTask(with: url) { data, _, error in
4503
+ if let error = error {
4504
+ self.logger.error("App Store lookup from native update prompt failed: \(error.localizedDescription)")
4505
+ return
4506
+ }
4507
+
4508
+ guard let data = data,
4509
+ let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
4510
+ let results = json["results"] as? [[String: Any]],
4511
+ let appInfo = results.first,
4512
+ let trackId = appInfo["trackId"] as? Int else {
4513
+ self.logger.error("App Store lookup from native update prompt did not return a trackId for bundleId \(bundleId)")
4514
+ return
4515
+ }
4516
+
4517
+ self.openAppStorePageFromNativeUpdatePrompt(urlString: "https://apps.apple.com/app/id\(trackId)")
4518
+ }
4519
+ task.resume()
4520
+ }
4521
+ }
4522
+
4523
+ private func openAppStorePageFromNativeUpdatePrompt(urlString: String) {
4524
+ guard let url = URL(string: urlString) else {
4525
+ logger.error("Invalid App Store URL from native update prompt")
4526
+ return
4527
+ }
4528
+ DispatchQueue.main.async {
4529
+ UIApplication.shared.open(url, options: [:], completionHandler: nil)
4530
+ }
4292
4531
  }
4293
4532
 
4294
4533
  static func normalizedUpdateResponseKind(kind: String?) -> String {
@@ -4302,26 +4541,25 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4302
4541
  Self.normalizedUpdateResponseKind(kind: kind)
4303
4542
  }
4304
4543
 
4305
- private func endBackgroundDownloadAfterLatestError(
4544
+ /// Emits `updateCheckResult` for an error / kind response and logs it.
4545
+ @discardableResult
4546
+ private func notifyUpdateCheckResult(
4306
4547
  backendError: String,
4307
4548
  res: AppVersion,
4308
- current: BundleInfo,
4309
- plannedDirectUpdate: Bool
4310
- ) {
4311
- let statusCode = res.statusCode
4549
+ current: BundleInfo
4550
+ ) -> (kind: String, message: String, latestVersionName: String) {
4312
4551
  let responseKind = self.updateResponseKind(kind: res.kind)
4313
4552
  let responseMessage = res.message?.isEmpty == false ? res.message : nil
4314
4553
  let message = responseMessage ?? (backendError.isEmpty ? "server did not provide a message" : backendError)
4315
4554
  let latestVersionName = res.version.isEmpty ? current.getVersionName() : res.version
4316
- self.notifyListeners("updateCheckResult", data: [
4555
+ self.notifyListenersOnMain("updateCheckResult", data: [
4317
4556
  "kind": responseKind,
4318
4557
  "error": backendError,
4319
4558
  "message": message,
4320
- "statusCode": statusCode,
4559
+ "statusCode": res.statusCode,
4321
4560
  "version": latestVersionName,
4322
4561
  "bundle": current.toJSON()
4323
4562
  ])
4324
- self.notifyBreakingEventsIfNeeded(response: res, version: res.version)
4325
4563
 
4326
4564
  if responseKind == "up_to_date" {
4327
4565
  self.logger.info("No new version available")
@@ -4330,15 +4568,39 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4330
4568
  } else {
4331
4569
  self.logger.error("getLatest failed with error: \(backendError)")
4332
4570
  }
4571
+ return (responseKind, message, latestVersionName)
4572
+ }
4573
+
4574
+ private func endBackgroundDownloadAfterLatestError(
4575
+ backendError: String,
4576
+ res: AppVersion,
4577
+ current: BundleInfo,
4578
+ plannedDirectUpdate: Bool
4579
+ ) {
4580
+ let (responseKind, message, latestVersionName) = self.notifyUpdateCheckResult(
4581
+ backendError: backendError,
4582
+ res: res,
4583
+ current: current
4584
+ )
4585
+ self.notifyBreakingEventsIfNeeded(response: res, version: res.version)
4333
4586
 
4334
4587
  let isFailure = responseKind == "failed"
4588
+ if isFailure {
4589
+ // The check itself failed: nothing was downloaded, so report it apart from download_fail.
4590
+ self.implementation.sendStats(
4591
+ action: CapacitorUpdaterPlugin.updateCheckErrorAction,
4592
+ versionName: current.getVersionName(),
4593
+ oldVersionName: "",
4594
+ metadata: CapacitorUpdaterPlugin.updateCheckErrorMetadata(error: backendError, statusCode: res.statusCode)
4595
+ )
4596
+ }
4335
4597
  self.endBackGroundTaskWithNotif(
4336
4598
  msg: message,
4337
4599
  latestVersionName: latestVersionName,
4338
4600
  current: current,
4339
4601
  error: isFailure,
4340
4602
  plannedDirectUpdate: plannedDirectUpdate,
4341
- sendStats: isFailure
4603
+ sendStats: false
4342
4604
  )
4343
4605
  }
4344
4606
 
@@ -4366,10 +4628,10 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4366
4628
  if sendStats {
4367
4629
  self.implementation.sendStats(action: failureAction, versionName: current.getVersionName())
4368
4630
  }
4369
- self.notifyListeners(failureEvent, data: ["version": latestVersionName])
4631
+ self.notifyListenersOnMain(failureEvent, data: ["version": latestVersionName])
4370
4632
  }
4371
4633
  if notifyNoNeedUpdate {
4372
- self.notifyListeners("noNeedUpdate", data: ["bundle": current.toJSON()])
4634
+ self.notifyListenersOnMain("noNeedUpdate", data: ["bundle": current.toJSON()])
4373
4635
  }
4374
4636
  self.sendReadyToJs(current: current, msg: msg)
4375
4637
  logger.info("endBackGroundTaskWithNotif \(msg) current: \(current.getVersionName()) latestVersionName: \(latestVersionName)")
@@ -4411,7 +4673,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4411
4673
  DispatchQueue.global(qos: .userInitiated).async(execute: work)
4412
4674
  }
4413
4675
 
4414
- private func beginDownloadBackgroundTask() {
4676
+ func beginDownloadBackgroundTask() {
4415
4677
  let registerTask = {
4416
4678
  self.backgroundTaskID = UIApplication.shared.beginBackgroundTask(withName: "Finish Download Tasks") {
4417
4679
  self.endBackGroundTask()
@@ -4526,7 +4788,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4526
4788
  let builtinUpdateAvailable = !current.isBuiltin()
4527
4789
  if builtinUpdateAvailable {
4528
4790
  let builtinBundle = self.implementation.getBundleInfo(id: BundleInfo.ID_BUILTIN)
4529
- self.notifyListeners("updateAvailable", data: ["bundle": builtinBundle.toJSON()], retainUntilConsumed: true)
4791
+ self.notifyListenersOnMain("updateAvailable", data: ["bundle": builtinBundle.toJSON()], retainUntilConsumed: true)
4530
4792
  }
4531
4793
  self.endBackGroundTaskWithNotif(
4532
4794
  msg: "Latest version is builtin, autoUpdate onlyDownload",
@@ -4594,7 +4856,14 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4594
4856
  )
4595
4857
  return
4596
4858
  }
4597
- nextImpl = try self.implementation.download(url: downloadUrl, version: latestVersionName, sessionKey: sessionKey, link: res.link, comment: res.comment)
4859
+ nextImpl = try self.implementation.downloadVerified(
4860
+ url: downloadUrl,
4861
+ version: latestVersionName,
4862
+ sessionKey: sessionKey,
4863
+ expectedChecksum: res.checksum,
4864
+ link: res.link,
4865
+ comment: res.comment
4866
+ )
4598
4867
  }
4599
4868
  }
4600
4869
  guard let next = nextImpl else {
@@ -4651,11 +4920,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4651
4920
  let directUpdateAllowed = plannedDirectUpdate && !self.autoSplashscreenTimedOut
4652
4921
  if directUpdateAllowed {
4653
4922
  let delayUpdatePreferences = UserDefaults.standard.string(forKey: DelayUpdateUtils.DELAY_CONDITION_PREFERENCES) ?? "[]"
4654
- let delayConditionList: [DelayCondition] = self.fromJsonArr(json: delayUpdatePreferences).map { obj -> DelayCondition in
4655
- let kind: String = obj.value(forKey: "kind") as! String
4656
- let value: String? = obj.value(forKey: "value") as? String
4657
- return DelayCondition(kind: kind, value: value)
4658
- }
4923
+ let delayConditionList = DelayUpdateUtils.parseDelayConditions(json: delayUpdatePreferences)
4659
4924
  if !delayConditionList.isEmpty {
4660
4925
  self.logger.info("Update delayed until delay conditions met")
4661
4926
  self.endBackGroundTaskWithNotif(
@@ -4677,7 +4942,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4677
4942
  plannedDirectUpdate: plannedDirectUpdate
4678
4943
  )
4679
4944
  } else if self.queueBundleForNextBackgroundInstall(next) {
4680
- self.notifyListeners("updateAvailable", data: ["bundle": next.toJSON()])
4945
+ self.notifyListenersOnMain("updateAvailable", data: ["bundle": next.toJSON()])
4681
4946
  self.endBackGroundTaskWithNotif(
4682
4947
  msg: "Direct update reload failed, update will install next background",
4683
4948
  latestVersionName: latestVersionName,
@@ -4698,11 +4963,12 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4698
4963
  self.logger.info("Direct update skipped because splashscreen timeout occurred. Update will install on next app background.")
4699
4964
  }
4700
4965
  if self.queueBundleForNextBackgroundInstall(next) {
4701
- self.notifyListeners("updateAvailable", data: ["bundle": next.toJSON()])
4966
+ self.notifyListenersOnMain("updateAvailable", data: ["bundle": next.toJSON()])
4967
+ let installed = self.installNextIfInBackground()
4702
4968
  self.endBackGroundTaskWithNotif(
4703
- msg: "update downloaded, will install next background",
4969
+ msg: installed ? "update downloaded and installed in background" : "update downloaded, will install next background",
4704
4970
  latestVersionName: latestVersionName,
4705
- current: current,
4971
+ current: self.implementation.getCurrentBundle(),
4706
4972
  error: false,
4707
4973
  plannedDirectUpdate: plannedDirectUpdate
4708
4974
  )
@@ -4716,7 +4982,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4716
4982
  }
4717
4983
  } else {
4718
4984
  self.logger.info("autoUpdate is set to onlyDownload, downloaded update will not be set as next bundle")
4719
- self.notifyListeners("updateAvailable", data: ["bundle": next.toJSON()], retainUntilConsumed: true)
4985
+ self.notifyListenersOnMain("updateAvailable", data: ["bundle": next.toJSON()], retainUntilConsumed: true)
4720
4986
  self.endBackGroundTaskWithNotif(
4721
4987
  msg: "update downloaded, autoUpdate onlyDownload",
4722
4988
  latestVersionName: latestVersionName,
@@ -4731,7 +4997,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4731
4997
  self.logger.error("Error downloading file \(error.localizedDescription)")
4732
4998
  let current: BundleInfo = self.implementation.getCurrentBundle()
4733
4999
  self.endBackGroundTaskWithNotif(
4734
- msg: "Error downloading file",
5000
+ msg: (error as? ObjectSavableError) == .checksum ? "Error checksum" : "Error downloading file",
4735
5001
  latestVersionName: latestVersionName,
4736
5002
  current: current,
4737
5003
  plannedDirectUpdate: plannedDirectUpdate
@@ -4752,33 +5018,85 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4752
5018
  }
4753
5019
  }
4754
5020
 
4755
- private func installNext() {
4756
- if self.shouldBlockAutoUpdateForPreviewSession() {
5021
+ /// A download that finishes while the app is in the background (silent push,
5022
+ /// background fetch, cold background launch) would otherwise wait for the next
5023
+ /// didEnterBackground, which a background launch never posts, so the user would
5024
+ /// open the old bundle. Install now; the notifyAppReady check stays deferred
5025
+ /// until the app reaches the foreground.
5026
+ @discardableResult
5027
+ func installNextIfInBackground() -> Bool {
5028
+ let install = {
5029
+ self.appInBackground && self.shouldInstallQueuedBundleWhileInBackground() && self.installNext()
5030
+ }
5031
+ if Thread.isMainThread {
5032
+ return install()
5033
+ }
5034
+ return DispatchQueue.main.sync(execute: install)
5035
+ }
5036
+
5037
+ /// Immediate background install applies to deferred (`atBackground`) updates only.
5038
+ /// Direct-update modes retry from `appMovedToForeground` when a reload failed earlier.
5039
+ private func shouldInstallQueuedBundleWhileInBackground() -> Bool {
5040
+ autoUpdateMode == Self.autoUpdateModeBackground
5041
+ }
5042
+
5043
+ /// Direct-update modes queue `next` when an immediate reload fails; retry once the app is active again.
5044
+ private func shouldInstallQueuedBundleOnForeground() -> Bool {
5045
+ switch directUpdateMode {
5046
+ case Self.autoUpdateModeAlways, Self.autoUpdateModeLaunch:
5047
+ return true
5048
+ default:
5049
+ return false
5050
+ }
5051
+ }
5052
+
5053
+ private func installQueuedBundleOnForegroundIfNeeded() {
5054
+ guard shouldInstallQueuedBundleOnForeground() else {
4757
5055
  return
4758
5056
  }
4759
- let delayUpdatePreferences = UserDefaults.standard.string(forKey: DelayUpdateUtils.DELAY_CONDITION_PREFERENCES) ?? "[]"
4760
- let delayConditionList: [DelayCondition] = fromJsonArr(json: delayUpdatePreferences).map { obj -> DelayCondition in
4761
- let kind: String = obj.value(forKey: "kind") as! String
4762
- let value: String? = obj.value(forKey: "value") as? String
4763
- return DelayCondition(kind: kind, value: value)
5057
+ let current = self.implementation.getCurrentBundle()
5058
+ guard let next = self.implementation.getNextBundle(),
5059
+ !next.isErrorStatus(),
5060
+ next.getVersionName() != current.getVersionName() else {
5061
+ return
5062
+ }
5063
+ _ = self.installNext()
5064
+ }
5065
+
5066
+ /// Returns true when the next bundle became the active WebView bundle.
5067
+ @discardableResult
5068
+ private func installNext() -> Bool {
5069
+ if self.shouldBlockAutoUpdateForPreviewSession() {
5070
+ return false
4764
5071
  }
5072
+ let delayUpdatePreferences = UserDefaults.standard.string(forKey: DelayUpdateUtils.DELAY_CONDITION_PREFERENCES) ?? "[]"
5073
+ let delayConditionList = DelayUpdateUtils.parseDelayConditions(json: delayUpdatePreferences)
4765
5074
  if !delayConditionList.isEmpty {
4766
5075
  logger.info("Update delayed until delay conditions met")
4767
- return
5076
+ return false
4768
5077
  }
4769
5078
  let current: BundleInfo = self.implementation.getCurrentBundle()
4770
5079
  let next: BundleInfo? = self.implementation.getNextBundle()
4771
5080
 
4772
5081
  if next != nil && !next!.isErrorStatus() && next!.getVersionName() != current.getVersionName() {
4773
5082
  logger.info("Next bundle is: \(next!.toString())")
4774
- if self.implementation.set(bundle: next!) && self._reload() {
4775
- logger.info("Updated to bundle: \(next!.toString())")
4776
- self.notifyBundleSet(next!)
4777
- _ = self.implementation.setNextBundle(next: Optional<String>.none)
4778
- } else {
5083
+ let resetState = self.implementation.captureResetState()
5084
+ guard self.implementation.set(bundle: next!) else {
4779
5085
  logger.error("Update to bundle: \(next!.toString()) Failed!")
5086
+ return false
5087
+ }
5088
+ guard self._reload() else {
5089
+ // Built-in `set` may reset fallback/next; restore the full pre-install state for retry.
5090
+ self.implementation.restoreResetState(resetState)
5091
+ logger.error("Update to bundle: \(next!.toString()) Failed! Reload failed, keeping it as next")
5092
+ return false
4780
5093
  }
5094
+ logger.info("Updated to bundle: \(next!.toString())")
5095
+ self.notifyBundleSet(next!)
5096
+ _ = self.implementation.setNextBundle(next: Optional<String>.none)
5097
+ return true
4781
5098
  }
5099
+ return false
4782
5100
  }
4783
5101
 
4784
5102
  @objc private func toJson(object: Any) -> String {
@@ -4788,18 +5106,8 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4788
5106
  return String(data: data, encoding: String.Encoding.utf8) ?? ""
4789
5107
  }
4790
5108
 
4791
- @objc private func fromJsonArr(json: String) -> [NSObject] {
4792
- guard let jsonData = json.data(using: .utf8) else {
4793
- return []
4794
- }
4795
- let object = try? JSONSerialization.jsonObject(
4796
- with: jsonData,
4797
- options: .mutableContainers
4798
- ) as? [NSObject]
4799
- return object ?? []
4800
- }
4801
-
4802
5109
  @objc func appMovedToForeground() {
5110
+ self.appInBackground = false
4803
5111
  appHealthTracker?.markForeground(true)
4804
5112
  let current: BundleInfo = self.implementation.getCurrentBundle()
4805
5113
  self.implementation.sendStats(action: "app_moved_to_foreground", versionName: current.getVersionName())
@@ -4809,6 +5117,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4809
5117
  backgroundWork!.cancel()
4810
5118
  logger.info("Background Timer Task canceled, Activity resumed before timer completes")
4811
5119
  }
5120
+ self.installQueuedBundleOnForegroundIfNeeded()
4812
5121
  if self._isAutoUpdateEnabled() {
4813
5122
  // Check if download is already in progress (with timeout protection)
4814
5123
  if !isDownloadStuckOrTimedOut() {
@@ -4847,30 +5156,43 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4847
5156
  return
4848
5157
  }
4849
5158
  DispatchQueue.global(qos: .utility).async {
4850
- if self.shouldBlockAutoUpdateForPreviewSession() {
4851
- return
4852
- }
4853
- let res = self.implementation.getLatest(url: url, channel: nil)
4854
- let current = self.implementation.getCurrentBundle()
4855
- if self.shouldBlockAutoUpdateForPreviewSession() {
4856
- return
4857
- }
4858
-
4859
- if res.version != current.getVersionName() {
4860
- self.logger.info("New version found: \(res.version)")
4861
- // Check if download is already in progress (with timeout protection)
4862
- if !self.isDownloadStuckOrTimedOut() {
4863
- self.backgroundDownload()
4864
- } else {
4865
- self.logger.info("Download already in progress, skipping duplicate download request")
4866
- }
4867
- }
5159
+ self.runPeriodicUpdateCheck(url: url)
4868
5160
  }
4869
5161
  }
4870
5162
  RunLoop.current.add(periodicUpdateTimer!, forMode: .default)
4871
5163
  }
4872
5164
 
5165
+ func runPeriodicUpdateCheck(url: URL) {
5166
+ if self.shouldBlockAutoUpdateForPreviewSession() {
5167
+ return
5168
+ }
5169
+ let res = self.implementation.getLatest(url: url, channel: nil)
5170
+ let current = self.implementation.getCurrentBundle()
5171
+ if self.shouldBlockAutoUpdateForPreviewSession() {
5172
+ return
5173
+ }
5174
+
5175
+ // Error / kind responses carry no downloadable bundle: report them, like Android.
5176
+ let backendError = res.error ?? ""
5177
+ let backendKind = res.kind ?? ""
5178
+ if !backendError.isEmpty || !backendKind.isEmpty {
5179
+ self.notifyUpdateCheckResult(backendError: backendError, res: res, current: current)
5180
+ return
5181
+ }
5182
+
5183
+ if !res.version.isEmpty && res.version != current.getVersionName() {
5184
+ self.logger.info("New version found: \(res.version)")
5185
+ // Check if download is already in progress (with timeout protection)
5186
+ if !self.isDownloadStuckOrTimedOut() {
5187
+ self.backgroundDownload()
5188
+ } else {
5189
+ self.logger.info("Download already in progress, skipping duplicate download request")
5190
+ }
5191
+ }
5192
+ }
5193
+
4873
5194
  @objc func appMovedToBackground() {
5195
+ self.appInBackground = true
4874
5196
  // Reset timeout flag at start of each background cycle
4875
5197
  self.autoSplashscreenTimedOut = false
4876
5198
  appHealthTracker?.markForeground(false)
@@ -4911,6 +5233,8 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4911
5233
  }
4912
5234
 
4913
5235
  @objc func getNextBundle(_ call: CAPPluginCall) {
5236
+ // Heals a next bundle left stored after it was activated (set() did not clear it before).
5237
+ self.implementation.clearNextBundleIfCurrent()
4914
5238
  let bundle = self.implementation.getNextBundle()
4915
5239
  if bundle == nil || bundle?.isUnknown() == true {
4916
5240
  call.resolve()
@@ -5061,8 +5385,8 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
5061
5385
  // Determine update availability by comparing versions
5062
5386
  if let availableVersion = availableVersion {
5063
5387
  do {
5064
- let currentVer = try Version(currentVersionName)
5065
- let availableVer = try Version(availableVersion)
5388
+ let currentVer = try CapgoSemanticVersion(currentVersionName)
5389
+ let availableVer = try CapgoSemanticVersion(availableVersion)
5066
5390
  if availableVer > currentVer {
5067
5391
  result["updateAvailability"] = AppUpdateAvailability.updateAvailable.rawValue
5068
5392
  } else {
@@ -5090,6 +5414,10 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
5090
5414
  }
5091
5415
 
5092
5416
  self.resolveCall(call, data: result)
5417
+ if let availability = result["updateAvailability"] as? Int,
5418
+ availability == AppUpdateAvailability.updateAvailable.rawValue {
5419
+ self.nativeUpdatePromptCoordinator?.maybeShowForStoreUpdateAvailable()
5420
+ }
5093
5421
  } catch {
5094
5422
  self.logger.error("Failed to parse App Store response: \(error.localizedDescription)")
5095
5423
  self.rejectCall(call, message: "Failed to parse App Store response: \(error.localizedDescription)")