@gfean/react-native-bundle-drop 0.6.0 → 0.7.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 (58) hide show
  1. package/BundleDrop.podspec +96 -0
  2. package/README.md +34 -9
  3. package/android/build.gradle +65 -0
  4. package/android/src/main/java/com/bundledrop/BundleDropModule.kt +137 -13
  5. package/android/src/main/java/com/bundledrop/BundleDropNativePaths.kt +43 -13
  6. package/android/src/main/java/com/bundledrop/BundleDropOtaResolver.kt +35 -0
  7. package/android/src/main/java/com/bundledrop/BundleDropStartupRecovery.kt +1117 -0
  8. package/ios/BundleDropBridge.m +27 -0
  9. package/ios/BundleDropLocator.swift +31 -15
  10. package/ios/BundleDropModule.swift +106 -3
  11. package/ios/BundleDropOtaResolver.swift +137 -29
  12. package/ios/BundleDropStartupRecovery.swift +1108 -0
  13. package/ios/BundleDropStartupRecoveryAdapter.swift +301 -0
  14. package/lib/CLI/cli.js +4 -5
  15. package/lib/CLI/scripts/doctor.js +28 -9
  16. package/lib/CLI/scripts/expo/configure-expo.js +2 -1
  17. package/lib/CLI/scripts/init-config.d.ts +2 -2
  18. package/lib/CLI/scripts/init-config.js +23 -14
  19. package/lib/CLI/scripts/login-cli.js +2 -3
  20. package/lib/CLI/scripts/native/write-runtime-identity.d.ts +19 -0
  21. package/lib/CLI/scripts/native/write-runtime-identity.js +92 -0
  22. package/lib/CLI/scripts/upload-cli.d.ts +12 -2
  23. package/lib/CLI/scripts/upload-cli.js +74 -11
  24. package/lib/CLI/serverUrl.d.ts +3 -0
  25. package/lib/CLI/serverUrl.js +31 -0
  26. package/lib/bundleInfo.d.ts +2 -0
  27. package/lib/bundleInfo.js +16 -1
  28. package/lib/context.js +12 -2
  29. package/lib/fs/bundlePointer.d.ts +1 -17
  30. package/lib/fs/bundlePointer.js +5 -93
  31. package/lib/install/bundleInstallShared.js +4 -4
  32. package/lib/manager/downloadAndInstall.js +25 -22
  33. package/lib/manager/reporting.d.ts +8 -1
  34. package/lib/manager/reporting.js +17 -22
  35. package/lib/manager/rollbackState.d.ts +18 -54
  36. package/lib/manager/rollbackState.js +115 -216
  37. package/lib/manager/updateCheck.js +9 -3
  38. package/lib/manager/updateState.d.ts +2 -1
  39. package/lib/manager/updateState.js +59 -6
  40. package/lib/metro.d.ts +1 -1
  41. package/lib/metro.js +4 -3
  42. package/lib/native/bundleDropNative.d.ts +62 -0
  43. package/lib/native/bundleDropNative.js +266 -1
  44. package/lib/patch-engine/installFromPatchSet.js +2 -2
  45. package/lib/runtime/service.js +29 -71
  46. package/lib/runtime-delivery/bootstrapConfig.d.ts +29 -11
  47. package/lib/runtime-delivery/bootstrapConfig.js +83 -22
  48. package/lib/runtime-delivery/manifestState.d.ts +3 -1
  49. package/lib/runtime-delivery/manifestState.js +22 -1
  50. package/lib/runtime-delivery/manifestVerifier.js +7 -1
  51. package/lib/scripts/bundle.d.ts +9 -2
  52. package/lib/scripts/bundle.js +68 -18
  53. package/lib/scripts/download-bundle.d.ts +1 -0
  54. package/lib/scripts/download-bundle.js +2 -2
  55. package/lib/scripts/resolveModule.d.ts +2 -0
  56. package/lib/scripts/resolveModule.js +5 -0
  57. package/package.json +5 -2
  58. package/plugin/xcodeBuildPhase.js +2 -1
@@ -1,7 +1,85 @@
1
+ require "digest"
2
+ require "fileutils"
1
3
  require "json"
4
+ require "open3"
5
+ require "shellwords"
6
+
7
+ bundle_drop_native_runtime_identity_resource = lambda do
8
+ return nil unless defined?(Pod::Config)
9
+
10
+ project_root = File.expand_path("..", Pod::Config.instance.installation_root.to_s)
11
+ config_path = File.join(project_root, "bundle.drop.config.js")
12
+ writer_path = File.join(
13
+ __dir__,
14
+ "lib",
15
+ "CLI",
16
+ "scripts",
17
+ "native",
18
+ "write-runtime-identity.js"
19
+ )
20
+ unless File.file?(writer_path)
21
+ raise Pod::Informative,
22
+ "Bundle Drop native runtime identity writer is missing: #{writer_path}"
23
+ end
24
+
25
+ resource_path = File.join(
26
+ "ios",
27
+ "build",
28
+ "generated",
29
+ "runtime-identity",
30
+ Digest::SHA256.hexdigest(project_root)[0, 16],
31
+ "bundle-drop-build-identity.json"
32
+ )
33
+ output_path = File.join(__dir__, resource_path)
34
+
35
+ if File.file?(config_path)
36
+ stdout, stderr, status = Open3.capture3(
37
+ ENV.fetch("NODE_BINARY", "node"),
38
+ writer_path,
39
+ "--project-root", project_root,
40
+ "--platform", "ios",
41
+ "--output", output_path
42
+ )
43
+ unless status.success?
44
+ detail = stderr.strip.empty? ? stdout.strip : stderr.strip
45
+ raise Pod::Informative,
46
+ "Bundle Drop could not generate the iOS runtime identity: #{detail}"
47
+ end
48
+
49
+ identity = JSON.parse(File.read(output_path))
50
+ return nil if identity["source"] == "expo"
51
+ unless identity["runtimeVersion"].is_a?(String) && !identity["runtimeVersion"].empty?
52
+ raise Pod::Informative, "Bundle Drop generated an invalid iOS runtime identity."
53
+ end
54
+ else
55
+ # CocoaPods evaluates the podspec before `bundle-drop login` in the documented
56
+ # fresh-install flow. Keep the resource and build phase in the Pods project so
57
+ # the first native build can replace this inert placeholder after setup.
58
+ FileUtils.mkdir_p(File.dirname(output_path))
59
+ File.write(
60
+ output_path,
61
+ JSON.generate({
62
+ "schemaVersion" => 1,
63
+ "platform" => "ios",
64
+ "source" => "unconfigured"
65
+ }) + "\n"
66
+ )
67
+ end
68
+ resource_path
69
+ end
2
70
 
3
71
  package = JSON.parse(File.read(File.join(__dir__, "package.json")))
4
72
  native_version = package["nativeVersion"] || package["version"]
73
+ native_runtime_identity_resource = bundle_drop_native_runtime_identity_resource.call
74
+ native_runtime_identity_project_root = if native_runtime_identity_resource
75
+ File.expand_path("..", Pod::Config.instance.installation_root.to_s)
76
+ end
77
+ native_runtime_identity_writer = if native_runtime_identity_resource
78
+ File.join(__dir__, "lib", "CLI", "scripts", "native", "write-runtime-identity.js")
79
+ end
80
+ native_runtime_identity_output = if native_runtime_identity_resource
81
+ File.join(__dir__, native_runtime_identity_resource)
82
+ end
5
83
 
6
84
  Pod::Spec.new do |s|
7
85
  s.name = "BundleDrop"
@@ -15,6 +93,24 @@ Pod::Spec.new do |s|
15
93
  s.source = { :git => ".git", :tag => "#{s.version}" }
16
94
 
17
95
  s.source_files = "ios/**/*.{h,m,mm,swift}", "third_party/xdelta/**/*.{c,h}"
96
+ s.resources = native_runtime_identity_resource if native_runtime_identity_resource
97
+ if native_runtime_identity_resource
98
+ # Intentionally omit output files so Xcode reruns this when a bare app builds,
99
+ # even when CocoaPods has not been reinstalled since its config changed.
100
+ s.script_phase = {
101
+ :name => "Regenerate Bundle Drop runtime identity",
102
+ :execution_position => :before_compile,
103
+ :show_env_vars_in_log => "0",
104
+ :script => <<-SCRIPT
105
+ set -e
106
+ "${NODE_BINARY:-node}" \
107
+ #{Shellwords.escape(native_runtime_identity_writer)} \
108
+ --project-root #{Shellwords.escape(native_runtime_identity_project_root)} \
109
+ --platform ios \
110
+ --output #{Shellwords.escape(native_runtime_identity_output)}
111
+ SCRIPT
112
+ }
113
+ end
18
114
  s.public_header_files = "ios/BundleDropLocator.h", "ios/BundleDropZipExtractor.h"
19
115
  s.private_header_files = "third_party/xdelta/**/*.h"
20
116
  s.pod_target_xcconfig = {
package/README.md CHANGED
@@ -125,13 +125,14 @@ npx bundle-drop doctor
125
125
  Apps upgrading from an inline `runtimeDelivery` block or a direct Metro alias should
126
126
  remove that stale block and run `npx bundle-drop init` once to install the
127
127
  package-managed Metro wrapper. Inline delivery data is ignored: the validated
128
- generated bootstrap is the sole trust source. After that one-time migration, `sync`
128
+ runtime-delivery lockfile is the sole trust source. After that one-time migration, `sync`
129
129
  is the narrow command for refreshing trust data.
130
130
 
131
- The generated bootstrap is not a secret and should be committed. Setup keeps the
131
+ The runtime-delivery lockfile is not a secret and should be committed. Setup keeps the
132
132
  generated Metro wrapper, build receipts, and other transient `.bundle-drop` files
133
- ignored while allowing `.bundle-drop/runtime-delivery.generated.json` into source
134
- control.
133
+ ignored while allowing `.bundle-drop/runtime-delivery.lock.json` into source
134
+ control. Projects with the former `runtime-delivery.generated.json` filename remain
135
+ readable; run `bundle-drop sync` to migrate and remove that legacy file.
135
136
 
136
137
  ### Manual setup without AI planning
137
138
 
@@ -189,9 +190,9 @@ npx bundle-drop sync
189
190
  npx bundle-drop doctor
190
191
  ```
191
192
 
192
- `sync` creates `.bundle-drop/runtime-delivery.generated.json`, recreates it if it or
193
+ `sync` creates `.bundle-drop/runtime-delivery.lock.json`, recreates it if it or
193
194
  the entire `.bundle-drop` directory was deleted, and repairs the corresponding
194
- `.gitignore` rules. The bootstrap contains public identity and verification material,
195
+ `.gitignore` rules. The lockfile contains public identity and verification material,
195
196
  not secrets, so commit it with the application.
196
197
 
197
198
  ## Initialize the Runtime
@@ -320,6 +321,30 @@ example, an iOS-only native change should bump `runtimeVersion.ios`; Android can
320
321
  its existing value. This makes the compatibility boundary explicit and prevents an
321
322
  update from reaching a binary that cannot run it.
322
323
 
324
+ ## Native Startup Recovery
325
+
326
+ Bundle Drop records every OTA startup attempt in native storage before React Native
327
+ receives the bundle path. If an attempt does not reach its configured health boundary,
328
+ the next distinct app launch counts it as incomplete. The candidate is retried until
329
+ `rollback.maxCrashCount` is reached, then quarantined locally and replaced with the
330
+ previous native-proven healthy OTA bundle. If that bundle is missing, corrupt,
331
+ incompatible, or locally revoked, startup falls back to the bundle embedded in the app.
332
+
333
+ Automatic health waits for React content to appear and then applies
334
+ `rollback.healthyAfterSec`. Apps with a stronger readiness boundary can opt into
335
+ `healthCheckMode: 'manual'` and call `BundleDrop.reportHealthy()` after hydration,
336
+ migrations, authentication bootstrap, or navigation setup completes. Health is committed
337
+ against the exact native launch attempt, so a delayed callback from an older React runtime
338
+ cannot approve a newer launch.
339
+
340
+ Recovery is local and offline; it never waits for a network request during startup. With
341
+ `maxCrashCount: 0`, launch-health counting and automatic crash-loop rollback are disabled,
342
+ while integrity, runtime compatibility, quarantine, and locally persisted revocation checks
343
+ still apply. Native startup recovery requires a binary built with the corresponding SDK
344
+ `nativeVersion`; it cannot be added to an older installed binary through OTA JavaScript.
345
+ Crashes after an attempt is healthy do not trigger this rollback path and should use normal
346
+ crash reporting plus fix-forward or explicit rollback controls.
347
+
323
348
  ## Managed Runtime Delivery
324
349
 
325
350
  Runtime delivery is package-managed. `bundle.drop.config.js` stays focused on
@@ -330,14 +355,14 @@ a delivery-mode switch.
330
355
  `bundle-drop login` and `bundle-drop init` synchronize the trust bootstrap during
331
356
  setup. `bundle-drop sync` performs the same narrow operation later for repair or key
332
357
  rotation. Each command validates authenticated project credentials and writes the
333
- identity-bound `.bundle-drop/runtime-delivery.generated.json`. Metro confirms that
358
+ identity-bound `.bundle-drop/runtime-delivery.lock.json`. Metro confirms that
334
359
  the bootstrap belongs to the same server, organization, and project before merging
335
360
  it into the runtime module. Malformed, copied, unsupported, or private-key-bearing
336
361
  data is rejected.
337
362
 
338
363
  Older apps with an inline `runtimeDelivery` block keep their ordinary project
339
364
  configuration, but the inline block is ignored and should be removed during
340
- migration. Only the identity-bound generated bootstrap can enable managed delivery.
365
+ migration. Only the identity-bound runtime-delivery lockfile can enable managed delivery.
341
366
  If the server explicitly disables delivery for a project, synchronization removes a
342
367
  stale bootstrap and the SDK continues through the compatible `/ota/resolve` path.
343
368
 
@@ -529,7 +554,7 @@ Import the runtime API from `@gfean/react-native-bundle-drop`.
529
554
  | `BundleDrop.init(options)` | Initialize the runtime for the app process. |
530
555
  | `BundleDrop.setChannel(name)` / `setChannel` | Change the active channel for singleton actions. |
531
556
  | `BundleDrop.getChannelName()` / `getChannelName` | Read the active channel. |
532
- | `BundleDrop.reportHealthy()` / `reportHealthy` | Mark the running OTA candidate healthy for this device. |
557
+ | `BundleDrop.reportHealthy()` / `reportHealthy` | In manual health mode, ask native recovery to mark the exact running OTA attempt healthy. |
533
558
 
534
559
  **`BundleDrop.init(options)`**
535
560
 
@@ -1,3 +1,19 @@
1
+ import javax.inject.Inject
2
+ import org.gradle.process.ExecOperations
3
+
4
+ abstract class BundleDropNativeIdentityCommandExecutor {
5
+ @Inject
6
+ abstract ExecOperations getExecOperations()
7
+
8
+ void execute(File workingDirectory, String executable, List<?> arguments) {
9
+ execOperations.exec { spec ->
10
+ spec.workingDir workingDirectory
11
+ spec.executable executable
12
+ spec.args arguments
13
+ }.assertNormalExitValue()
14
+ }
15
+ }
16
+
1
17
  buildscript {
2
18
  ext.getExtOrDefault = {name ->
3
19
  return rootProject.ext.has(name) ? rootProject.ext.get(name) : project.properties['BundleDrop_' + name]
@@ -88,6 +104,49 @@ android {
88
104
  }
89
105
  }
90
106
 
107
+ if (!project.hasProperty("standalone") && rootProject.findProject(":bundledrop-expo") == null) {
108
+ def bundleDropProjectRoot = rootProject.projectDir.parentFile.canonicalFile
109
+ def bundleDropConfigFile = new File(bundleDropProjectRoot, "bundle.drop.config.js")
110
+ if (bundleDropConfigFile.isFile()) {
111
+ def bundleDropIdentityWriter = file(
112
+ "../lib/CLI/scripts/native/write-runtime-identity.js"
113
+ ).canonicalFile
114
+ if (!bundleDropIdentityWriter.isFile()) {
115
+ throw new GradleException(
116
+ "Bundle Drop native runtime identity writer is missing: ${bundleDropIdentityWriter}"
117
+ )
118
+ }
119
+ def bundleDropGeneratedAssets = file("${buildDir}/generated/bundleDropIdentity/assets")
120
+ def bundleDropIdentityOutput = new File(
121
+ bundleDropGeneratedAssets,
122
+ "bundle-drop/build-identity.json"
123
+ )
124
+ android.sourceSets.main.assets.srcDir(bundleDropGeneratedAssets)
125
+ def bundleDropCommandExecutor = objects.newInstance(
126
+ BundleDropNativeIdentityCommandExecutor
127
+ )
128
+ def generateBundleDropNativeRuntimeIdentity = tasks.register(
129
+ "generateBundleDropNativeRuntimeIdentity"
130
+ ) { task ->
131
+ task.inputs.file(bundleDropConfigFile)
132
+ task.inputs.file(bundleDropIdentityWriter)
133
+ task.outputs.file(bundleDropIdentityOutput)
134
+ task.doLast {
135
+ def nodeBinary = System.getenv("NODE_BINARY") ?: "node"
136
+ bundleDropCommandExecutor.execute(bundleDropProjectRoot, nodeBinary, [
137
+ bundleDropIdentityWriter.path,
138
+ "--project-root", bundleDropProjectRoot.path,
139
+ "--platform", "android",
140
+ "--output", bundleDropIdentityOutput.path
141
+ ])
142
+ }
143
+ }
144
+ tasks.named("preBuild").configure { task ->
145
+ task.dependsOn(generateBundleDropNativeRuntimeIdentity)
146
+ }
147
+ }
148
+ }
149
+
91
150
  afterEvaluate {
92
151
  tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).configureEach { kotlinTask ->
93
152
  def javaTask = tasks.findByName(kotlinTask.name.replace("Kotlin", "JavaWithJavac"))
@@ -200,6 +259,12 @@ if (project.hasProperty("standalone")) {
200
259
  limit { counter = "LINE"; minimum = 0.90 }
201
260
  limit { counter = "BRANCH"; minimum = 0.85 }
202
261
  }
262
+ rule {
263
+ element = "CLASS"
264
+ includes = ["com.bundledrop.BundleDropStartupRecoveryController"]
265
+ limit { counter = "LINE"; minimum = 0.90 }
266
+ limit { counter = "BRANCH"; minimum = 0.70 }
267
+ }
203
268
  rule {
204
269
  element = "CLASS"
205
270
  includes = ["com.bundledrop.BundleDropFileOps"]
@@ -6,22 +6,19 @@ import android.util.Log
6
6
  import com.facebook.react.bridge.*
7
7
  import com.facebook.react.modules.network.OkHttpClientProvider
8
8
  import java.io.File
9
+ import org.json.JSONArray
10
+ import org.json.JSONObject
9
11
 
10
12
  class BundleDropModule(reactContext: ReactApplicationContext) :
11
13
  ReactContextBaseJavaModule(reactContext) {
12
14
 
13
- private var downloadedBundlePath: String? = null
14
-
15
15
  companion object {
16
- var latestBundlePath: String? = null
17
- private set
18
-
19
16
  fun getDownloadedBundlePath(context: Context): String? =
20
- BundleDropNativePaths.getDownloadedBundlePath(context)
17
+ BundleDropNativePaths.getDownloadedBundlePathPassive(context)
21
18
 
22
19
  @JvmStatic
23
20
  fun resolveJSBundleFile(context: Context, fallback: String?): String? {
24
- val path = getDownloadedBundlePath(context)
21
+ val path = BundleDropNativePaths.getDownloadedBundlePath(context)
25
22
  return if (!path.isNullOrEmpty()) path else fallback
26
23
  }
27
24
  }
@@ -30,10 +27,7 @@ class BundleDropModule(reactContext: ReactApplicationContext) :
30
27
 
31
28
  @ReactMethod
32
29
  fun getDownloadedBundlePath(promise: Promise) {
33
- val path = getDownloadedBundlePath(reactApplicationContext)
34
- downloadedBundlePath = path
35
- latestBundlePath = path
36
- promise.resolve(path)
30
+ promise.resolve(getDownloadedBundlePath(reactApplicationContext))
37
31
  }
38
32
 
39
33
  @ReactMethod
@@ -69,6 +63,95 @@ class BundleDropModule(reactContext: ReactApplicationContext) :
69
63
  }
70
64
  }
71
65
 
66
+ @ReactMethod
67
+ fun activateStartupCandidate(
68
+ hash: String,
69
+ maxCrashCount: Double,
70
+ healthCheckMode: String,
71
+ healthyAfterSec: Double,
72
+ promise: Promise,
73
+ ) {
74
+ try {
75
+ require(maxCrashCount.isFinite() && maxCrashCount >= 0 && maxCrashCount % 1.0 == 0.0) {
76
+ "maxCrashCount must be a non-negative integer"
77
+ }
78
+ require(maxCrashCount <= Int.MAX_VALUE) { "maxCrashCount is outside the supported range" }
79
+ val result = BundleDropStartupRecovery.controller(reactApplicationContext)
80
+ .activateCandidate(hash, maxCrashCount.toInt(), healthCheckMode, healthyAfterSec)
81
+ promise.resolve(Arguments.createMap().apply {
82
+ putString("hash", result.hash)
83
+ putString("bundlePath", result.bundlePath)
84
+ })
85
+ } catch (error: Exception) {
86
+ promise.reject("ERR_STARTUP_RECOVERY_ACTIVATE", error.message, error)
87
+ }
88
+ }
89
+
90
+ @ReactMethod
91
+ fun markStartupHealthy(hash: String, attemptId: String, promise: Promise) {
92
+ try {
93
+ val marked = BundleDropStartupRecovery.controller(reactApplicationContext)
94
+ .markHealthy(hash, attemptId)
95
+ promise.resolve(marked)
96
+ } catch (error: Exception) {
97
+ promise.reject("ERR_STARTUP_RECOVERY_HEALTH", error.message, error)
98
+ }
99
+ }
100
+
101
+ @ReactMethod
102
+ fun getStartupRecoveryState(promise: Promise) {
103
+ try {
104
+ val state = BundleDropStartupRecovery.controller(reactApplicationContext).snapshot()
105
+ promise.resolve(jsonObjectToWritableMap(state))
106
+ } catch (error: Exception) {
107
+ promise.reject("ERR_STARTUP_RECOVERY_STATE", error.message, error)
108
+ }
109
+ }
110
+
111
+ @ReactMethod
112
+ fun setStartupRecoveryRevokedHashes(hashes: ReadableArray, promise: Promise) {
113
+ try {
114
+ val values = buildSet {
115
+ for (index in 0 until hashes.size()) {
116
+ val hash = hashes.getString(index)
117
+ ?: throw IllegalArgumentException("Revoked bundle hashes must be strings")
118
+ add(hash)
119
+ }
120
+ }
121
+ BundleDropStartupRecovery.controller(reactApplicationContext).setRevokedHashes(values)
122
+ promise.resolve(true)
123
+ } catch (error: Exception) {
124
+ promise.reject("ERR_STARTUP_RECOVERY_REVOKE", error.message, error)
125
+ }
126
+ }
127
+
128
+ @ReactMethod
129
+ fun acknowledgeStartupRecovery(eventId: String, promise: Promise) {
130
+ try {
131
+ promise.resolve(
132
+ BundleDropStartupRecovery.controller(reactApplicationContext)
133
+ .acknowledgeRecovery(eventId),
134
+ )
135
+ } catch (error: Exception) {
136
+ promise.reject("ERR_STARTUP_RECOVERY_ACK", error.message, error)
137
+ }
138
+ }
139
+
140
+ @ReactMethod
141
+ fun rollbackStartupBundle(forceEmbedded: Boolean, promise: Promise) {
142
+ try {
143
+ val result = BundleDropStartupRecovery.controller(reactApplicationContext)
144
+ .rollbackStartupBundle(forceEmbedded)
145
+ promise.resolve(Arguments.createMap().apply {
146
+ putBoolean("rolledBack", result.rolledBack)
147
+ putBoolean("toEmbedded", result.toEmbedded)
148
+ result.hash?.let { putString("hash", it) }
149
+ })
150
+ } catch (error: Exception) {
151
+ promise.reject("ERR_STARTUP_RECOVERY_ROLLBACK", error.message, error)
152
+ }
153
+ }
154
+
72
155
  @ReactMethod(isBlockingSynchronousMethod = true)
73
156
  fun getImageManifestSync(): String? {
74
157
  return readImageManifestRaw()
@@ -332,12 +415,53 @@ class BundleDropModule(reactContext: ReactApplicationContext) :
332
415
 
333
416
  override fun getConstants(): MutableMap<String, Any> {
334
417
  val map = mutableMapOf<String, Any>()
335
- downloadedBundlePath?.let {
336
- map["downloadedBundlePath"] = it
418
+ map["startupRecoveryProtocolVersion"] = BundleDropStartupRecoveryController.PROTOCOL_VERSION
419
+ @Suppress("UNCHECKED_CAST")
420
+ (map as MutableMap<String, Any?>)["startupRecoverySelectedHash"] =
421
+ BundleDropStartupRecovery.startupSelectedHash()
422
+ BundleDropStartupRecovery.startupAttempt()?.let { (hash, attemptId) ->
423
+ map["startupRecoveryAttemptHash"] = hash
424
+ map["startupRecoveryAttemptId"] = attemptId
337
425
  }
338
426
  val context = reactApplicationContext
339
427
  map["DocumentDirectoryPath"] = context.filesDir.absolutePath
340
428
  map["LibraryDirectoryPath"] = context.filesDir.absolutePath
341
429
  return map
342
430
  }
431
+
432
+ private fun jsonObjectToWritableMap(json: JSONObject): WritableMap {
433
+ val map = Arguments.createMap()
434
+ val keys = json.keys()
435
+ while (keys.hasNext()) {
436
+ val key = keys.next()
437
+ putJsonValue(map, key, json.opt(key))
438
+ }
439
+ return map
440
+ }
441
+
442
+ private fun jsonArrayToWritableArray(json: JSONArray): WritableArray {
443
+ val array = Arguments.createArray()
444
+ for (index in 0 until json.length()) {
445
+ when (val value = json.opt(index)) {
446
+ null, JSONObject.NULL -> array.pushNull()
447
+ is JSONObject -> array.pushMap(jsonObjectToWritableMap(value))
448
+ is JSONArray -> array.pushArray(jsonArrayToWritableArray(value))
449
+ is Boolean -> array.pushBoolean(value)
450
+ is Number -> array.pushDouble(value.toDouble())
451
+ else -> array.pushString(value.toString())
452
+ }
453
+ }
454
+ return array
455
+ }
456
+
457
+ private fun putJsonValue(map: WritableMap, key: String, value: Any?) {
458
+ when (value) {
459
+ null, JSONObject.NULL -> map.putNull(key)
460
+ is JSONObject -> map.putMap(key, jsonObjectToWritableMap(value))
461
+ is JSONArray -> map.putArray(key, jsonArrayToWritableArray(value))
462
+ is Boolean -> map.putBoolean(key, value)
463
+ is Number -> map.putDouble(key, value.toDouble())
464
+ else -> map.putString(key, value.toString())
465
+ }
466
+ }
343
467
  }
@@ -8,8 +8,8 @@ import org.json.JSONObject
8
8
  /**
9
9
  * Resolves the on-disk OTA JS bundle path (no React / bridge types).
10
10
  *
11
- * Shared by [BundleDropModule] so cold-start `resolveJSBundleFile`, the JS bridge
12
- * `getDownloadedBundlePath`, and tests use the same logic — including the OTA-disabled gate.
11
+ * Cold-start resolution records a launch attempt, while bridge lookups are passive and never
12
+ * change the attempt selected for the current React runtime.
13
13
  */
14
14
  object BundleDropNativePaths {
15
15
  private const val KEY_BINARY_VERSION = "binary_version"
@@ -40,6 +40,9 @@ object BundleDropNativePaths {
40
40
  return binaryVersionKey(versionName, versionCode, runtimeVersion)
41
41
  }
42
42
 
43
+ internal fun currentBinaryIdentity(context: Context): String =
44
+ getBinaryVersionKey(context, readEmbeddedRuntimeVersion(context))
45
+
43
46
  internal fun readEmbeddedRuntimeVersion(context: Context): String? {
44
47
  return try {
45
48
  context.assets.open(BUILD_IDENTITY_ASSET).bufferedReader().use { reader ->
@@ -64,11 +67,37 @@ object BundleDropNativePaths {
64
67
 
65
68
  @JvmStatic
66
69
  fun getDownloadedBundlePath(context: Context): String? {
67
- if (!BundleDropOtaPrefs.isOtaEnabled(context)) return null
68
- return getDownloadedBundlePath(context, readEmbeddedRuntimeVersion(context))
70
+ if (!BundleDropOtaPrefs.isOtaEnabled(context)) {
71
+ BundleDropStartupRecovery.clearStartupSelection()
72
+ return null
73
+ }
74
+ resolveForBinary(context, readEmbeddedRuntimeVersion(context))
75
+ val selection = BundleDropStartupRecovery.selectForStartup(context)
76
+ logResolvedPath(selection.bundlePath)
77
+ return selection.bundlePath
69
78
  }
70
79
 
71
80
  internal fun getDownloadedBundlePath(context: Context, runtimeVersion: String?): String? {
81
+ if (!BundleDropOtaPrefs.isOtaEnabled(context)) {
82
+ BundleDropStartupRecovery.clearStartupSelection()
83
+ return null
84
+ }
85
+ resolveForBinary(context, runtimeVersion)
86
+ val selection = BundleDropStartupRecovery.selectForStartup(context)
87
+ logResolvedPath(selection.bundlePath)
88
+ return selection.bundlePath
89
+ }
90
+
91
+ internal fun getDownloadedBundlePathPassive(context: Context): String? {
92
+ if (!BundleDropOtaPrefs.isOtaEnabled(context)) return null
93
+ val resolved = resolveForBinary(context, readEmbeddedRuntimeVersion(context))
94
+ if (resolved == null) return null
95
+ val path = BundleDropStartupRecovery.controller(context).resolvePassive()
96
+ logResolvedPath(path)
97
+ return path
98
+ }
99
+
100
+ private fun resolveForBinary(context: Context, runtimeVersion: String?): String? {
72
101
  val bundleDropRoot = File(context.filesDir, "bundle-drop")
73
102
  val result = BundleDropOtaResolver.resolve(
74
103
  bundleDropRoot = bundleDropRoot,
@@ -79,16 +108,17 @@ object BundleDropNativePaths {
79
108
 
80
109
  result.storedVersion?.let { setStoredBinaryVersion(context, it) }
81
110
 
82
- if (result.bundlePath == null) {
83
- if (result.clearedOta) {
84
- Log.d("BundleDrop", "Binary updated, clearing OTA bundle")
85
- } else {
86
- Log.d("BundleDrop", "📦 No OTA bundle found.")
87
- }
88
- } else {
89
- Log.d("BundleDrop", "🔁 Using OTA bundle at: ${result.bundlePath}")
111
+ if (result.clearedOta) {
112
+ Log.d("BundleDrop", "Binary updated, clearing OTA bundle")
90
113
  }
91
-
92
114
  return result.bundlePath
93
115
  }
116
+
117
+ private fun logResolvedPath(path: String?) {
118
+ if (path == null) {
119
+ Log.d("BundleDrop", "📦 No OTA bundle found.")
120
+ } else {
121
+ Log.d("BundleDrop", "🔁 Using OTA bundle at: $path")
122
+ }
123
+ }
94
124
  }
@@ -43,6 +43,39 @@ object BundleDropOtaResolver {
43
43
  }
44
44
  }
45
45
 
46
+ /** Verify an installed bundle independently of the active pointer. */
47
+ internal fun readBundleForHash(bundleDropRoot: File, hash: String): String? {
48
+ if (!bundleHashPattern.matches(hash)) return null
49
+ return try {
50
+ val bundleDir = File(File(bundleDropRoot, "bundles"), hash)
51
+ val bundleFile = File(bundleDir, "main.jsbundle")
52
+ val manifestFile = File(bundleDir, "bundle-manifest.json")
53
+ if (!bundleFile.exists() || !manifestFile.exists()) return null
54
+ val manifest = JSONObject(manifestFile.readText())
55
+ if (
56
+ manifest.optInt("manifestVersion", -1) != 1 ||
57
+ manifest.optString("bundleHash", "") != hash ||
58
+ !verifyBundleDir(bundleDir, manifest, hash)
59
+ ) {
60
+ return null
61
+ }
62
+ bundleFile.absolutePath
63
+ } catch (_: Exception) {
64
+ null
65
+ }
66
+ }
67
+
68
+ internal fun readBundleRuntimeVersion(bundleDropRoot: File, hash: String): String? {
69
+ readBundleForHash(bundleDropRoot, hash) ?: return null
70
+ return try {
71
+ JSONObject(File(File(File(bundleDropRoot, "bundles"), hash), "bundle-manifest.json").readText())
72
+ .optString("runtimeVersion", "")
73
+ .takeIf(String::isNotEmpty)
74
+ } catch (_: Exception) {
75
+ null
76
+ }
77
+ }
78
+
46
79
  private fun verifyBundleDir(bundleDir: File, manifest: JSONObject, expectedHash: String): Boolean {
47
80
  val files = manifest.optJSONArray("files") ?: return false
48
81
  if (manifest.optString("platform", "") != "android") {
@@ -184,6 +217,7 @@ object BundleDropOtaResolver {
184
217
  File(bundleDropRoot, "current.json"),
185
218
  File(bundleDropRoot, "previous.json"),
186
219
  File(bundleDropRoot, "state.json"),
220
+ File(bundleDropRoot, BundleDropStartupRecoveryController.RECOVERY_LEDGER),
187
221
  File(filesDir, "bundle-info.json"),
188
222
  )
189
223
  filesToClear.forEach {
@@ -196,6 +230,7 @@ object BundleDropOtaResolver {
196
230
  File(bundleDropRoot, "current.json"),
197
231
  File(bundleDropRoot, "previous.json"),
198
232
  File(bundleDropRoot, "state.json"),
233
+ File(bundleDropRoot, BundleDropStartupRecoveryController.RECOVERY_LEDGER),
199
234
  File(filesDir, "bundle-info.json"),
200
235
  ).any { it.exists() }
201
236
  }