@capgo/capacitor-updater 6.51.21 → 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 +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 = "6.51.21"
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
  }
@@ -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 {
@@ -1609,37 +1670,40 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
1609
1670
  throw makePreviewError("Invalid download URL")
1610
1671
  }
1611
1672
 
1673
+ if !self.implementation.publicKey.isEmpty && !CryptoCipher.isValidSessionKey(sessionKey) {
1674
+ self.logger.error("Public key present but no valid session key provided")
1675
+ self.implementation.sendStats(action: "session_key_required", versionName: version)
1676
+ throw makePreviewError("Session key required when public key is present")
1677
+ }
1678
+
1612
1679
  var checksum = rawChecksum
1680
+ if manifestEntries == nil && checksum.isEmpty {
1681
+ self.logger.error("No checksum provided")
1682
+ self.implementation.sendStats(action: "checksum_required", versionName: version)
1683
+ throw makePreviewError("Checksum required")
1684
+ }
1685
+
1613
1686
  let next: BundleInfo
1614
1687
  if let manifestEntries = manifestEntries {
1615
1688
  next = try self.implementation.downloadManifest(manifest: manifestEntries, version: version, sessionKey: sessionKey)
1616
1689
  } else {
1617
- next = try self.implementation.download(url: url, version: version, sessionKey: sessionKey)
1618
- }
1619
-
1620
- if self.implementation.publicKey != "" && checksum == "" {
1621
- self.logger.error("Public key present but no checksum provided")
1622
- self.implementation.sendStats(action: "checksum_required", versionName: next.getVersionName())
1623
- let id = next.getId()
1624
- let resDel = self.implementation.delete(id: id)
1625
- if !resDel {
1626
- self.logger.error("Delete failed, id \(id) doesn't exist")
1627
- }
1628
- throw ObjectSavableError.checksum
1629
- }
1630
-
1631
- checksum = try CryptoCipher.decryptChecksum(checksum: checksum, publicKey: self.implementation.publicKey)
1632
- CryptoCipher.logChecksumInfo(label: "Bundle checksum", hexChecksum: next.getChecksum())
1633
- CryptoCipher.logChecksumInfo(label: "Expected checksum", hexChecksum: checksum)
1634
- if (checksum != "" || self.implementation.publicKey != "") && next.getChecksum() != checksum {
1635
- self.logger.error("Error checksum \(next.getChecksum()) \(checksum)")
1636
- self.implementation.sendStats(action: "checksum_fail", versionName: next.getVersionName())
1637
- let id = next.getId()
1638
- let resDel = self.implementation.delete(id: id)
1639
- if !resDel {
1640
- self.logger.error("Delete failed, id \(id) doesn't exist")
1690
+ next = try self.implementation.downloadVerified(url: url, version: version, sessionKey: sessionKey, expectedChecksum: rawChecksum)
1691
+ }
1692
+
1693
+ if manifestEntries == nil {
1694
+ checksum = try CryptoCipher.decryptChecksum(checksum: checksum, publicKey: self.implementation.publicKey)
1695
+ CryptoCipher.logChecksumInfo(label: "Bundle checksum", hexChecksum: next.getChecksum())
1696
+ CryptoCipher.logChecksumInfo(label: "Expected checksum", hexChecksum: checksum)
1697
+ if next.getChecksum() != checksum {
1698
+ self.logger.error("Error checksum \(next.getChecksum()) \(checksum)")
1699
+ self.implementation.sendStats(action: "checksum_fail", versionName: next.getVersionName())
1700
+ let id = next.getId()
1701
+ let resDel = self.implementation.delete(id: id)
1702
+ if !resDel {
1703
+ self.logger.error("Delete failed, id \(id) doesn't exist")
1704
+ }
1705
+ throw ObjectSavableError.checksum
1641
1706
  }
1642
- throw ObjectSavableError.checksum
1643
1707
  }
1644
1708
 
1645
1709
  self.logger.info("Good checksum \(next.getChecksum()) \(checksum)")
@@ -1691,8 +1755,10 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
1691
1755
  let id = self.implementation.getCurrentBundleId()
1692
1756
  if BundleInfo.ID_BUILTIN == id {
1693
1757
  return Bundle.main.resourceURL!.appendingPathComponent("public")
1758
+ } else if let bundleDir = try? self.implementation.getBundleDirectory(id: id) {
1759
+ return bundleDir
1694
1760
  } else {
1695
- return self.implementation.getBundleDirectory(id: id)
1761
+ return Bundle.main.resourceURL!.appendingPathComponent("public")
1696
1762
  }
1697
1763
  }
1698
1764
 
@@ -1709,6 +1775,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
1709
1775
  self.logger.error("Cannot get capBridge")
1710
1776
  return false
1711
1777
  }
1778
+ self.armReadyGuard(webView: vc.webView)
1712
1779
  if self.keepUrlPathAfterReload {
1713
1780
  if let currentURL = vc.webView?.url {
1714
1781
  capBridge.setServerBasePath(dest.path)
@@ -1760,7 +1827,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
1760
1827
  return false
1761
1828
  }
1762
1829
  self.checkAppReady()
1763
- self.notifyListeners("appReloaded", data: [:])
1830
+ self.notifyListenersOnMain("appReloaded", data: [:])
1764
1831
  return true
1765
1832
  }
1766
1833
 
@@ -1783,7 +1850,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
1783
1850
  return false
1784
1851
  }
1785
1852
  self.checkAppReady()
1786
- self.notifyListeners("appReloaded", data: [:])
1853
+ self.notifyListenersOnMain("appReloaded", data: [:])
1787
1854
  return true
1788
1855
  }
1789
1856
 
@@ -1900,7 +1967,11 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
1900
1967
  if !res {
1901
1968
  logger.info("Bundle successfully set to: \(id) ")
1902
1969
  call.reject("Update failed, id \(id) doesn't exist")
1903
- } 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 {
1904
1975
  let bundle = self.implementation.getBundleInfo(id: id)
1905
1976
  _ = self.recordPreviewBundle(bundle)
1906
1977
  if !self.reloadWithoutWaitingForAppReady() {
@@ -2698,12 +2769,12 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
2698
2769
  var response: URLResponse?
2699
2770
  var responseError: Error?
2700
2771
 
2701
- URLSession.shared.dataTask(with: request) { data, urlResponse, error in
2772
+ self.implementation.startRawDataTask(request) { data, urlResponse, error in
2702
2773
  responseData = data
2703
2774
  response = urlResponse
2704
2775
  responseError = error
2705
2776
  semaphore.signal()
2706
- }.resume()
2777
+ }
2707
2778
 
2708
2779
  if semaphore.wait(timeout: .now() + 60) == .timedOut {
2709
2780
  throw makePreviewError("Preview payload request timed out")
@@ -2994,8 +3065,13 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
2994
3065
  logger.error("Error no url or wrong format")
2995
3066
  return "unavailable"
2996
3067
  }
3068
+ // The TS contract only knows queued / already_running / unavailable.
2997
3069
  if self.shouldBlockAutoUpdateForPreviewSession() {
2998
- 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"
2999
3075
  }
3000
3076
  if self.isDownloadStuckOrTimedOut() {
3001
3077
  logger.info("Download already in progress, skipping duplicate download request")
@@ -3018,11 +3094,16 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
3018
3094
  self.saveCallForAsyncHandling(call)
3019
3095
  DispatchQueue.global(qos: .utility).async {
3020
3096
  let configDefaultChannel = self.getConfig().getString("defaultChannel", "")!
3021
- 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
+ )
3022
3102
  if res.error != "" {
3023
- self.rejectCall(call, message: res.error, code: "UNSETCHANNEL_FAILED", data: [
3024
- "message": res.error,
3025
- "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
3026
3107
  ])
3027
3108
  } else {
3028
3109
  guard self.persistDefaultChannelStateFromDefaults() else {
@@ -3070,9 +3151,20 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
3070
3151
  "message": res.error
3071
3152
  ])
3072
3153
  }
3073
- self.rejectCall(call, message: res.error, code: "SETCHANNEL_FAILED", data: [
3074
- "message": res.error,
3075
- "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
3076
3168
  ])
3077
3169
  } else {
3078
3170
  guard self.persistDefaultChannelStateFromDefaults() else {
@@ -3265,11 +3357,10 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
3265
3357
  }
3266
3358
 
3267
3359
  private func reportAppLaunchReady(_ bundle: BundleInfo) {
3268
- guard !self.implementation.statsUrl.isEmpty, !launchReadyReported else {
3360
+ guard !self.implementation.statsUrl.isEmpty, self.claimLaunchReport(timeout: false) else {
3269
3361
  return
3270
3362
  }
3271
3363
 
3272
- launchReadyReported = true
3273
3364
  let duration = max(0, Int64(Date().timeIntervalSince1970 * 1000) - launchStartedAtMs)
3274
3365
  self.implementation.sendStats(
3275
3366
  action: "app_launch_ready",
@@ -3283,8 +3374,23 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
3283
3374
  )
3284
3375
  }
3285
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
+
3286
3392
  private func reportAppLaunchTimeout(_ bundle: BundleInfo) {
3287
- guard !self.implementation.statsUrl.isEmpty else {
3393
+ guard !self.implementation.statsUrl.isEmpty, self.claimLaunchReport(timeout: true) else {
3288
3394
  return
3289
3395
  }
3290
3396
 
@@ -3302,7 +3408,65 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
3302
3408
  )
3303
3409
  }
3304
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
+
3305
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
+ }
3306
3470
  self.semaphoreDown()
3307
3471
  let bundle = self.implementation.getCurrentBundle()
3308
3472
  self.implementation.setSuccess(bundle: bundle, autoDeletePrevious: self.autoDeletePrevious)
@@ -3321,7 +3485,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
3321
3485
  return
3322
3486
  }
3323
3487
 
3324
- // Handle background conditions with empty value (set to "0")
3488
+ var conditionsPayload: Any = delayConditionList
3325
3489
  if var modifiableList = delayConditionList as? [[String: Any]] {
3326
3490
  for i in 0..<modifiableList.count {
3327
3491
  if let kind = modifiableList[i]["kind"] as? String,
@@ -3331,20 +3495,33 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
3331
3495
  modifiableList[i]["value"] = "0"
3332
3496
  }
3333
3497
  }
3334
- let delayConditions: String = toJson(object: modifiableList)
3335
- if delayUpdateUtils.setMultiDelay(delayConditions: delayConditions) {
3336
- call.resolve()
3337
- } else {
3338
- 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")
3339
3509
  }
3340
- } else {
3341
- let delayConditions: String = toJson(object: delayConditionList)
3342
- if delayUpdateUtils.setMultiDelay(delayConditions: delayConditions) {
3343
- call.resolve()
3344
- } else {
3345
- 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")
3346
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
3347
3523
  }
3524
+ call.resolve()
3348
3525
  }
3349
3526
 
3350
3527
  // Note: _setMultiDelay and _cancelDelay methods have been moved to DelayUpdateUtils class
@@ -3410,7 +3587,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
3410
3587
  if BundleStatus.SUCCESS.storedValue != current.getStatus() {
3411
3588
  logger.error("notifyAppReady was not called, roll back current bundle: \(current.toString())")
3412
3589
  logger.error("Did you forget to call 'notifyAppReady()' in your Capacitor App code?")
3413
- self.notifyListeners("updateFailed", data: [
3590
+ self.notifyListenersOnMain("updateFailed", data: [
3414
3591
  "bundle": current.toJSON()
3415
3592
  ])
3416
3593
  self.persistLastFailedBundle(current)
@@ -3442,8 +3619,14 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
3442
3619
  }
3443
3620
 
3444
3621
  func DeferredNotifyAppReadyCheck() {
3445
- self.checkRevert()
3446
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()
3447
3630
  }
3448
3631
 
3449
3632
  func endBackGroundTask() {
@@ -3452,7 +3635,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
3452
3635
  }
3453
3636
 
3454
3637
  private func notifyBundleSet(_ bundle: BundleInfo) {
3455
- self.notifyListeners("set", data: ["bundle": bundle.toJSON()], retainUntilConsumed: true)
3638
+ self.notifyListenersOnMain("set", data: ["bundle": bundle.toJSON()], retainUntilConsumed: true)
3456
3639
  }
3457
3640
 
3458
3641
  func sendReadyToJs(current: BundleInfo, msg: String) {
@@ -3464,7 +3647,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
3464
3647
  if self.consumePendingNotifyAppReady() {
3465
3648
  self.semaphoreWait(waitTime: self.appReadyTimeout)
3466
3649
  }
3467
- self.notifyListeners("appReady", data: ["bundle": current.toJSON(), "status": msg], retainUntilConsumed: true)
3650
+ self.notifyListenersOnMain("appReady", data: ["bundle": current.toJSON(), "status": msg], retainUntilConsumed: true)
3468
3651
 
3469
3652
  // Auto hide splashscreen if enabled
3470
3653
  // We show it on background when conditions are met, so we should hide it on foreground regardless of update outcome
@@ -4197,6 +4380,26 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4197
4380
  self.updateUrl = updateUrl
4198
4381
  }
4199
4382
 
4383
+ func notifyListenersOnMainForTesting(_ eventName: String, data: [String: Any]?, retainUntilConsumed: Bool) {
4384
+ self.notifyListenersOnMain(eventName, data: data, retainUntilConsumed: retainUntilConsumed)
4385
+ }
4386
+
4387
+ func downloadBundleForTesting(
4388
+ urlString: String,
4389
+ version: String,
4390
+ sessionKey: String,
4391
+ checksum: String,
4392
+ manifestEntries: [ManifestEntry]?
4393
+ ) throws -> BundleInfo {
4394
+ try downloadBundle(
4395
+ urlString: urlString,
4396
+ version: version,
4397
+ sessionKey: sessionKey,
4398
+ checksum: checksum,
4399
+ manifestEntries: manifestEntries
4400
+ )
4401
+ }
4402
+
4200
4403
  func setAutoUpdateModeForTesting(_ autoUpdateMode: String) {
4201
4404
  self.autoUpdateMode = Self.normalizedAutoUpdateMode(autoUpdateMode)
4202
4405
  self.autoUpdate = Self.isAutoUpdateModeEnabled(self.autoUpdateMode)
@@ -4208,10 +4411,28 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4208
4411
  self.currentBuildVersion = currentBuildVersion
4209
4412
  }
4210
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
+
4211
4428
  func setAppReadyTimeoutForTesting(_ timeout: Int) {
4212
4429
  self.appReadyTimeout = timeout
4213
4430
  }
4214
4431
 
4432
+ func setDelayUpdateUtilsForTesting(_ delayUpdateUtils: DelayUpdateUtils) {
4433
+ self.delayUpdateUtils = delayUpdateUtils
4434
+ }
4435
+
4215
4436
  func armPendingNotifyAppReadyForTesting() {
4216
4437
  pendingNotifyAppReady = true
4217
4438
  }
@@ -4249,16 +4470,12 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4249
4470
  return
4250
4471
  }
4251
4472
  let payload: [String: Any] = ["version": version]
4252
- self.notifyListeners("breakingAvailable", data: payload)
4253
- self.notifyListeners("majorAvailable", data: payload)
4473
+ self.notifyListenersOnMain("breakingAvailable", data: payload)
4474
+ self.notifyListenersOnMain("majorAvailable", data: payload)
4254
4475
  }
4255
4476
 
4256
4477
  private func shouldNotifyBreakingEvents(response: AppVersion) -> Bool {
4257
- if response.breaking == true {
4258
- return true
4259
- }
4260
-
4261
- return response.error == "disable_auto_update_to_major" || response.message == "store_update_required"
4478
+ NativeUpdatePromptCoordinator.isNativeStoreUpdateBlock(response: response)
4262
4479
  }
4263
4480
 
4264
4481
  private func notifyBreakingEventsIfNeeded(response: AppVersion, version: String) {
@@ -4266,6 +4483,51 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4266
4483
  let eventVersion = version.isEmpty ? self.implementation.getCurrentBundle().getVersionName() : version
4267
4484
  self.notifyBreakingEvents(version: eventVersion)
4268
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
+ }
4269
4531
  }
4270
4532
 
4271
4533
  static func normalizedUpdateResponseKind(kind: String?) -> String {
@@ -4279,26 +4541,25 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4279
4541
  Self.normalizedUpdateResponseKind(kind: kind)
4280
4542
  }
4281
4543
 
4282
- private func endBackgroundDownloadAfterLatestError(
4544
+ /// Emits `updateCheckResult` for an error / kind response and logs it.
4545
+ @discardableResult
4546
+ private func notifyUpdateCheckResult(
4283
4547
  backendError: String,
4284
4548
  res: AppVersion,
4285
- current: BundleInfo,
4286
- plannedDirectUpdate: Bool
4287
- ) {
4288
- let statusCode = res.statusCode
4549
+ current: BundleInfo
4550
+ ) -> (kind: String, message: String, latestVersionName: String) {
4289
4551
  let responseKind = self.updateResponseKind(kind: res.kind)
4290
4552
  let responseMessage = res.message?.isEmpty == false ? res.message : nil
4291
4553
  let message = responseMessage ?? (backendError.isEmpty ? "server did not provide a message" : backendError)
4292
4554
  let latestVersionName = res.version.isEmpty ? current.getVersionName() : res.version
4293
- self.notifyListeners("updateCheckResult", data: [
4555
+ self.notifyListenersOnMain("updateCheckResult", data: [
4294
4556
  "kind": responseKind,
4295
4557
  "error": backendError,
4296
4558
  "message": message,
4297
- "statusCode": statusCode,
4559
+ "statusCode": res.statusCode,
4298
4560
  "version": latestVersionName,
4299
4561
  "bundle": current.toJSON()
4300
4562
  ])
4301
- self.notifyBreakingEventsIfNeeded(response: res, version: res.version)
4302
4563
 
4303
4564
  if responseKind == "up_to_date" {
4304
4565
  self.logger.info("No new version available")
@@ -4307,15 +4568,39 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4307
4568
  } else {
4308
4569
  self.logger.error("getLatest failed with error: \(backendError)")
4309
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)
4310
4586
 
4311
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
+ }
4312
4597
  self.endBackGroundTaskWithNotif(
4313
4598
  msg: message,
4314
4599
  latestVersionName: latestVersionName,
4315
4600
  current: current,
4316
4601
  error: isFailure,
4317
4602
  plannedDirectUpdate: plannedDirectUpdate,
4318
- sendStats: isFailure
4603
+ sendStats: false
4319
4604
  )
4320
4605
  }
4321
4606
 
@@ -4343,10 +4628,10 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4343
4628
  if sendStats {
4344
4629
  self.implementation.sendStats(action: failureAction, versionName: current.getVersionName())
4345
4630
  }
4346
- self.notifyListeners(failureEvent, data: ["version": latestVersionName])
4631
+ self.notifyListenersOnMain(failureEvent, data: ["version": latestVersionName])
4347
4632
  }
4348
4633
  if notifyNoNeedUpdate {
4349
- self.notifyListeners("noNeedUpdate", data: ["bundle": current.toJSON()])
4634
+ self.notifyListenersOnMain("noNeedUpdate", data: ["bundle": current.toJSON()])
4350
4635
  }
4351
4636
  self.sendReadyToJs(current: current, msg: msg)
4352
4637
  logger.info("endBackGroundTaskWithNotif \(msg) current: \(current.getVersionName()) latestVersionName: \(latestVersionName)")
@@ -4388,7 +4673,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4388
4673
  DispatchQueue.global(qos: .userInitiated).async(execute: work)
4389
4674
  }
4390
4675
 
4391
- private func beginDownloadBackgroundTask() {
4676
+ func beginDownloadBackgroundTask() {
4392
4677
  let registerTask = {
4393
4678
  self.backgroundTaskID = UIApplication.shared.beginBackgroundTask(withName: "Finish Download Tasks") {
4394
4679
  self.endBackGroundTask()
@@ -4503,7 +4788,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4503
4788
  let builtinUpdateAvailable = !current.isBuiltin()
4504
4789
  if builtinUpdateAvailable {
4505
4790
  let builtinBundle = self.implementation.getBundleInfo(id: BundleInfo.ID_BUILTIN)
4506
- self.notifyListeners("updateAvailable", data: ["bundle": builtinBundle.toJSON()], retainUntilConsumed: true)
4791
+ self.notifyListenersOnMain("updateAvailable", data: ["bundle": builtinBundle.toJSON()], retainUntilConsumed: true)
4507
4792
  }
4508
4793
  self.endBackGroundTaskWithNotif(
4509
4794
  msg: "Latest version is builtin, autoUpdate onlyDownload",
@@ -4532,6 +4817,17 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4532
4817
  if latestVersionName != "" && current.getVersionName() != latestVersionName {
4533
4818
  do {
4534
4819
  self.logger.info("New bundle: \(latestVersionName) found. Current is: \(current.getVersionName()). \(messageUpdate)")
4820
+ if !self.implementation.publicKey.isEmpty && !CryptoCipher.isValidSessionKey(sessionKey) {
4821
+ self.logger.error("Public key present but no valid session key provided")
4822
+ self.implementation.sendStats(action: "session_key_required", versionName: latestVersionName)
4823
+ self.endBackGroundTaskWithNotif(
4824
+ msg: "Session key required when public key is present",
4825
+ latestVersionName: latestVersionName,
4826
+ current: current,
4827
+ plannedDirectUpdate: plannedDirectUpdate
4828
+ )
4829
+ return
4830
+ }
4535
4831
  var nextImpl = self.implementation.getBundleInfoByVersionName(version: latestVersionName)
4536
4832
  let needsDownload = nextImpl.map(Self.shouldRetryDownloadForExistingBundle) ?? true
4537
4833
  if needsDownload {
@@ -4549,7 +4845,25 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4549
4845
  if res.manifest != nil {
4550
4846
  nextImpl = try self.implementation.downloadManifest(manifest: res.manifest!, version: latestVersionName, sessionKey: sessionKey, link: res.link, comment: res.comment)
4551
4847
  } else {
4552
- nextImpl = try self.implementation.download(url: downloadUrl, version: latestVersionName, sessionKey: sessionKey, link: res.link, comment: res.comment)
4848
+ if res.checksum.isEmpty {
4849
+ self.logger.error("No checksum provided")
4850
+ self.implementation.sendStats(action: "checksum_required", versionName: latestVersionName)
4851
+ self.endBackGroundTaskWithNotif(
4852
+ msg: "Checksum required",
4853
+ latestVersionName: latestVersionName,
4854
+ current: current,
4855
+ plannedDirectUpdate: plannedDirectUpdate
4856
+ )
4857
+ return
4858
+ }
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
+ )
4553
4867
  }
4554
4868
  }
4555
4869
  guard let next = nextImpl else {
@@ -4577,24 +4891,26 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4577
4891
  self.endBackGroundTask()
4578
4892
  return
4579
4893
  }
4580
- res.checksum = try CryptoCipher.decryptChecksum(checksum: res.checksum, publicKey: self.implementation.publicKey)
4581
- CryptoCipher.logChecksumInfo(label: "Bundle checksum", hexChecksum: next.getChecksum())
4582
- CryptoCipher.logChecksumInfo(label: "Expected checksum", hexChecksum: res.checksum)
4583
- if res.checksum != "" && next.getChecksum() != res.checksum && res.manifest == nil {
4584
- self.logger.error("Error checksum \(next.getChecksum()) \(res.checksum)")
4585
- self.implementation.sendStats(action: "checksum_fail", versionName: next.getVersionName())
4586
- let id = next.getId()
4587
- let resDel = self.implementation.delete(id: id)
4588
- if !resDel {
4589
- self.logger.error("Delete failed, id \(id) doesn't exist")
4894
+ if res.manifest == nil {
4895
+ res.checksum = try CryptoCipher.decryptChecksum(checksum: res.checksum, publicKey: self.implementation.publicKey)
4896
+ CryptoCipher.logChecksumInfo(label: "Bundle checksum", hexChecksum: next.getChecksum())
4897
+ CryptoCipher.logChecksumInfo(label: "Expected checksum", hexChecksum: res.checksum)
4898
+ if next.getChecksum() != res.checksum {
4899
+ self.logger.error("Error checksum \(next.getChecksum()) \(res.checksum)")
4900
+ self.implementation.sendStats(action: "checksum_fail", versionName: next.getVersionName())
4901
+ let id = next.getId()
4902
+ let resDel = self.implementation.delete(id: id)
4903
+ if !resDel {
4904
+ self.logger.error("Delete failed, id \(id) doesn't exist")
4905
+ }
4906
+ self.endBackGroundTaskWithNotif(
4907
+ msg: "Error checksum",
4908
+ latestVersionName: latestVersionName,
4909
+ current: current,
4910
+ plannedDirectUpdate: plannedDirectUpdate
4911
+ )
4912
+ return
4590
4913
  }
4591
- self.endBackGroundTaskWithNotif(
4592
- msg: "Error checksum",
4593
- latestVersionName: latestVersionName,
4594
- current: current,
4595
- plannedDirectUpdate: plannedDirectUpdate
4596
- )
4597
- return
4598
4914
  }
4599
4915
  if self.shouldBlockAutoUpdateForPreviewSession() {
4600
4916
  self.clearDownloadInProgressState()
@@ -4604,11 +4920,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4604
4920
  let directUpdateAllowed = plannedDirectUpdate && !self.autoSplashscreenTimedOut
4605
4921
  if directUpdateAllowed {
4606
4922
  let delayUpdatePreferences = UserDefaults.standard.string(forKey: DelayUpdateUtils.DELAY_CONDITION_PREFERENCES) ?? "[]"
4607
- let delayConditionList: [DelayCondition] = self.fromJsonArr(json: delayUpdatePreferences).map { obj -> DelayCondition in
4608
- let kind: String = obj.value(forKey: "kind") as! String
4609
- let value: String? = obj.value(forKey: "value") as? String
4610
- return DelayCondition(kind: kind, value: value)
4611
- }
4923
+ let delayConditionList = DelayUpdateUtils.parseDelayConditions(json: delayUpdatePreferences)
4612
4924
  if !delayConditionList.isEmpty {
4613
4925
  self.logger.info("Update delayed until delay conditions met")
4614
4926
  self.endBackGroundTaskWithNotif(
@@ -4630,7 +4942,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4630
4942
  plannedDirectUpdate: plannedDirectUpdate
4631
4943
  )
4632
4944
  } else if self.queueBundleForNextBackgroundInstall(next) {
4633
- self.notifyListeners("updateAvailable", data: ["bundle": next.toJSON()])
4945
+ self.notifyListenersOnMain("updateAvailable", data: ["bundle": next.toJSON()])
4634
4946
  self.endBackGroundTaskWithNotif(
4635
4947
  msg: "Direct update reload failed, update will install next background",
4636
4948
  latestVersionName: latestVersionName,
@@ -4651,11 +4963,12 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4651
4963
  self.logger.info("Direct update skipped because splashscreen timeout occurred. Update will install on next app background.")
4652
4964
  }
4653
4965
  if self.queueBundleForNextBackgroundInstall(next) {
4654
- self.notifyListeners("updateAvailable", data: ["bundle": next.toJSON()])
4966
+ self.notifyListenersOnMain("updateAvailable", data: ["bundle": next.toJSON()])
4967
+ let installed = self.installNextIfInBackground()
4655
4968
  self.endBackGroundTaskWithNotif(
4656
- msg: "update downloaded, will install next background",
4969
+ msg: installed ? "update downloaded and installed in background" : "update downloaded, will install next background",
4657
4970
  latestVersionName: latestVersionName,
4658
- current: current,
4971
+ current: self.implementation.getCurrentBundle(),
4659
4972
  error: false,
4660
4973
  plannedDirectUpdate: plannedDirectUpdate
4661
4974
  )
@@ -4669,7 +4982,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4669
4982
  }
4670
4983
  } else {
4671
4984
  self.logger.info("autoUpdate is set to onlyDownload, downloaded update will not be set as next bundle")
4672
- self.notifyListeners("updateAvailable", data: ["bundle": next.toJSON()], retainUntilConsumed: true)
4985
+ self.notifyListenersOnMain("updateAvailable", data: ["bundle": next.toJSON()], retainUntilConsumed: true)
4673
4986
  self.endBackGroundTaskWithNotif(
4674
4987
  msg: "update downloaded, autoUpdate onlyDownload",
4675
4988
  latestVersionName: latestVersionName,
@@ -4684,7 +4997,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4684
4997
  self.logger.error("Error downloading file \(error.localizedDescription)")
4685
4998
  let current: BundleInfo = self.implementation.getCurrentBundle()
4686
4999
  self.endBackGroundTaskWithNotif(
4687
- msg: "Error downloading file",
5000
+ msg: (error as? ObjectSavableError) == .checksum ? "Error checksum" : "Error downloading file",
4688
5001
  latestVersionName: latestVersionName,
4689
5002
  current: current,
4690
5003
  plannedDirectUpdate: plannedDirectUpdate
@@ -4705,33 +5018,85 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4705
5018
  }
4706
5019
  }
4707
5020
 
4708
- private func installNext() {
4709
- 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 {
4710
5055
  return
4711
5056
  }
4712
- let delayUpdatePreferences = UserDefaults.standard.string(forKey: DelayUpdateUtils.DELAY_CONDITION_PREFERENCES) ?? "[]"
4713
- let delayConditionList: [DelayCondition] = fromJsonArr(json: delayUpdatePreferences).map { obj -> DelayCondition in
4714
- let kind: String = obj.value(forKey: "kind") as! String
4715
- let value: String? = obj.value(forKey: "value") as? String
4716
- 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
4717
5071
  }
5072
+ let delayUpdatePreferences = UserDefaults.standard.string(forKey: DelayUpdateUtils.DELAY_CONDITION_PREFERENCES) ?? "[]"
5073
+ let delayConditionList = DelayUpdateUtils.parseDelayConditions(json: delayUpdatePreferences)
4718
5074
  if !delayConditionList.isEmpty {
4719
5075
  logger.info("Update delayed until delay conditions met")
4720
- return
5076
+ return false
4721
5077
  }
4722
5078
  let current: BundleInfo = self.implementation.getCurrentBundle()
4723
5079
  let next: BundleInfo? = self.implementation.getNextBundle()
4724
5080
 
4725
5081
  if next != nil && !next!.isErrorStatus() && next!.getVersionName() != current.getVersionName() {
4726
5082
  logger.info("Next bundle is: \(next!.toString())")
4727
- if self.implementation.set(bundle: next!) && self._reload() {
4728
- logger.info("Updated to bundle: \(next!.toString())")
4729
- self.notifyBundleSet(next!)
4730
- _ = self.implementation.setNextBundle(next: Optional<String>.none)
4731
- } else {
5083
+ let resetState = self.implementation.captureResetState()
5084
+ guard self.implementation.set(bundle: next!) else {
4732
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
4733
5093
  }
5094
+ logger.info("Updated to bundle: \(next!.toString())")
5095
+ self.notifyBundleSet(next!)
5096
+ _ = self.implementation.setNextBundle(next: Optional<String>.none)
5097
+ return true
4734
5098
  }
5099
+ return false
4735
5100
  }
4736
5101
 
4737
5102
  @objc private func toJson(object: Any) -> String {
@@ -4741,18 +5106,8 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4741
5106
  return String(data: data, encoding: String.Encoding.utf8) ?? ""
4742
5107
  }
4743
5108
 
4744
- @objc private func fromJsonArr(json: String) -> [NSObject] {
4745
- guard let jsonData = json.data(using: .utf8) else {
4746
- return []
4747
- }
4748
- let object = try? JSONSerialization.jsonObject(
4749
- with: jsonData,
4750
- options: .mutableContainers
4751
- ) as? [NSObject]
4752
- return object ?? []
4753
- }
4754
-
4755
5109
  @objc func appMovedToForeground() {
5110
+ self.appInBackground = false
4756
5111
  appHealthTracker?.markForeground(true)
4757
5112
  let current: BundleInfo = self.implementation.getCurrentBundle()
4758
5113
  self.implementation.sendStats(action: "app_moved_to_foreground", versionName: current.getVersionName())
@@ -4762,6 +5117,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4762
5117
  backgroundWork!.cancel()
4763
5118
  logger.info("Background Timer Task canceled, Activity resumed before timer completes")
4764
5119
  }
5120
+ self.installQueuedBundleOnForegroundIfNeeded()
4765
5121
  if self._isAutoUpdateEnabled() {
4766
5122
  // Check if download is already in progress (with timeout protection)
4767
5123
  if !isDownloadStuckOrTimedOut() {
@@ -4800,30 +5156,43 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4800
5156
  return
4801
5157
  }
4802
5158
  DispatchQueue.global(qos: .utility).async {
4803
- if self.shouldBlockAutoUpdateForPreviewSession() {
4804
- return
4805
- }
4806
- let res = self.implementation.getLatest(url: url, channel: nil)
4807
- let current = self.implementation.getCurrentBundle()
4808
- if self.shouldBlockAutoUpdateForPreviewSession() {
4809
- return
4810
- }
4811
-
4812
- if res.version != current.getVersionName() {
4813
- self.logger.info("New version found: \(res.version)")
4814
- // Check if download is already in progress (with timeout protection)
4815
- if !self.isDownloadStuckOrTimedOut() {
4816
- self.backgroundDownload()
4817
- } else {
4818
- self.logger.info("Download already in progress, skipping duplicate download request")
4819
- }
4820
- }
5159
+ self.runPeriodicUpdateCheck(url: url)
4821
5160
  }
4822
5161
  }
4823
5162
  RunLoop.current.add(periodicUpdateTimer!, forMode: .default)
4824
5163
  }
4825
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
+
4826
5194
  @objc func appMovedToBackground() {
5195
+ self.appInBackground = true
4827
5196
  // Reset timeout flag at start of each background cycle
4828
5197
  self.autoSplashscreenTimedOut = false
4829
5198
  appHealthTracker?.markForeground(false)
@@ -4864,6 +5233,8 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4864
5233
  }
4865
5234
 
4866
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()
4867
5238
  let bundle = self.implementation.getNextBundle()
4868
5239
  if bundle == nil || bundle?.isUnknown() == true {
4869
5240
  call.resolve()
@@ -5014,8 +5385,8 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
5014
5385
  // Determine update availability by comparing versions
5015
5386
  if let availableVersion = availableVersion {
5016
5387
  do {
5017
- let currentVer = try Version(currentVersionName)
5018
- let availableVer = try Version(availableVersion)
5388
+ let currentVer = try CapgoSemanticVersion(currentVersionName)
5389
+ let availableVer = try CapgoSemanticVersion(availableVersion)
5019
5390
  if availableVer > currentVer {
5020
5391
  result["updateAvailability"] = AppUpdateAvailability.updateAvailable.rawValue
5021
5392
  } else {
@@ -5043,6 +5414,10 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
5043
5414
  }
5044
5415
 
5045
5416
  self.resolveCall(call, data: result)
5417
+ if let availability = result["updateAvailability"] as? Int,
5418
+ availability == AppUpdateAvailability.updateAvailable.rawValue {
5419
+ self.nativeUpdatePromptCoordinator?.maybeShowForStoreUpdateAvailable()
5420
+ }
5046
5421
  } catch {
5047
5422
  self.logger.error("Failed to parse App Store response: \(error.localizedDescription)")
5048
5423
  self.rejectCall(call, message: "Failed to parse App Store response: \(error.localizedDescription)")