1"use strict";
2var __importDefault = (this && this.__importDefault) || function (mod) {
3    return (mod && mod.__esModule) ? mod : { "default": mod };
4};
5Object.defineProperty(exports, "__esModule", { value: true });
6exports.modifyJavaMainActivity = void 0;
7const config_plugins_1 = require("@expo/config-plugins");
8const fs_1 = __importDefault(require("fs"));
9const path_1 = __importDefault(require("path"));
10const semver_1 = __importDefault(require("semver"));
11const constants_1 = require("./constants");
12const resolveExpoUpdatesVersion_1 = require("./resolveExpoUpdatesVersion");
13const utils_1 = require("./utils");
14const withDevLauncherAppDelegate_1 = require("./withDevLauncherAppDelegate");
15const pkg = require('expo-dev-launcher/package.json');
16const DEV_LAUNCHER_ANDROID_IMPORT = 'expo.modules.devlauncher.DevLauncherController';
17const DEV_LAUNCHER_UPDATES_ANDROID_IMPORT = 'expo.modules.updates.UpdatesDevLauncherController';
18const DEV_LAUNCHER_ON_NEW_INTENT = [
19    '',
20    '  @Override',
21    '  public void onNewIntent(Intent intent) {',
22    '    super.onNewIntent(intent);',
23    '  }',
24    '',
25].join('\n');
26const DEV_LAUNCHER_HANDLE_INTENT = [
27    '    if (DevLauncherController.tryToHandleIntent(this, intent)) {',
28    '      return;',
29    '    }',
30].join('\n');
31const DEV_LAUNCHER_WRAPPED_ACTIVITY_DELEGATE = (activityDelegateDeclaration) => `DevLauncherController.wrapReactActivityDelegate(this, () -> ${activityDelegateDeclaration})`;
32const DEV_LAUNCHER_ANDROID_INIT = 'DevLauncherController.initialize(this, getReactNativeHost());';
33const DEV_LAUNCHER_UPDATES_ANDROID_INIT = `if (BuildConfig.DEBUG) {
34      DevLauncherController.getInstance().setUpdatesInterface(UpdatesDevLauncherController.initialize(this));
35    }`;
36const DEV_LAUNCHER_UPDATES_DEVELOPER_SUPPORT = 'return DevLauncherController.getInstance().getUseDeveloperSupport();';
37const DEV_LAUNCHER_JS_REGISTER_ERROR_HANDLERS_REGEX = /import ['"](?:expo-dev-client|expo-dev-launcher)['"]/;
38async function readFileAsync(path) {
39    return fs_1.default.promises.readFile(path, 'utf8');
40}
41async function saveFileAsync(path, content) {
42    return fs_1.default.promises.writeFile(path, content, 'utf8');
43}
44function findClosingBracketMatchIndex(str, pos) {
45    if (str[pos] !== '(') {
46        throw new Error("No '(' at index " + pos);
47    }
48    let depth = 1;
49    for (let i = pos + 1; i < str.length; i++) {
50        switch (str[i]) {
51            case '(':
52                depth++;
53                break;
54            case ')':
55                if (--depth === 0) {
56                    return i;
57                }
58                break;
59        }
60    }
61    return -1; // No matching closing parenthesis
62}
63const replaceBetween = (origin, startIndex, endIndex, insertion) => `${origin.substring(0, startIndex)}${insertion}${origin.substring(endIndex)}`;
64function addJavaImports(javaSource, javaImports) {
65    const lines = javaSource.split('\n');
66    const lineIndexWithPackageDeclaration = lines.findIndex((line) => line.match(/^package .*;$/));
67    for (const javaImport of javaImports) {
68        if (!javaSource.includes(javaImport)) {
69            const importStatement = `import ${javaImport};`;
70            lines.splice(lineIndexWithPackageDeclaration + 1, 0, importStatement);
71        }
72    }
73    return lines.join('\n');
74}
75async function editMainApplication(config, action) {
76    const mainApplicationPath = path_1.default.join(config.modRequest.platformProjectRoot, 'app', 'src', 'main', 'java', ...config.android.package.split('.'), 'MainApplication.java');
77    try {
78        const mainApplication = action(await readFileAsync(mainApplicationPath));
79        return await saveFileAsync(mainApplicationPath, mainApplication);
80    }
81    catch (e) {
82        config_plugins_1.WarningAggregator.addWarningAndroid('expo-dev-launcher', `Couldn't modify MainApplication.java - ${e}.
83See the expo-dev-client installation instructions to modify your MainApplication.java manually: ${constants_1.InstallationPage}`);
84    }
85}
86async function editPodfile(config, action) {
87    const podfilePath = path_1.default.join(config.modRequest.platformProjectRoot, 'Podfile');
88    try {
89        const podfile = action(await readFileAsync(podfilePath));
90        return await saveFileAsync(podfilePath, podfile);
91    }
92    catch (e) {
93        config_plugins_1.WarningAggregator.addWarningIOS('expo-dev-launcher', `Couldn't modify AppDelegate.m - ${e}.
94See the expo-dev-client installation instructions to modify your AppDelegate.m manually: ${constants_1.InstallationPage}`);
95    }
96}
97async function editIndex(config, action) {
98    const indexPath = path_1.default.join(config.modRequest.projectRoot, 'index.js');
99    try {
100        const index = action(await readFileAsync(indexPath));
101        return await saveFileAsync(indexPath, index);
102    }
103    catch (e) {
104        config_plugins_1.WarningAggregator.addWarningIOS('expo-dev-launcher', `Couldn't modify index.js - ${e}.
105See the expo-dev-client installation instructions to modify your index.js manually: ${constants_1.InstallationPage}`);
106    }
107}
108const withDevLauncherApplication = (config) => {
109    return (0, config_plugins_1.withDangerousMod)(config, [
110        'android',
111        async (config) => {
112            await editMainApplication(config, (mainApplication) => {
113                mainApplication = addJavaImports(mainApplication, [DEV_LAUNCHER_ANDROID_IMPORT]);
114                mainApplication = (0, utils_1.addLines)(mainApplication, 'initializeFlipper\\(this', 0, [
115                    `    ${DEV_LAUNCHER_ANDROID_INIT}`,
116                ]);
117                let expoUpdatesVersion;
118                try {
119                    expoUpdatesVersion = (0, resolveExpoUpdatesVersion_1.resolveExpoUpdatesVersion)(config.modRequest.projectRoot);
120                }
121                catch (e) {
122                    config_plugins_1.WarningAggregator.addWarningAndroid('expo-dev-launcher', `Failed to check compatibility with expo-updates - ${e}`);
123                }
124                if (expoUpdatesVersion && semver_1.default.gt(expoUpdatesVersion, '0.6.0')) {
125                    mainApplication = addJavaImports(mainApplication, [DEV_LAUNCHER_UPDATES_ANDROID_IMPORT]);
126                    mainApplication = (0, utils_1.addLines)(mainApplication, 'initializeFlipper\\(this', 0, [
127                        `    ${DEV_LAUNCHER_UPDATES_ANDROID_INIT}`,
128                    ]);
129                    mainApplication = (0, utils_1.replaceLine)(mainApplication, 'return BuildConfig.DEBUG;', `      ${DEV_LAUNCHER_UPDATES_DEVELOPER_SUPPORT}`);
130                }
131                return mainApplication;
132            });
133            return config;
134        },
135    ]);
136};
137function modifyJavaMainActivity(content) {
138    content = addJavaImports(content, [DEV_LAUNCHER_ANDROID_IMPORT, 'android.content.Intent']);
139    if (!content.includes('onNewIntent')) {
140        const lines = content.split('\n');
141        const onCreateIndex = lines.findIndex((line) => line.includes('public class MainActivity'));
142        lines.splice(onCreateIndex + 1, 0, DEV_LAUNCHER_ON_NEW_INTENT);
143        content = lines.join('\n');
144    }
145    if (!content.includes(DEV_LAUNCHER_HANDLE_INTENT)) {
146        content = (0, utils_1.addLines)(content, /super\.onNewIntent\(intent\)/, 0, [DEV_LAUNCHER_HANDLE_INTENT]);
147    }
148    if (!content.includes('DevLauncherController.wrapReactActivityDelegate')) {
149        const activityDelegateMatches = Array.from(content.matchAll(/new ReactActivityDelegate(Wrapper)/g));
150        if (activityDelegateMatches.length !== 1) {
151            config_plugins_1.WarningAggregator.addWarningAndroid('expo-dev-launcher', `Failed to wrap 'ReactActivityDelegate'
152See the expo-dev-client installation instructions to modify your MainActivity.java manually: ${constants_1.InstallationPage}`);
153            return content;
154        }
155        const activityDelegateMatch = activityDelegateMatches[0];
156        const matchIndex = activityDelegateMatch.index;
157        const openingBracketIndex = matchIndex + activityDelegateMatch[0].length; // next character after `new ReactActivityDelegateWrapper`
158        const closingBracketIndex = findClosingBracketMatchIndex(content, openingBracketIndex);
159        const reactActivityDelegateDeclaration = content.substring(matchIndex, closingBracketIndex + 1);
160        content = replaceBetween(content, matchIndex, closingBracketIndex + 1, DEV_LAUNCHER_WRAPPED_ACTIVITY_DELEGATE(reactActivityDelegateDeclaration));
161    }
162    return content;
163}
164exports.modifyJavaMainActivity = modifyJavaMainActivity;
165const withDevLauncherActivity = (config) => {
166    return (0, config_plugins_1.withMainActivity)(config, (config) => {
167        if (config.modResults.language === 'java') {
168            config.modResults.contents = modifyJavaMainActivity(config.modResults.contents);
169        }
170        else {
171            config_plugins_1.WarningAggregator.addWarningAndroid('expo-dev-launcher', `Cannot automatically configure MainActivity if it's not java.
172See the expo-dev-client installation instructions to modify your MainActivity manually: ${constants_1.InstallationPage}`);
173        }
174        return config;
175    });
176};
177const withDevLauncherPodfile = (config) => {
178    return (0, config_plugins_1.withDangerousMod)(config, [
179        'ios',
180        async (config) => {
181            await editPodfile(config, (podfile) => {
182                // replace all iOS versions below 12
183                podfile = podfile.replace(/platform :ios, '((\d\.0)|(1[0-1].0))'/, "platform :ios, '12.0'");
184                // Match both variations of Ruby config:
185                // unknown: pod 'expo-dev-launcher', path: '../node_modules/expo-dev-launcher', :configurations => :debug
186                // Rubocop: pod 'expo-dev-launcher', path: '../node_modules/expo-dev-launcher', configurations: :debug
187                if (!podfile.match(/pod ['"]expo-dev-launcher['"],\s?path: ['"][^'"]*node_modules\/expo-dev-launcher['"],\s?:?configurations:?\s(?:=>\s)?:debug/)) {
188                    const packagePath = path_1.default.dirname(require.resolve('expo-dev-launcher/package.json'));
189                    const relativePath = path_1.default.relative(config.modRequest.platformProjectRoot, packagePath);
190                    podfile = (0, utils_1.addLines)(podfile, 'use_react_native', 0, [
191                        `  pod 'expo-dev-launcher', path: '${relativePath}', :configurations => :debug`,
192                    ]);
193                }
194                return podfile;
195            });
196            return config;
197        },
198    ]);
199};
200const withErrorHandling = (config) => {
201    const injectErrorHandlers = async (config) => {
202        await editIndex(config, (index) => {
203            if (!DEV_LAUNCHER_JS_REGISTER_ERROR_HANDLERS_REGEX.test(index)) {
204                index = `import 'expo-dev-client';\n\n${index}`;
205            }
206            return index;
207        });
208        return config;
209    };
210    // We need to run the same task twice to ensure it will work on both platforms,
211    // because if someone runs `expo run:ios`, it will trigger only dangerous mode for that specific platform.
212    // Note: after the first execution, the second one won't change anything.
213    config = (0, config_plugins_1.withDangerousMod)(config, ['android', injectErrorHandlers]);
214    config = (0, config_plugins_1.withDangerousMod)(config, ['ios', injectErrorHandlers]);
215    return config;
216};
217const withDevLauncher = (config) => {
218    config = withDevLauncherActivity(config);
219    config = withDevLauncherApplication(config);
220    config = withDevLauncherPodfile(config);
221    config = (0, withDevLauncherAppDelegate_1.withDevLauncherAppDelegate)(config);
222    config = withErrorHandling(config);
223    return config;
224};
225exports.default = (0, config_plugins_1.createRunOncePlugin)(withDevLauncher, pkg.name, pkg.version);
226