@gfean/react-native-bundle-drop 0.1.31

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 (47) hide show
  1. package/BundleDrop.podspec +23 -0
  2. package/CLIENT_README.md +139 -0
  3. package/README.md +91 -0
  4. package/android/build.gradle +79 -0
  5. package/android/gradle.properties +5 -0
  6. package/android/src/main/AndroidManifest.xml +3 -0
  7. package/android/src/main/AndroidManifestNew.xml +2 -0
  8. package/android/src/main/java/com/bundledrop/BundleDropModule.kt +148 -0
  9. package/android/src/main/java/com/bundledrop/BundleDropPackage.kt +16 -0
  10. package/ios/BundleDropBridge.m +16 -0
  11. package/ios/BundleDropLocator.swift +34 -0
  12. package/ios/BundleDropModule.swift +58 -0
  13. package/lib/CLI/cli.d.ts +2 -0
  14. package/lib/CLI/cli.js +122 -0
  15. package/lib/CLI/scripts/init-config.d.ts +17 -0
  16. package/lib/CLI/scripts/init-config.js +106 -0
  17. package/lib/CLI/scripts/init-native-config.d.ts +2 -0
  18. package/lib/CLI/scripts/init-native-config.js +137 -0
  19. package/lib/CLI/scripts/login-cli.d.ts +2 -0
  20. package/lib/CLI/scripts/login-cli.js +56 -0
  21. package/lib/CLI/scripts/upload-cli.d.ts +8 -0
  22. package/lib/CLI/scripts/upload-cli.js +248 -0
  23. package/lib/CLI/utils/ui.d.ts +8 -0
  24. package/lib/CLI/utils/ui.js +16 -0
  25. package/lib/bundleInfo.d.ts +14 -0
  26. package/lib/bundleInfo.js +34 -0
  27. package/lib/image-manifest.d.ts +1 -0
  28. package/lib/image-manifest.js +4 -0
  29. package/lib/index.d.ts +51 -0
  30. package/lib/index.js +415 -0
  31. package/lib/injectImageResolver.d.ts +2 -0
  32. package/lib/injectImageResolver.js +121 -0
  33. package/lib/loadConfig.d.ts +17 -0
  34. package/lib/loadConfig.js +33 -0
  35. package/lib/patchImageAutoResolve.d.ts +1 -0
  36. package/lib/patchImageAutoResolve.js +25 -0
  37. package/lib/scripts/bundle.d.ts +2 -0
  38. package/lib/scripts/bundle.js +163 -0
  39. package/lib/scripts/download-bundle.d.ts +2 -0
  40. package/lib/scripts/download-bundle.js +79 -0
  41. package/lib/scripts/upload-bundle.d.ts +2 -0
  42. package/lib/scripts/upload-bundle.js +290 -0
  43. package/lib/types.d.ts +1 -0
  44. package/lib/types.js +2 -0
  45. package/lib/useBundleDrop.d.ts +40 -0
  46. package/lib/useBundleDrop.js +131 -0
  47. package/package.json +66 -0
@@ -0,0 +1,23 @@
1
+ require "json"
2
+
3
+ package = JSON.parse(File.read(File.join(__dir__, "package.json")))
4
+
5
+ Pod::Spec.new do |s|
6
+ s.name = "BundleDrop"
7
+ s.version = package["version"]
8
+ s.summary = package["description"]
9
+ s.homepage = package["homepage"]
10
+ s.license = package["license"]
11
+ s.authors = package["author"]
12
+
13
+ s.platforms = { :ios => min_ios_version_supported }
14
+ s.source = { :git => ".git", :tag => "#{s.version}" }
15
+
16
+ s.source_files = "ios/**/*.{h,m,mm,swift}"
17
+
18
+ if respond_to?(:install_modules_dependencies, true)
19
+ install_modules_dependencies(s)
20
+ else
21
+ s.dependency "React-Core"
22
+ end
23
+ end
@@ -0,0 +1,139 @@
1
+ # Bundle Drop Client Quickstart (React Native)
2
+
3
+ This guide is for app teams integrating the `react-native-bundle-drop` module to fetch and apply OTA bundles from your Bundle Drop backend.
4
+
5
+ ## 1) Install and link
6
+ ```bash
7
+ yarn add react-native-bundle-drop
8
+ cd ios && pod install && cd ..
9
+ ```
10
+
11
+ ## 2) App config
12
+ Add `bundle.drop.config.js` to your project root:
13
+ ```js
14
+ module.exports = {
15
+ serverUrl: '<YOUR_BACKEND_URL>',
16
+ org: { slug: '<org-slug>' },
17
+ project: { name: '<Project Name>', slug: '<project-slug>', apiKey: '<optional-api-key>' },
18
+ debugLocal: false, // set true to force localhost (10.0.2.2 on Android)
19
+ };
20
+ ```
21
+
22
+ ## 3) Minimal usage
23
+ Startup (optional auto mode):
24
+ ```ts
25
+ // App.tsx
26
+ import { useEffect } from 'react';
27
+ import { initUpdateManager } from 'react-native-bundle-drop';
28
+
29
+ useEffect(() => {
30
+ initUpdateManager({
31
+ policy: __DEV__ ? 'manual' : 'on-next-launch', // or 'immediate'
32
+ channelName: 'General',
33
+ onStatusUpdate: msg => console.log('[OTA]', msg),
34
+ });
35
+ }, []);
36
+ ```
37
+
38
+ Manual UI example:
39
+ ```ts
40
+ import { useBundleDrop } from 'react-native-bundle-drop/useBundleDrop';
41
+
42
+ const {
43
+ status,
44
+ isBusy,
45
+ installedInfo,
46
+ pendingApply,
47
+ checkLatest,
48
+ downloadImmediate,
49
+ downloadForNextLaunch,
50
+ downloadManual,
51
+ applyPending,
52
+ } = useBundleDrop({ channelName: 'General', policy: 'manual' });
53
+ ```
54
+ - `downloadImmediate`: download and reload now.
55
+ - `downloadForNextLaunch`: download and apply on next app launch (no extra reload).
56
+ - `downloadManual`: download only; call `applyPending` when ready.
57
+
58
+ Quick check-only pattern (no download):
59
+ ```ts
60
+ const { checkLatest, status } = useBundleDrop({ channelName: 'General' });
61
+ await checkLatest();
62
+ console.log(status);
63
+ ```
64
+
65
+ ## 4) Policies
66
+ - `manual`: nothing automatic; call the actions yourself.
67
+ - `immediate`: download and reload as soon as an update is available; pending updates apply on startup.
68
+ - `on-next-launch`: download in background; apply on next cold start without an extra reload.
69
+
70
+ ## 5) Channels (naming tips)
71
+ - Keep names simple and stable: `General`, `Beta`, `QA`.
72
+ - Use `channelName` consistently in both the client (init/useBundleDrop) and upload CLI flag.
73
+ - Prefer a default channel like `General` so your app can fall back gracefully.
74
+
75
+ ## 6) Compatibility (runtimeVersion)
76
+ - Define a `runtimeVersion` per platform in `bundle.drop.config.js` (e.g. `{ ios: "1.0.0", android: "1.0.0" }`).
77
+ - The bundler injects `runtimeVersion` into the metadata JSON inside the ZIP; upload includes it automatically.
78
+ - The client sends `runtimeVersion` on `checkForUpdate`; server should only return bundles that match the requesting runtime.
79
+
80
+ ## 7) Server expectations
81
+ - Endpoint `/bundle/checkForUpdate` should accept `project`, `platform`, `channelName`, `currentBundleVersion?`, `currentHash?`, `runtimeVersion?` and return `{ upToDate, bundleVersion, version, hash, downloadUrl?, reason?, incompatible? }`.
82
+ - Endpoint `/bundle/latest` (or the `downloadUrl` returned) should serve the zip built by your upload script.
83
+
84
+ ## 8) Bundling/Upload (CI/local)
85
+ - Bundle and upload (Android):
86
+ ```bash
87
+ # Prefer explicit version, otherwise falls back to parsing android/app/build.gradle (or --buildgradle-path)
88
+ corepack yarn ts-node modules/react-native-bundle-drop/src/scripts/upload-bundle.ts android --version=1.2.3 --channel=General
89
+ # or: --buildgradle-path=android/app/build.gradle
90
+ ```
91
+ - Bundle and upload (iOS):
92
+ ```bash
93
+ # Prefer --version; otherwise pass --plist-file so version is read from CFBundleShortVersionString
94
+ corepack yarn ts-node modules/react-native-bundle-drop/src/scripts/upload-bundle.ts ios --version=1.2.3 --channel=General
95
+ # or: --plist-file=ios/Info.plist
96
+ ```
97
+ - Requires `~/.bundle-drop/auth.json` from `bundle-drop login` and `bundle.drop.config.js` in project root (with `org.slug`, `project.slug`, `serverUrl`).
98
+
99
+ ## 9) App entry hooks (JS bundle resolution)
100
+ - **Android (MainApplication)**: ensure OTA bundles are used when present.
101
+ ```kt
102
+ import com.bundledrop.BundleDropModule
103
+ // ...
104
+ override fun getJSBundleFile(): String? {
105
+ val bundlePath = BundleDropModule.getDownloadedBundlePath(application)
106
+ return bundlePath ?: super.getJSBundleFile()
107
+ }
108
+ - **iOS (AppDelegate.swift)**: prefer the OTA bundle via the module’s locator (works in debug and release).
109
+ ```swift
110
+ // Add this near the top of AppDelegate.swift
111
+ import BundleDrop
112
+
113
+ // Override to prefer OTA in release
114
+ override func bundleURL() -> URL? {
115
+ if let url = BundleDropModule.getJSBundleURL() {
116
+ return url
117
+ }
118
+ #if !DEBUG
119
+ return Bundle.main.url(forResource: "main", withExtension: "jsbundle")
120
+ #else
121
+ return RCTBundleURLProvider.sharedSettings().jsBundleURL(forBundleRoot: "index")
122
+ #endif
123
+ }
124
+ ```
125
+
126
+ ## 10) Notes
127
+ - Android asset resolver is patched automatically; OTA assets should resolve like bundled ones.
128
+ - Local metadata is stored at `bundle-info.json` in the app document directory.
129
+ - `getUpdateState()` returns `{ hasBundle, info, pendingApply }` if you need raw state.
130
+ - Types are re-exported from the package entry: `BundleInfo`, `UpdatePolicy`.
131
+ - Env tips:
132
+ - Set `debugLocal: true` in config to force localhost/10.0.2.2.
133
+ - If you want a kill switch, guard your `initUpdateManager` call (e.g., `if (!Config.BUNDLE_DROP_DISABLE) { ... }`).
134
+
135
+ ## 11) QA checklist
136
+ - Verify `checkLatest` on the target channel reports up-to-date when expected.
137
+ - Download and apply once with `downloadImmediate` (app reloads) and once with `downloadForNextLaunch` (applies next cold start).
138
+ - Confirm pending flag/UI (`applyPending`) behaves correctly after download but before apply.
139
+ - Spot-check a couple of images/assets after OTA (Android manifest remap) to ensure they resolve.
package/README.md ADDED
@@ -0,0 +1,91 @@
1
+ # React Native Bundle Drop (OTA) — Module Guide
2
+
3
+ This package powers OTA bundle download/upload and asset resolution for React Native.
4
+
5
+ ## Prerequisites
6
+ - `bundle.drop.config.js` in your app root:
7
+ ```js
8
+ module.exports = {
9
+ serverUrl: 'http://localhost:4000', // or prod URL
10
+ org: { slug: 'your-org-slug' },
11
+ project: {
12
+ name: 'ProCredit Mobile App',
13
+ slug: 'procredit-mobile',
14
+ apiKey: 'optional-api-key', // used if provided
15
+ },
16
+ debugLocal: true, // optional: force localhost (10.0.2.2 on Android, localhost on iOS)
17
+ };
18
+ ```
19
+ - Login token stored at `~/.bundle-drop/auth.json` (use CLI `bundle-drop login`).
20
+
21
+ ## Runtime APIs (app code)
22
+ - `checkForUpdate(channelName?, onStatusUpdate?)`: metadata-only check; no download.
23
+ - `downloadAndInstallBundle(platform?, onStatusUpdate?, { channelName, forceDownload, applyBehavior })`: downloads and (optionally) applies. `applyBehavior`: `immediate` (default), `on-next-launch`, `manual`.
24
+ - `restartAppAndInstallUpdate(onStatusUpdate, options?)`: wrapper that downloads then reloads if `applyBehavior` is `immediate`.
25
+ - `downloadUpdate(options?, onStatusUpdate?)`: downloads only (defaults to `applyBehavior: manual`).
26
+ - `applyReadyUpdate(onStatusUpdate?)`: apply a downloaded bundle if pending.
27
+ - `getUpdateState()`: returns `{ hasBundle, info, pendingApply }` from local metadata.
28
+ - `initUpdateManager({ channelName, policy, onStatusUpdate, checkOnly })`: startup helper
29
+ - `policy: 'manual' | 'immediate' | 'on-next-launch'`
30
+ - `immediate`: download/apply now (reload); if pending, applies immediately
31
+ - `on-next-launch`: download and mark pending; on next launch, native loads it and we clear the pending flag without a second reload
32
+ - `manual`: no auto download/apply; optional `checkOnly` will just run a check
33
+ - `useBundleDrop` hook (optional helper): returns status, busy flag, installed info, pending state, and actions (`checkLatest`, `downloadImmediate`, `downloadForNextLaunch`, `downloadManual`, `applyPending`, `refresh`). Supports `autoInit` + `policy` to mirror `initUpdateManager`.
34
+
35
+ Android extras:
36
+ - Asset resolver patches (`injectBundleDropImageResolver`, `patchImageRenderToForceResolve`) are applied on module load so images referenced directly still resolve after OTA.
37
+ - Manifest is built at bundle time and merged with a runtime manifest built during unzip to cover filename-only lookups.
38
+
39
+ ## Config loading
40
+ - `src/loadConfig.ts` loads `bundle.drop.config.js` (fixed relative path) and honors `debugLocal` to force localhost.
41
+
42
+ ## Bundling & Uploading (Node scripts)
43
+ - Bundle only:
44
+ ```bash
45
+ corepack yarn ts-node modules/react-native-bundle-drop/src/scripts/bundle.ts android|ios
46
+ ```
47
+ - Upload (builds, zips, uploads, cleans up):
48
+ ```bash
49
+ corepack yarn ts-node modules/react-native-bundle-drop/src/scripts/upload-bundle.ts android --version=1.2.3 --channel=General
50
+ corepack yarn ts-node modules/react-native-bundle-drop/src/scripts/upload-bundle.ts ios --plist-file=ios/Info.plist --channel=General
51
+ ```
52
+ - Requires `bundle.drop.config.js` (with `serverUrl`, `org.slug`, `project.slug`) and `~/.bundle-drop/auth.json` token.
53
+ - Uses `Authorization: Bearer <token>`, `orgSlug`, `projectSlug`, and `x-api-key` if provided in config.
54
+
55
+ ## Typical usage
56
+ ```ts
57
+ // App.tsx startup (optional auto behavior)
58
+ useEffect(() => {
59
+ initUpdateManager({
60
+ policy: __DEV__ ? 'manual' : 'on-next-launch', // or 'immediate'
61
+ channelName: 'General',
62
+ onStatusUpdate: msg => console.log('[OTA]', msg),
63
+ });
64
+ }, []);
65
+
66
+ // Manual UI (hook)
67
+ const {
68
+ status,
69
+ isBusy,
70
+ installedInfo,
71
+ pendingApply,
72
+ checkLatest,
73
+ downloadImmediate,
74
+ downloadForNextLaunch,
75
+ downloadManual,
76
+ applyPending,
77
+ } = useBundleDrop({ channelName: 'General', policy: 'manual' });
78
+ ```
79
+
80
+ ## CLI (bin)
81
+ - `modules/react-native-bundle-drop/src/CLI/cli.ts` provides:
82
+ - `bundle-drop login|logout|whoami`
83
+ - `bundle-drop upload <platform> --version <ver> --channel <name> [--plist-file <path>] [--runtimeVersion <v>] [--release-notes "<text>"]`
84
+ - Same auth/config requirements as scripts.
85
+
86
+ ## Android localhost note
87
+ - When `debugLocal` is true (or env is set), Android uses `http://10.0.2.2:4000`; iOS uses `http://localhost:4000`.
88
+
89
+ ## Troubleshooting
90
+ - If bundling fails with `EMFILE`, raise file descriptor limit (`ulimit -n 8192`) and retry.
91
+ - Ensure `bundle.drop.config.js` has `serverUrl`, `org.slug`, and `project.slug`; otherwise the module falls back to localhost defaults.
@@ -0,0 +1,79 @@
1
+ buildscript {
2
+ ext.getExtOrDefault = {name ->
3
+ return rootProject.ext.has(name) ? rootProject.ext.get(name) : project.properties['BundleDrop_' + name]
4
+ }
5
+
6
+ repositories {
7
+ google()
8
+ mavenCentral()
9
+ }
10
+
11
+ dependencies {
12
+ classpath "com.android.tools.build:gradle:8.7.2"
13
+ // noinspection DifferentKotlinGradleVersion
14
+ classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:${getExtOrDefault('kotlinVersion')}"
15
+ }
16
+ }
17
+
18
+
19
+ apply plugin: "com.android.library"
20
+ apply plugin: "kotlin-android"
21
+
22
+ def getExtOrIntegerDefault(name) {
23
+ return rootProject.ext.has(name) ? rootProject.ext.get(name) : (project.properties["BundleDrop_" + name]).toInteger()
24
+ }
25
+
26
+ def supportsNamespace() {
27
+ def parsed = com.android.Version.ANDROID_GRADLE_PLUGIN_VERSION.tokenize('.')
28
+ def major = parsed[0].toInteger()
29
+ def minor = parsed[1].toInteger()
30
+
31
+ // Namespace support was added in 7.3.0
32
+ return (major == 7 && minor >= 3) || major >= 8
33
+ }
34
+
35
+ android {
36
+ if (supportsNamespace()) {
37
+ namespace "com.bundledrop"
38
+
39
+ sourceSets {
40
+ main {
41
+ manifest.srcFile "src/main/AndroidManifestNew.xml"
42
+ }
43
+ }
44
+ }
45
+
46
+ compileSdkVersion getExtOrIntegerDefault("compileSdkVersion")
47
+
48
+ defaultConfig {
49
+ minSdkVersion getExtOrIntegerDefault("minSdkVersion")
50
+ targetSdkVersion getExtOrIntegerDefault("targetSdkVersion")
51
+ }
52
+
53
+ buildTypes {
54
+ release {
55
+ minifyEnabled false
56
+ }
57
+ }
58
+
59
+ lintOptions {
60
+ disable "GradleCompatible"
61
+ }
62
+
63
+ compileOptions {
64
+ sourceCompatibility JavaVersion.VERSION_1_8
65
+ targetCompatibility JavaVersion.VERSION_1_8
66
+ }
67
+ }
68
+
69
+ repositories {
70
+ mavenCentral()
71
+ google()
72
+ }
73
+
74
+ def kotlin_version = getExtOrDefault("kotlinVersion")
75
+
76
+ dependencies {
77
+ implementation "com.facebook.react:react-android"
78
+ implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
79
+ }
@@ -0,0 +1,5 @@
1
+ BundleDrop_kotlinVersion=2.0.21
2
+ BundleDrop_minSdkVersion=24
3
+ BundleDrop_targetSdkVersion=34
4
+ BundleDrop_compileSdkVersion=35
5
+ BundleDrop_ndkVersion=27.1.12297006
@@ -0,0 +1,3 @@
1
+ <manifest xmlns:android="http://schemas.android.com/apk/res/android"
2
+ package="com.bundledrop">
3
+ </manifest>
@@ -0,0 +1,2 @@
1
+ <manifest xmlns:android="http://schemas.android.com/apk/res/android">
2
+ </manifest>
@@ -0,0 +1,148 @@
1
+ package com.bundledrop
2
+
3
+ import android.app.AlarmManager
4
+ import android.app.PendingIntent
5
+ import android.content.Context
6
+ import android.content.Intent
7
+ import android.util.Log
8
+ import com.facebook.react.ReactApplication
9
+ import com.facebook.react.bridge.*
10
+ 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
+
17
+ class BundleDropModule(reactContext: ReactApplicationContext) :
18
+ ReactContextBaseJavaModule(reactContext) {
19
+
20
+ private var downloadedBundlePath: String? = null
21
+
22
+ companion object {
23
+ var latestBundlePath: String? = null
24
+ private set
25
+
26
+ private fun currentJsonPath(context: Context): File {
27
+ return File(context.filesDir, "bundle-drop/current.json")
28
+ }
29
+
30
+ private fun readCurrentPointer(context: Context): String? {
31
+ return try {
32
+ val jsonFile = currentJsonPath(context)
33
+ if (!jsonFile.exists()) return null
34
+ val raw = jsonFile.readText()
35
+ val parsed = JSONObject(raw)
36
+ val path = parsed.optString("bundlePath", null)
37
+ if (path != null && path.isNotEmpty()) {
38
+ val file = File(path)
39
+ if (file.exists()) path else null
40
+ } else {
41
+ null
42
+ }
43
+ } catch (e: Exception) {
44
+ Log.w("BundleDrop", "Failed to read current.json: ${e.message}", e)
45
+ null
46
+ }
47
+ }
48
+
49
+ private fun legacyBundlePath(context: Context): String? {
50
+ val file = File(context.filesDir, "main.jsbundle")
51
+ return if (file.exists()) file.absolutePath else null
52
+ }
53
+
54
+ // Call this from MainApplication.kt to fetch the custom bundle path
55
+ fun getDownloadedBundlePath(context: Context): String? {
56
+ val path = readCurrentPointer(context) ?: legacyBundlePath(context)
57
+ return if (path != null) {
58
+ Log.d("BundleDrop", "🔁 Using OTA bundle at: $path")
59
+ path
60
+ } else {
61
+ Log.d("BundleDrop", "📦 No OTA bundle found.")
62
+ null
63
+ }
64
+ }
65
+ }
66
+
67
+ override fun getName(): String = "BundleDrop"
68
+
69
+ @ReactMethod
70
+ fun getDownloadedBundlePath(promise: Promise) {
71
+ val path = getDownloadedBundlePath(reactApplicationContext)
72
+ downloadedBundlePath = path
73
+ latestBundlePath = path
74
+ promise.resolve(path)
75
+ }
76
+
77
+ @ReactMethod
78
+ fun restartReactNative() {
79
+ val activity = currentActivity ?: return
80
+ val context = reactApplicationContext
81
+
82
+ val intent = context.packageManager.getLaunchIntentForPackage(context.packageName)
83
+ if (intent == null) {
84
+ Log.e("BundleDrop", "❌ Could not get launch intent for package")
85
+ return
86
+ }
87
+
88
+ try {
89
+ intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_NEW_TASK)
90
+ activity.finish()
91
+ context.startActivity(intent)
92
+ Runtime.getRuntime().exit(0)
93
+
94
+ Log.d("BundleDrop", "🔁 Restarting app with new bundle...")
95
+ } catch (e: Exception) {
96
+ Log.e("BundleDrop", "❌ Failed to restart app: ${e.message}", e)
97
+ }
98
+ }
99
+
100
+ // Backward compat
101
+ @ReactMethod
102
+ fun forceReloadJS() {
103
+ restartReactNative()
104
+ }
105
+
106
+ @ReactMethod(isBlockingSynchronousMethod = true)
107
+ fun getImageManifestSync(): String? {
108
+ val context = reactApplicationContext
109
+ val current = readCurrentPointer(context) ?: return null
110
+ val bundleDir = File(current).parentFile ?: return null
111
+ val path = File(bundleDir, "image-manifest.json").absolutePath
112
+ return try {
113
+ val file = File(path)
114
+ if (file.exists()) file.readText() else null
115
+ } catch (e: Exception) {
116
+ Log.e("BundleDrop", "Failed to read manifest: ${e.message}", e)
117
+ null
118
+ }
119
+ }
120
+
121
+ // @ReactMethod
122
+ // fun forceReloadJS() {
123
+ // val manager = (reactApplicationContext.currentActivity?.application as? ReactApplication)
124
+ // ?.reactNativeHost?.reactInstanceManager
125
+ //
126
+ // if (manager != null) {
127
+ // Log.d("BundleDrop", "🔁 Forcing React context recreation from native...")
128
+ //
129
+ // reactApplicationContext
130
+ // .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java)
131
+ // .emit("bundleReloadStart", null)
132
+ //
133
+ // reactApplicationContext.runOnUiQueueThread {
134
+ // manager.recreateReactContextInBackground()
135
+ // }
136
+ // } else {
137
+ // Log.e("BundleDrop", "❌ ReactInstanceManager is null.")
138
+ // }
139
+ // }
140
+
141
+ override fun getConstants(): MutableMap<String, Any> {
142
+ val map = mutableMapOf<String, Any>()
143
+ downloadedBundlePath?.let {
144
+ map["downloadedBundlePath"] = it
145
+ }
146
+ return map
147
+ }
148
+ }
@@ -0,0 +1,16 @@
1
+ package com.bundledrop
2
+
3
+ import com.facebook.react.ReactPackage
4
+ import com.facebook.react.bridge.NativeModule
5
+ import com.facebook.react.bridge.ReactApplicationContext
6
+ import com.facebook.react.uimanager.ViewManager
7
+
8
+ class BundleDropPackage : ReactPackage {
9
+ override fun createNativeModules(reactContext: ReactApplicationContext): List<NativeModule> {
10
+ return listOf(BundleDropModule(reactContext))
11
+ }
12
+
13
+ override fun createViewManagers(reactContext: ReactApplicationContext): List<ViewManager<*, *>> {
14
+ return emptyList()
15
+ }
16
+ }
@@ -0,0 +1,16 @@
1
+ #import <React/RCTBridgeModule.h>
2
+
3
+ // JS name "BundleDrop" -> Swift class "BundleDropModule"
4
+ @interface RCT_EXTERN_REMAP_MODULE(BundleDrop, BundleDropModule, NSObject)
5
+
6
+ RCT_EXTERN_METHOD(getDownloadedBundlePath:(RCTPromiseResolveBlock)resolve
7
+ rejecter:(RCTPromiseRejectBlock)reject)
8
+
9
+ RCT_EXTERN_METHOD(restartReactNative)
10
+
11
+ + (BOOL)requiresMainQueueSetup
12
+ {
13
+ return NO;
14
+ }
15
+
16
+ @end
@@ -0,0 +1,34 @@
1
+ import Foundation
2
+
3
+ @objc public final class BundleDropLocator: NSObject {
4
+ @objc public static func bundleURL() -> URL? {
5
+ let fm = FileManager.default
6
+ guard let lib = fm.urls(for: .libraryDirectory, in: .userDomainMask).first else { return nil }
7
+ let root = lib.appendingPathComponent("bundle-drop", isDirectory: true)
8
+ let current = root.appendingPathComponent("current.json")
9
+
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)")
19
+ }
20
+ }
21
+
22
+ // legacy fallback: Documents/main.jsbundle
23
+ if let docs = fm.urls(for: .documentDirectory, in: .userDomainMask).first {
24
+ let legacy = docs.appendingPathComponent("main.jsbundle")
25
+ if fm.fileExists(atPath: legacy.path) { return legacy }
26
+ }
27
+
28
+ return nil
29
+ }
30
+
31
+ @objc public static func fileSize(at url: URL) -> UInt64 {
32
+ (try? FileManager.default.attributesOfItem(atPath: url.path)[.size] as? UInt64) ?? 0
33
+ }
34
+ }
@@ -0,0 +1,58 @@
1
+ import Foundation
2
+ import React
3
+
4
+ @objc(BundleDropModule) // native class name
5
+ final class BundleDropModule: NSObject {
6
+
7
+ private static var isReloading = false
8
+
9
+ // MARK: - OTA bundle path
10
+
11
+ @objc
12
+ func getDownloadedBundlePath(
13
+ _ resolve: @escaping RCTPromiseResolveBlock,
14
+ rejecter reject: @escaping RCTPromiseRejectBlock
15
+ ) {
16
+ if let url = BundleDropLocator.bundleURL() {
17
+ print("📦 Found downloaded bundle at: \(url.path)")
18
+ resolve(url.path)
19
+ return
20
+ }
21
+ print("📦 No downloaded bundle found.")
22
+ resolve(nil)
23
+ }
24
+
25
+ // 🚨 Restart RN safely (debounced)
26
+ @objc
27
+ func restartReactNative() {
28
+ DispatchQueue.main.async {
29
+ if Self.isReloading {
30
+ print("🔁 Restart already in progress - ignoring.")
31
+ return
32
+ }
33
+
34
+ guard let url = BundleDropLocator.bundleURL() else {
35
+ print("⚠️ No downloaded bundle found; skipping restart.")
36
+ return
37
+ }
38
+
39
+ let size = BundleDropLocator.fileSize(at: url)
40
+ if size < 1024 {
41
+ print("⚠️ Bundle exists but looks invalid (size=\(size)). Skipping restart.")
42
+ return
43
+ }
44
+
45
+ Self.isReloading = true
46
+ print("🔄 Restarting RN from \(url.path) size=\(size)")
47
+
48
+ // Trigger a standard RN reload; AppDelegate.bundleURL() decides OTA vs embedded
49
+ RCTReloadCommandSetBundleURL(url)
50
+ RCTTriggerReloadCommandListeners("bundle-drop-restart")
51
+
52
+ // release lock after a short moment to prevent double-trigger
53
+ DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
54
+ Self.isReloading = false
55
+ }
56
+ }
57
+ }
58
+ }
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};