@capgo/capacitor-updater 7.51.21 → 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 +202 -67
  4. package/android/build.gradle +2 -3
  5. package/android/src/main/java/ee/forgr/capacitor_updater/CapacitorUpdaterPlugin.java +610 -177
  6. package/android/src/main/java/ee/forgr/capacitor_updater/CapgoUpdater.java +909 -196
  7. package/android/src/main/java/ee/forgr/capacitor_updater/CryptoCipher.java +53 -19
  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 +210 -58
  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 +562 -187
  19. package/ios/Sources/CapacitorUpdaterPlugin/CapgoSemanticVersion.swift +162 -0
  20. package/ios/Sources/CapacitorUpdaterPlugin/CapgoUpdater.swift +564 -109
  21. package/ios/Sources/CapacitorUpdaterPlugin/CryptoCipher.swift +11 -2
  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 +9 -3
  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.21"
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
  }
@@ -582,8 +589,10 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
582
589
  var dest: URL
583
590
  if BundleInfo.ID_BUILTIN == id {
584
591
  dest = Bundle.main.resourceURL!.appendingPathComponent("public")
592
+ } else if let bundleDir = try? self.implementation.getBundleDirectory(id: id) {
593
+ dest = bundleDir
585
594
  } else {
586
- dest = self.implementation.getBundleDirectory(id: id)
595
+ dest = Bundle.main.resourceURL!.appendingPathComponent("public")
587
596
  }
588
597
 
589
598
  if !FileManager.default.fileExists(atPath: dest.path) {
@@ -1042,6 +1051,33 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
1042
1051
  return true
1043
1052
  }
1044
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
+
1045
1081
  private func cleanupObsoleteVersions(resetWhenUpdate: Bool = true, didResetCurrentBundle: Bool = false) {
1046
1082
  // Enter before publishing incomplete state so waiters cannot hit an empty group.
1047
1083
  self.cleanupStateLock.lock()
@@ -1242,9 +1278,34 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
1242
1278
  call.keepAlive = true
1243
1279
  }
1244
1280
 
1245
- 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) {
1246
1300
  let notify = {
1247
- 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
+ }
1248
1309
  }
1249
1310
 
1250
1311
  if Thread.isMainThread {
@@ -1611,37 +1672,40 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
1611
1672
  throw makePreviewError("Invalid download URL")
1612
1673
  }
1613
1674
 
1675
+ if !self.implementation.publicKey.isEmpty && !CryptoCipher.isValidSessionKey(sessionKey) {
1676
+ self.logger.error("Public key present but no valid session key provided")
1677
+ self.implementation.sendStats(action: "session_key_required", versionName: version)
1678
+ throw makePreviewError("Session key required when public key is present")
1679
+ }
1680
+
1614
1681
  var checksum = rawChecksum
1682
+ if manifestEntries == nil && checksum.isEmpty {
1683
+ self.logger.error("No checksum provided")
1684
+ self.implementation.sendStats(action: "checksum_required", versionName: version)
1685
+ throw makePreviewError("Checksum required")
1686
+ }
1687
+
1615
1688
  let next: BundleInfo
1616
1689
  if let manifestEntries = manifestEntries {
1617
1690
  next = try self.implementation.downloadManifest(manifest: manifestEntries, version: version, sessionKey: sessionKey)
1618
1691
  } else {
1619
- next = try self.implementation.download(url: url, version: version, sessionKey: sessionKey)
1620
- }
1621
-
1622
- if self.implementation.publicKey != "" && checksum == "" {
1623
- self.logger.error("Public key present but no checksum provided")
1624
- self.implementation.sendStats(action: "checksum_required", versionName: next.getVersionName())
1625
- let id = next.getId()
1626
- let resDel = self.implementation.delete(id: id)
1627
- if !resDel {
1628
- self.logger.error("Delete failed, id \(id) doesn't exist")
1629
- }
1630
- throw ObjectSavableError.checksum
1631
- }
1632
-
1633
- checksum = try CryptoCipher.decryptChecksum(checksum: checksum, publicKey: self.implementation.publicKey)
1634
- CryptoCipher.logChecksumInfo(label: "Bundle checksum", hexChecksum: next.getChecksum())
1635
- CryptoCipher.logChecksumInfo(label: "Expected checksum", hexChecksum: checksum)
1636
- if (checksum != "" || self.implementation.publicKey != "") && next.getChecksum() != checksum {
1637
- self.logger.error("Error checksum \(next.getChecksum()) \(checksum)")
1638
- self.implementation.sendStats(action: "checksum_fail", versionName: next.getVersionName())
1639
- let id = next.getId()
1640
- let resDel = self.implementation.delete(id: id)
1641
- if !resDel {
1642
- self.logger.error("Delete failed, id \(id) doesn't exist")
1692
+ next = try self.implementation.downloadVerified(url: url, version: version, sessionKey: sessionKey, expectedChecksum: rawChecksum)
1693
+ }
1694
+
1695
+ if manifestEntries == nil {
1696
+ checksum = try CryptoCipher.decryptChecksum(checksum: checksum, publicKey: self.implementation.publicKey)
1697
+ CryptoCipher.logChecksumInfo(label: "Bundle checksum", hexChecksum: next.getChecksum())
1698
+ CryptoCipher.logChecksumInfo(label: "Expected checksum", hexChecksum: checksum)
1699
+ if next.getChecksum() != checksum {
1700
+ self.logger.error("Error checksum \(next.getChecksum()) \(checksum)")
1701
+ self.implementation.sendStats(action: "checksum_fail", versionName: next.getVersionName())
1702
+ let id = next.getId()
1703
+ let resDel = self.implementation.delete(id: id)
1704
+ if !resDel {
1705
+ self.logger.error("Delete failed, id \(id) doesn't exist")
1706
+ }
1707
+ throw ObjectSavableError.checksum
1643
1708
  }
1644
- throw ObjectSavableError.checksum
1645
1709
  }
1646
1710
 
1647
1711
  self.logger.info("Good checksum \(next.getChecksum()) \(checksum)")
@@ -1693,8 +1757,10 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
1693
1757
  let id = self.implementation.getCurrentBundleId()
1694
1758
  if BundleInfo.ID_BUILTIN == id {
1695
1759
  return Bundle.main.resourceURL!.appendingPathComponent("public")
1760
+ } else if let bundleDir = try? self.implementation.getBundleDirectory(id: id) {
1761
+ return bundleDir
1696
1762
  } else {
1697
- return self.implementation.getBundleDirectory(id: id)
1763
+ return Bundle.main.resourceURL!.appendingPathComponent("public")
1698
1764
  }
1699
1765
  }
1700
1766
 
@@ -1711,6 +1777,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
1711
1777
  self.logger.error("Cannot get capBridge")
1712
1778
  return false
1713
1779
  }
1780
+ self.armReadyGuard(webView: vc.webView)
1714
1781
  if self.keepUrlPathAfterReload {
1715
1782
  if let currentURL = vc.webView?.url {
1716
1783
  capBridge.setServerBasePath(dest.path)
@@ -1762,7 +1829,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
1762
1829
  return false
1763
1830
  }
1764
1831
  self.checkAppReady()
1765
- self.notifyListeners("appReloaded", data: [:])
1832
+ self.notifyListenersOnMain("appReloaded", data: [:])
1766
1833
  return true
1767
1834
  }
1768
1835
 
@@ -1785,7 +1852,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
1785
1852
  return false
1786
1853
  }
1787
1854
  self.checkAppReady()
1788
- self.notifyListeners("appReloaded", data: [:])
1855
+ self.notifyListenersOnMain("appReloaded", data: [:])
1789
1856
  return true
1790
1857
  }
1791
1858
 
@@ -1902,7 +1969,11 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
1902
1969
  if !res {
1903
1970
  logger.info("Bundle successfully set to: \(id) ")
1904
1971
  call.reject("Update failed, id \(id) doesn't exist")
1905
- } 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 {
1906
1977
  let bundle = self.implementation.getBundleInfo(id: id)
1907
1978
  _ = self.recordPreviewBundle(bundle)
1908
1979
  if !self.reloadWithoutWaitingForAppReady() {
@@ -2700,12 +2771,12 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
2700
2771
  var response: URLResponse?
2701
2772
  var responseError: Error?
2702
2773
 
2703
- URLSession.shared.dataTask(with: request) { data, urlResponse, error in
2774
+ self.implementation.startRawDataTask(request) { data, urlResponse, error in
2704
2775
  responseData = data
2705
2776
  response = urlResponse
2706
2777
  responseError = error
2707
2778
  semaphore.signal()
2708
- }.resume()
2779
+ }
2709
2780
 
2710
2781
  if semaphore.wait(timeout: .now() + 60) == .timedOut {
2711
2782
  throw makePreviewError("Preview payload request timed out")
@@ -2996,8 +3067,13 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
2996
3067
  logger.error("Error no url or wrong format")
2997
3068
  return "unavailable"
2998
3069
  }
3070
+ // The TS contract only knows queued / already_running / unavailable.
2999
3071
  if self.shouldBlockAutoUpdateForPreviewSession() {
3000
- 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"
3001
3077
  }
3002
3078
  if self.isDownloadStuckOrTimedOut() {
3003
3079
  logger.info("Download already in progress, skipping duplicate download request")
@@ -3020,11 +3096,16 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
3020
3096
  self.saveCallForAsyncHandling(call)
3021
3097
  DispatchQueue.global(qos: .utility).async {
3022
3098
  let configDefaultChannel = self.getConfig().getString("defaultChannel", "")!
3023
- 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
+ )
3024
3104
  if res.error != "" {
3025
- self.rejectCall(call, message: res.error, code: "UNSETCHANNEL_FAILED", data: [
3026
- "message": res.error,
3027
- "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
3028
3109
  ])
3029
3110
  } else {
3030
3111
  guard self.persistDefaultChannelStateFromDefaults() else {
@@ -3072,9 +3153,20 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
3072
3153
  "message": res.error
3073
3154
  ])
3074
3155
  }
3075
- self.rejectCall(call, message: res.error, code: "SETCHANNEL_FAILED", data: [
3076
- "message": res.error,
3077
- "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
3078
3170
  ])
3079
3171
  } else {
3080
3172
  guard self.persistDefaultChannelStateFromDefaults() else {
@@ -3267,11 +3359,10 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
3267
3359
  }
3268
3360
 
3269
3361
  private func reportAppLaunchReady(_ bundle: BundleInfo) {
3270
- guard !self.implementation.statsUrl.isEmpty, !launchReadyReported else {
3362
+ guard !self.implementation.statsUrl.isEmpty, self.claimLaunchReport(timeout: false) else {
3271
3363
  return
3272
3364
  }
3273
3365
 
3274
- launchReadyReported = true
3275
3366
  let duration = max(0, Int64(Date().timeIntervalSince1970 * 1000) - launchStartedAtMs)
3276
3367
  self.implementation.sendStats(
3277
3368
  action: "app_launch_ready",
@@ -3285,8 +3376,23 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
3285
3376
  )
3286
3377
  }
3287
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
+
3288
3394
  private func reportAppLaunchTimeout(_ bundle: BundleInfo) {
3289
- guard !self.implementation.statsUrl.isEmpty else {
3395
+ guard !self.implementation.statsUrl.isEmpty, self.claimLaunchReport(timeout: true) else {
3290
3396
  return
3291
3397
  }
3292
3398
 
@@ -3304,7 +3410,65 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
3304
3410
  )
3305
3411
  }
3306
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
+
3307
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
+ }
3308
3472
  self.semaphoreDown()
3309
3473
  let bundle = self.implementation.getCurrentBundle()
3310
3474
  self.implementation.setSuccess(bundle: bundle, autoDeletePrevious: self.autoDeletePrevious)
@@ -3323,7 +3487,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
3323
3487
  return
3324
3488
  }
3325
3489
 
3326
- // Handle background conditions with empty value (set to "0")
3490
+ var conditionsPayload: Any = delayConditionList
3327
3491
  if var modifiableList = delayConditionList as? [[String: Any]] {
3328
3492
  for i in 0..<modifiableList.count {
3329
3493
  if let kind = modifiableList[i]["kind"] as? String,
@@ -3333,20 +3497,33 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
3333
3497
  modifiableList[i]["value"] = "0"
3334
3498
  }
3335
3499
  }
3336
- let delayConditions: String = toJson(object: modifiableList)
3337
- if delayUpdateUtils.setMultiDelay(delayConditions: delayConditions) {
3338
- call.resolve()
3339
- } else {
3340
- 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")
3341
3511
  }
3342
- } else {
3343
- let delayConditions: String = toJson(object: delayConditionList)
3344
- if delayUpdateUtils.setMultiDelay(delayConditions: delayConditions) {
3345
- call.resolve()
3346
- } else {
3347
- 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")
3348
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
3349
3525
  }
3526
+ call.resolve()
3350
3527
  }
3351
3528
 
3352
3529
  // Note: _setMultiDelay and _cancelDelay methods have been moved to DelayUpdateUtils class
@@ -3412,7 +3589,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
3412
3589
  if BundleStatus.SUCCESS.storedValue != current.getStatus() {
3413
3590
  logger.error("notifyAppReady was not called, roll back current bundle: \(current.toString())")
3414
3591
  logger.error("Did you forget to call 'notifyAppReady()' in your Capacitor App code?")
3415
- self.notifyListeners("updateFailed", data: [
3592
+ self.notifyListenersOnMain("updateFailed", data: [
3416
3593
  "bundle": current.toJSON()
3417
3594
  ])
3418
3595
  self.persistLastFailedBundle(current)
@@ -3444,8 +3621,14 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
3444
3621
  }
3445
3622
 
3446
3623
  func DeferredNotifyAppReadyCheck() {
3447
- self.checkRevert()
3448
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()
3449
3632
  }
3450
3633
 
3451
3634
  func endBackGroundTask() {
@@ -3454,7 +3637,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
3454
3637
  }
3455
3638
 
3456
3639
  private func notifyBundleSet(_ bundle: BundleInfo) {
3457
- self.notifyListeners("set", data: ["bundle": bundle.toJSON()], retainUntilConsumed: true)
3640
+ self.notifyListenersOnMain("set", data: ["bundle": bundle.toJSON()], retainUntilConsumed: true)
3458
3641
  }
3459
3642
 
3460
3643
  func sendReadyToJs(current: BundleInfo, msg: String) {
@@ -3466,7 +3649,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
3466
3649
  if self.consumePendingNotifyAppReady() {
3467
3650
  self.semaphoreWait(waitTime: self.appReadyTimeout)
3468
3651
  }
3469
- self.notifyListeners("appReady", data: ["bundle": current.toJSON(), "status": msg], retainUntilConsumed: true)
3652
+ self.notifyListenersOnMain("appReady", data: ["bundle": current.toJSON(), "status": msg], retainUntilConsumed: true)
3470
3653
 
3471
3654
  // Auto hide splashscreen if enabled
3472
3655
  // We show it on background when conditions are met, so we should hide it on foreground regardless of update outcome
@@ -4174,6 +4357,26 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4174
4357
  self.updateUrl = updateUrl
4175
4358
  }
4176
4359
 
4360
+ func notifyListenersOnMainForTesting(_ eventName: String, data: [String: Any]?, retainUntilConsumed: Bool) {
4361
+ self.notifyListenersOnMain(eventName, data: data, retainUntilConsumed: retainUntilConsumed)
4362
+ }
4363
+
4364
+ func downloadBundleForTesting(
4365
+ urlString: String,
4366
+ version: String,
4367
+ sessionKey: String,
4368
+ checksum: String,
4369
+ manifestEntries: [ManifestEntry]?
4370
+ ) throws -> BundleInfo {
4371
+ try downloadBundle(
4372
+ urlString: urlString,
4373
+ version: version,
4374
+ sessionKey: sessionKey,
4375
+ checksum: checksum,
4376
+ manifestEntries: manifestEntries
4377
+ )
4378
+ }
4379
+
4177
4380
  func setAutoUpdateModeForTesting(_ autoUpdateMode: String) {
4178
4381
  self.autoUpdateMode = Self.normalizedAutoUpdateMode(autoUpdateMode)
4179
4382
  self.autoUpdate = Self.isAutoUpdateModeEnabled(self.autoUpdateMode)
@@ -4185,10 +4388,28 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4185
4388
  self.currentBuildVersion = currentBuildVersion
4186
4389
  }
4187
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
+
4188
4405
  func setAppReadyTimeoutForTesting(_ timeout: Int) {
4189
4406
  self.appReadyTimeout = timeout
4190
4407
  }
4191
4408
 
4409
+ func setDelayUpdateUtilsForTesting(_ delayUpdateUtils: DelayUpdateUtils) {
4410
+ self.delayUpdateUtils = delayUpdateUtils
4411
+ }
4412
+
4192
4413
  func armPendingNotifyAppReadyForTesting() {
4193
4414
  pendingNotifyAppReady = true
4194
4415
  }
@@ -4226,16 +4447,12 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4226
4447
  return
4227
4448
  }
4228
4449
  let payload: [String: Any] = ["version": version]
4229
- self.notifyListeners("breakingAvailable", data: payload)
4230
- self.notifyListeners("majorAvailable", data: payload)
4450
+ self.notifyListenersOnMain("breakingAvailable", data: payload)
4451
+ self.notifyListenersOnMain("majorAvailable", data: payload)
4231
4452
  }
4232
4453
 
4233
4454
  private func shouldNotifyBreakingEvents(response: AppVersion) -> Bool {
4234
- if response.breaking == true {
4235
- return true
4236
- }
4237
-
4238
- return response.error == "disable_auto_update_to_major" || response.message == "store_update_required"
4455
+ NativeUpdatePromptCoordinator.isNativeStoreUpdateBlock(response: response)
4239
4456
  }
4240
4457
 
4241
4458
  private func notifyBreakingEventsIfNeeded(response: AppVersion, version: String) {
@@ -4243,6 +4460,51 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4243
4460
  let eventVersion = version.isEmpty ? self.implementation.getCurrentBundle().getVersionName() : version
4244
4461
  self.notifyBreakingEvents(version: eventVersion)
4245
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
+ }
4246
4508
  }
4247
4509
 
4248
4510
  static func normalizedUpdateResponseKind(kind: String?) -> String {
@@ -4256,26 +4518,25 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4256
4518
  Self.normalizedUpdateResponseKind(kind: kind)
4257
4519
  }
4258
4520
 
4259
- private func endBackgroundDownloadAfterLatestError(
4521
+ /// Emits `updateCheckResult` for an error / kind response and logs it.
4522
+ @discardableResult
4523
+ private func notifyUpdateCheckResult(
4260
4524
  backendError: String,
4261
4525
  res: AppVersion,
4262
- current: BundleInfo,
4263
- plannedDirectUpdate: Bool
4264
- ) {
4265
- let statusCode = res.statusCode
4526
+ current: BundleInfo
4527
+ ) -> (kind: String, message: String, latestVersionName: String) {
4266
4528
  let responseKind = self.updateResponseKind(kind: res.kind)
4267
4529
  let responseMessage = res.message?.isEmpty == false ? res.message : nil
4268
4530
  let message = responseMessage ?? (backendError.isEmpty ? "server did not provide a message" : backendError)
4269
4531
  let latestVersionName = res.version.isEmpty ? current.getVersionName() : res.version
4270
- self.notifyListeners("updateCheckResult", data: [
4532
+ self.notifyListenersOnMain("updateCheckResult", data: [
4271
4533
  "kind": responseKind,
4272
4534
  "error": backendError,
4273
4535
  "message": message,
4274
- "statusCode": statusCode,
4536
+ "statusCode": res.statusCode,
4275
4537
  "version": latestVersionName,
4276
4538
  "bundle": current.toJSON()
4277
4539
  ])
4278
- self.notifyBreakingEventsIfNeeded(response: res, version: res.version)
4279
4540
 
4280
4541
  if responseKind == "up_to_date" {
4281
4542
  self.logger.info("No new version available")
@@ -4284,15 +4545,39 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4284
4545
  } else {
4285
4546
  self.logger.error("getLatest failed with error: \(backendError)")
4286
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)
4287
4563
 
4288
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
+ }
4289
4574
  self.endBackGroundTaskWithNotif(
4290
4575
  msg: message,
4291
4576
  latestVersionName: latestVersionName,
4292
4577
  current: current,
4293
4578
  error: isFailure,
4294
4579
  plannedDirectUpdate: plannedDirectUpdate,
4295
- sendStats: isFailure
4580
+ sendStats: false
4296
4581
  )
4297
4582
  }
4298
4583
 
@@ -4320,10 +4605,10 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4320
4605
  if sendStats {
4321
4606
  self.implementation.sendStats(action: failureAction, versionName: current.getVersionName())
4322
4607
  }
4323
- self.notifyListeners(failureEvent, data: ["version": latestVersionName])
4608
+ self.notifyListenersOnMain(failureEvent, data: ["version": latestVersionName])
4324
4609
  }
4325
4610
  if notifyNoNeedUpdate {
4326
- self.notifyListeners("noNeedUpdate", data: ["bundle": current.toJSON()])
4611
+ self.notifyListenersOnMain("noNeedUpdate", data: ["bundle": current.toJSON()])
4327
4612
  }
4328
4613
  self.sendReadyToJs(current: current, msg: msg)
4329
4614
  logger.info("endBackGroundTaskWithNotif \(msg) current: \(current.getVersionName()) latestVersionName: \(latestVersionName)")
@@ -4365,7 +4650,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4365
4650
  DispatchQueue.global(qos: .userInitiated).async(execute: work)
4366
4651
  }
4367
4652
 
4368
- private func beginDownloadBackgroundTask() {
4653
+ func beginDownloadBackgroundTask() {
4369
4654
  let registerTask = {
4370
4655
  self.backgroundTaskID = UIApplication.shared.beginBackgroundTask(withName: "Finish Download Tasks") {
4371
4656
  self.endBackGroundTask()
@@ -4480,7 +4765,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4480
4765
  let builtinUpdateAvailable = !current.isBuiltin()
4481
4766
  if builtinUpdateAvailable {
4482
4767
  let builtinBundle = self.implementation.getBundleInfo(id: BundleInfo.ID_BUILTIN)
4483
- self.notifyListeners("updateAvailable", data: ["bundle": builtinBundle.toJSON()], retainUntilConsumed: true)
4768
+ self.notifyListenersOnMain("updateAvailable", data: ["bundle": builtinBundle.toJSON()], retainUntilConsumed: true)
4484
4769
  }
4485
4770
  self.endBackGroundTaskWithNotif(
4486
4771
  msg: "Latest version is builtin, autoUpdate onlyDownload",
@@ -4509,6 +4794,17 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4509
4794
  if latestVersionName != "" && current.getVersionName() != latestVersionName {
4510
4795
  do {
4511
4796
  self.logger.info("New bundle: \(latestVersionName) found. Current is: \(current.getVersionName()). \(messageUpdate)")
4797
+ if !self.implementation.publicKey.isEmpty && !CryptoCipher.isValidSessionKey(sessionKey) {
4798
+ self.logger.error("Public key present but no valid session key provided")
4799
+ self.implementation.sendStats(action: "session_key_required", versionName: latestVersionName)
4800
+ self.endBackGroundTaskWithNotif(
4801
+ msg: "Session key required when public key is present",
4802
+ latestVersionName: latestVersionName,
4803
+ current: current,
4804
+ plannedDirectUpdate: plannedDirectUpdate
4805
+ )
4806
+ return
4807
+ }
4512
4808
  var nextImpl = self.implementation.getBundleInfoByVersionName(version: latestVersionName)
4513
4809
  let needsDownload = nextImpl.map(Self.shouldRetryDownloadForExistingBundle) ?? true
4514
4810
  if needsDownload {
@@ -4526,7 +4822,25 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4526
4822
  if res.manifest != nil {
4527
4823
  nextImpl = try self.implementation.downloadManifest(manifest: res.manifest!, version: latestVersionName, sessionKey: sessionKey, link: res.link, comment: res.comment)
4528
4824
  } else {
4529
- nextImpl = try self.implementation.download(url: downloadUrl, version: latestVersionName, sessionKey: sessionKey, link: res.link, comment: res.comment)
4825
+ if res.checksum.isEmpty {
4826
+ self.logger.error("No checksum provided")
4827
+ self.implementation.sendStats(action: "checksum_required", versionName: latestVersionName)
4828
+ self.endBackGroundTaskWithNotif(
4829
+ msg: "Checksum required",
4830
+ latestVersionName: latestVersionName,
4831
+ current: current,
4832
+ plannedDirectUpdate: plannedDirectUpdate
4833
+ )
4834
+ return
4835
+ }
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
+ )
4530
4844
  }
4531
4845
  }
4532
4846
  guard let next = nextImpl else {
@@ -4554,24 +4868,26 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4554
4868
  self.endBackGroundTask()
4555
4869
  return
4556
4870
  }
4557
- res.checksum = try CryptoCipher.decryptChecksum(checksum: res.checksum, publicKey: self.implementation.publicKey)
4558
- CryptoCipher.logChecksumInfo(label: "Bundle checksum", hexChecksum: next.getChecksum())
4559
- CryptoCipher.logChecksumInfo(label: "Expected checksum", hexChecksum: res.checksum)
4560
- if res.checksum != "" && next.getChecksum() != res.checksum && res.manifest == nil {
4561
- self.logger.error("Error checksum \(next.getChecksum()) \(res.checksum)")
4562
- self.implementation.sendStats(action: "checksum_fail", versionName: next.getVersionName())
4563
- let id = next.getId()
4564
- let resDel = self.implementation.delete(id: id)
4565
- if !resDel {
4566
- self.logger.error("Delete failed, id \(id) doesn't exist")
4871
+ if res.manifest == nil {
4872
+ res.checksum = try CryptoCipher.decryptChecksum(checksum: res.checksum, publicKey: self.implementation.publicKey)
4873
+ CryptoCipher.logChecksumInfo(label: "Bundle checksum", hexChecksum: next.getChecksum())
4874
+ CryptoCipher.logChecksumInfo(label: "Expected checksum", hexChecksum: res.checksum)
4875
+ if next.getChecksum() != res.checksum {
4876
+ self.logger.error("Error checksum \(next.getChecksum()) \(res.checksum)")
4877
+ self.implementation.sendStats(action: "checksum_fail", versionName: next.getVersionName())
4878
+ let id = next.getId()
4879
+ let resDel = self.implementation.delete(id: id)
4880
+ if !resDel {
4881
+ self.logger.error("Delete failed, id \(id) doesn't exist")
4882
+ }
4883
+ self.endBackGroundTaskWithNotif(
4884
+ msg: "Error checksum",
4885
+ latestVersionName: latestVersionName,
4886
+ current: current,
4887
+ plannedDirectUpdate: plannedDirectUpdate
4888
+ )
4889
+ return
4567
4890
  }
4568
- self.endBackGroundTaskWithNotif(
4569
- msg: "Error checksum",
4570
- latestVersionName: latestVersionName,
4571
- current: current,
4572
- plannedDirectUpdate: plannedDirectUpdate
4573
- )
4574
- return
4575
4891
  }
4576
4892
  if self.shouldBlockAutoUpdateForPreviewSession() {
4577
4893
  self.clearDownloadInProgressState()
@@ -4581,11 +4897,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4581
4897
  let directUpdateAllowed = plannedDirectUpdate && !self.autoSplashscreenTimedOut
4582
4898
  if directUpdateAllowed {
4583
4899
  let delayUpdatePreferences = UserDefaults.standard.string(forKey: DelayUpdateUtils.DELAY_CONDITION_PREFERENCES) ?? "[]"
4584
- let delayConditionList: [DelayCondition] = self.fromJsonArr(json: delayUpdatePreferences).map { obj -> DelayCondition in
4585
- let kind: String = obj.value(forKey: "kind") as! String
4586
- let value: String? = obj.value(forKey: "value") as? String
4587
- return DelayCondition(kind: kind, value: value)
4588
- }
4900
+ let delayConditionList = DelayUpdateUtils.parseDelayConditions(json: delayUpdatePreferences)
4589
4901
  if !delayConditionList.isEmpty {
4590
4902
  self.logger.info("Update delayed until delay conditions met")
4591
4903
  self.endBackGroundTaskWithNotif(
@@ -4607,7 +4919,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4607
4919
  plannedDirectUpdate: plannedDirectUpdate
4608
4920
  )
4609
4921
  } else if self.queueBundleForNextBackgroundInstall(next) {
4610
- self.notifyListeners("updateAvailable", data: ["bundle": next.toJSON()])
4922
+ self.notifyListenersOnMain("updateAvailable", data: ["bundle": next.toJSON()])
4611
4923
  self.endBackGroundTaskWithNotif(
4612
4924
  msg: "Direct update reload failed, update will install next background",
4613
4925
  latestVersionName: latestVersionName,
@@ -4628,11 +4940,12 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4628
4940
  self.logger.info("Direct update skipped because splashscreen timeout occurred. Update will install on next app background.")
4629
4941
  }
4630
4942
  if self.queueBundleForNextBackgroundInstall(next) {
4631
- self.notifyListeners("updateAvailable", data: ["bundle": next.toJSON()])
4943
+ self.notifyListenersOnMain("updateAvailable", data: ["bundle": next.toJSON()])
4944
+ let installed = self.installNextIfInBackground()
4632
4945
  self.endBackGroundTaskWithNotif(
4633
- msg: "update downloaded, will install next background",
4946
+ msg: installed ? "update downloaded and installed in background" : "update downloaded, will install next background",
4634
4947
  latestVersionName: latestVersionName,
4635
- current: current,
4948
+ current: self.implementation.getCurrentBundle(),
4636
4949
  error: false,
4637
4950
  plannedDirectUpdate: plannedDirectUpdate
4638
4951
  )
@@ -4646,7 +4959,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4646
4959
  }
4647
4960
  } else {
4648
4961
  self.logger.info("autoUpdate is set to onlyDownload, downloaded update will not be set as next bundle")
4649
- self.notifyListeners("updateAvailable", data: ["bundle": next.toJSON()], retainUntilConsumed: true)
4962
+ self.notifyListenersOnMain("updateAvailable", data: ["bundle": next.toJSON()], retainUntilConsumed: true)
4650
4963
  self.endBackGroundTaskWithNotif(
4651
4964
  msg: "update downloaded, autoUpdate onlyDownload",
4652
4965
  latestVersionName: latestVersionName,
@@ -4661,7 +4974,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4661
4974
  self.logger.error("Error downloading file \(error.localizedDescription)")
4662
4975
  let current: BundleInfo = self.implementation.getCurrentBundle()
4663
4976
  self.endBackGroundTaskWithNotif(
4664
- msg: "Error downloading file",
4977
+ msg: (error as? ObjectSavableError) == .checksum ? "Error checksum" : "Error downloading file",
4665
4978
  latestVersionName: latestVersionName,
4666
4979
  current: current,
4667
4980
  plannedDirectUpdate: plannedDirectUpdate
@@ -4682,33 +4995,85 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4682
4995
  }
4683
4996
  }
4684
4997
 
4685
- private func installNext() {
4686
- 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 {
4687
5032
  return
4688
5033
  }
4689
- let delayUpdatePreferences = UserDefaults.standard.string(forKey: DelayUpdateUtils.DELAY_CONDITION_PREFERENCES) ?? "[]"
4690
- let delayConditionList: [DelayCondition] = fromJsonArr(json: delayUpdatePreferences).map { obj -> DelayCondition in
4691
- let kind: String = obj.value(forKey: "kind") as! String
4692
- let value: String? = obj.value(forKey: "value") as? String
4693
- 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
4694
5048
  }
5049
+ let delayUpdatePreferences = UserDefaults.standard.string(forKey: DelayUpdateUtils.DELAY_CONDITION_PREFERENCES) ?? "[]"
5050
+ let delayConditionList = DelayUpdateUtils.parseDelayConditions(json: delayUpdatePreferences)
4695
5051
  if !delayConditionList.isEmpty {
4696
5052
  logger.info("Update delayed until delay conditions met")
4697
- return
5053
+ return false
4698
5054
  }
4699
5055
  let current: BundleInfo = self.implementation.getCurrentBundle()
4700
5056
  let next: BundleInfo? = self.implementation.getNextBundle()
4701
5057
 
4702
5058
  if next != nil && !next!.isErrorStatus() && next!.getVersionName() != current.getVersionName() {
4703
5059
  logger.info("Next bundle is: \(next!.toString())")
4704
- if self.implementation.set(bundle: next!) && self._reload() {
4705
- logger.info("Updated to bundle: \(next!.toString())")
4706
- self.notifyBundleSet(next!)
4707
- _ = self.implementation.setNextBundle(next: Optional<String>.none)
4708
- } else {
5060
+ let resetState = self.implementation.captureResetState()
5061
+ guard self.implementation.set(bundle: next!) else {
4709
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
4710
5070
  }
5071
+ logger.info("Updated to bundle: \(next!.toString())")
5072
+ self.notifyBundleSet(next!)
5073
+ _ = self.implementation.setNextBundle(next: Optional<String>.none)
5074
+ return true
4711
5075
  }
5076
+ return false
4712
5077
  }
4713
5078
 
4714
5079
  @objc private func toJson(object: Any) -> String {
@@ -4718,18 +5083,8 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4718
5083
  return String(data: data, encoding: String.Encoding.utf8) ?? ""
4719
5084
  }
4720
5085
 
4721
- @objc private func fromJsonArr(json: String) -> [NSObject] {
4722
- guard let jsonData = json.data(using: .utf8) else {
4723
- return []
4724
- }
4725
- let object = try? JSONSerialization.jsonObject(
4726
- with: jsonData,
4727
- options: .mutableContainers
4728
- ) as? [NSObject]
4729
- return object ?? []
4730
- }
4731
-
4732
5086
  @objc func appMovedToForeground() {
5087
+ self.appInBackground = false
4733
5088
  appHealthTracker?.markForeground(true)
4734
5089
  let current: BundleInfo = self.implementation.getCurrentBundle()
4735
5090
  self.implementation.sendStats(action: "app_moved_to_foreground", versionName: current.getVersionName())
@@ -4739,6 +5094,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4739
5094
  backgroundWork!.cancel()
4740
5095
  logger.info("Background Timer Task canceled, Activity resumed before timer completes")
4741
5096
  }
5097
+ self.installQueuedBundleOnForegroundIfNeeded()
4742
5098
  if self._isAutoUpdateEnabled() {
4743
5099
  // Check if download is already in progress (with timeout protection)
4744
5100
  if !isDownloadStuckOrTimedOut() {
@@ -4777,30 +5133,43 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4777
5133
  return
4778
5134
  }
4779
5135
  DispatchQueue.global(qos: .utility).async {
4780
- if self.shouldBlockAutoUpdateForPreviewSession() {
4781
- return
4782
- }
4783
- let res = self.implementation.getLatest(url: url, channel: nil)
4784
- let current = self.implementation.getCurrentBundle()
4785
- if self.shouldBlockAutoUpdateForPreviewSession() {
4786
- return
4787
- }
4788
-
4789
- if res.version != current.getVersionName() {
4790
- self.logger.info("New version found: \(res.version)")
4791
- // Check if download is already in progress (with timeout protection)
4792
- if !self.isDownloadStuckOrTimedOut() {
4793
- self.backgroundDownload()
4794
- } else {
4795
- self.logger.info("Download already in progress, skipping duplicate download request")
4796
- }
4797
- }
5136
+ self.runPeriodicUpdateCheck(url: url)
4798
5137
  }
4799
5138
  }
4800
5139
  RunLoop.current.add(periodicUpdateTimer!, forMode: .default)
4801
5140
  }
4802
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
+
4803
5171
  @objc func appMovedToBackground() {
5172
+ self.appInBackground = true
4804
5173
  // Reset timeout flag at start of each background cycle
4805
5174
  self.autoSplashscreenTimedOut = false
4806
5175
  appHealthTracker?.markForeground(false)
@@ -4841,6 +5210,8 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4841
5210
  }
4842
5211
 
4843
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()
4844
5215
  let bundle = self.implementation.getNextBundle()
4845
5216
  if bundle == nil || bundle?.isUnknown() == true {
4846
5217
  call.resolve()
@@ -4991,8 +5362,8 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4991
5362
  // Determine update availability by comparing versions
4992
5363
  if let availableVersion = availableVersion {
4993
5364
  do {
4994
- let currentVer = try Version(currentVersionName)
4995
- let availableVer = try Version(availableVersion)
5365
+ let currentVer = try CapgoSemanticVersion(currentVersionName)
5366
+ let availableVer = try CapgoSemanticVersion(availableVersion)
4996
5367
  if availableVer > currentVer {
4997
5368
  result["updateAvailability"] = AppUpdateAvailability.updateAvailable.rawValue
4998
5369
  } else {
@@ -5020,6 +5391,10 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
5020
5391
  }
5021
5392
 
5022
5393
  self.resolveCall(call, data: result)
5394
+ if let availability = result["updateAvailability"] as? Int,
5395
+ availability == AppUpdateAvailability.updateAvailable.rawValue {
5396
+ self.nativeUpdatePromptCoordinator?.maybeShowForStoreUpdateAvailable()
5397
+ }
5023
5398
  } catch {
5024
5399
  self.logger.error("Failed to parse App Store response: \(error.localizedDescription)")
5025
5400
  self.rejectCall(call, message: "Failed to parse App Store response: \(error.localizedDescription)")