@gfean/react-native-bundle-drop 0.1.82 → 0.1.91

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.
package/CLIENT_README.md CHANGED
@@ -162,6 +162,44 @@ npx bundle-drop upload android \
162
162
  --author "CI Pipeline"
163
163
  ```
164
164
 
165
+ ### Upload result file
166
+
167
+ After a successful upload, the CLI writes a result file inside the module directory at `node_modules/@gfean/react-native-bundle-drop/dist/bundle-drop-result.json` with all upload details:
168
+
169
+ ```json
170
+ {
171
+ "platform": "android",
172
+ "appVersion": "1.2.3",
173
+ "channel": "General",
174
+ "orgSlug": "my-org",
175
+ "projectSlug": "my-app",
176
+ "runtimeVersion": "1.0.0",
177
+ "bundleId": "abc123",
178
+ "bundleVersion": 42,
179
+ "bundleVersionLabel": "v42",
180
+ "hash": "sha256hex...",
181
+ "releaseNotes": "Bug fixes",
182
+ "author": "CI Pipeline"
183
+ }
184
+ ```
185
+
186
+ Use this in CI to read any field — no output parsing needed:
187
+
188
+ ```bash
189
+ BD_RESULT="node_modules/@gfean/react-native-bundle-drop/dist/bundle-drop-result.json"
190
+
191
+ # Read any field
192
+ jq -r '.bundleVersionLabel' "$BD_RESULT"
193
+ jq -r '.appVersion' "$BD_RESULT"
194
+ jq -r '.channel' "$BD_RESULT"
195
+
196
+ # Azure DevOps
197
+ echo "##vso[task.setvariable variable=BundleVersion]$(jq -r '.bundleVersionLabel' "$BD_RESULT")"
198
+
199
+ # GitHub Actions
200
+ echo "bundle_version=$(jq -r '.bundleVersionLabel' "$BD_RESULT")" >> "$GITHUB_OUTPUT"
201
+ ```
202
+
165
203
  ## 9) Native setup (Android)
166
204
 
167
205
  The only change in your `MainApplication` (Kotlin or Java) is a single override that delegates bundle resolution to BundleDrop. It returns the OTA bundle path when available, otherwise falls back to the default.
package/README.md CHANGED
@@ -8,12 +8,6 @@ yarn add @gfean/react-native-bundle-drop
8
8
  cd ios && pod install && cd ..
9
9
  ```
10
10
 
11
- Add the Android bootstrap side-effect import once (images resolver patch):
12
- ```js
13
- // index.js (or entry file)
14
- import '@gfean/react-native-bundle-drop/bootstrap';
15
- ```
16
-
17
11
  ### Metro config (to resolve bundle.drop.config.js from node_modules)
18
12
  If Metro cannot resolve `bundle.drop.config.js` from within `node_modules`, add an alias in `metro.config.js`:
19
13
  ```js
@@ -23,6 +23,9 @@ class BundleDropModule(reactContext: ReactApplicationContext) :
23
23
  var latestBundlePath: String? = null
24
24
  private set
25
25
 
26
+ private const val PREFS_NAME = "BundleDropPrefs"
27
+ private const val KEY_BINARY_VERSION = "binary_version"
28
+
26
29
  private fun currentJsonPath(context: Context): File {
27
30
  return File(context.filesDir, "bundle-drop/current.json")
28
31
  }
@@ -51,16 +54,65 @@ class BundleDropModule(reactContext: ReactApplicationContext) :
51
54
  return if (file.exists()) file.absolutePath else null
52
55
  }
53
56
 
54
- // Call this from MainApplication.kt to fetch the custom bundle path
57
+ private fun getBinaryVersionKey(context: Context): String {
58
+ val pInfo = context.packageManager.getPackageInfo(context.packageName, 0)
59
+ val versionName = pInfo.versionName ?: "unknown"
60
+ @Suppress("DEPRECATION")
61
+ val versionCode = if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.P) {
62
+ pInfo.longVersionCode
63
+ } else {
64
+ pInfo.versionCode.toLong()
65
+ }
66
+ return "$versionName-$versionCode"
67
+ }
68
+
69
+ private fun getStoredBinaryVersion(context: Context): String? {
70
+ return context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
71
+ .getString(KEY_BINARY_VERSION, null)
72
+ }
73
+
74
+ private fun setStoredBinaryVersion(context: Context, version: String) {
75
+ context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
76
+ .edit().putString(KEY_BINARY_VERSION, version).apply()
77
+ }
78
+
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
+
55
94
  fun getDownloadedBundlePath(context: Context): String? {
56
95
  val path = readCurrentPointer(context) ?: legacyBundlePath(context)
57
- return if (path != null) {
58
- Log.d("BundleDrop", "🔁 Using OTA bundle at: $path")
59
- path
60
- } else {
96
+
97
+ if (path == null) {
98
+ setStoredBinaryVersion(context, getBinaryVersionKey(context))
61
99
  Log.d("BundleDrop", "📦 No OTA bundle found.")
62
- null
100
+ return null
63
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
111
+ }
112
+
113
+ setStoredBinaryVersion(context, currentVersion)
114
+ Log.d("BundleDrop", "🔁 Using OTA bundle at: $path")
115
+ return path
64
116
  }
65
117
 
66
118
  @JvmStatic
@@ -112,12 +164,20 @@ class BundleDropModule(reactContext: ReactApplicationContext) :
112
164
 
113
165
  @ReactMethod(isBlockingSynchronousMethod = true)
114
166
  fun getImageManifestSync(): String? {
167
+ return readImageManifestRaw()
168
+ }
169
+
170
+ @ReactMethod
171
+ fun getImageManifest(promise: Promise) {
172
+ promise.resolve(readImageManifestRaw())
173
+ }
174
+
175
+ private fun readImageManifestRaw(): String? {
115
176
  val context = reactApplicationContext
116
177
  val current = readCurrentPointer(context) ?: return null
117
178
  val bundleDir = File(current).parentFile ?: return null
118
- val path = File(bundleDir, "image-manifest.json").absolutePath
119
179
  return try {
120
- val file = File(path)
180
+ val file = File(bundleDir, "image-manifest.json")
121
181
  if (file.exists()) file.readText() else null
122
182
  } catch (e: Exception) {
123
183
  Log.e("BundleDrop", "Failed to read manifest: ${e.message}", e)
@@ -125,11 +185,97 @@ class BundleDropModule(reactContext: ReactApplicationContext) :
125
185
  }
126
186
  }
127
187
 
188
+ // ---------------------------------------------------------------------------
189
+ // FS primitives (replaces react-native-fs dependency)
190
+ // ---------------------------------------------------------------------------
191
+
192
+ @ReactMethod
193
+ fun fsExists(path: String, promise: Promise) {
194
+ promise.resolve(File(path).exists())
195
+ }
196
+
197
+ @ReactMethod
198
+ fun fsReadFile(path: String, encoding: String, promise: Promise) {
199
+ try {
200
+ val file = File(path)
201
+ if (!file.exists()) {
202
+ promise.reject("ENOENT", "File not found: $path")
203
+ return
204
+ }
205
+ if (encoding == "base64") {
206
+ val bytes = file.readBytes()
207
+ promise.resolve(android.util.Base64.encodeToString(bytes, android.util.Base64.NO_WRAP))
208
+ } else {
209
+ promise.resolve(file.readText(Charsets.UTF_8))
210
+ }
211
+ } catch (e: Exception) {
212
+ promise.reject("ERR_READ", e.message, e)
213
+ }
214
+ }
215
+
216
+ @ReactMethod
217
+ fun fsWriteFile(path: String, content: String, encoding: String, promise: Promise) {
218
+ try {
219
+ val file = File(path)
220
+ file.parentFile?.mkdirs()
221
+ if (encoding == "base64") {
222
+ val bytes = android.util.Base64.decode(content, android.util.Base64.DEFAULT)
223
+ file.writeBytes(bytes)
224
+ } else {
225
+ file.writeText(content, Charsets.UTF_8)
226
+ }
227
+ promise.resolve(null)
228
+ } catch (e: Exception) {
229
+ promise.reject("ERR_WRITE", e.message, e)
230
+ }
231
+ }
232
+
233
+ @ReactMethod
234
+ fun fsMkdir(path: String, promise: Promise) {
235
+ try {
236
+ val dir = File(path)
237
+ if (!dir.exists()) dir.mkdirs()
238
+ promise.resolve(null)
239
+ } catch (e: Exception) {
240
+ promise.reject("ERR_MKDIR", e.message, e)
241
+ }
242
+ }
243
+
244
+ @ReactMethod
245
+ fun fsUnlink(path: String, promise: Promise) {
246
+ try {
247
+ val file = File(path)
248
+ if (file.exists()) file.delete()
249
+ promise.resolve(null)
250
+ } catch (e: Exception) {
251
+ promise.reject("ERR_UNLINK", e.message, e)
252
+ }
253
+ }
254
+
255
+ @ReactMethod
256
+ fun fsMoveFile(src: String, dest: String, promise: Promise) {
257
+ 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
+ }
265
+ promise.resolve(null)
266
+ } catch (e: Exception) {
267
+ promise.reject("ERR_MOVE", e.message, e)
268
+ }
269
+ }
270
+
128
271
  override fun getConstants(): MutableMap<String, Any> {
129
272
  val map = mutableMapOf<String, Any>()
130
273
  downloadedBundlePath?.let {
131
274
  map["downloadedBundlePath"] = it
132
275
  }
276
+ val context = reactApplicationContext
277
+ map["DocumentDirectoryPath"] = context.filesDir.absolutePath
278
+ map["LibraryDirectoryPath"] = context.filesDir.absolutePath
133
279
  return map
134
280
  }
135
281
  }
@@ -1,6 +1,5 @@
1
1
  #import <React/RCTBridgeModule.h>
2
2
 
3
- // JS name "BundleDrop" -> Swift class "BundleDropModule"
4
3
  @interface RCT_EXTERN_REMAP_MODULE(BundleDrop, BundleDropModule, NSObject)
5
4
 
6
5
  RCT_EXTERN_METHOD(getDownloadedBundlePath:(RCTPromiseResolveBlock)resolve
@@ -8,6 +7,35 @@ RCT_EXTERN_METHOD(getDownloadedBundlePath:(RCTPromiseResolveBlock)resolve
8
7
 
9
8
  RCT_EXTERN_METHOD(restartReactNative)
10
9
 
10
+ // FS primitives
11
+ RCT_EXTERN_METHOD(fsExists:(NSString *)path
12
+ resolve:(RCTPromiseResolveBlock)resolve
13
+ reject:(RCTPromiseRejectBlock)reject)
14
+
15
+ RCT_EXTERN_METHOD(fsReadFile:(NSString *)path
16
+ encoding:(NSString *)encoding
17
+ resolve:(RCTPromiseResolveBlock)resolve
18
+ reject:(RCTPromiseRejectBlock)reject)
19
+
20
+ RCT_EXTERN_METHOD(fsWriteFile:(NSString *)path
21
+ content:(NSString *)content
22
+ encoding:(NSString *)encoding
23
+ resolve:(RCTPromiseResolveBlock)resolve
24
+ reject:(RCTPromiseRejectBlock)reject)
25
+
26
+ RCT_EXTERN_METHOD(fsMkdir:(NSString *)path
27
+ resolve:(RCTPromiseResolveBlock)resolve
28
+ reject:(RCTPromiseRejectBlock)reject)
29
+
30
+ RCT_EXTERN_METHOD(fsUnlink:(NSString *)path
31
+ resolve:(RCTPromiseResolveBlock)resolve
32
+ reject:(RCTPromiseRejectBlock)reject)
33
+
34
+ RCT_EXTERN_METHOD(fsMoveFile:(NSString *)src
35
+ dest:(NSString *)dest
36
+ resolve:(RCTPromiseResolveBlock)resolve
37
+ reject:(RCTPromiseRejectBlock)reject)
38
+
11
39
  + (BOOL)requiresMainQueueSetup
12
40
  {
13
41
  return NO;
@@ -1,22 +1,61 @@
1
1
  import Foundation
2
2
 
3
3
  @objc public final class BundleDropLocator: NSObject {
4
+
5
+ private static let binaryVersionKey = "BundleDropBinaryVersion"
6
+
7
+ private static func getBinaryVersionKey() -> String {
8
+ let version = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "unknown"
9
+ let build = Bundle.main.infoDictionary?["CFBundleVersion"] as? String ?? "0"
10
+ return "\(version)-\(build)"
11
+ }
12
+
13
+ private static func clearOtaState(root: URL) {
14
+ let fm = FileManager.default
15
+ let filesToClear = [
16
+ root.appendingPathComponent("current.json"),
17
+ root.appendingPathComponent("previous.json"),
18
+ root.appendingPathComponent("state.json"),
19
+ ]
20
+ filesToClear.forEach { try? fm.removeItem(at: $0) }
21
+
22
+ if let docs = fm.urls(for: .documentDirectory, in: .userDomainMask).first {
23
+ try? fm.removeItem(at: docs.appendingPathComponent("bundle-info.json"))
24
+ }
25
+ }
26
+
4
27
  @objc public static func bundleURL() -> URL? {
5
28
  let fm = FileManager.default
6
29
  guard let lib = fm.urls(for: .libraryDirectory, in: .userDomainMask).first else { return nil }
7
30
  let root = lib.appendingPathComponent("bundle-drop", isDirectory: true)
8
31
  let current = root.appendingPathComponent("current.json")
9
32
 
10
- if fm.fileExists(atPath: current.path) {
11
- do {
12
- let data = try Data(contentsOf: current)
13
- let obj = try JSONSerialization.jsonObject(with: data) as? [String: Any]
14
- guard let bundlePath = obj?["bundlePath"] as? String else { return nil }
15
- let url = URL(fileURLWithPath: bundlePath)
16
- return fm.fileExists(atPath: url.path) ? url : nil
17
- } catch {
18
- print("⚠️ BundleDrop: failed reading current.json: \(error)")
33
+ let currentVersion = getBinaryVersionKey()
34
+
35
+ guard fm.fileExists(atPath: current.path) else {
36
+ UserDefaults.standard.set(currentVersion, forKey: binaryVersionKey)
37
+ return nil
38
+ }
39
+
40
+ do {
41
+ let data = try Data(contentsOf: current)
42
+ let obj = try JSONSerialization.jsonObject(with: data) as? [String: Any]
43
+ guard let bundlePath = obj?["bundlePath"] as? String else { return nil }
44
+ let url = URL(fileURLWithPath: bundlePath)
45
+ guard fm.fileExists(atPath: url.path) else { return nil }
46
+
47
+ let lastVersion = UserDefaults.standard.string(forKey: binaryVersionKey)
48
+ if let lastVersion = lastVersion, lastVersion != currentVersion {
49
+ print("BundleDrop: Binary updated (\(lastVersion) → \(currentVersion)), clearing OTA bundle")
50
+ clearOtaState(root: root)
51
+ UserDefaults.standard.set(currentVersion, forKey: binaryVersionKey)
52
+ return nil
19
53
  }
54
+
55
+ UserDefaults.standard.set(currentVersion, forKey: binaryVersionKey)
56
+ return url
57
+ } catch {
58
+ print("⚠️ BundleDrop: failed reading current.json: \(error)")
20
59
  }
21
60
 
22
61
  return nil
@@ -1,10 +1,11 @@
1
1
  import Foundation
2
2
  import React
3
3
 
4
- @objc(BundleDropModule) // native class name
4
+ @objc(BundleDropModule)
5
5
  final class BundleDropModule: NSObject {
6
6
 
7
7
  private static var isReloading = false
8
+ private static let fm = FileManager.default
8
9
 
9
10
  // MARK: - OTA bundle path
10
11
 
@@ -22,7 +23,6 @@ final class BundleDropModule: NSObject {
22
23
  resolve(nil)
23
24
  }
24
25
 
25
- // 🚨 Restart RN safely (debounced)
26
26
  @objc
27
27
  func restartReactNative() {
28
28
  DispatchQueue.main.async {
@@ -45,14 +45,142 @@ final class BundleDropModule: NSObject {
45
45
  Self.isReloading = true
46
46
  print("🔄 Restarting RN from \(url.path) size=\(size)")
47
47
 
48
- // Trigger a standard RN reload; AppDelegate.bundleURL() decides OTA vs embedded
49
48
  RCTReloadCommandSetBundleURL(url)
50
49
  RCTTriggerReloadCommandListeners("bundle-drop-restart")
51
50
 
52
- // release lock after a short moment to prevent double-trigger
53
51
  DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
54
52
  Self.isReloading = false
55
53
  }
56
54
  }
57
55
  }
56
+
57
+ // MARK: - Constants
58
+
59
+ @objc
60
+ func constantsToExport() -> [String: Any] {
61
+ let fm = FileManager.default
62
+ let docs = fm.urls(for: .documentDirectory, in: .userDomainMask).first?.path ?? ""
63
+ let lib = fm.urls(for: .libraryDirectory, in: .userDomainMask).first?.path ?? ""
64
+ return [
65
+ "DocumentDirectoryPath": docs,
66
+ "LibraryDirectoryPath": lib,
67
+ ]
68
+ }
69
+
70
+ // MARK: - FS primitives (replaces react-native-fs dependency)
71
+
72
+ @objc
73
+ func fsExists(
74
+ _ path: String,
75
+ resolve: @escaping RCTPromiseResolveBlock,
76
+ reject: @escaping RCTPromiseRejectBlock
77
+ ) {
78
+ resolve(Self.fm.fileExists(atPath: path))
79
+ }
80
+
81
+ @objc
82
+ func fsReadFile(
83
+ _ path: String,
84
+ encoding: String,
85
+ resolve: @escaping RCTPromiseResolveBlock,
86
+ reject: @escaping RCTPromiseRejectBlock
87
+ ) {
88
+ guard Self.fm.fileExists(atPath: path) else {
89
+ reject("ENOENT", "File not found: \(path)", nil)
90
+ return
91
+ }
92
+ do {
93
+ if encoding == "base64" {
94
+ let data = try Data(contentsOf: URL(fileURLWithPath: path))
95
+ resolve(data.base64EncodedString())
96
+ } else {
97
+ let text = try String(contentsOfFile: path, encoding: .utf8)
98
+ resolve(text)
99
+ }
100
+ } catch {
101
+ reject("ERR_READ", error.localizedDescription, error)
102
+ }
103
+ }
104
+
105
+ @objc
106
+ func fsWriteFile(
107
+ _ path: String,
108
+ content: String,
109
+ encoding: String,
110
+ resolve: @escaping RCTPromiseResolveBlock,
111
+ reject: @escaping RCTPromiseRejectBlock
112
+ ) {
113
+ do {
114
+ let dir = (path as NSString).deletingLastPathComponent
115
+ if !Self.fm.fileExists(atPath: dir) {
116
+ try Self.fm.createDirectory(atPath: dir, withIntermediateDirectories: true)
117
+ }
118
+ if encoding == "base64" {
119
+ guard let data = Data(base64Encoded: content) else {
120
+ reject("ERR_WRITE", "Invalid base64 data", nil)
121
+ return
122
+ }
123
+ try data.write(to: URL(fileURLWithPath: path))
124
+ } else {
125
+ try content.write(toFile: path, atomically: true, encoding: .utf8)
126
+ }
127
+ resolve(nil)
128
+ } catch {
129
+ reject("ERR_WRITE", error.localizedDescription, error)
130
+ }
131
+ }
132
+
133
+ @objc
134
+ func fsMkdir(
135
+ _ path: String,
136
+ resolve: @escaping RCTPromiseResolveBlock,
137
+ reject: @escaping RCTPromiseRejectBlock
138
+ ) {
139
+ do {
140
+ if !Self.fm.fileExists(atPath: path) {
141
+ try Self.fm.createDirectory(atPath: path, withIntermediateDirectories: true)
142
+ }
143
+ resolve(nil)
144
+ } catch {
145
+ reject("ERR_MKDIR", error.localizedDescription, error)
146
+ }
147
+ }
148
+
149
+ @objc
150
+ func fsUnlink(
151
+ _ path: String,
152
+ resolve: @escaping RCTPromiseResolveBlock,
153
+ reject: @escaping RCTPromiseRejectBlock
154
+ ) {
155
+ do {
156
+ if Self.fm.fileExists(atPath: path) {
157
+ try Self.fm.removeItem(atPath: path)
158
+ }
159
+ resolve(nil)
160
+ } catch {
161
+ reject("ERR_UNLINK", error.localizedDescription, error)
162
+ }
163
+ }
164
+
165
+ @objc
166
+ func fsMoveFile(
167
+ _ src: String,
168
+ dest: String,
169
+ resolve: @escaping RCTPromiseResolveBlock,
170
+ reject: @escaping RCTPromiseRejectBlock
171
+ ) {
172
+ do {
173
+ let destDir = (dest as NSString).deletingLastPathComponent
174
+ if !Self.fm.fileExists(atPath: destDir) {
175
+ try Self.fm.createDirectory(atPath: destDir, withIntermediateDirectories: true)
176
+ }
177
+ if Self.fm.fileExists(atPath: dest) {
178
+ try Self.fm.removeItem(atPath: dest)
179
+ }
180
+ try Self.fm.moveItem(atPath: src, toPath: dest)
181
+ resolve(nil)
182
+ } catch {
183
+ reject("ERR_MOVE", error.localizedDescription, error)
184
+ }
185
+ }
58
186
  }
@@ -125,6 +125,7 @@ async function initConfig(params) {
125
125
  }
126
126
  const content = `module.exports = {
127
127
  serverUrl: '${resolvedServerUrl}',
128
+ defaultChannel: 'General',
128
129
  runtimeVersion: {
129
130
  ios: '1.0.0',
130
131
  android: '1.0.0',
@@ -217,7 +217,33 @@ async function upload(platform, options) {
217
217
  maxContentLength: Infinity,
218
218
  maxBodyLength: Infinity,
219
219
  });
220
- ui_1.log.success(`✅ Upload complete (bundleId: ${res.data?.bundleId || 'N/A'})`);
220
+ const result = {
221
+ platform,
222
+ appVersion: version ?? null,
223
+ channel: channel ?? null,
224
+ orgSlug: orgSlug ?? null,
225
+ projectSlug: projectSlug ?? null,
226
+ runtimeVersion: res.data?.runtimeVersion ?? runtimeVersion ?? null,
227
+ bundleId: res.data?.bundleId ?? null,
228
+ bundleVersion: res.data?.bundleVersion ?? null,
229
+ bundleVersionLabel: res.data?.bundleVersionLabel ?? null,
230
+ hash: res.data?.hash ?? null,
231
+ releaseNotes: releaseNotes ?? null,
232
+ author: options.author ?? null,
233
+ };
234
+ ui_1.log.success(`✅ Upload complete`);
235
+ if (result.bundleVersion != null)
236
+ ui_1.log.label('Bundle Version', `${result.bundleVersion}`);
237
+ if (result.bundleVersionLabel)
238
+ ui_1.log.label('Bundle Label', result.bundleVersionLabel);
239
+ if (result.hash)
240
+ ui_1.log.label('Hash', result.hash);
241
+ const resultDir = path.join(packageRoot, 'dist');
242
+ if (!fs.existsSync(resultDir))
243
+ fs.mkdirSync(resultDir, { recursive: true });
244
+ const resultPath = path.join(resultDir, 'bundle-drop-result.json');
245
+ fs.writeFileSync(resultPath, JSON.stringify(result, null, 2));
246
+ ui_1.log.label('Result file', resultPath);
221
247
  }
222
248
  catch (err) {
223
249
  const raw = err?.response?.data || err.message;
package/lib/bootstrap.js CHANGED
@@ -4,7 +4,9 @@ const context_1 = require("./context");
4
4
  const injectImageResolver_1 = require("./injectImageResolver");
5
5
  const patchImageAutoResolve_1 = require("./patchImageAutoResolve");
6
6
  // Patch early so assets bundled with the app (before OTA) still resolve on Android.
7
+ // Image.render is patched synchronously (cheap), but the manifest-based resolver
8
+ // loads asynchronously to avoid blocking the JS thread with a sync native bridge call.
7
9
  if (!context_1.isIOS) {
8
- (0, injectImageResolver_1.injectBundleDropImageResolver)();
9
10
  (0, patchImageAutoResolve_1.patchImageRenderToForceResolve)();
11
+ (0, injectImageResolver_1.injectBundleDropImageResolverAsync)().catch(() => { });
10
12
  }
package/lib/bundleInfo.js CHANGED
@@ -6,13 +6,13 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.readBundleInfo = readBundleInfo;
7
7
  exports.writeBundleInfo = writeBundleInfo;
8
8
  exports.updateBundleInfo = updateBundleInfo;
9
- const react_native_fs_1 = __importDefault(require("react-native-fs"));
10
- const BUNDLE_INFO_PATH = `${react_native_fs_1.default.DocumentDirectoryPath}/bundle-info.json`;
9
+ const fs_1 = __importDefault(require("./native/fs"));
10
+ const BUNDLE_INFO_PATH = `${fs_1.default.DocumentDirectoryPath}/bundle-info.json`;
11
11
  async function readBundleInfo() {
12
12
  try {
13
- if (!(await react_native_fs_1.default.exists(BUNDLE_INFO_PATH)))
13
+ if (!(await fs_1.default.exists(BUNDLE_INFO_PATH)))
14
14
  return null;
15
- const raw = await react_native_fs_1.default.readFile(BUNDLE_INFO_PATH, 'utf8');
15
+ const raw = await fs_1.default.readFile(BUNDLE_INFO_PATH, 'utf8');
16
16
  return JSON.parse(raw);
17
17
  }
18
18
  catch (e) {
@@ -22,7 +22,7 @@ async function readBundleInfo() {
22
22
  }
23
23
  async function writeBundleInfo(info) {
24
24
  try {
25
- await react_native_fs_1.default.writeFile(BUNDLE_INFO_PATH, JSON.stringify(info, null, 2), 'utf8');
25
+ await fs_1.default.writeFile(BUNDLE_INFO_PATH, JSON.stringify(info, null, 2), 'utf8');
26
26
  }
27
27
  catch (e) {
28
28
  console.warn('⚠️ Failed to write bundle-info.json', e);
package/lib/context.d.ts CHANGED
@@ -2,4 +2,5 @@ export declare const config: import("./loadConfig").BundleDropProjectConfig;
2
2
  export declare const platform: string;
3
3
  export declare const isIOS: boolean;
4
4
  export declare const runtimeVersion: string;
5
+ export declare const defaultChannel: string;
5
6
  export declare const BUNDLE_DROP_ROOT: string;
package/lib/context.js CHANGED
@@ -3,14 +3,15 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.BUNDLE_DROP_ROOT = exports.runtimeVersion = exports.isIOS = exports.platform = exports.config = void 0;
6
+ exports.BUNDLE_DROP_ROOT = exports.defaultChannel = exports.runtimeVersion = exports.isIOS = exports.platform = exports.config = void 0;
7
7
  const react_native_1 = require("react-native");
8
- const react_native_fs_1 = __importDefault(require("react-native-fs"));
8
+ const fs_1 = __importDefault(require("./native/fs"));
9
9
  const loadConfig_1 = require("./loadConfig");
10
10
  exports.config = (0, loadConfig_1.loadConfig)();
11
11
  exports.platform = react_native_1.Platform.OS === 'ios' ? 'ios' : 'android';
12
12
  exports.isIOS = exports.platform === 'ios';
13
13
  exports.runtimeVersion = exports.config.runtimeVersion?.[exports.platform];
14
+ exports.defaultChannel = exports.config.defaultChannel || 'General';
14
15
  exports.BUNDLE_DROP_ROOT = exports.isIOS
15
- ? `${react_native_fs_1.default.LibraryDirectoryPath}/bundle-drop`
16
- : `${react_native_fs_1.default.DocumentDirectoryPath}/bundle-drop`;
16
+ ? `${fs_1.default.LibraryDirectoryPath}/bundle-drop`
17
+ : `${fs_1.default.DocumentDirectoryPath}/bundle-drop`;
@@ -10,16 +10,16 @@ exports.writePreviousBundlePointer = writePreviousBundlePointer;
10
10
  exports.setCurrentBundlePointer = setCurrentBundlePointer;
11
11
  exports.rollbackToPreviousPointer = rollbackToPreviousPointer;
12
12
  exports.clearCurrentBundlePointer = clearCurrentBundlePointer;
13
- const react_native_fs_1 = __importDefault(require("react-native-fs"));
13
+ const fs_1 = __importDefault(require("../native/fs"));
14
14
  const context_1 = require("../context");
15
15
  const fsUtils_1 = require("./fsUtils");
16
16
  const CURRENT_POINTER_PATH = `${context_1.BUNDLE_DROP_ROOT}/current.json`;
17
17
  const PREVIOUS_POINTER_PATH = `${context_1.BUNDLE_DROP_ROOT}/previous.json`;
18
18
  async function readPointer(path) {
19
19
  try {
20
- if (!(await react_native_fs_1.default.exists(path)))
20
+ if (!(await fs_1.default.exists(path)))
21
21
  return null;
22
- const raw = await react_native_fs_1.default.readFile(path, 'utf8');
22
+ const raw = await fs_1.default.readFile(path, 'utf8');
23
23
  const parsed = JSON.parse(raw);
24
24
  if (!parsed?.hash || !parsed?.bundlePath)
25
25
  return null;
@@ -67,8 +67,8 @@ async function rollbackToPreviousPointer() {
67
67
  }
68
68
  async function clearCurrentBundlePointer() {
69
69
  try {
70
- if (await react_native_fs_1.default.exists(CURRENT_POINTER_PATH)) {
71
- await react_native_fs_1.default.unlink(CURRENT_POINTER_PATH);
70
+ if (await fs_1.default.exists(CURRENT_POINTER_PATH)) {
71
+ await fs_1.default.unlink(CURRENT_POINTER_PATH);
72
72
  }
73
73
  }
74
74
  catch {
package/lib/fs/fsUtils.js CHANGED
@@ -7,32 +7,32 @@ exports.ensureDir = ensureDir;
7
7
  exports.atomicWriteJson = atomicWriteJson;
8
8
  exports.ensureParentDir = ensureParentDir;
9
9
  exports.writeFileAtomicBase64 = writeFileAtomicBase64;
10
- const react_native_fs_1 = __importDefault(require("react-native-fs"));
10
+ const fs_1 = __importDefault(require("../native/fs"));
11
11
  async function ensureDir(dir) {
12
- if (!(await react_native_fs_1.default.exists(dir))) {
13
- await react_native_fs_1.default.mkdir(dir);
12
+ if (!(await fs_1.default.exists(dir))) {
13
+ await fs_1.default.mkdir(dir);
14
14
  }
15
15
  }
16
16
  async function atomicWriteJson(path, data) {
17
17
  const tmp = `${path}.tmp`;
18
- await react_native_fs_1.default.writeFile(tmp, JSON.stringify(data), 'utf8');
19
- if (await react_native_fs_1.default.exists(path)) {
20
- await react_native_fs_1.default.unlink(path);
18
+ await fs_1.default.writeFile(tmp, JSON.stringify(data), 'utf8');
19
+ if (await fs_1.default.exists(path)) {
20
+ await fs_1.default.unlink(path);
21
21
  }
22
- await react_native_fs_1.default.moveFile(tmp, path);
22
+ await fs_1.default.moveFile(tmp, path);
23
23
  }
24
24
  async function ensureParentDir(filePath) {
25
25
  const dir = filePath.substring(0, filePath.lastIndexOf('/'));
26
- if (!(await react_native_fs_1.default.exists(dir))) {
27
- await react_native_fs_1.default.mkdir(dir);
26
+ if (!(await fs_1.default.exists(dir))) {
27
+ await fs_1.default.mkdir(dir);
28
28
  }
29
29
  }
30
30
  async function writeFileAtomicBase64(path, base64) {
31
31
  const tmp = `${path}.tmp`;
32
32
  await ensureParentDir(path);
33
- await react_native_fs_1.default.writeFile(tmp, base64, 'base64');
34
- if (await react_native_fs_1.default.exists(path)) {
35
- await react_native_fs_1.default.unlink(path);
33
+ await fs_1.default.writeFile(tmp, base64, 'base64');
34
+ if (await fs_1.default.exists(path)) {
35
+ await fs_1.default.unlink(path);
36
36
  }
37
- await react_native_fs_1.default.moveFile(tmp, path);
37
+ await fs_1.default.moveFile(tmp, path);
38
38
  }
@@ -4,7 +4,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.getOrCreateInstallId = getOrCreateInstallId;
7
- const react_native_fs_1 = __importDefault(require("react-native-fs"));
7
+ const fs_1 = __importDefault(require("../native/fs"));
8
8
  const context_1 = require("../context");
9
9
  const fsUtils_1 = require("./fsUtils");
10
10
  function getInstallIdPath() {
@@ -13,7 +13,7 @@ function getInstallIdPath() {
13
13
  async function getOrCreateInstallId() {
14
14
  const path = getInstallIdPath();
15
15
  try {
16
- const existing = await react_native_fs_1.default.readFile(path, 'utf8');
16
+ const existing = await fs_1.default.readFile(path, 'utf8');
17
17
  if (existing?.trim())
18
18
  return existing.trim();
19
19
  }
@@ -24,6 +24,6 @@ async function getOrCreateInstallId() {
24
24
  `${Math.random().toString(36).slice(2, 10)}-` +
25
25
  `${Math.random().toString(36).slice(2, 10)}`;
26
26
  await (0, fsUtils_1.ensureDir)(context_1.BUNDLE_DROP_ROOT);
27
- await react_native_fs_1.default.writeFile(path, id, 'utf8');
27
+ await fs_1.default.writeFile(path, id, 'utf8');
28
28
  return id;
29
29
  }
@@ -9,7 +9,7 @@ exports.getUserProperties = getUserProperties;
9
9
  exports.setUserProperty = setUserProperty;
10
10
  exports.removeUserProperty = removeUserProperty;
11
11
  exports.resetUserProperties = resetUserProperties;
12
- const react_native_fs_1 = __importDefault(require("react-native-fs"));
12
+ const fs_1 = __importDefault(require("../native/fs"));
13
13
  const context_1 = require("../context");
14
14
  const fsUtils_1 = require("./fsUtils");
15
15
  const USER_PROPERTIES_PATH = `${context_1.BUNDLE_DROP_ROOT}/user-properties.json`;
@@ -36,9 +36,9 @@ async function writeUserProperties(properties) {
36
36
  }
37
37
  async function getCurrentUserProperties() {
38
38
  try {
39
- if (!(await react_native_fs_1.default.exists(USER_PROPERTIES_PATH)))
39
+ if (!(await fs_1.default.exists(USER_PROPERTIES_PATH)))
40
40
  return [];
41
- const raw = await react_native_fs_1.default.readFile(USER_PROPERTIES_PATH, 'utf8');
41
+ const raw = await fs_1.default.readFile(USER_PROPERTIES_PATH, 'utf8');
42
42
  const parsed = JSON.parse(raw);
43
43
  if (Array.isArray(parsed)) {
44
44
  return unique(parsed.filter(value => typeof value === 'string').map(normalizeUserProperty).filter(Boolean));
@@ -88,8 +88,8 @@ async function removeUserProperty(value) {
88
88
  }
89
89
  async function resetUserProperties() {
90
90
  try {
91
- if (await react_native_fs_1.default.exists(USER_PROPERTIES_PATH)) {
92
- await react_native_fs_1.default.unlink(USER_PROPERTIES_PATH);
91
+ if (await fs_1.default.exists(USER_PROPERTIES_PATH)) {
92
+ await fs_1.default.unlink(USER_PROPERTIES_PATH);
93
93
  }
94
94
  }
95
95
  catch (e) {
@@ -1,2 +1,3 @@
1
1
  export declare function patchImageResolverWithManifest(manifest: Record<string, string>): void;
2
2
  export declare function injectBundleDropImageResolver(manifestOverride?: Record<string, string>): void;
3
+ export declare function injectBundleDropImageResolverAsync(): Promise<void>;
@@ -5,8 +5,9 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.patchImageResolverWithManifest = patchImageResolverWithManifest;
7
7
  exports.injectBundleDropImageResolver = injectBundleDropImageResolver;
8
+ exports.injectBundleDropImageResolverAsync = injectBundleDropImageResolverAsync;
8
9
  const react_native_1 = require("react-native");
9
- const react_native_fs_1 = __importDefault(require("react-native-fs"));
10
+ const fs_1 = __importDefault(require("./native/fs"));
10
11
  let hasPatched = false;
11
12
  const { BundleDrop } = react_native_1.NativeModules;
12
13
  // Build lookup maps: exact keys and basename aliases so we can resolve filename-only URIs.
@@ -89,11 +90,9 @@ function patchImageResolverWithManifest(manifest) {
89
90
  }
90
91
  if (finalPath) {
91
92
  const hasExtension = /\.[a-zA-Z0-9]+$/.test(finalPath);
92
- const fullPath = `file://${react_native_fs_1.default.DocumentDirectoryPath}/${finalPath}${hasExtension ? '' : (uri.match(/\.[^.]+$/)?.[0] ?? '')}`;
93
- console.log(`🧩 Overriding asset path: ${uri} → ${fullPath}`);
93
+ const fullPath = `file://${fs_1.default.DocumentDirectoryPath}/${finalPath}${hasExtension ? '' : (uri.match(/\.[^.]+$/)?.[0] ?? '')}`;
94
94
  return { ...resolved, uri: fullPath };
95
95
  }
96
- console.warn('🧩 No matching key found in manifest for URI:', uri);
97
96
  return resolved;
98
97
  };
99
98
  }
@@ -106,16 +105,31 @@ function injectBundleDropImageResolver(manifestOverride) {
106
105
  let manifest = manifestOverride;
107
106
  if (!manifest) {
108
107
  const raw = BundleDrop.getImageManifestSync?.();
109
- if (!raw) {
110
- console.warn('🧩 No manifest returned from native');
108
+ if (!raw)
111
109
  return;
112
- }
113
110
  manifest = JSON.parse(raw);
114
111
  }
115
112
  patchImageResolverWithManifest(manifest);
116
113
  hasPatched = true;
117
114
  }
118
- catch (e) {
119
- console.warn('🧩 Failed to patch image resolver:', e.message);
115
+ catch {
116
+ // Silently ignore – async path will retry
117
+ }
118
+ }
119
+ async function injectBundleDropImageResolverAsync() {
120
+ if (react_native_1.Platform.OS !== 'android')
121
+ return;
122
+ if (hasPatched)
123
+ return;
124
+ try {
125
+ const raw = await BundleDrop.getImageManifest?.();
126
+ if (!raw)
127
+ return;
128
+ const manifest = JSON.parse(raw);
129
+ patchImageResolverWithManifest(manifest);
130
+ hasPatched = true;
131
+ }
132
+ catch {
133
+ // Non-critical: images fall back to default resolution
120
134
  }
121
135
  }
@@ -6,7 +6,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.installFromZip = installFromZip;
7
7
  const buffer_1 = require("buffer");
8
8
  const fflate_1 = require("fflate");
9
- const react_native_fs_1 = __importDefault(require("react-native-fs"));
9
+ const fs_1 = __importDefault(require("../native/fs"));
10
10
  const context_1 = require("../context");
11
11
  const image_manifest_1 = require("../image-manifest");
12
12
  const injectImageResolver_1 = require("../injectImageResolver");
@@ -60,7 +60,7 @@ async function installFromZip(params) {
60
60
  // Write other files under bundleDir (e.g., metadata, assets)
61
61
  const filePath = `${bundleDir}/${filename}`;
62
62
  await (0, fsUtils_1.ensureParentDir)(filePath);
63
- await react_native_fs_1.default.writeFile(filePath, base64, 'base64');
63
+ await fs_1.default.writeFile(filePath, base64, 'base64');
64
64
  // Collect runtime manifest entries for assets; support paths with or without "assets/" prefix.
65
65
  if (filename.includes('drawable') || filename.startsWith('assets/') || filename.startsWith('res/')) {
66
66
  const noExt = filename.replace(/\.[^.]+$/, '');
@@ -13,6 +13,7 @@ export type BundleDropProjectConfig = {
13
13
  ios: string;
14
14
  android: string;
15
15
  };
16
+ defaultChannel?: string;
16
17
  rollback?: {
17
18
  maxCrashCount?: number;
18
19
  crashWindowSec?: number;
@@ -14,7 +14,7 @@ const errors_1 = require("../errors");
14
14
  const rollbackState_1 = require("./rollbackState");
15
15
  async function downloadAndStageUpdate(options, onStatusUpdate) {
16
16
  const { project } = context_1.config;
17
- const channelName = options?.channelName || 'General';
17
+ const channelName = options?.channelName || context_1.defaultChannel;
18
18
  const platform = context_1.platform;
19
19
  const statusCb = onStatusUpdate;
20
20
  const resolvedTarget = options?.resolvedTarget;
@@ -5,23 +5,36 @@ const downloadAndInstall_1 = require("./downloadAndInstall");
5
5
  const updateCheck_1 = require("./updateCheck");
6
6
  const updateState_1 = require("./updateState");
7
7
  const rollbackState_1 = require("./rollbackState");
8
+ const bundleInfo_1 = require("../bundleInfo");
9
+ const context_1 = require("../context");
10
+ const bundlePointer_1 = require("../fs/bundlePointer");
8
11
  const bundleDropNative_1 = require("../native/bundleDropNative");
9
12
  async function initUpdateManager(opts) {
10
13
  const policy = opts?.policy || 'manual';
11
- const channelName = opts?.channelName || 'General';
14
+ const channelName = opts?.channelName || context_1.defaultChannel;
12
15
  const statusCb = opts?.onStatusUpdate;
13
- // Reconcile pending state on launch (assume downloaded bundle is active if present).
14
- await (0, updateState_1.reconcileAppliedBundleOnLaunch)();
16
+ // Prefetch all startup data in parallel (single bridge round-trip instead of
17
+ // 8+ sequential reads across reconcile / rollback / commit / getUpdateState).
18
+ const [bundleInfo, bundlePath, currentPointer, rollbackStateData] = await Promise.all([
19
+ (0, bundleInfo_1.readBundleInfo)(),
20
+ (0, bundleDropNative_1.getDownloadedBundlePathNative)(),
21
+ (0, bundlePointer_1.readCurrentBundlePointer)(),
22
+ (0, rollbackState_1.readRollbackState)(),
23
+ ]);
24
+ await (0, updateState_1.reconcileAppliedBundleOnLaunch)({ bundleInfo, bundlePath });
15
25
  const rollbackPolicy = (0, rollbackState_1.getRollbackPolicy)();
16
- const rollbackResult = await (0, rollbackState_1.rollbackToPreviousIfNeeded)(rollbackPolicy);
26
+ const rollbackResult = await (0, rollbackState_1.rollbackToPreviousIfNeeded)(rollbackPolicy, {
27
+ currentPointer,
28
+ rollbackState: rollbackStateData,
29
+ });
17
30
  if (rollbackResult.rolledBack) {
18
31
  statusCb?.('↩️ Rolled back to previous bundle');
19
32
  (0, bundleDropNative_1.restartReactNativeNative)();
20
33
  return;
21
34
  }
22
- // If we got this far, JS booted successfully for the current bundle.
23
- await (0, rollbackState_1.commitActiveBundle)();
24
- const pendingState = await (0, updateState_1.getUpdateState)();
35
+ await (0, rollbackState_1.commitActiveBundle)({ currentPointer });
36
+ // bundlePath hasn't changed; let bundleInfo re-read (reconcile may have updated it).
37
+ const pendingState = await (0, updateState_1.getUpdateState)({ bundlePath });
25
38
  if (pendingState.pendingApply) {
26
39
  if (policy === 'immediate') {
27
40
  statusCb?.('♻️ Applying previously downloaded update...');
@@ -1,3 +1,4 @@
1
+ import { type BundlePointer } from '../fs/bundlePointer';
1
2
  export type RollbackPolicy = {
2
3
  maxCrashCount?: number;
3
4
  crashWindowSec?: number;
@@ -13,13 +14,23 @@ export type RollbackState = {
13
14
  crashWindowStartedAt?: number;
14
15
  lastLaunchAt?: number;
15
16
  };
17
+ declare function readState(): Promise<RollbackState | null>;
18
+ export { readState as readRollbackState };
16
19
  export declare function markCandidateActivated(hash: string): Promise<void>;
17
- export declare function commitActiveBundle(): Promise<void>;
18
- export declare function evaluateRollbackOnLaunch(policy?: RollbackPolicy): Promise<{
20
+ export declare function commitActiveBundle(cached?: {
21
+ currentPointer?: BundlePointer | null;
22
+ }): Promise<void>;
23
+ export declare function evaluateRollbackOnLaunch(policy?: RollbackPolicy, cached?: {
24
+ currentPointer?: BundlePointer | null;
25
+ rollbackState?: RollbackState | null;
26
+ }): Promise<{
19
27
  shouldRollback: boolean;
20
28
  reason?: 'crash_loop' | 'commit_timeout';
21
29
  }>;
22
- export declare function rollbackToPreviousIfNeeded(policy?: RollbackPolicy): Promise<{
30
+ export declare function rollbackToPreviousIfNeeded(policy?: RollbackPolicy, cached?: {
31
+ currentPointer?: BundlePointer | null;
32
+ rollbackState?: RollbackState | null;
33
+ }): Promise<{
23
34
  rolledBack: boolean;
24
35
  reason?: 'crash_loop' | 'commit_timeout';
25
36
  }>;
@@ -3,13 +3,14 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.readRollbackState = readState;
6
7
  exports.markCandidateActivated = markCandidateActivated;
7
8
  exports.commitActiveBundle = commitActiveBundle;
8
9
  exports.evaluateRollbackOnLaunch = evaluateRollbackOnLaunch;
9
10
  exports.rollbackToPreviousIfNeeded = rollbackToPreviousIfNeeded;
10
11
  exports.getRollbackPolicy = getRollbackPolicy;
11
12
  exports.rollbackToPreviousOrNative = rollbackToPreviousOrNative;
12
- const react_native_fs_1 = __importDefault(require("react-native-fs"));
13
+ const fs_1 = __importDefault(require("../native/fs"));
13
14
  const context_1 = require("../context");
14
15
  const fsUtils_1 = require("../fs/fsUtils");
15
16
  const bundlePointer_1 = require("../fs/bundlePointer");
@@ -32,9 +33,9 @@ function normalizePolicy(policy) {
32
33
  }
33
34
  async function readState() {
34
35
  try {
35
- if (!(await react_native_fs_1.default.exists(STATE_PATH)))
36
+ if (!(await fs_1.default.exists(STATE_PATH)))
36
37
  return null;
37
- const raw = await react_native_fs_1.default.readFile(STATE_PATH, 'utf8');
38
+ const raw = await fs_1.default.readFile(STATE_PATH, 'utf8');
38
39
  return JSON.parse(raw);
39
40
  }
40
41
  catch {
@@ -66,8 +67,8 @@ async function markCandidateActivated(hash) {
66
67
  lastGoodHash: previousHash ?? undefined,
67
68
  });
68
69
  }
69
- async function commitActiveBundle() {
70
- const current = await (0, bundlePointer_1.readCurrentBundlePointer)();
70
+ async function commitActiveBundle(cached) {
71
+ const current = cached?.currentPointer !== undefined ? cached.currentPointer : await (0, bundlePointer_1.readCurrentBundlePointer)();
71
72
  const hash = current?.hash;
72
73
  if (!hash)
73
74
  return;
@@ -80,13 +81,13 @@ async function commitActiveBundle() {
80
81
  lastGoodHash: hash,
81
82
  });
82
83
  }
83
- async function evaluateRollbackOnLaunch(policy) {
84
- const current = await (0, bundlePointer_1.readCurrentBundlePointer)();
84
+ async function evaluateRollbackOnLaunch(policy, cached) {
85
+ const current = cached?.currentPointer !== undefined ? cached.currentPointer : await (0, bundlePointer_1.readCurrentBundlePointer)();
85
86
  const activeHash = current?.hash;
86
87
  if (!activeHash)
87
88
  return { shouldRollback: false };
88
89
  const now = nowSec();
89
- const state = (await readState()) || {};
90
+ const state = (cached?.rollbackState !== undefined ? cached.rollbackState : await readState()) || {};
90
91
  const normalized = normalizePolicy(policy);
91
92
  const next = {
92
93
  ...state,
@@ -115,8 +116,8 @@ async function evaluateRollbackOnLaunch(policy) {
115
116
  await writeState(next);
116
117
  return { shouldRollback: false };
117
118
  }
118
- async function rollbackToPreviousIfNeeded(policy) {
119
- const decision = await evaluateRollbackOnLaunch(policy);
119
+ async function rollbackToPreviousIfNeeded(policy, cached) {
120
+ const decision = await evaluateRollbackOnLaunch(policy, cached);
120
121
  if (!decision.shouldRollback)
121
122
  return { rolledBack: false };
122
123
  const res = await rollbackToPreviousOrNative();
@@ -170,9 +171,9 @@ async function readBundleMetadata(bundlePath) {
170
171
  const dir = bundlePath.substring(0, bundlePath.lastIndexOf('/'));
171
172
  const metadataFile = context_1.platform === 'android' ? 'metadata-android.json' : 'metadata-ios.json';
172
173
  const filePath = `${dir}/${metadataFile}`;
173
- if (!(await react_native_fs_1.default.exists(filePath)))
174
+ if (!(await fs_1.default.exists(filePath)))
174
175
  return null;
175
- const raw = await react_native_fs_1.default.readFile(filePath, 'utf8');
176
+ const raw = await fs_1.default.readFile(filePath, 'utf8');
176
177
  const parsed = JSON.parse(raw);
177
178
  return {
178
179
  bundleVersion: parsed?.bundleVersion,
@@ -6,6 +6,7 @@ exports.getInstalledBundleInfo = getInstalledBundleInfo;
6
6
  const context_1 = require("../context");
7
7
  const bundleInfo_1 = require("../bundleInfo");
8
8
  const clientApi_1 = require("../api/clientApi");
9
+ const context_2 = require("../context");
9
10
  const bundlePointer_1 = require("../fs/bundlePointer");
10
11
  const installId_1 = require("../fs/installId");
11
12
  const userProperties_1 = require("../fs/userProperties");
@@ -28,19 +29,19 @@ async function getAvailableChannels() {
28
29
  throw e;
29
30
  }
30
31
  }
31
- async function checkForUpdate(channelName = 'General', onStatusUpdate) {
32
+ async function checkForUpdate(channelName = context_2.defaultChannel, onStatusUpdate) {
32
33
  const { project } = context_1.config;
33
- const local = await (0, bundleInfo_1.readBundleInfo)();
34
34
  try {
35
35
  onStatusUpdate?.('🔍 Checking for updates...');
36
- const [currentPtr, previousPtr, currentUserProperties] = await Promise.all([
36
+ const [local, currentPtr, previousPtr, currentUserProperties, installId] = await Promise.all([
37
+ (0, bundleInfo_1.readBundleInfo)(),
37
38
  (0, bundlePointer_1.readCurrentBundlePointer)(),
38
39
  (0, bundlePointer_1.readPreviousBundlePointer)(),
39
40
  (0, userProperties_1.getCurrentUserProperties)(),
41
+ (0, installId_1.getOrCreateInstallId)(),
40
42
  ]);
41
43
  const currentHash = currentPtr?.hash ?? local?.hash ?? null;
42
44
  const previousHash = previousPtr?.hash ?? null;
43
- const installId = await (0, installId_1.getOrCreateInstallId)();
44
45
  const res = await (0, clientApi_1.postOtaResolve)(project.slug, {
45
46
  channelName,
46
47
  platform: context_1.platform,
@@ -1,3 +1,4 @@
1
+ import { BundleInfo } from '../bundleInfo';
1
2
  export type ApplyUpdateResult = {
2
3
  status: 'applied';
3
4
  } | {
@@ -5,10 +6,16 @@ export type ApplyUpdateResult = {
5
6
  } | {
6
7
  status: 'alreadyApplied';
7
8
  };
8
- export declare const getUpdateState: () => Promise<{
9
+ export declare const getUpdateState: (cached?: {
10
+ bundleInfo?: BundleInfo | null;
11
+ bundlePath?: string | null;
12
+ }) => Promise<{
9
13
  hasBundle: boolean;
10
- info: import("../bundleInfo").BundleInfo;
14
+ info: BundleInfo;
11
15
  pendingApply: boolean;
12
16
  }>;
13
- export declare const reconcileAppliedBundleOnLaunch: () => Promise<void>;
17
+ export declare const reconcileAppliedBundleOnLaunch: (cached?: {
18
+ bundleInfo?: BundleInfo | null;
19
+ bundlePath?: string | null;
20
+ }) => Promise<void>;
14
21
  export declare const applyUpdate: (onStatusUpdate?: (status: string) => void) => Promise<ApplyUpdateResult>;
@@ -5,9 +5,9 @@ const bundleDropNative_1 = require("../native/bundleDropNative");
5
5
  const bundleInfo_1 = require("../bundleInfo");
6
6
  const reporting_1 = require("./reporting");
7
7
  const errors_1 = require("../errors");
8
- const getUpdateState = async () => {
9
- const info = await (0, bundleInfo_1.readBundleInfo)();
10
- const path = await (0, bundleDropNative_1.getDownloadedBundlePathNative)();
8
+ const getUpdateState = async (cached) => {
9
+ const info = cached?.bundleInfo !== undefined ? cached.bundleInfo : await (0, bundleInfo_1.readBundleInfo)();
10
+ const path = cached?.bundlePath !== undefined ? cached.bundlePath : await (0, bundleDropNative_1.getDownloadedBundlePathNative)();
11
11
  return {
12
12
  hasBundle: !!path,
13
13
  info,
@@ -15,18 +15,18 @@ const getUpdateState = async () => {
15
15
  };
16
16
  };
17
17
  exports.getUpdateState = getUpdateState;
18
- const reconcileAppliedBundleOnLaunch = async () => {
19
- const state = await (0, exports.getUpdateState)();
18
+ const reconcileAppliedBundleOnLaunch = async (cached) => {
19
+ const state = await (0, exports.getUpdateState)(cached);
20
20
  if (!state.info?.pendingApply)
21
21
  return;
22
22
  if (!state.hasBundle)
23
23
  return;
24
- // Assume that if a downloaded bundle exists on disk during app launch, it is the active bundle.
25
24
  await (0, bundleInfo_1.updateBundleInfo)({ pendingApply: false, installedAt: new Date().toISOString() });
26
- await (0, reporting_1.reportInstalledIfReady)({
25
+ // Fire-and-forget: don't block the startup path for server reporting
26
+ (0, reporting_1.reportInstalledIfReady)({
27
27
  hasBundle: true,
28
28
  info: state.info ? { ...state.info, pendingApply: false } : state.info,
29
- });
29
+ }).catch(() => { });
30
30
  };
31
31
  exports.reconcileAppliedBundleOnLaunch = reconcileAppliedBundleOnLaunch;
32
32
  const applyUpdate = async (onStatusUpdate) => {
@@ -0,0 +1,17 @@
1
+ declare function exists(path: string): Promise<boolean>;
2
+ declare function readFile(path: string, encoding?: 'utf8' | 'base64'): Promise<string>;
3
+ declare function writeFile(path: string, content: string, encoding?: 'utf8' | 'base64'): Promise<void>;
4
+ declare function mkdir(path: string): Promise<void>;
5
+ declare function unlink(path: string): Promise<void>;
6
+ declare function moveFile(src: string, dest: string): Promise<void>;
7
+ declare const BundleDropFS: {
8
+ DocumentDirectoryPath: string;
9
+ LibraryDirectoryPath: string;
10
+ exists: typeof exists;
11
+ readFile: typeof readFile;
12
+ writeFile: typeof writeFile;
13
+ mkdir: typeof mkdir;
14
+ unlink: typeof unlink;
15
+ moveFile: typeof moveFile;
16
+ };
17
+ export default BundleDropFS;
@@ -0,0 +1,33 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const react_native_1 = require("react-native");
4
+ const { BundleDrop } = react_native_1.NativeModules;
5
+ async function exists(path) {
6
+ return BundleDrop.fsExists(path);
7
+ }
8
+ async function readFile(path, encoding = 'utf8') {
9
+ return BundleDrop.fsReadFile(path, encoding);
10
+ }
11
+ async function writeFile(path, content, encoding = 'utf8') {
12
+ return BundleDrop.fsWriteFile(path, content, encoding);
13
+ }
14
+ async function mkdir(path) {
15
+ return BundleDrop.fsMkdir(path);
16
+ }
17
+ async function unlink(path) {
18
+ return BundleDrop.fsUnlink(path);
19
+ }
20
+ async function moveFile(src, dest) {
21
+ return BundleDrop.fsMoveFile(src, dest);
22
+ }
23
+ const BundleDropFS = {
24
+ DocumentDirectoryPath: (BundleDrop?.DocumentDirectoryPath ?? ''),
25
+ LibraryDirectoryPath: (BundleDrop?.LibraryDirectoryPath ?? ''),
26
+ exists,
27
+ readFile,
28
+ writeFile,
29
+ mkdir,
30
+ unlink,
31
+ moveFile,
32
+ };
33
+ exports.default = BundleDropFS;
@@ -8,7 +8,6 @@ function patchImageRenderToForceResolve() {
8
8
  if (isPatched || !react_native_1.Image.render)
9
9
  return;
10
10
  isPatched = true;
11
- console.log('🧩 Patching Image.render to force resolveAssetSource');
12
11
  const OriginalRender = react_native_1.Image.render;
13
12
  react_native_1.Image.render = function (...args) {
14
13
  const props = args[0];
@@ -21,5 +20,4 @@ function patchImageRenderToForceResolve() {
21
20
  }
22
21
  return OriginalRender.apply(this, args);
23
22
  };
24
- console.log('🧩 Patched Image.render to force resolveAssetSource');
25
23
  }
@@ -62,7 +62,7 @@ if (!project?.slug) {
62
62
  process.exit(1);
63
63
  }
64
64
  const runtimeVersion = config?.runtimeVersion?.[platform] || config?.runtimeVersion?.[platform];
65
- const channelName = process.argv[3] || 'General';
65
+ const channelName = process.argv[3] || config?.defaultChannel || 'General';
66
66
  const resolveEndpoint = `${serverUrl}/projects/${encodeURIComponent(project.slug)}/ota/resolve`;
67
67
  const outputPath = path.join(outputDir, `main.${platform}.jsbundle`);
68
68
  if (!fs.existsSync(outputDir)) {
@@ -3,7 +3,7 @@ import { DownloadUpdateResult } from './manager/downloadAndInstall';
3
3
  import { ApplyUpdateResult } from './manager/updateState';
4
4
  import { UpdateCheckResponse } from './api/types';
5
5
  type UseBundleDropOptions = {
6
- /** Channel to target; defaults to "General". */
6
+ /** Channel to target; defaults to config.defaultChannel or "General". */
7
7
  channelName?: string;
8
8
  };
9
9
  type UseBundleDropReturn = {
@@ -2,12 +2,13 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.useBundleDrop = useBundleDrop;
4
4
  const react_1 = require("react");
5
+ const context_1 = require("./context");
5
6
  const updateCheck_1 = require("./manager/updateCheck");
6
7
  const downloadAndInstall_1 = require("./manager/downloadAndInstall");
7
8
  const updateState_1 = require("./manager/updateState");
8
9
  const rollbackState_1 = require("./manager/rollbackState");
9
10
  function useBundleDrop(options) {
10
- const channelName = options?.channelName || 'General';
11
+ const channelName = options?.channelName || context_1.defaultChannel;
11
12
  const [status, setStatus] = (0, react_1.useState)('Click the button to check for updates');
12
13
  const [installedInfo, setInstalledInfo] = (0, react_1.useState)(null);
13
14
  const [pendingApply, setPendingApply] = (0, react_1.useState)(false);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gfean/react-native-bundle-drop",
3
- "version": "0.1.82",
3
+ "version": "0.1.91",
4
4
  "description": "react native ota by gFean",
5
5
  "main": "lib/index.js",
6
6
  "types": "lib/index.d.ts",
@@ -68,7 +68,6 @@
68
68
  "fs-extra": "^11.2.0",
69
69
  "plist": "^3.1.0",
70
70
  "prompts": "^2.4.2",
71
- "react-native-fs": "^2.20.0",
72
71
  "undici": "^7.8.0"
73
72
  },
74
73
  "publishConfig": {