@capgo/capacitor-updater 8.54.2 → 9.0.1

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 (45) hide show
  1. package/CapgoCapacitorUpdater.podspec +2 -2
  2. package/Package.swift +3 -4
  3. package/README.md +162 -417
  4. package/android/build.gradle +7 -7
  5. package/android/consumer-rules.pro +48 -0
  6. package/android/proguard-rules.pro +1 -23
  7. package/android/src/main/java/ee/forgr/capacitor_updater/CapacitorUpdaterPlugin.java +1420 -404
  8. package/android/src/main/java/ee/forgr/capacitor_updater/CapgoUpdater.java +1100 -308
  9. package/android/src/main/java/ee/forgr/capacitor_updater/CryptoCipher.java +102 -65
  10. package/android/src/main/java/ee/forgr/capacitor_updater/DownloadService.java +155 -18
  11. package/android/src/main/java/ee/forgr/capacitor_updater/DownloadWorkerManager.java +22 -2
  12. package/android/src/main/java/ee/forgr/capacitor_updater/HeadlessUpdateWorker.java +82 -21
  13. package/android/src/main/java/ee/forgr/capacitor_updater/Http3.java +356 -0
  14. package/android/src/main/java/ee/forgr/capacitor_updater/HttpEngineTransport.java +553 -0
  15. package/dist/docs.json +44 -566
  16. package/dist/esm/definitions.d.ts +97 -215
  17. package/dist/esm/definitions.js.map +1 -1
  18. package/ios/Sources/CapacitorUpdaterPlugin/CapacitorUpdaterPlugin.swift +197 -84
  19. package/ios/Sources/CapacitorUpdaterPlugin/CapgoUpdater.swift +402 -139
  20. package/ios/Sources/CapacitorUpdaterPlugin/CryptoCipher.swift +81 -55
  21. package/ios/Sources/CapacitorUpdaterPlugin/RedirectPolicyDelegate.swift +24 -0
  22. package/ios/Sources/CapacitorUpdaterPlugin/ShakeMenu.swift +2 -1
  23. package/ios/Sources/CapacitorUpdaterPlugin/WKWebView+CapgoObjcBridge.swift +20 -0
  24. package/ios/Tests/CapacitorUpdaterPluginTests/BuiltinHashesTests.swift +210 -0
  25. package/ios/Tests/CapacitorUpdaterPluginTests/BundleHardeningTests.swift +292 -0
  26. package/ios/Tests/CapacitorUpdaterPluginTests/CapacitorUpdaterPluginTests.swift +3905 -0
  27. package/ios/Tests/CapacitorUpdaterPluginTests/CapgoSemanticVersionTests.swift +64 -0
  28. package/ios/Tests/CapacitorUpdaterPluginTests/ChecksumRequiredTests.swift +151 -0
  29. package/ios/Tests/CapacitorUpdaterPluginTests/CliCryptoFixtureTests.swift +249 -0
  30. package/ios/Tests/CapacitorUpdaterPluginTests/HttpsOnlyBuiltinMinimumTests.swift +528 -0
  31. package/ios/Tests/CapacitorUpdaterPluginTests/InstallPerfTests.swift +174 -0
  32. package/ios/Tests/CapacitorUpdaterPluginTests/ListChannelsTests.swift +74 -0
  33. package/ios/Tests/CapacitorUpdaterPluginTests/LoggerSecurityTests.swift +149 -0
  34. package/ios/Tests/CapacitorUpdaterPluginTests/NativeContractTests.swift +160 -0
  35. package/ios/Tests/CapacitorUpdaterPluginTests/NetworkTransportTests.swift +1095 -0
  36. package/ios/Tests/CapacitorUpdaterPluginTests/PopulateDeltaCacheTests.swift +573 -0
  37. package/ios/Tests/CapacitorUpdaterPluginTests/RedirectPolicyTests.swift +63 -0
  38. package/ios/Tests/CapacitorUpdaterPluginTests/RsaContractTests.swift +281 -0
  39. package/ios/Tests/CapacitorUpdaterPluginTests/SessionKeyRequiredTests.swift +192 -0
  40. package/ios/Tests/CapacitorUpdaterPluginTests/TestZipWriter.swift +235 -0
  41. package/ios/Tests/CapacitorUpdaterPluginTests/UpdateLifecycleTests.swift +454 -0
  42. package/ios/Tests/CapacitorUpdaterPluginTests/WebKitOverlayGuardTests.swift +32 -0
  43. package/ios/Tests/CapacitorUpdaterPluginTests/ZipArchiveReaderTests.swift +302 -0
  44. package/ios/Tests/CapacitorUpdaterPluginTests/ZipBundleExtractionTests.swift +122 -0
  45. package/package.json +15 -13
@@ -95,7 +95,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
95
95
  deinit {
96
96
  implementation.shutdown()
97
97
  }
98
- private let pluginVersion: String = "8.54.2"
98
+ private let pluginVersion: String = "9.0.1"
99
99
  private let launchStartedAtMs = Int64(Date().timeIntervalSince1970 * 1000)
100
100
  static let updateUrlDefault = "https://plugin.capgo.app/updates"
101
101
  static let statsUrlDefault = "https://plugin.capgo.app/stats"
@@ -105,8 +105,8 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
105
105
  static let updateCheckErrorAction = "update_check_error"
106
106
  // Single listener that receives every plugin event as { type, data }.
107
107
  static let updaterEvent = "updaterEvent"
108
- // Deprecated alias emitted next to breakingAvailable; not forwarded to avoid duplicates.
109
- static let deprecatedMajorAvailableEvent = "majorAvailable"
108
+ // Config key removed in 9.0.0. Still read once at load to warn apps that kept it.
109
+ static let removedDirectUpdateConfigKey = "directUpdate"
110
110
  static let autoUpdateModeOff = "off"
111
111
  static let autoUpdateModeBackground = "atBackground"
112
112
  static let autoUpdateModeInstall = "atInstall"
@@ -122,6 +122,8 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
122
122
  private let statsUrlDefaultsKey = "CapacitorUpdater.statsUrl"
123
123
  private let channelUrlDefaultsKey = "CapacitorUpdater.channelUrl"
124
124
  private let defaultChannelDefaultsKey = "CapacitorUpdater.defaultChannel"
125
+ static let defaultChannelFromSetChannelStorageKey = "CapacitorUpdater.defaultChannelFromSetChannel"
126
+ private let defaultChannelFromSetChannelDefaultsKey = CapacitorUpdaterPlugin.defaultChannelFromSetChannelStorageKey
125
127
  private let lastFailedBundleDefaultsKey = "CapacitorUpdater.lastFailedBundle"
126
128
  private let lastVersionOsDefaultsKey = "CapacitorUpdater.lastVersionOs"
127
129
  private let lastVersionBuildDefaultsKey = "CapacitorUpdater.lastVersionBuild"
@@ -184,7 +186,21 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
184
186
  private let splashscreenPluginName = "SplashScreen"
185
187
  private let splashscreenRetryDelayMilliseconds = 100
186
188
  private let splashscreenMaxRetries = 20
187
- private var autoSplashscreenTimedOut = false
189
+ private let splashscreenTimeoutStateLock = NSLock()
190
+ private var splashscreenTimeoutGeneration = 0
191
+ private var splashscreenTimedOut = false
192
+ private var autoSplashscreenTimedOut: Bool {
193
+ get {
194
+ splashscreenTimeoutStateLock.lock()
195
+ defer { splashscreenTimeoutStateLock.unlock() }
196
+ return splashscreenTimedOut
197
+ }
198
+ set {
199
+ splashscreenTimeoutStateLock.lock()
200
+ defer { splashscreenTimeoutStateLock.unlock() }
201
+ splashscreenTimedOut = newValue
202
+ }
203
+ }
188
204
  private var splashscreenInvocationToken = 0
189
205
  private var autoDeleteFailed = false
190
206
  private var autoDeletePrevious = false
@@ -210,7 +226,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
210
226
  private var cleanupTimedOut = false
211
227
  private var cleanupThread: Thread?
212
228
  private var defaultChannelCleanupMustRetry = false
213
- private var persistCustomId = false
229
+ var persistCustomId = true
214
230
  private var persistModifyUrl = false
215
231
  private var allowManualBundleError = false
216
232
  private var allowPreview = false
@@ -240,6 +256,8 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
240
256
  private var delayUpdateUtils: DelayUpdateUtils!
241
257
  private var nativeUpdatePromptCoordinator: NativeUpdatePromptCoordinator?
242
258
 
259
+ /// Reads the plugin config, applies its defaults (`httpsOnly`, `builtinMinimum` and `persistCustomId` are on
260
+ /// unless the app opts out) and starts the updater.
243
261
  override public func load() {
244
262
  let disableJSLogging = getConfig().getBoolean("disableJSLogging", false)
245
263
  // Set webView for logging to JavaScript console
@@ -270,7 +288,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
270
288
  }
271
289
  // Use DeviceIdHelper to get or create device ID that persists across reinstalls
272
290
  self.implementation.deviceID = DeviceIdHelper.getOrCreateDeviceId()
273
- persistCustomId = getConfig().getBoolean("persistCustomId", false)
291
+ persistCustomId = getConfig().getBoolean("persistCustomId", true)
274
292
  allowSetDefaultChannel = getConfig().getBoolean("allowSetDefaultChannel", true)
275
293
  persistDefaultChannelOnReinstall = getConfig().getBoolean("persistDefaultChannelOnReinstall", true)
276
294
  if persistCustomId {
@@ -315,8 +333,9 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
315
333
  appReadyTimeout = max(1000, getConfig().getInt("appReadyTimeout", 10000)) // Minimum 1 second
316
334
  implementation.timeout = Double(getConfig().getInt("responseTimeout", 20))
317
335
  implementation.allowHttpsToHttpRedirect = getConfig().getBoolean("allowHttpsToHttpRedirect", false)
336
+ implementation.http3Enabled = getConfig().getBoolean("http3", true)
318
337
  implementation.httpsOnly = getConfig().getBoolean("httpsOnly", true)
319
- implementation.builtinMinimum = getConfig().getBoolean("builtinMinimum", false)
338
+ implementation.builtinMinimum = getConfig().getBoolean("builtinMinimum", true)
320
339
  resetWhenUpdate = getConfig().getBoolean("resetWhenUpdate", true)
321
340
  shakeMenuEnabled = getConfig().getBoolean("shakeMenu", false)
322
341
  shakeChannelSelectorEnabled = getConfig().getBoolean("allowShakeChannelSelector", false)
@@ -670,6 +689,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
670
689
  file: previewSnapshotFile
671
690
  )
672
691
  UserDefaults.standard.removeObject(forKey: defaultChannelDefaultsKey)
692
+ UserDefaults.standard.removeObject(forKey: defaultChannelFromSetChannelDefaultsKey)
673
693
  UserDefaults.standard.removeObject(forKey: previewPreviousDefaultChannelDefaultsKey)
674
694
  UserDefaults.standard.removeObject(forKey: previewPreviousDefaultChannelWasSetDefaultsKey)
675
695
  return true
@@ -881,6 +901,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
881
901
  UserDefaults.standard.set(channel, forKey: defaultChannelDefaultsKey)
882
902
  } else {
883
903
  UserDefaults.standard.removeObject(forKey: defaultChannelDefaultsKey)
904
+ UserDefaults.standard.removeObject(forKey: defaultChannelFromSetChannelDefaultsKey)
884
905
  }
885
906
  }
886
907
 
@@ -1081,7 +1102,19 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
1081
1102
  UserDefaults.standard.set(self.currentBuildVersion, forKey: "LatestNativeBuildVersion")
1082
1103
  UserDefaults.standard.synchronize()
1083
1104
  }
1084
- let didResetCurrentBundle = resetWhenUpdate ? self.resetCurrentBundleForNativeBuildChangeIfNeeded() : false
1105
+ var didResetCurrentBundle = resetWhenUpdate ? self.resetCurrentBundleForNativeBuildChangeIfNeeded() : false
1106
+ // Preview restoration can change the stored current bundle too. Enforce the startup
1107
+ // floor after every selection, before reporting or loading the chosen bundle.
1108
+ let currentBundle = self.implementation.getCurrentBundle()
1109
+ if !currentBundle.isBuiltin() {
1110
+ do {
1111
+ try self.implementation.requireVersionNotBelowBuiltin(currentBundle.getVersionName())
1112
+ } catch {
1113
+ self.logger.warn("Stored bundle is below the native version. Resetting startup bundle to builtin.")
1114
+ self.implementation.reset(isInternal: true)
1115
+ didResetCurrentBundle = true
1116
+ }
1117
+ }
1085
1118
  self.reportAppLaunchStart()
1086
1119
  return didResetCurrentBundle
1087
1120
  }
@@ -1298,22 +1331,18 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
1298
1331
  return ["type": eventName, "data": data ?? [:]]
1299
1332
  }
1300
1333
 
1301
- static func shouldForwardToUpdaterEvent(_ eventName: String) -> Bool {
1302
- return eventName != updaterEvent && eventName != deprecatedMajorAvailableEvent
1303
- }
1304
-
1334
+ /// Every plugin event is delivered to JavaScript as a single `updaterEvent` with `{ type, data }`.
1335
+ /// `eventName` is the event type (`download`, `appReady`, ...). The per-event listeners were removed in 9.0.0.
1336
+ ///
1305
1337
  /// CAPPlugin's listener storage is not thread-safe (ionic-team/capacitor#8157), so every
1306
1338
  /// event this plugin emits goes through the main thread. Calls already on main stay synchronous.
1307
1339
  private func notifyListenersOnMain(_ eventName: String, data: [String: Any]?, retainUntilConsumed: Bool = false) {
1308
1340
  let notify = {
1309
- self.notifyListeners(eventName, data: data, retainUntilConsumed: retainUntilConsumed)
1310
- if CapacitorUpdaterPlugin.shouldForwardToUpdaterEvent(eventName) {
1311
- self.notifyListeners(
1312
- CapacitorUpdaterPlugin.updaterEvent,
1313
- data: CapacitorUpdaterPlugin.updaterEventPayload(eventName: eventName, data: data),
1314
- retainUntilConsumed: retainUntilConsumed
1315
- )
1316
- }
1341
+ self.notifyListeners(
1342
+ CapacitorUpdaterPlugin.updaterEvent,
1343
+ data: CapacitorUpdaterPlugin.updaterEventPayload(eventName: eventName, data: data),
1344
+ retainUntilConsumed: retainUntilConsumed
1345
+ )
1317
1346
  }
1318
1347
 
1319
1348
  if Thread.isMainThread {
@@ -1343,9 +1372,15 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
1343
1372
  var downloadCompletePayload: JSObject = [:]
1344
1373
  downloadCompletePayload["bundle"] = bundlePayload(bundleInfo)
1345
1374
  self.notifyListenersOnMain("downloadComplete", data: downloadCompletePayload)
1346
- self.implementation.sendStats(action: "download_complete", versionName: bundleInfo.getVersionName())
1375
+ self.implementation.sendStats(
1376
+ action: "download_complete", versionName: bundleInfo.getVersionName(),
1377
+ oldVersionName: "", metadata: ["attempt_id": id]
1378
+ )
1347
1379
  } else if percent.isMultiple(of: 10) || ignoreMultipleOfTen {
1348
- self.implementation.sendStats(action: "download_\(percent)", versionName: bundleInfo.getVersionName())
1380
+ self.implementation.sendStats(
1381
+ action: "download_\(percent)", versionName: bundleInfo.getVersionName(),
1382
+ oldVersionName: "", metadata: ["attempt_id": id]
1383
+ )
1349
1384
  }
1350
1385
  }
1351
1386
 
@@ -1848,7 +1883,8 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
1848
1883
  }
1849
1884
  }
1850
1885
 
1851
- public func _reload() -> Bool {
1886
+ /// Reloads the current bundle on the main thread and starts its app-ready timeout.
1887
+ public func reloadCurrentBundle() -> Bool {
1852
1888
  guard let bridge = self.bridge else { return false }
1853
1889
  self.semaphoreUp()
1854
1890
 
@@ -1896,6 +1932,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
1896
1932
  }
1897
1933
  }
1898
1934
 
1935
+ /// Reloads the app, rejecting an incompatible pending bundle with VERSION_BELOW_NATIVE before changing state.
1899
1936
  @objc func reload(_ call: CAPPluginCall) {
1900
1937
  let current: BundleInfo = self.implementation.getCurrentBundle()
1901
1938
  let next: BundleInfo? = self.implementation.getNextBundle()
@@ -1904,6 +1941,14 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
1904
1941
  let next = next,
1905
1942
  !next.isErrorStatus(),
1906
1943
  next.getId() != current.getId() {
1944
+ if !next.isBuiltin() {
1945
+ do {
1946
+ try self.implementation.requireVersionNotBelowBuiltin(next.getVersionName())
1947
+ } catch {
1948
+ call.reject(error.localizedDescription, "VERSION_BELOW_NATIVE", error)
1949
+ return
1950
+ }
1951
+ }
1907
1952
  let previousState = self.implementation.captureResetState()
1908
1953
  let previousBundleName = self.implementation.getCurrentBundle().getVersionName()
1909
1954
  logger.info("Applying pending bundle before reload: \(next.toString())")
@@ -1914,7 +1959,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
1914
1959
  } else {
1915
1960
  didApplyPendingBundle = self.implementation.stagePendingReload(bundle: next)
1916
1961
  }
1917
- if didApplyPendingBundle && self._reload() {
1962
+ if didApplyPendingBundle && self.reloadCurrentBundle() {
1918
1963
  if next.isBuiltin() {
1919
1964
  self.implementation.finalizeResetTransition(previousBundleName: previousBundleName, isInternal: false)
1920
1965
  } else {
@@ -1933,7 +1978,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
1933
1978
  return
1934
1979
  }
1935
1980
 
1936
- if self._reload() {
1981
+ if self.reloadCurrentBundle() {
1937
1982
  self.showPreviewSessionNoticeIfNeeded()
1938
1983
  call.resolve()
1939
1984
  } else {
@@ -1960,7 +2005,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
1960
2005
  return false
1961
2006
  }
1962
2007
 
1963
- if self._reload() {
2008
+ if self.reloadCurrentBundle() {
1964
2009
  self.implementation.finalizePendingReload(bundle: next, previousBundleName: previousBundleName)
1965
2010
  _ = self.implementation.setNextBundle(next: Optional<String>.none)
1966
2011
  return true
@@ -1996,7 +2041,16 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
1996
2041
  let res = implementation.set(id: id)
1997
2042
  logger.info("Set active bundle: \(id)")
1998
2043
  if !res {
1999
- logger.info("Bundle successfully set to: \(id) ")
2044
+ let bundle = self.implementation.getBundleInfo(id: id)
2045
+ if !bundle.isBuiltin(), self.implementation.bundleExists(id: id) {
2046
+ do {
2047
+ try self.implementation.requireVersionNotBelowBuiltin(bundle.getVersionName())
2048
+ } catch {
2049
+ call.reject(error.localizedDescription, "VERSION_BELOW_NATIVE", error)
2050
+ return
2051
+ }
2052
+ }
2053
+ logger.info("No such bundle: \(id)")
2000
2054
  call.reject("Update failed, id \(id) doesn't exist")
2001
2055
  return
2002
2056
  }
@@ -2012,7 +2066,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
2012
2066
  self.notifyBundleSet(bundle)
2013
2067
  self.showPreviewSessionNoticeIfNeeded()
2014
2068
  call.resolve()
2015
- } else if !self._reload() {
2069
+ } else if !self.reloadCurrentBundle() {
2016
2070
  call.reject("Reload failed after setting bundle \(id)")
2017
2071
  } else {
2018
2072
  self.notifyBundleSet(self.implementation.getBundleInfo(id: id))
@@ -2664,6 +2718,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
2664
2718
  logger.info("Restored defaultChannel after preview")
2665
2719
  } else {
2666
2720
  UserDefaults.standard.removeObject(forKey: self.defaultChannelDefaultsKey)
2721
+ UserDefaults.standard.removeObject(forKey: self.defaultChannelFromSetChannelDefaultsKey)
2667
2722
  self.implementation.defaultChannel = configDefaultChannel
2668
2723
  logger.info("Restored defaultChannel after preview to config value")
2669
2724
  }
@@ -3127,6 +3182,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
3127
3182
  let configDefaultChannel = self.getConfig().getString("defaultChannel", "")!
3128
3183
  let res = self.implementation.unsetChannel(
3129
3184
  defaultChannelKey: self.defaultChannelDefaultsKey,
3185
+ defaultChannelFromSetChannelKey: self.defaultChannelFromSetChannelDefaultsKey,
3130
3186
  configDefaultChannel: configDefaultChannel,
3131
3187
  allowSetDefaultChannel: self.allowSetDefaultChannel
3132
3188
  )
@@ -3171,6 +3227,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
3171
3227
  let res = self.implementation.setChannel(
3172
3228
  channel: channel,
3173
3229
  defaultChannelKey: self.defaultChannelDefaultsKey,
3230
+ defaultChannelFromSetChannelKey: self.defaultChannelFromSetChannelDefaultsKey,
3174
3231
  allowSetDefaultChannel: self.allowSetDefaultChannel,
3175
3232
  configDefaultChannel: configDefaultChannel
3176
3233
  )
@@ -3219,7 +3276,12 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
3219
3276
  @objc func getChannel(_ call: CAPPluginCall) {
3220
3277
  self.saveCallForAsyncHandling(call)
3221
3278
  DispatchQueue.global(qos: .utility).async {
3222
- let res = self.implementation.getChannel(defaultChannelKey: self.defaultChannelDefaultsKey)
3279
+ let configDefaultChannel = self.getConfig().getString("defaultChannel", "")!
3280
+ let res = self.implementation.getChannel(
3281
+ defaultChannelKey: self.defaultChannelDefaultsKey,
3282
+ defaultChannelFromSetChannelKey: self.defaultChannelFromSetChannelDefaultsKey,
3283
+ configDefaultChannel: configDefaultChannel
3284
+ )
3223
3285
  if res.error != "" {
3224
3286
  self.rejectCall(call, message: res.error, code: "GETCHANNEL_FAILED", data: [
3225
3287
  "message": res.error,
@@ -3259,12 +3321,11 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
3259
3321
  return
3260
3322
  }
3261
3323
  self.implementation.customId = customId
3262
- if persistCustomId {
3263
- if customId.isEmpty {
3264
- UserDefaults.standard.removeObject(forKey: customIdDefaultsKey)
3265
- } else {
3266
- UserDefaults.standard.set(customId, forKey: customIdDefaultsKey)
3267
- }
3324
+ if customId.isEmpty {
3325
+ UserDefaults.standard.removeObject(forKey: customIdDefaultsKey)
3326
+ UserDefaults.standard.synchronize()
3327
+ } else if persistCustomId {
3328
+ UserDefaults.standard.set(customId, forKey: customIdDefaultsKey)
3268
3329
  UserDefaults.standard.synchronize()
3269
3330
  }
3270
3331
  call.resolve()
@@ -3299,7 +3360,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
3299
3360
  } else {
3300
3361
  didApplyPendingBundle = self.implementation.set(bundle: pending)
3301
3362
  }
3302
- if didApplyPendingBundle && self._reload() {
3363
+ if didApplyPendingBundle && self.reloadCurrentBundle() {
3303
3364
  self.implementation.finalizeResetTransition(previousBundleName: previousBundleName, isInternal: isInternal)
3304
3365
  self.notifyBundleSet(pending)
3305
3366
  _ = self.implementation.setNextBundle(next: Optional<String>.none)
@@ -3316,7 +3377,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
3316
3377
  if self.implementation.canSet(bundle: fallback) {
3317
3378
  self.implementation.prepareResetStateForTransition()
3318
3379
  logger.info("Resetting to: \(fallback.toString())")
3319
- if self.implementation.set(bundle: fallback) && self._reload() {
3380
+ if self.implementation.set(bundle: fallback) && self.reloadCurrentBundle() {
3320
3381
  self.implementation.finalizeResetTransition(previousBundleName: previousBundleName, isInternal: isInternal)
3321
3382
  self.notifyBundleSet(fallback)
3322
3383
  return true
@@ -3334,7 +3395,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
3334
3395
 
3335
3396
  self.implementation.prepareResetStateForTransition()
3336
3397
  logger.info("Resetting to builtin version")
3337
- if self._reload() {
3398
+ if self.reloadCurrentBundle() {
3338
3399
  self.implementation.finalizeResetTransition(previousBundleName: previousBundleName, isInternal: isInternal)
3339
3400
  return true
3340
3401
  }
@@ -3868,16 +3929,11 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
3868
3929
  guard let self = self, requestToken == self.splashscreenInvocationToken else {
3869
3930
  return
3870
3931
  }
3871
- webView.callAsyncJavaScript(
3872
- script,
3873
- arguments: [:],
3874
- in: nil,
3875
- in: .page
3876
- ) { [weak self] (result: Result<Any, Error>) in
3932
+ webView.capgo_callAsyncJavaScriptInPage(script, arguments: [:]) { [weak self] (_, error) in
3877
3933
  guard let self = self, requestToken == self.splashscreenInvocationToken else {
3878
3934
  return
3879
3935
  }
3880
- if case .failure(let error) = result {
3936
+ if let error {
3881
3937
  self.retrySplashscreenAction(
3882
3938
  action,
3883
3939
  retriesRemaining: retriesRemaining,
@@ -4132,6 +4188,70 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4132
4188
  )
4133
4189
  }
4134
4190
 
4191
+ private func isDirectUpdateEligibleForLaunchSplashTimeout() -> Bool {
4192
+ if !self.autoUpdate || self.autoUpdateMode == Self.autoUpdateModeOnlyDownload {
4193
+ return false
4194
+ }
4195
+ if self.autoSplashscreenTimedOut {
4196
+ return false
4197
+ }
4198
+ switch directUpdateMode {
4199
+ case "false":
4200
+ return false
4201
+ case "always":
4202
+ return true
4203
+ case "atInstall":
4204
+ return self.wasRecentlyInstalledOrUpdated
4205
+ case "onLaunch":
4206
+ return !self.getOnLaunchDirectUpdateUsed()
4207
+ default:
4208
+ return false
4209
+ }
4210
+ }
4211
+
4212
+ private func scheduleLaunchSplashscreenTimeoutIfNeeded() {
4213
+ guard self.autoSplashscreen else {
4214
+ return
4215
+ }
4216
+ guard self.isDirectUpdateEligibleForLaunchSplashTimeout() else {
4217
+ return
4218
+ }
4219
+ self.scheduleSplashscreenTimeout()
4220
+ }
4221
+
4222
+ func hasSplashscreenTimeoutScheduledForTesting() -> Bool {
4223
+ self.autoSplashscreenTimeoutWorkItem != nil
4224
+ }
4225
+
4226
+ func scheduleLaunchSplashscreenTimeoutIfNeededForTesting() {
4227
+ self.scheduleLaunchSplashscreenTimeoutIfNeeded()
4228
+ }
4229
+
4230
+ func fireSplashscreenTimeoutForTesting() {
4231
+ self.autoSplashscreenTimeoutWorkItem?.perform()
4232
+ self.cancelSplashscreenTimeout()
4233
+ }
4234
+
4235
+ private func recordSplashscreenTimeout() {
4236
+ splashscreenTimeoutStateLock.lock()
4237
+ defer { splashscreenTimeoutStateLock.unlock() }
4238
+ splashscreenTimedOut = true
4239
+ splashscreenTimeoutGeneration += 1
4240
+ }
4241
+
4242
+ private func getSplashscreenTimeoutGeneration() -> Int {
4243
+ splashscreenTimeoutStateLock.lock()
4244
+ defer { splashscreenTimeoutStateLock.unlock() }
4245
+ return splashscreenTimeoutGeneration
4246
+ }
4247
+
4248
+ private func isDirectUpdateAllowedAfterDownload(timeoutGeneration: Int) -> Bool {
4249
+ splashscreenTimeoutStateLock.lock()
4250
+ defer { splashscreenTimeoutStateLock.unlock() }
4251
+ // A later lifecycle cycle may clear the flag, but cannot revive an expired download.
4252
+ return !splashscreenTimedOut && splashscreenTimeoutGeneration == timeoutGeneration
4253
+ }
4254
+
4135
4255
  private func scheduleSplashscreenTimeout() {
4136
4256
  guard self.autoSplashscreenTimeout > 0 else {
4137
4257
  return
@@ -4143,7 +4263,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4143
4263
 
4144
4264
  let workItem = DispatchWorkItem { [weak self] in
4145
4265
  guard let self = self else { return }
4146
- self.autoSplashscreenTimedOut = true
4266
+ self.recordSplashscreenTimeout()
4147
4267
  self.logger.info("autoSplashscreen timeout reached, hiding splashscreen")
4148
4268
  self.hideSplashscreen()
4149
4269
  }
@@ -4221,6 +4341,8 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4221
4341
  }
4222
4342
  }
4223
4343
 
4344
+ /// Resolves `autoUpdate` (boolean or string mode) into the auto update and instant apply state.
4345
+ /// The `directUpdate` key removed in 9.0.0 is ignored and only logged.
4224
4346
  private func configureAutoUpdateModeFromConfig() {
4225
4347
  if let configuredMode = getConfig().getString("autoUpdate"),
4226
4348
  configuredMode != "",
@@ -4236,9 +4358,11 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4236
4358
  } else {
4237
4359
  let configuredMode = getConfig().getString("autoUpdate")
4238
4360
  let enabled = configuredMode != nil ? configuredMode == "true" : getConfig().getBoolean("autoUpdate", true)
4239
- autoUpdateMode = enabled
4240
- ? Self.autoUpdateModeForLegacyDirectUpdateMode(resolveLegacyDirectUpdateModeFromConfig())
4241
- : Self.autoUpdateModeOff
4361
+ autoUpdateMode = enabled ? Self.autoUpdateModeBackground : Self.autoUpdateModeOff
4362
+ }
4363
+
4364
+ if getConfig().getConfigJSON()[Self.removedDirectUpdateConfigKey] != nil {
4365
+ logger.error(Self.removedDirectUpdateConfigMessage)
4242
4366
  }
4243
4367
 
4244
4368
  autoUpdate = Self.isAutoUpdateModeEnabled(autoUpdateMode)
@@ -4246,23 +4370,9 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4246
4370
  directUpdate = Self.isDirectUpdateMode(directUpdateMode)
4247
4371
  }
4248
4372
 
4249
- private func resolveLegacyDirectUpdateModeFromConfig() -> String {
4250
- if let directUpdateString = getConfig().getString("directUpdate") {
4251
- if directUpdateString == "true" {
4252
- return Self.autoUpdateModeAlways
4253
- }
4254
- if directUpdateString == "false" || Self.isDirectUpdateMode(directUpdateString) {
4255
- return directUpdateString
4256
- }
4257
- logger.error(
4258
- "Invalid directUpdate value: \"\(directUpdateString)\". Supported values are: false, true, " +
4259
- "\"always\", \"atInstall\", \"onLaunch\". Defaulting to \"false\"."
4260
- )
4261
- return "false"
4262
- }
4263
-
4264
- return getConfig().getBoolean("directUpdate", false) ? Self.autoUpdateModeAlways : "false"
4265
- }
4373
+ static let removedDirectUpdateConfigMessage =
4374
+ "The directUpdate config option was removed in 9.0.0 and is ignored. " +
4375
+ "Use autoUpdate: \"atInstall\", \"onLaunch\" or \"always\" instead."
4266
4376
 
4267
4377
  static func normalizedAutoUpdateMode(_ value: String?) -> String {
4268
4378
  guard let value else {
@@ -4302,15 +4412,6 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4302
4412
  return normalized == shakeMenuGestureShake || normalized == shakeMenuGestureThreeFingerPinch
4303
4413
  }
4304
4414
 
4305
- static func autoUpdateModeForLegacyDirectUpdateMode(_ directUpdateMode: String) -> String {
4306
- switch directUpdateMode {
4307
- case autoUpdateModeInstall, autoUpdateModeLaunch, autoUpdateModeAlways:
4308
- return directUpdateMode
4309
- default:
4310
- return autoUpdateModeBackground
4311
- }
4312
- }
4313
-
4314
4415
  static func directUpdateModeForAutoUpdateMode(_ autoUpdateMode: String) -> String {
4315
4416
  switch autoUpdateMode {
4316
4417
  case autoUpdateModeInstall, autoUpdateModeLaunch, autoUpdateModeAlways:
@@ -4374,14 +4475,25 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4374
4475
  self.setOnLaunchDirectUpdateUsed(true)
4375
4476
  }
4376
4477
 
4478
+ /// Test hook: sets an instant apply mode (`"false"`, `"always"`, `"atInstall"`, `"onLaunch"`) and the
4479
+ /// matching `autoUpdate` mode, as if it came from the config.
4377
4480
  func configureDirectUpdateModeForTesting(_ directUpdateMode: String, onLaunchDirectUpdateUsed: Bool = false) {
4378
4481
  self.directUpdateMode = directUpdateMode
4379
- self.autoUpdateMode = Self.autoUpdateModeForLegacyDirectUpdateMode(directUpdateMode)
4482
+ self.autoUpdateMode = Self.isDirectUpdateMode(directUpdateMode) ? directUpdateMode : Self.autoUpdateModeBackground
4380
4483
  self.autoUpdate = Self.isAutoUpdateModeEnabled(self.autoUpdateMode)
4381
4484
  self.directUpdate = Self.isDirectUpdateMode(self.directUpdateMode)
4382
4485
  self.setOnLaunchDirectUpdateUsed(onLaunchDirectUpdateUsed)
4383
4486
  }
4384
4487
 
4488
+ func configureAutoSplashscreenForTesting(enabled: Bool, timeoutMs: Int) {
4489
+ self.autoSplashscreen = enabled
4490
+ self.autoSplashscreenTimeout = max(0, timeoutMs)
4491
+ }
4492
+
4493
+ func setWasRecentlyInstalledOrUpdatedForTesting(_ value: Bool) {
4494
+ self.wasRecentlyInstalledOrUpdated = value
4495
+ }
4496
+
4385
4497
  func setUpdateUrlForTesting(_ updateUrl: String) {
4386
4498
  self.updateUrl = updateUrl
4387
4499
  }
@@ -4471,13 +4583,12 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4471
4583
  self.getOnLaunchDirectUpdateUsed()
4472
4584
  }
4473
4585
 
4586
+ /// Emits the `breakingAvailable` updater event for `version`. Empty versions are skipped.
4474
4587
  private func notifyBreakingEvents(version: String) {
4475
4588
  guard !version.isEmpty else {
4476
4589
  return
4477
4590
  }
4478
- let payload: [String: Any] = ["version": version]
4479
- self.notifyListenersOnMain("breakingAvailable", data: payload)
4480
- self.notifyListenersOnMain("majorAvailable", data: payload)
4591
+ self.notifyListenersOnMain("breakingAvailable", data: ["version": version])
4481
4592
  }
4482
4593
 
4483
4594
  private func shouldNotifyBreakingEvents(response: AppVersion) -> Bool {
@@ -4707,6 +4818,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4707
4818
  downloadStartTime = Date()
4708
4819
  downloadLock.unlock()
4709
4820
 
4821
+ let timeoutGeneration = self.getSplashscreenTimeoutGeneration()
4710
4822
  let plannedDirectUpdate = self.shouldUseDirectUpdate()
4711
4823
  let messageUpdate: String
4712
4824
  if plannedDirectUpdate {
@@ -4765,7 +4877,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4765
4877
  current = self.implementation.getCurrentBundle()
4766
4878
  if res.version == "builtin" {
4767
4879
  self.logger.info("Latest version is builtin")
4768
- let directUpdateAllowed = plannedDirectUpdate && !self.autoSplashscreenTimedOut
4880
+ let directUpdateAllowed = plannedDirectUpdate && self.isDirectUpdateAllowedAfterDownload(timeoutGeneration: timeoutGeneration)
4769
4881
  if directUpdateAllowed {
4770
4882
  self.logger.info("Direct update to builtin version")
4771
4883
  _ = self._reset(toLastSuccessful: false, usePendingBundle: false)
@@ -4935,7 +5047,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4935
5047
  self.endBackGroundTask()
4936
5048
  return
4937
5049
  }
4938
- let directUpdateAllowed = plannedDirectUpdate && !self.autoSplashscreenTimedOut
5050
+ let directUpdateAllowed = plannedDirectUpdate && self.isDirectUpdateAllowedAfterDownload(timeoutGeneration: timeoutGeneration)
4939
5051
  if directUpdateAllowed {
4940
5052
  let delayUpdatePreferences = UserDefaults.standard.string(forKey: DelayUpdateUtils.DELAY_CONDITION_PREFERENCES) ?? "[]"
4941
5053
  let delayConditionList = DelayUpdateUtils.parseDelayConditions(json: delayUpdatePreferences)
@@ -5103,7 +5215,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
5103
5215
  logger.error("Update to bundle: \(next!.toString()) Failed!")
5104
5216
  return false
5105
5217
  }
5106
- guard self._reload() else {
5218
+ guard self.reloadCurrentBundle() else {
5107
5219
  // Built-in `set` may reset fallback/next; restore the full pre-install state for retry.
5108
5220
  self.implementation.restoreResetState(resetState)
5109
5221
  logger.error("Update to bundle: \(next!.toString()) Failed! Reload failed, keeping it as next")
@@ -5137,6 +5249,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
5137
5249
  }
5138
5250
  self.installQueuedBundleOnForegroundIfNeeded()
5139
5251
  if self._isAutoUpdateEnabled() {
5252
+ self.scheduleLaunchSplashscreenTimeoutIfNeeded()
5140
5253
  // Check if download is already in progress (with timeout protection)
5141
5254
  if !isDownloadStuckOrTimedOut() {
5142
5255
  self.backgroundDownload()
@@ -5231,9 +5344,9 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
5231
5344
 
5232
5345
  if !self.shouldUseDirectUpdate() {
5233
5346
  if self.directUpdateMode == "false" {
5234
- logger.warn("autoSplashscreen is enabled but directUpdate is not configured for immediate updates. Set directUpdate to 'always' or disable autoSplashscreen.")
5347
+ logger.warn("autoSplashscreen is enabled but autoUpdate is not configured for immediate updates. Set autoUpdate to 'always' or disable autoSplashscreen.")
5235
5348
  } else if self.directUpdateMode == "atInstall" || self.directUpdateMode == "onLaunch" {
5236
- logger.info("autoSplashscreen is enabled but directUpdate is set to \"\(self.directUpdateMode)\". This is normal. Skipping autoSplashscreen logic.")
5349
+ logger.info("autoSplashscreen is enabled but autoUpdate is set to \"\(self.autoUpdateMode)\". This is normal. Skipping autoSplashscreen logic.")
5237
5350
  }
5238
5351
  canShowSplashscreen = false
5239
5352
  }