@gfean/react-native-bundle-drop 0.3.3 → 0.3.6

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 (84) hide show
  1. package/BundleDrop.podspec +2 -0
  2. package/README.md +8 -2
  3. package/android/build.gradle +91 -1
  4. package/android/gradle.properties +1 -0
  5. package/android/src/main/java/com/bundledrop/BundleDropFileOps.kt +131 -0
  6. package/android/src/main/java/com/bundledrop/BundleDropModule.kt +65 -89
  7. package/android/src/main/java/com/bundledrop/BundleDropOtaResolver.kt +93 -0
  8. package/ios/BundleDropBridge.m +14 -0
  9. package/ios/BundleDropFileOps.swift +220 -0
  10. package/ios/BundleDropLocator.h +11 -0
  11. package/ios/BundleDropLocator.swift +34 -45
  12. package/ios/BundleDropModule.swift +65 -15
  13. package/ios/BundleDropOtaResolver.swift +112 -0
  14. package/ios/BundleDropZipExtractor.h +13 -0
  15. package/ios/BundleDropZipExtractor.m +226 -0
  16. package/lib/CLI/cli.js +56 -6
  17. package/lib/CLI/scripts/aipowered/apply-plan.d.ts +10 -0
  18. package/lib/CLI/scripts/aipowered/apply-plan.js +50 -0
  19. package/lib/CLI/scripts/aipowered/backend-client.d.ts +6 -0
  20. package/lib/CLI/scripts/aipowered/backend-client.js +34 -0
  21. package/lib/CLI/scripts/aipowered/diff-preview.d.ts +7 -0
  22. package/lib/CLI/scripts/aipowered/diff-preview.js +33 -0
  23. package/lib/CLI/scripts/aipowered/init-native-config.d.ts +2 -0
  24. package/lib/CLI/scripts/aipowered/init-native-config.js +131 -0
  25. package/lib/CLI/scripts/aipowered/scanner.d.ts +5 -0
  26. package/lib/CLI/scripts/aipowered/scanner.js +349 -0
  27. package/lib/CLI/scripts/aipowered/types.d.ts +53 -0
  28. package/lib/CLI/scripts/aipowered/types.js +2 -0
  29. package/lib/CLI/scripts/aipowered/validate-plan.d.ts +8 -0
  30. package/lib/CLI/scripts/aipowered/validate-plan.js +164 -0
  31. package/lib/CLI/scripts/init-config.js +10 -5
  32. package/lib/CLI/scripts/init-native-config.js +1 -1
  33. package/lib/CLI/scripts/post-init.js +7 -18
  34. package/lib/CLI/scripts/upload-cli.d.ts +2 -0
  35. package/lib/CLI/scripts/upload-cli.js +67 -28
  36. package/lib/CLI/utils/ui.d.ts +3 -0
  37. package/lib/CLI/utils/ui.js +26 -0
  38. package/lib/api/clientApi.d.ts +2 -1
  39. package/lib/api/clientApi.js +9 -0
  40. package/lib/api/types.d.ts +21 -3
  41. package/lib/bundleInfo.d.ts +12 -0
  42. package/lib/context.d.ts +19 -2
  43. package/lib/context.js +5 -2
  44. package/lib/errors.d.ts +25 -0
  45. package/lib/errors.js +26 -1
  46. package/lib/fs/bundlePointer.d.ts +2 -0
  47. package/lib/fs/bundlePointer.js +14 -4
  48. package/lib/fs/fsUtils.d.ts +1 -2
  49. package/lib/fs/fsUtils.js +12 -27
  50. package/lib/fs/userProperties.d.ts +25 -4
  51. package/lib/fs/userProperties.js +51 -7
  52. package/lib/index.d.ts +7 -3
  53. package/lib/index.js +5 -1
  54. package/lib/injectImageResolver.js +6 -15
  55. package/lib/install/installFromZip.d.ts +1 -1
  56. package/lib/install/installFromZip.js +47 -42
  57. package/lib/loadConfig.d.ts +21 -2
  58. package/lib/loadConfig.js +11 -7
  59. package/lib/manager/downloadAndInstall.d.ts +3 -0
  60. package/lib/manager/downloadAndInstall.js +30 -28
  61. package/lib/manager/reporting.d.ts +2 -0
  62. package/lib/manager/reporting.js +27 -2
  63. package/lib/manager/rollbackState.d.ts +28 -11
  64. package/lib/manager/rollbackState.js +90 -38
  65. package/lib/manager/updateCheck.js +17 -3
  66. package/lib/manager/updateState.d.ts +5 -1
  67. package/lib/manager/updateState.js +20 -11
  68. package/lib/native/fs.d.ts +6 -0
  69. package/lib/native/fs.js +27 -0
  70. package/lib/runtime/initState.d.ts +2 -2
  71. package/lib/runtime/service.d.ts +28 -0
  72. package/lib/runtime/service.js +136 -10
  73. package/lib/scripts/bundle.d.ts +4 -1
  74. package/lib/scripts/bundle.js +42 -29
  75. package/lib/scripts/projectRoot.d.ts +1 -0
  76. package/lib/scripts/projectRoot.js +54 -0
  77. package/lib/scripts/resolve-ios-version.d.ts +2 -0
  78. package/lib/scripts/resolve-ios-version.js +74 -0
  79. package/lib/scripts/upload-bundle.d.ts +2 -1
  80. package/lib/scripts/upload-bundle.js +56 -41
  81. package/lib/types.d.ts +3 -0
  82. package/lib/useBundleDrop.d.ts +2 -0
  83. package/lib/useBundleDrop.js +1 -0
  84. package/package.json +9 -11
@@ -15,6 +15,8 @@ Pod::Spec.new do |s|
15
15
  s.source = { :git => ".git", :tag => "#{s.version}" }
16
16
 
17
17
  s.source_files = "ios/**/*.{h,m,mm,swift}"
18
+ s.libraries = "z"
19
+ s.swift_version = "5.0"
18
20
 
19
21
  if respond_to?(:install_modules_dependencies, true)
20
22
  install_modules_dependencies(s)
package/README.md CHANGED
@@ -67,7 +67,7 @@ import { BundleDrop } from '@gfean/react-native-bundle-drop';
67
67
 
68
68
  BundleDrop.init({
69
69
  enabled: !__DEV__,
70
- environment: __DEV__ ? 'STAG' : 'PROD',
70
+ environment: __DEV__ ? 'development' : 'production',
71
71
  policy: 'on-next-launch',
72
72
  channelName: 'General',
73
73
  });
@@ -111,9 +111,15 @@ Use user properties to target specific cohorts:
111
111
  ```ts
112
112
  import { setUserProperty } from '@gfean/react-native-bundle-drop';
113
113
 
114
- await setUserProperty('beta');
114
+ await setUserProperty('plan', 'pro');
115
+ await setUserProperty('age', 33);
116
+ await setUserProperty('beta', true);
115
117
  ```
116
118
 
119
+ User property values must be strings, finite numbers, or booleans. Keys are trimmed and must be
120
+ non-empty, 128 characters or fewer, and cannot start with `$`, contain `.`, contain a null byte, or
121
+ use reserved prototype names.
122
+
117
123
  ---
118
124
 
119
125
  ## Docs
@@ -19,6 +19,10 @@ buildscript {
19
19
  apply plugin: "com.android.library"
20
20
  apply plugin: "kotlin-android"
21
21
 
22
+ if (project.hasProperty("standalone")) {
23
+ apply plugin: "jacoco"
24
+ }
25
+
22
26
  def getExtOrIntegerDefault(name) {
23
27
  return rootProject.ext.has(name) ? rootProject.ext.get(name) : (project.properties["BundleDrop_" + name]).toInteger()
24
28
  }
@@ -64,6 +68,19 @@ android {
64
68
  sourceCompatibility JavaVersion.VERSION_1_8
65
69
  targetCompatibility JavaVersion.VERSION_1_8
66
70
  }
71
+
72
+ kotlinOptions {
73
+ jvmTarget = "1.8"
74
+ }
75
+ }
76
+
77
+ afterEvaluate {
78
+ tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).configureEach { kotlinTask ->
79
+ def javaTask = tasks.findByName(kotlinTask.name.replace("Kotlin", "JavaWithJavac"))
80
+ if (javaTask != null && javaTask.hasProperty("targetCompatibility")) {
81
+ kotlinTask.kotlinOptions.jvmTarget = javaTask.targetCompatibility.toString()
82
+ }
83
+ }
67
84
  }
68
85
 
69
86
  repositories {
@@ -74,6 +91,79 @@ repositories {
74
91
  def kotlin_version = getExtOrDefault("kotlinVersion")
75
92
 
76
93
  dependencies {
77
- implementation "com.facebook.react:react-android"
94
+ if (project.hasProperty("standalone")) {
95
+ compileOnly "com.facebook.react:react-android:+"
96
+ } else {
97
+ implementation "com.facebook.react:react-android"
98
+ }
78
99
  implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
100
+ testImplementation "junit:junit:4.13.2"
101
+ testImplementation "org.json:json:20231013"
102
+ }
103
+
104
+ // ---------------------------------------------------------------------------
105
+ // JaCoCo coverage for host-side unit tests (standalone only)
106
+ // ---------------------------------------------------------------------------
107
+
108
+ if (project.hasProperty("standalone")) {
109
+ android.testOptions.unitTests.all {
110
+ jacoco {
111
+ includeNoLocationClasses = true
112
+ excludes = ["jdk.internal.*"]
113
+ }
114
+ }
115
+
116
+ def excludedFromCoverage = ["**/BundleDropModule*", "**/BundleDropPackage*"]
117
+
118
+ tasks.register("jacocoTestReport", JacocoReport) {
119
+ dependsOn "testDebugUnitTest"
120
+ group = "verification"
121
+ description = "Generate JaCoCo coverage report for debug unit tests"
122
+
123
+ def mainSrc = "${project.projectDir}/src/main/java"
124
+ def debugTree = fileTree(
125
+ dir: "${buildDir}/tmp/kotlin-classes/debug",
126
+ excludes: excludedFromCoverage
127
+ )
128
+ def execData = file("${buildDir}/jacoco/testDebugUnitTest.exec")
129
+
130
+ sourceDirectories.setFrom(files(mainSrc))
131
+ classDirectories.setFrom(debugTree)
132
+ executionData.setFrom(files(execData))
133
+
134
+ reports {
135
+ html.required = true
136
+ xml.required = true
137
+ }
138
+ }
139
+
140
+ tasks.register("jacocoCoverageGate", JacocoCoverageVerification) {
141
+ dependsOn "jacocoTestReport"
142
+ group = "verification"
143
+ description = "Enforce coverage thresholds on testable native classes"
144
+
145
+ def debugTree = fileTree(
146
+ dir: "${buildDir}/tmp/kotlin-classes/debug",
147
+ excludes: excludedFromCoverage
148
+ )
149
+ def execData = file("${buildDir}/jacoco/testDebugUnitTest.exec")
150
+
151
+ classDirectories.setFrom(debugTree)
152
+ executionData.setFrom(files(execData))
153
+
154
+ violationRules {
155
+ rule {
156
+ element = "CLASS"
157
+ includes = ["com.bundledrop.BundleDropOtaResolver"]
158
+ limit { counter = "LINE"; minimum = 0.90 }
159
+ limit { counter = "BRANCH"; minimum = 0.85 }
160
+ }
161
+ rule {
162
+ element = "CLASS"
163
+ includes = ["com.bundledrop.BundleDropFileOps"]
164
+ limit { counter = "LINE"; minimum = 0.55 }
165
+ limit { counter = "BRANCH"; minimum = 0.55 }
166
+ }
167
+ }
168
+ }
79
169
  }
@@ -3,3 +3,4 @@ BundleDrop_minSdkVersion=24
3
3
  BundleDrop_targetSdkVersion=34
4
4
  BundleDrop_compileSdkVersion=35
5
5
  BundleDrop_ndkVersion=27.1.12297006
6
+ android.useAndroidX=true
@@ -0,0 +1,131 @@
1
+ package com.bundledrop
2
+
3
+ import java.io.File
4
+ import java.io.FileInputStream
5
+ import java.io.FileOutputStream
6
+ import java.net.URL
7
+ import java.util.zip.ZipInputStream
8
+
9
+ object BundleDropFileOps {
10
+
11
+ fun validateHttpUrl(url: String): URL {
12
+ val parsed = URL(url)
13
+ val scheme = parsed.protocol?.lowercase()
14
+ if (scheme != "https" && scheme != "http") {
15
+ throw java.io.IOException("Invalid or non-HTTP URL: $url")
16
+ }
17
+ return parsed
18
+ }
19
+
20
+ fun unlinkPath(path: String) {
21
+ val file = File(path)
22
+ if (file.exists()) {
23
+ if (file.isDirectory) file.deleteRecursively() else file.delete()
24
+ }
25
+ }
26
+
27
+ fun unzipFile(
28
+ zipPath: String,
29
+ destPath: String,
30
+ maxEntryBytes: Long = 128L * 1024 * 1024,
31
+ maxTotalBytes: Long = 512L * 1024 * 1024,
32
+ ): List<String> {
33
+ val destDir = File(destPath)
34
+ java.util.zip.ZipFile(zipPath).use { /* validate central directory before extraction */ }
35
+ if (!destDir.exists()) destDir.mkdirs()
36
+
37
+ val filenames = mutableListOf<String>()
38
+ val buf = ByteArray(8192)
39
+ var totalWritten = 0L
40
+
41
+ ZipInputStream(FileInputStream(zipPath)).use { zis ->
42
+ var entry = zis.nextEntry
43
+ while (entry != null) {
44
+ if (!entry.isDirectory) {
45
+ val outFile = File(destDir, entry.name)
46
+ if (!outFile.canonicalPath.startsWith(destDir.canonicalPath + File.separator)) {
47
+ throw SecurityException("Zip entry outside target dir: ${entry.name}")
48
+ }
49
+ outFile.parentFile?.mkdirs()
50
+ var entryWritten = 0L
51
+ FileOutputStream(outFile).use { fos ->
52
+ var len: Int
53
+ while (zis.read(buf).also { len = it } > 0) {
54
+ entryWritten += len
55
+ totalWritten += len
56
+ if (entryWritten > maxEntryBytes) {
57
+ throw java.io.IOException("ZIP entry exceeds ${maxEntryBytes / (1024 * 1024)} MB limit: ${entry.name}")
58
+ }
59
+ if (totalWritten > maxTotalBytes) {
60
+ throw java.io.IOException("ZIP total uncompressed exceeds ${maxTotalBytes / (1024 * 1024)} MB limit")
61
+ }
62
+ fos.write(buf, 0, len)
63
+ }
64
+ }
65
+ filenames.add(entry.name)
66
+ } else {
67
+ val dirFile = File(destDir, entry.name)
68
+ if (!dirFile.canonicalPath.startsWith(destDir.canonicalPath + File.separator)) {
69
+ throw SecurityException("Zip entry outside target dir: ${entry.name}")
70
+ }
71
+ dirFile.mkdirs()
72
+ }
73
+ zis.closeEntry()
74
+ entry = zis.nextEntry
75
+ }
76
+ }
77
+
78
+ return filenames
79
+ }
80
+
81
+ fun moveFile(src: File, dest: File) {
82
+ dest.parentFile?.mkdirs()
83
+ if (!src.renameTo(dest)) {
84
+ src.copyTo(dest, overwrite = true)
85
+ src.delete()
86
+ }
87
+ }
88
+
89
+ fun downloadToFile(
90
+ parsedUrl: URL,
91
+ destFile: File,
92
+ maxBytes: Long = 256L * 1024 * 1024,
93
+ connectTimeout: Int = 30_000,
94
+ readTimeout: Int = 60_000,
95
+ ) {
96
+ var connection: java.net.HttpURLConnection? = null
97
+ try {
98
+ destFile.parentFile?.mkdirs()
99
+
100
+ connection = parsedUrl.openConnection() as java.net.HttpURLConnection
101
+ connection.connectTimeout = connectTimeout
102
+ connection.readTimeout = readTimeout
103
+ connection.instanceFollowRedirects = true
104
+
105
+ val status = connection.responseCode
106
+ if (status !in 200..299) {
107
+ throw java.io.IOException("HTTP $status: ${connection.responseMessage}")
108
+ }
109
+
110
+ var totalRead = 0L
111
+ connection.inputStream.use { input ->
112
+ FileOutputStream(destFile).use { output ->
113
+ val buf = ByteArray(8192)
114
+ var len: Int
115
+ while (input.read(buf).also { len = it } > 0) {
116
+ totalRead += len
117
+ if (totalRead > maxBytes) {
118
+ throw java.io.IOException("Download exceeds ${maxBytes / (1024 * 1024)} MB limit")
119
+ }
120
+ output.write(buf, 0, len)
121
+ }
122
+ }
123
+ }
124
+ } catch (e: Exception) {
125
+ try { destFile.delete() } catch (_: Exception) {}
126
+ throw e
127
+ } finally {
128
+ try { connection?.disconnect() } catch (_: Exception) {}
129
+ }
130
+ }
131
+ }
@@ -1,18 +1,10 @@
1
1
  package com.bundledrop
2
2
 
3
- import android.app.AlarmManager
4
- import android.app.PendingIntent
5
3
  import android.content.Context
6
4
  import android.content.Intent
7
5
  import android.util.Log
8
- import com.facebook.react.ReactApplication
9
6
  import com.facebook.react.bridge.*
10
7
  import java.io.File
11
- import android.os.Handler
12
- import android.os.Looper
13
- import com.facebook.react.bridge.JSBundleLoader
14
- import com.facebook.react.modules.core.DeviceEventManagerModule
15
- import org.json.JSONObject
16
8
 
17
9
  class BundleDropModule(reactContext: ReactApplicationContext) :
18
10
  ReactContextBaseJavaModule(reactContext) {
@@ -26,34 +18,6 @@ class BundleDropModule(reactContext: ReactApplicationContext) :
26
18
  private const val PREFS_NAME = "BundleDropPrefs"
27
19
  private const val KEY_BINARY_VERSION = "binary_version"
28
20
 
29
- private fun currentJsonPath(context: Context): File {
30
- return File(context.filesDir, "bundle-drop/current.json")
31
- }
32
-
33
- private fun readCurrentPointer(context: Context): String? {
34
- return try {
35
- val jsonFile = currentJsonPath(context)
36
- if (!jsonFile.exists()) return null
37
- val raw = jsonFile.readText()
38
- val parsed = JSONObject(raw)
39
- val path = parsed.optString("bundlePath", null)
40
- if (path != null && path.isNotEmpty()) {
41
- val file = File(path)
42
- if (file.exists()) path else null
43
- } else {
44
- null
45
- }
46
- } catch (e: Exception) {
47
- Log.w("BundleDrop", "Failed to read current.json: ${e.message}", e)
48
- null
49
- }
50
- }
51
-
52
- private fun legacyBundlePath(context: Context): String? {
53
- val file = File(context.filesDir, "main.jsbundle")
54
- return if (file.exists()) file.absolutePath else null
55
- }
56
-
57
21
  private fun getBinaryVersionKey(context: Context): String {
58
22
  val pInfo = context.packageManager.getPackageInfo(context.packageName, 0)
59
23
  val versionName = pInfo.versionName ?: "unknown"
@@ -76,43 +40,28 @@ class BundleDropModule(reactContext: ReactApplicationContext) :
76
40
  .edit().putString(KEY_BINARY_VERSION, version).apply()
77
41
  }
78
42
 
79
- private fun clearOtaState(context: Context) {
80
- try {
81
- val root = File(context.filesDir, "bundle-drop")
82
- val filesToClear = listOf(
83
- File(root, "current.json"),
84
- File(root, "previous.json"),
85
- File(root, "state.json"),
86
- File(context.filesDir, "bundle-info.json"),
87
- )
88
- filesToClear.forEach { if (it.exists()) it.delete() }
89
- } catch (e: Exception) {
90
- Log.w("BundleDrop", "Failed to clear OTA state: ${e.message}", e)
91
- }
92
- }
93
-
94
43
  fun getDownloadedBundlePath(context: Context): String? {
95
- val path = readCurrentPointer(context) ?: legacyBundlePath(context)
96
-
97
- if (path == null) {
98
- setStoredBinaryVersion(context, getBinaryVersionKey(context))
99
- Log.d("BundleDrop", "📦 No OTA bundle found.")
100
- return null
101
- }
102
-
103
- val currentVersion = getBinaryVersionKey(context)
104
- val lastVersion = getStoredBinaryVersion(context)
105
-
106
- if (lastVersion != null && lastVersion != currentVersion) {
107
- Log.d("BundleDrop", "Binary updated ($lastVersion → $currentVersion), clearing OTA bundle")
108
- clearOtaState(context)
109
- setStoredBinaryVersion(context, currentVersion)
110
- return null
44
+ val bundleDropRoot = File(context.filesDir, "bundle-drop")
45
+ val result = BundleDropOtaResolver.resolve(
46
+ bundleDropRoot = bundleDropRoot,
47
+ filesDir = context.filesDir,
48
+ currentBinaryVersion = getBinaryVersionKey(context),
49
+ storedBinaryVersion = getStoredBinaryVersion(context),
50
+ )
51
+
52
+ result.storedVersion?.let { setStoredBinaryVersion(context, it) }
53
+
54
+ if (result.bundlePath == null) {
55
+ if (result.clearedOta) {
56
+ Log.d("BundleDrop", "Binary updated, clearing OTA bundle")
57
+ } else {
58
+ Log.d("BundleDrop", "📦 No OTA bundle found.")
59
+ }
60
+ } else {
61
+ Log.d("BundleDrop", "🔁 Using OTA bundle at: ${result.bundlePath}")
111
62
  }
112
63
 
113
- setStoredBinaryVersion(context, currentVersion)
114
- Log.d("BundleDrop", "🔁 Using OTA bundle at: $path")
115
- return path
64
+ return result.bundlePath
116
65
  }
117
66
 
118
67
  @JvmStatic
@@ -134,7 +83,6 @@ class BundleDropModule(reactContext: ReactApplicationContext) :
134
83
 
135
84
  @ReactMethod
136
85
  fun restartReactNative() {
137
- // ✅ Only change: don't access `currentActivity` directly; use reactApplicationContext.currentActivity
138
86
  val activity = reactApplicationContext.currentActivity ?: return
139
87
  val context = reactApplicationContext
140
88
 
@@ -174,15 +122,9 @@ class BundleDropModule(reactContext: ReactApplicationContext) :
174
122
 
175
123
  private fun readImageManifestRaw(): String? {
176
124
  val context = reactApplicationContext
177
- val current = readCurrentPointer(context) ?: return null
178
- val bundleDir = File(current).parentFile ?: return null
179
- return try {
180
- val file = File(bundleDir, "image-manifest.json")
181
- if (file.exists()) file.readText() else null
182
- } catch (e: Exception) {
183
- Log.e("BundleDrop", "Failed to read manifest: ${e.message}", e)
184
- null
185
- }
125
+ val bundleDropRoot = File(context.filesDir, "bundle-drop")
126
+ val current = BundleDropOtaResolver.readCurrentPointer(bundleDropRoot) ?: return null
127
+ return BundleDropOtaResolver.readImageManifest(current)
186
128
  }
187
129
 
188
130
  // ---------------------------------------------------------------------------
@@ -241,11 +183,23 @@ class BundleDropModule(reactContext: ReactApplicationContext) :
241
183
  }
242
184
  }
243
185
 
186
+ @ReactMethod
187
+ fun fsReadDir(path: String, promise: Promise) {
188
+ try {
189
+ val dir = File(path)
190
+ val names = dir.list() ?: emptyArray()
191
+ val result = Arguments.createArray()
192
+ names.forEach { result.pushString(it) }
193
+ promise.resolve(result)
194
+ } catch (e: Exception) {
195
+ promise.reject("ERR_READDIR", e.message, e)
196
+ }
197
+ }
198
+
244
199
  @ReactMethod
245
200
  fun fsUnlink(path: String, promise: Promise) {
246
201
  try {
247
- val file = File(path)
248
- if (file.exists()) file.delete()
202
+ BundleDropFileOps.unlinkPath(path)
249
203
  promise.resolve(null)
250
204
  } catch (e: Exception) {
251
205
  promise.reject("ERR_UNLINK", e.message, e)
@@ -255,19 +209,41 @@ class BundleDropModule(reactContext: ReactApplicationContext) :
255
209
  @ReactMethod
256
210
  fun fsMoveFile(src: String, dest: String, promise: Promise) {
257
211
  try {
258
- val srcFile = File(src)
259
- val destFile = File(dest)
260
- destFile.parentFile?.mkdirs()
261
- if (!srcFile.renameTo(destFile)) {
262
- srcFile.copyTo(destFile, overwrite = true)
263
- srcFile.delete()
264
- }
212
+ BundleDropFileOps.moveFile(File(src), File(dest))
265
213
  promise.resolve(null)
266
214
  } catch (e: Exception) {
267
215
  promise.reject("ERR_MOVE", e.message, e)
268
216
  }
269
217
  }
270
218
 
219
+ @ReactMethod
220
+ fun fsUnzip(zipPath: String, destPath: String, promise: Promise) {
221
+ Thread {
222
+ try {
223
+ val filenames = BundleDropFileOps.unzipFile(zipPath, destPath)
224
+ val result = Arguments.createArray()
225
+ filenames.forEach { result.pushString(it) }
226
+ promise.resolve(result)
227
+ } catch (e: Exception) {
228
+ promise.reject("ERR_UNZIP", e.message, e)
229
+ }
230
+ }.start()
231
+ }
232
+
233
+ @ReactMethod
234
+ fun fsDownloadFile(url: String, destPath: String, promise: Promise) {
235
+ Thread {
236
+ try {
237
+ val parsedUrl = BundleDropFileOps.validateHttpUrl(url)
238
+ BundleDropFileOps.downloadToFile(parsedUrl, File(destPath))
239
+ promise.resolve(null)
240
+ } catch (e: Exception) {
241
+ try { File(destPath).delete() } catch (_: Exception) {}
242
+ promise.reject("ERR_DOWNLOAD", e.message, e)
243
+ }
244
+ }.start()
245
+ }
246
+
271
247
  override fun getConstants(): MutableMap<String, Any> {
272
248
  val map = mutableMapOf<String, Any>()
273
249
  downloadedBundlePath?.let {
@@ -0,0 +1,93 @@
1
+ package com.bundledrop
2
+
3
+ import java.io.File
4
+ import org.json.JSONObject
5
+
6
+ /**
7
+ * Pure OTA bundle resolution logic, decoupled from Android Context for testability.
8
+ * All file system operations go through the provided root directory.
9
+ */
10
+ object BundleDropOtaResolver {
11
+
12
+ data class ResolveResult(
13
+ val bundlePath: String?,
14
+ val clearedOta: Boolean = false,
15
+ val storedVersion: String? = null,
16
+ )
17
+
18
+ fun readCurrentPointer(bundleDropRoot: File): String? {
19
+ return try {
20
+ val jsonFile = File(bundleDropRoot, "current.json")
21
+ if (!jsonFile.exists()) return null
22
+ val raw = jsonFile.readText()
23
+ val parsed = JSONObject(raw)
24
+ val path = parsed.optString("bundlePath", null)
25
+ if (!path.isNullOrEmpty() && File(path).exists()) path else null
26
+ } catch (_: Exception) {
27
+ null
28
+ }
29
+ }
30
+
31
+ fun clearOtaState(bundleDropRoot: File, filesDir: File) {
32
+ val filesToClear = listOf(
33
+ File(bundleDropRoot, "current.json"),
34
+ File(bundleDropRoot, "previous.json"),
35
+ File(bundleDropRoot, "state.json"),
36
+ File(filesDir, "bundle-info.json"),
37
+ )
38
+ filesToClear.forEach {
39
+ try { if (it.exists()) it.delete() } catch (_: Exception) {}
40
+ }
41
+ }
42
+
43
+ fun hasOtaState(bundleDropRoot: File, filesDir: File): Boolean {
44
+ return listOf(
45
+ File(bundleDropRoot, "current.json"),
46
+ File(bundleDropRoot, "previous.json"),
47
+ File(bundleDropRoot, "state.json"),
48
+ File(filesDir, "bundle-info.json"),
49
+ ).any { it.exists() }
50
+ }
51
+
52
+ fun resolve(
53
+ bundleDropRoot: File,
54
+ filesDir: File,
55
+ currentBinaryVersion: String,
56
+ storedBinaryVersion: String?,
57
+ ): ResolveResult {
58
+ if (storedBinaryVersion != null && storedBinaryVersion != currentBinaryVersion) {
59
+ val hadOtaState = hasOtaState(bundleDropRoot, filesDir)
60
+ clearOtaState(bundleDropRoot, filesDir)
61
+ return ResolveResult(
62
+ bundlePath = null,
63
+ clearedOta = hadOtaState,
64
+ storedVersion = currentBinaryVersion,
65
+ )
66
+ }
67
+
68
+ val path = readCurrentPointer(bundleDropRoot)
69
+
70
+ if (path == null) {
71
+ return ResolveResult(
72
+ bundlePath = null,
73
+ storedVersion = currentBinaryVersion,
74
+ )
75
+ }
76
+
77
+ return ResolveResult(
78
+ bundlePath = path,
79
+ storedVersion = currentBinaryVersion,
80
+ )
81
+ }
82
+
83
+ fun readImageManifest(bundlePath: String): String? {
84
+ return try {
85
+ val bundleDir = File(bundlePath).parentFile ?: return null
86
+ val file = File(bundleDir, "image-manifest.json")
87
+ if (file.exists()) file.readText() else null
88
+ } catch (_: Exception) {
89
+ null
90
+ }
91
+ }
92
+
93
+ }
@@ -31,11 +31,25 @@ RCT_EXTERN_METHOD(fsUnlink:(NSString *)path
31
31
  resolve:(RCTPromiseResolveBlock)resolve
32
32
  reject:(RCTPromiseRejectBlock)reject)
33
33
 
34
+ RCT_EXTERN_METHOD(fsReadDir:(NSString *)path
35
+ resolve:(RCTPromiseResolveBlock)resolve
36
+ reject:(RCTPromiseRejectBlock)reject)
37
+
34
38
  RCT_EXTERN_METHOD(fsMoveFile:(NSString *)src
35
39
  dest:(NSString *)dest
36
40
  resolve:(RCTPromiseResolveBlock)resolve
37
41
  reject:(RCTPromiseRejectBlock)reject)
38
42
 
43
+ RCT_EXTERN_METHOD(fsUnzip:(NSString *)zipPath
44
+ destPath:(NSString *)destPath
45
+ resolve:(RCTPromiseResolveBlock)resolve
46
+ reject:(RCTPromiseRejectBlock)reject)
47
+
48
+ RCT_EXTERN_METHOD(fsDownloadFile:(NSString *)url
49
+ destPath:(NSString *)destPath
50
+ resolve:(RCTPromiseResolveBlock)resolve
51
+ reject:(RCTPromiseRejectBlock)reject)
52
+
39
53
  + (BOOL)requiresMainQueueSetup
40
54
  {
41
55
  return NO;