@gfean/react-native-bundle-drop 0.3.8 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/BundleDrop.podspec +9 -2
  2. package/README.md +19 -0
  3. package/android/build.gradle +25 -4
  4. package/android/src/main/cpp/CMakeLists.txt +33 -0
  5. package/android/src/main/cpp/bundle_drop_xdelta_jni.c +55 -0
  6. package/android/src/main/java/com/bundledrop/BundleDropBundleVerifier.kt +73 -0
  7. package/android/src/main/java/com/bundledrop/BundleDropFileOps.kt +193 -8
  8. package/android/src/main/java/com/bundledrop/BundleDropModule.kt +60 -7
  9. package/android/src/main/java/com/bundledrop/BundleDropOtaPrefs.kt +2 -12
  10. package/android/src/main/java/com/bundledrop/BundleDropOtaResolver.kt +208 -3
  11. package/android/src/main/java/com/bundledrop/BundleDropXdeltaNative.kt +57 -0
  12. package/ios/BundleDropBridge.m +27 -0
  13. package/ios/BundleDropBundleVerifier.swift +106 -0
  14. package/ios/BundleDropFileOps.swift +149 -0
  15. package/ios/BundleDropModule.swift +100 -11
  16. package/ios/BundleDropOtaResolver.swift +149 -3
  17. package/ios/BundleDropZipExtractor.m +75 -3
  18. package/lib/CLI/cli.js +1 -8
  19. package/lib/CLI/scripts/upload-cli.d.ts +0 -1
  20. package/lib/CLI/scripts/upload-cli.js +26 -20
  21. package/lib/api/client.d.ts +11 -1
  22. package/lib/api/client.js +84 -17
  23. package/lib/api/clientApi.d.ts +2 -1
  24. package/lib/api/clientApi.js +9 -0
  25. package/lib/api/types.d.ts +65 -13
  26. package/lib/bundleInfo.d.ts +2 -0
  27. package/lib/fs/bundlePointer.d.ts +2 -1
  28. package/lib/fs/bundlePointer.js +34 -6
  29. package/lib/fs/fsUtils.js +4 -1
  30. package/lib/injectImageResolver.js +135 -45
  31. package/lib/install/bundleInstallShared.d.ts +8 -0
  32. package/lib/install/bundleInstallShared.js +97 -0
  33. package/lib/install/bundleVerification.d.ts +5 -0
  34. package/lib/install/bundleVerification.js +34 -0
  35. package/lib/install/installFromZip.d.ts +2 -5
  36. package/lib/install/installFromZip.js +33 -62
  37. package/lib/loadConfig.js +12 -1
  38. package/lib/manager/downloadAndInstall.d.ts +9 -0
  39. package/lib/manager/downloadAndInstall.js +84 -24
  40. package/lib/manager/reporting.js +26 -2
  41. package/lib/manager/rollbackState.js +21 -12
  42. package/lib/manager/updateCheck.js +89 -11
  43. package/lib/manager/updateState.js +3 -9
  44. package/lib/manifest/bundleManifest.d.ts +33 -0
  45. package/lib/manifest/bundleManifest.js +298 -0
  46. package/lib/native/bundleDropNative.js +1 -2
  47. package/lib/native/fs.d.ts +14 -0
  48. package/lib/native/fs.js +35 -0
  49. package/lib/patch-engine/installFromPatchSet.d.ts +16 -0
  50. package/lib/patch-engine/installFromPatchSet.js +143 -0
  51. package/lib/patch-engine/patchOperations.d.ts +33 -0
  52. package/lib/patch-engine/patchOperations.js +77 -0
  53. package/lib/patch-engine/patchTransport.d.ts +18 -0
  54. package/lib/patch-engine/patchTransport.js +81 -0
  55. package/lib/patchAlgorithms.d.ts +4 -0
  56. package/lib/patchAlgorithms.js +9 -0
  57. package/lib/runtime/service.js +43 -9
  58. package/lib/scripts/bundle.d.ts +3 -0
  59. package/lib/scripts/bundle.js +184 -36
  60. package/lib/scripts/download-bundle.js +18 -7
  61. package/lib/scripts/upload-bundle.js +25 -28
  62. package/package.json +44 -5
  63. package/third_party/xdelta/NOTICE +7 -0
  64. package/third_party/xdelta/PROVENANCE.md +10 -0
  65. package/third_party/xdelta/bundle_drop_xdelta.c +252 -0
  66. package/third_party/xdelta/bundle_drop_xdelta.h +26 -0
  67. package/third_party/xdelta/xdelta3/LICENSE +176 -0
  68. package/third_party/xdelta/xdelta3/config.h +34 -0
  69. package/third_party/xdelta/xdelta3/xdelta3-cfgs.h +171 -0
  70. package/third_party/xdelta/xdelta3/xdelta3-decode.h +1219 -0
  71. package/third_party/xdelta/xdelta3/xdelta3-hash.h +159 -0
  72. package/third_party/xdelta/xdelta3/xdelta3-internal.h +385 -0
  73. package/third_party/xdelta/xdelta3/xdelta3-list.h +127 -0
  74. package/third_party/xdelta/xdelta3/xdelta3.c +4819 -0
  75. package/third_party/xdelta/xdelta3/xdelta3.h +1476 -0
  76. package/lib/CLI/scripts/init-native-config.d.ts +0 -18
  77. package/lib/CLI/scripts/init-native-config.js +0 -539
@@ -1,18 +0,0 @@
1
- export declare function findProjectRoot(startDir: string): string;
2
- export declare function findFileByName(root: string, fileName: string): string | null;
3
- /**
4
- * Starting from an opening brace at `openIndex`, count balanced braces
5
- * and return the index *after* the matching closing brace.
6
- * Returns -1 if unbalanced.
7
- */
8
- export declare function findMatchingBrace(content: string, openIndex: number): number;
9
- export declare function ensureImport(content: string, importLine: string): string;
10
- export declare function patchAndroidMainApplicationKotlin(filePath: string): void;
11
- export declare function ensureJavaImport(content: string, importLine: string): string;
12
- export declare function patchAndroidMainApplicationJava(filePath: string): void;
13
- export declare function patchAndroidMainApplication(filePath: string): void;
14
- export declare function patchIosAppDelegateSwift(filePath: string): void;
15
- export declare function patchIosAppDelegateObjc(filePath: string): void;
16
- export declare function patchIosAppDelegate(filePath: string): void;
17
- export declare function initNativeConfig(): Promise<void>;
18
- export default initNativeConfig;
@@ -1,539 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.findProjectRoot = findProjectRoot;
7
- exports.findFileByName = findFileByName;
8
- exports.findMatchingBrace = findMatchingBrace;
9
- exports.ensureImport = ensureImport;
10
- exports.patchAndroidMainApplicationKotlin = patchAndroidMainApplicationKotlin;
11
- exports.ensureJavaImport = ensureJavaImport;
12
- exports.patchAndroidMainApplicationJava = patchAndroidMainApplicationJava;
13
- exports.patchAndroidMainApplication = patchAndroidMainApplication;
14
- exports.patchIosAppDelegateSwift = patchIosAppDelegateSwift;
15
- exports.patchIosAppDelegateObjc = patchIosAppDelegateObjc;
16
- exports.patchIosAppDelegate = patchIosAppDelegate;
17
- exports.initNativeConfig = initNativeConfig;
18
- const chalk_1 = __importDefault(require("chalk"));
19
- const fs_extra_1 = __importDefault(require("fs-extra"));
20
- const path_1 = __importDefault(require("path"));
21
- const prompts_1 = __importDefault(require("prompts"));
22
- const DOCS_INSTALLATION_URL = 'https://bundledrop.app/docs/installation';
23
- const DOCS_ANDROID_NATIVE_SETUP_URL = `${DOCS_INSTALLATION_URL}#android-mainapplication`;
24
- const DOCS_IOS_NATIVE_SETUP_URL = `${DOCS_INSTALLATION_URL}#ios-appdelegate`;
25
- function findProjectRoot(startDir) {
26
- let dir = path_1.default.resolve(startDir);
27
- const MAX_UP = 12;
28
- for (let i = 0; i < MAX_UP; i++) {
29
- if (fs_extra_1.default.existsSync(path_1.default.join(dir, 'ios')) && fs_extra_1.default.existsSync(path_1.default.join(dir, 'android'))) {
30
- return dir;
31
- }
32
- const parent = path_1.default.dirname(dir);
33
- if (parent === dir)
34
- break;
35
- dir = parent;
36
- }
37
- return startDir;
38
- }
39
- function findFileByName(root, fileName) {
40
- const stack = [root];
41
- while (stack.length) {
42
- const current = stack.pop();
43
- const stat = fs_extra_1.default.statSync(current);
44
- if (stat.isDirectory()) {
45
- for (const entry of fs_extra_1.default.readdirSync(current)) {
46
- stack.push(path_1.default.join(current, entry));
47
- }
48
- }
49
- else if (stat.isFile() && current.endsWith(fileName)) {
50
- return current;
51
- }
52
- }
53
- return null;
54
- }
55
- // ---------------------------------------------------------------------------
56
- // Android MainApplication.kt patcher
57
- //
58
- // Decision tree:
59
- // 1. Already patched (resolveJSBundleFile or getDownloadedBundlePath) → skip.
60
- // 2. Has `override fun getJSBundleFile()` → inject one-liner (older template).
61
- // 3. Has ReactHost-style template (reactHost / getDefaultReactHost):
62
- // a. reactNativeHost property exists → add getJSBundleFile() override inside it.
63
- // b. reactNativeHost missing → insert full reactNativeHost block + rewire reactHost.
64
- // 4. None matched → print manual instructions.
65
- // ---------------------------------------------------------------------------
66
- const BUNDLE_DROP_IMPORT = 'import com.bundledrop.BundleDropModule';
67
- const ONE_LINER = `override fun getJSBundleFile(): String? =\n` +
68
- ` BundleDropModule.resolveJSBundleFile(applicationContext, super.getJSBundleFile())`;
69
- const REACT_HOST_IMPORTS = [
70
- 'import com.facebook.react.ReactHost',
71
- 'import com.facebook.react.ReactNativeHost',
72
- 'import com.facebook.react.ReactNativeApplicationEntryPoint.loadReactNative',
73
- 'import com.facebook.react.defaults.DefaultReactHost.getDefaultReactHost',
74
- 'import com.facebook.react.defaults.DefaultReactNativeHost',
75
- ];
76
- const REACT_NATIVE_HOST_BLOCK = `\
77
- override val reactNativeHost: ReactNativeHost =
78
- object : DefaultReactNativeHost(this) {
79
-
80
- override fun getPackages() = PackageList(this).packages
81
- override fun getJSMainModuleName(): String = "index"
82
- override fun getUseDeveloperSupport(): Boolean = BuildConfig.DEBUG
83
-
84
- override val isNewArchEnabled: Boolean = BuildConfig.IS_NEW_ARCHITECTURE_ENABLED
85
- override val isHermesEnabled: Boolean = BuildConfig.IS_HERMES_ENABLED
86
-
87
- override fun getJSBundleFile(): String? =
88
- BundleDropModule.resolveJSBundleFile(applicationContext, super.getJSBundleFile())
89
- }`;
90
- const REACT_HOST_OVERRIDE = `\
91
- override val reactHost: ReactHost by lazy {
92
- getDefaultReactHost(
93
- context = applicationContext,
94
- reactNativeHost = reactNativeHost
95
- )
96
- }`;
97
- /**
98
- * Starting from an opening brace at `openIndex`, count balanced braces
99
- * and return the index *after* the matching closing brace.
100
- * Returns -1 if unbalanced.
101
- */
102
- function findMatchingBrace(content, openIndex) {
103
- let depth = 1;
104
- let i = openIndex + 1;
105
- while (i < content.length && depth > 0) {
106
- if (content[i] === '{')
107
- depth++;
108
- else if (content[i] === '}')
109
- depth--;
110
- i++;
111
- }
112
- return depth === 0 ? i : -1;
113
- }
114
- function ensureImport(content, importLine) {
115
- if (content.includes(importLine))
116
- return content;
117
- const lastImport = content.lastIndexOf('\nimport ');
118
- if (lastImport !== -1) {
119
- const eol = content.indexOf('\n', lastImport + 1);
120
- return content.slice(0, eol + 1) + importLine + '\n' + content.slice(eol + 1);
121
- }
122
- return importLine + '\n' + content;
123
- }
124
- function patchAndroidMainApplicationKotlin(filePath) {
125
- let content = fs_extra_1.default.readFileSync(filePath, 'utf8');
126
- // 1. Already patched?
127
- if (content.includes('BundleDropModule.resolveJSBundleFile') ||
128
- content.includes('BundleDropModule.getDownloadedBundlePath')) {
129
- console.log(chalk_1.default.gray(` Already patched: ${filePath}`));
130
- return;
131
- }
132
- // 2. Older template — has getJSBundleFile() already
133
- const methodRegex = /override fun getJSBundleFile\(\)\s*:\s*String\?/;
134
- if (methodRegex.test(content)) {
135
- console.log(chalk_1.default.cyan(' Detected existing getJSBundleFile() override (older RN template)'));
136
- content = ensureImport(content, BUNDLE_DROP_IMPORT);
137
- // Expression-body form: override fun getJSBundleFile(): String? = ...
138
- const exprMethodRegex = /override fun getJSBundleFile\(\)\s*:\s*String\?\s*=[^\n]+/;
139
- if (exprMethodRegex.test(content)) {
140
- content = content.replace(exprMethodRegex, ONE_LINER);
141
- }
142
- else {
143
- // Block-body form: use brace-counting to safely capture the full method
144
- const methodStart = content.search(methodRegex);
145
- const openBrace = content.indexOf('{', methodStart);
146
- if (methodStart !== -1 && openBrace !== -1) {
147
- const afterClose = findMatchingBrace(content, openBrace);
148
- if (afterClose !== -1) {
149
- content = content.slice(0, methodStart) + ONE_LINER + content.slice(afterClose);
150
- }
151
- }
152
- }
153
- fs_extra_1.default.writeFileSync(filePath, content, 'utf8');
154
- console.log(chalk_1.default.green(` ✅ Patched getJSBundleFile() with BundleDrop one-liner: ${filePath}`));
155
- return;
156
- }
157
- // 3. RN 0.84+ ReactHost template
158
- const hasReactHost = content.includes('override val reactHost') || content.includes('getDefaultReactHost(');
159
- if (hasReactHost) {
160
- const hasReactNativeHost = content.includes('override val reactNativeHost');
161
- if (hasReactNativeHost) {
162
- // 3a. reactNativeHost exists — inject getJSBundleFile() inside the object block
163
- console.log(chalk_1.default.cyan(' Detected ReactHost template with existing reactNativeHost override'));
164
- content = ensureImport(content, BUNDLE_DROP_IMPORT);
165
- // Find the object block's opening brace using brace-counting
166
- const rnhIdx = content.indexOf('override val reactNativeHost');
167
- const objectIdx = rnhIdx !== -1 ? content.indexOf('{', content.indexOf('object', rnhIdx)) : -1;
168
- if (objectIdx !== -1) {
169
- const blockEnd = findMatchingBrace(content, objectIdx);
170
- if (blockEnd !== -1) {
171
- // Insert the one-liner just before the closing brace
172
- const closingBrace = blockEnd - 1;
173
- const indented = ONE_LINER.split('\n').join('\n ');
174
- content =
175
- content.slice(0, closingBrace) +
176
- '\n\n ' + indented + '\n ' +
177
- content.slice(closingBrace);
178
- }
179
- else {
180
- console.log(chalk_1.default.yellow(` ⚠️ Found reactNativeHost but could not parse its object block.\n` +
181
- ` Please add inside the DefaultReactNativeHost object:\n\n` +
182
- ` ${ONE_LINER.split('\n').join('\n ')}`));
183
- return;
184
- }
185
- }
186
- else {
187
- console.log(chalk_1.default.yellow(` ⚠️ Found reactNativeHost but could not locate the object block.\n` +
188
- ` Please add inside the DefaultReactNativeHost object:\n\n` +
189
- ` ${ONE_LINER.split('\n').join('\n ')}`));
190
- return;
191
- }
192
- fs_extra_1.default.writeFileSync(filePath, content, 'utf8');
193
- console.log(chalk_1.default.green(` ✅ Injected getJSBundleFile() into existing reactNativeHost: ${filePath}`));
194
- return;
195
- }
196
- // 3b. No reactNativeHost — insert full block + rewire reactHost
197
- console.log(chalk_1.default.cyan(' Detected RN 0.84+ ReactHost template without reactNativeHost — inserting full block'));
198
- content = ensureImport(content, BUNDLE_DROP_IMPORT);
199
- for (const imp of REACT_HOST_IMPORTS) {
200
- content = ensureImport(content, imp);
201
- }
202
- // Replace entire reactHost property using brace-counting (safe with nested blocks)
203
- const reactHostIdx = content.indexOf('override val reactHost');
204
- if (reactHostIdx !== -1) {
205
- const openBrace = content.indexOf('{', reactHostIdx);
206
- if (openBrace !== -1) {
207
- const afterClose = findMatchingBrace(content, openBrace);
208
- if (afterClose !== -1) {
209
- content =
210
- content.slice(0, reactHostIdx) +
211
- REACT_NATIVE_HOST_BLOCK +
212
- '\n\n' +
213
- REACT_HOST_OVERRIDE +
214
- content.slice(afterClose);
215
- }
216
- }
217
- }
218
- // Fallback: if replacement didn't happen (no brace match), insert before onCreate
219
- if (!content.includes('override val reactNativeHost')) {
220
- const onCreateIdx = content.indexOf('override fun onCreate');
221
- if (onCreateIdx !== -1) {
222
- content =
223
- content.slice(0, onCreateIdx) +
224
- REACT_NATIVE_HOST_BLOCK +
225
- '\n\n' +
226
- REACT_HOST_OVERRIDE +
227
- '\n\n ' +
228
- content.slice(onCreateIdx);
229
- }
230
- else {
231
- console.log(chalk_1.default.yellow(` ⚠️ Could not find a suitable insertion point in ${filePath}.\n` +
232
- ` Please add the reactNativeHost + reactHost blocks manually.\n` +
233
- ` See ${DOCS_ANDROID_NATIVE_SETUP_URL}`));
234
- return;
235
- }
236
- }
237
- // Ensure onCreate calls loadReactNative
238
- if (!content.includes('loadReactNative(')) {
239
- const onCreateBody = /override fun onCreate\(\)\s*\{/;
240
- if (onCreateBody.test(content)) {
241
- content = content.replace(onCreateBody, match => {
242
- return match + '\n loadReactNative(this)';
243
- });
244
- }
245
- }
246
- fs_extra_1.default.writeFileSync(filePath, content, 'utf8');
247
- console.log(chalk_1.default.green(` ✅ Inserted reactNativeHost block and rewired reactHost for BundleDrop: ${filePath}`));
248
- return;
249
- }
250
- // 4. No recognizable template
251
- console.log(chalk_1.default.yellow(` ⚠️ Could not detect a supported MainApplication template in ${filePath}.\n` +
252
- ` Please add the BundleDrop override manually.\n` +
253
- ` See ${DOCS_ANDROID_NATIVE_SETUP_URL}`));
254
- }
255
- // ---------------------------------------------------------------------------
256
- // Android MainApplication.java patcher (older RN versions)
257
- //
258
- // Decision tree:
259
- // 1. Already patched (BundleDropModule reference) → skip.
260
- // 2. Has getJSBundleFile() method → replace body with BundleDrop call.
261
- // 3. Has ReactNativeHost anonymous class → inject getJSBundleFile() inside it.
262
- // 4. None matched → print manual instructions.
263
- // ---------------------------------------------------------------------------
264
- const JAVA_BUNDLE_DROP_IMPORT = 'import com.bundledrop.BundleDropModule;';
265
- const JAVA_GET_JS_BUNDLE_METHOD = `@Override\n` +
266
- ` protected String getJSBundleFile() {\n` +
267
- ` return BundleDropModule.resolveJSBundleFile(getApplicationContext(), super.getJSBundleFile());\n` +
268
- ` }`;
269
- function ensureJavaImport(content, importLine) {
270
- if (content.includes(importLine))
271
- return content;
272
- const lastImport = content.lastIndexOf('\nimport ');
273
- if (lastImport !== -1) {
274
- const eol = content.indexOf('\n', lastImport + 1);
275
- return content.slice(0, eol + 1) + importLine + '\n' + content.slice(eol + 1);
276
- }
277
- return importLine + '\n' + content;
278
- }
279
- function patchAndroidMainApplicationJava(filePath) {
280
- let content = fs_extra_1.default.readFileSync(filePath, 'utf8');
281
- // 1. Already patched?
282
- if (content.includes('BundleDropModule.resolveJSBundleFile') ||
283
- content.includes('BundleDropModule.getDownloadedBundlePath')) {
284
- console.log(chalk_1.default.gray(` Already patched: ${filePath}`));
285
- return;
286
- }
287
- // 2. Has getJSBundleFile() method — replace its body
288
- const methodSignature = /protected\s+String\s+getJSBundleFile\s*\(\s*\)/;
289
- if (methodSignature.test(content)) {
290
- console.log(chalk_1.default.cyan(' Detected existing getJSBundleFile() override (Java)'));
291
- content = ensureJavaImport(content, JAVA_BUNDLE_DROP_IMPORT);
292
- const methodStart = content.search(methodSignature);
293
- const openBrace = content.indexOf('{', methodStart);
294
- if (methodStart !== -1 && openBrace !== -1) {
295
- const afterClose = findMatchingBrace(content, openBrace);
296
- if (afterClose !== -1) {
297
- content = content.slice(0, methodStart) + JAVA_GET_JS_BUNDLE_METHOD + content.slice(afterClose);
298
- fs_extra_1.default.writeFileSync(filePath, content, 'utf8');
299
- console.log(chalk_1.default.green(` ✅ Patched getJSBundleFile() with BundleDrop call (Java): ${filePath}`));
300
- return;
301
- }
302
- }
303
- console.log(chalk_1.default.yellow(` ⚠️ Found getJSBundleFile() but could not safely parse its body.\n` +
304
- ` Please replace the method body manually.\n` +
305
- ` See ${DOCS_ANDROID_NATIVE_SETUP_URL}`));
306
- return;
307
- }
308
- // 3. Has ReactNativeHost anonymous class — inject getJSBundleFile() inside it
309
- const rnhPattern = /new\s+(DefaultReactNativeHost|ReactNativeHost)\s*\(/;
310
- const rnhMatch = content.match(rnhPattern);
311
- if (rnhMatch) {
312
- console.log(chalk_1.default.cyan(` Detected ${rnhMatch[1]} anonymous class — injecting getJSBundleFile()`));
313
- content = ensureJavaImport(content, JAVA_BUNDLE_DROP_IMPORT);
314
- const rnhIdx = content.search(rnhPattern);
315
- // Find the opening brace of the anonymous class (after the constructor args)
316
- const ctorOpen = content.indexOf('(', rnhIdx);
317
- if (ctorOpen !== -1) {
318
- // Skip past constructor parens to find the class body brace
319
- let parenDepth = 1;
320
- let ci = ctorOpen + 1;
321
- while (ci < content.length && parenDepth > 0) {
322
- if (content[ci] === '(')
323
- parenDepth++;
324
- else if (content[ci] === ')')
325
- parenDepth--;
326
- ci++;
327
- }
328
- // ci is now right after the closing ')' of the constructor — find the '{'
329
- const classBodyOpen = content.indexOf('{', ci);
330
- if (classBodyOpen !== -1) {
331
- const classBodyEnd = findMatchingBrace(content, classBodyOpen);
332
- if (classBodyEnd !== -1) {
333
- const closingBrace = classBodyEnd - 1;
334
- content =
335
- content.slice(0, closingBrace) +
336
- '\n\n ' + JAVA_GET_JS_BUNDLE_METHOD.split('\n').join('\n ').trimStart() + '\n ' +
337
- content.slice(closingBrace);
338
- fs_extra_1.default.writeFileSync(filePath, content, 'utf8');
339
- console.log(chalk_1.default.green(` ✅ Injected getJSBundleFile() into ReactNativeHost (Java): ${filePath}`));
340
- return;
341
- }
342
- }
343
- }
344
- console.log(chalk_1.default.yellow(` ⚠️ Found ReactNativeHost but could not safely parse its anonymous class.\n` +
345
- ` Please add getJSBundleFile() override manually.\n` +
346
- ` See ${DOCS_ANDROID_NATIVE_SETUP_URL}`));
347
- return;
348
- }
349
- // 4. No recognizable template
350
- console.log(chalk_1.default.yellow(` ⚠️ Could not detect a supported MainApplication template in ${filePath}.\n` +
351
- ` Please add the BundleDrop override manually.\n` +
352
- ` See ${DOCS_ANDROID_NATIVE_SETUP_URL}`));
353
- }
354
- function patchAndroidMainApplication(filePath) {
355
- const ext = path_1.default.extname(filePath);
356
- console.log(chalk_1.default.cyan(` ✅ Found MainApplication: ${filePath}`));
357
- if (ext === '.kt') {
358
- patchAndroidMainApplicationKotlin(filePath);
359
- }
360
- else if (ext === '.java') {
361
- patchAndroidMainApplicationJava(filePath);
362
- }
363
- else {
364
- console.log(chalk_1.default.yellow(` ⚠️ Unsupported MainApplication file type (${ext}). Please patch manually.\n` +
365
- ` See ${DOCS_ANDROID_NATIVE_SETUP_URL}`));
366
- }
367
- }
368
- // ---------------------------------------------------------------------------
369
- // iOS AppDelegate patcher
370
- //
371
- // Supports:
372
- // - AppDelegate.swift (bundleURL() override)
373
- // - AppDelegate.m / .mm (sourceURLForBridge: method)
374
- //
375
- // Search order under ios/:
376
- // 1. AppDelegate.swift
377
- // 2. AppDelegate.mm
378
- // 3. AppDelegate.m
379
- // ---------------------------------------------------------------------------
380
- const SWIFT_BUNDLE_URL_BODY = `override func bundleURL() -> URL? {
381
- #if DEBUG
382
- return RCTBundleURLProvider.sharedSettings().jsBundleURL(forBundleRoot: "index")
383
- #else
384
- if let url = BundleDropLocator.bundleURL() {
385
- return url
386
- }
387
- return Bundle.main.url(forResource: "main", withExtension: "jsbundle")
388
- #endif
389
- }`;
390
- const OBJC_SOURCE_URL_BODY = `- (NSURL *)sourceURLForBridge:(RCTBridge *)bridge
391
- {
392
- #if DEBUG
393
- return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index"];
394
- #else
395
- NSURL *otaURL = [BundleDropLocator bundleURL];
396
- if (otaURL != nil) {
397
- return otaURL;
398
- }
399
- return [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"];
400
- #endif
401
- }`;
402
- function patchIosAppDelegateSwift(filePath) {
403
- let content = fs_extra_1.default.readFileSync(filePath, 'utf8');
404
- if (content.includes('BundleDropLocator.bundleURL()') || content.includes('import BundleDrop')) {
405
- console.log(chalk_1.default.gray(` Already patched: ${filePath}`));
406
- return;
407
- }
408
- // Ensure import
409
- const reactImport = content.match(/^import .*React.*$/m);
410
- if (reactImport) {
411
- content = content.replace(reactImport[0], reactImport[0] + '\nimport BundleDrop');
412
- }
413
- else {
414
- const firstImport = content.match(/^import .+$/m);
415
- if (firstImport) {
416
- content = content.replace(firstImport[0], firstImport[0] + '\nimport BundleDrop');
417
- }
418
- else {
419
- content = 'import BundleDrop\n' + content;
420
- }
421
- }
422
- // Patch bundleURL()
423
- const bundleRegex = /override func bundleURL\(\)\s*->\s*URL\?\s*\{[\s\S]*?#endif\s*\}/m;
424
- if (bundleRegex.test(content)) {
425
- content = content.replace(bundleRegex, SWIFT_BUNDLE_URL_BODY);
426
- fs_extra_1.default.writeFileSync(filePath, content, 'utf8');
427
- console.log(chalk_1.default.green(` ✅ Patched iOS AppDelegate (Swift): ${filePath}`));
428
- return;
429
- }
430
- // bundleURL without #if/#endif (simple body)
431
- const simpleBundleRegex = /override func bundleURL\(\)\s*->\s*URL\?\s*\{[^}]*\}/m;
432
- if (simpleBundleRegex.test(content)) {
433
- content = content.replace(simpleBundleRegex, SWIFT_BUNDLE_URL_BODY);
434
- fs_extra_1.default.writeFileSync(filePath, content, 'utf8');
435
- console.log(chalk_1.default.green(` ✅ Patched iOS AppDelegate (Swift): ${filePath}`));
436
- return;
437
- }
438
- // Write the import we added but warn about the method
439
- fs_extra_1.default.writeFileSync(filePath, content, 'utf8');
440
- console.log(chalk_1.default.yellow(` ⚠️ Could not find bundleURL() override in ${filePath}.\n` +
441
- ` Please add manually: Debug → Metro, Release → BundleDropLocator.bundleURL() fallback to main.jsbundle.\n` +
442
- ` See ${DOCS_IOS_NATIVE_SETUP_URL}`));
443
- }
444
- function patchIosAppDelegateObjc(filePath) {
445
- let content = fs_extra_1.default.readFileSync(filePath, 'utf8');
446
- const ext = path_1.default.extname(filePath);
447
- if (content.includes('[BundleDropLocator bundleURL]') ||
448
- content.includes('#import <BundleDrop/')) {
449
- console.log(chalk_1.default.gray(` Already patched: ${filePath}`));
450
- return;
451
- }
452
- // Ensure import
453
- const importLine = '#import <BundleDrop/BundleDropLocator.h>';
454
- if (!content.includes(importLine)) {
455
- const reactImport = content.match(/^#import\s+<React\/[^>]+>.*$/m);
456
- if (reactImport) {
457
- content = content.replace(reactImport[0], reactImport[0] + '\n' + importLine);
458
- }
459
- else {
460
- const firstImport = content.match(/^#import\s+.+$/m);
461
- if (firstImport) {
462
- content = content.replace(firstImport[0], firstImport[0] + '\n' + importLine);
463
- }
464
- else {
465
- content = importLine + '\n' + content;
466
- }
467
- }
468
- }
469
- // Patch sourceURLForBridge:
470
- const sourceUrlRegex = /-\s*\(NSURL\s*\*\)\s*sourceURLForBridge\s*:\s*\(RCTBridge\s*\*\)\s*bridge\s*\{[\s\S]*?\n\}/m;
471
- if (sourceUrlRegex.test(content)) {
472
- content = content.replace(sourceUrlRegex, OBJC_SOURCE_URL_BODY);
473
- fs_extra_1.default.writeFileSync(filePath, content, 'utf8');
474
- const label = ext === '.mm' ? 'ObjC++' : 'ObjC';
475
- console.log(chalk_1.default.green(` ✅ Patched iOS AppDelegate (${label}): ${filePath}`));
476
- return;
477
- }
478
- // Write the import we added but warn about the method
479
- fs_extra_1.default.writeFileSync(filePath, content, 'utf8');
480
- console.log(chalk_1.default.yellow(` ⚠️ Could not find sourceURLForBridge: in ${filePath}.\n` +
481
- ` Please locate the method that returns the JS bundle URL and apply the Release OTA fallback.\n` +
482
- ` See ${DOCS_IOS_NATIVE_SETUP_URL}`));
483
- }
484
- function patchIosAppDelegate(filePath) {
485
- const ext = path_1.default.extname(filePath);
486
- console.log(chalk_1.default.cyan(` ✅ Found AppDelegate: ${filePath}`));
487
- if (ext === '.swift') {
488
- patchIosAppDelegateSwift(filePath);
489
- }
490
- else if (ext === '.m' || ext === '.mm') {
491
- patchIosAppDelegateObjc(filePath);
492
- }
493
- else {
494
- console.log(chalk_1.default.yellow(` ⚠️ Unsupported AppDelegate file type (${ext}). Please patch manually.\n` +
495
- ` See ${DOCS_IOS_NATIVE_SETUP_URL}`));
496
- }
497
- }
498
- async function initNativeConfig() {
499
- const projectRoot = findProjectRoot(process.cwd());
500
- const configPath = path_1.default.join(projectRoot, 'bundle.drop.config.js');
501
- if (!fs_extra_1.default.existsSync(configPath)) {
502
- console.log(chalk_1.default.yellow('ℹ️ bundle.drop.config.js not found; run `bundle-drop init` first.'));
503
- return;
504
- }
505
- const { confirm } = await (0, prompts_1.default)({
506
- type: 'confirm',
507
- name: 'confirm',
508
- message: 'Apply BundleDrop native changes to iOS and Android?',
509
- initial: true,
510
- });
511
- if (!confirm) {
512
- console.log(chalk_1.default.gray('ℹ️ Skipping native changes.'));
513
- return;
514
- }
515
- // Android
516
- const androidPath = path_1.default.join(projectRoot, 'android', 'app', 'src', 'main', 'java');
517
- const mainAppKotlin = findFileByName(androidPath, 'MainApplication.kt');
518
- const mainAppJava = findFileByName(androidPath, 'MainApplication.java');
519
- const androidTarget = mainAppKotlin ?? mainAppJava;
520
- if (androidTarget) {
521
- patchAndroidMainApplication(androidTarget);
522
- }
523
- else {
524
- console.log(chalk_1.default.yellow(' ⚠️ Could not locate MainApplication in android/app/src/main/java.'));
525
- }
526
- // iOS — search recursively under ios/ (handles ios/AppDelegate.swift, ios/<ProjectName>/AppDelegate.swift, etc.)
527
- const iosRoot = path_1.default.join(projectRoot, 'ios');
528
- const appDelegateSwift = findFileByName(iosRoot, 'AppDelegate.swift');
529
- const appDelegateObjcpp = findFileByName(iosRoot, 'AppDelegate.mm');
530
- const appDelegateObjc = findFileByName(iosRoot, 'AppDelegate.m');
531
- const iosTarget = appDelegateSwift ?? appDelegateObjcpp ?? appDelegateObjc;
532
- if (iosTarget) {
533
- patchIosAppDelegate(iosTarget);
534
- }
535
- else {
536
- console.log(chalk_1.default.yellow(' ⚠️ Could not locate AppDelegate under ios/.'));
537
- }
538
- }
539
- exports.default = initNativeConfig;