"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.patchOldCapacitorPlugins = exports.migrateCommand = void 0;
const tslib_1 = require("tslib");
const utils_fs_1 = require("@ionic/utils-fs");
const path_1 = require("path");
const rimraf_1 = tslib_1.__importDefault(require("rimraf"));
const common_1 = require("../android/common");
const colors_1 = tslib_1.__importDefault(require("../colors"));
const common_2 = require("../common");
const errors_1 = require("../errors");
const log_1 = require("../log");
const plugin_1 = require("../plugin");
const fs_1 = require("../util/fs");
const node_1 = require("../util/node");
const subprocess_1 = require("../util/subprocess");
const template_1 = require("../util/template");
// eslint-disable-next-line prefer-const
let allDependencies = {};
const libs = [
    '@capacitor/core',
    '@capacitor/cli',
    '@capacitor/ios',
    '@capacitor/android',
];
const plugins = [
    '@capacitor/action-sheet',
    '@capacitor/app',
    '@capacitor/app-launcher',
    '@capacitor/browser',
    '@capacitor/camera',
    '@capacitor/clipboard',
    '@capacitor/device',
    '@capacitor/dialog',
    '@capacitor/filesystem',
    '@capacitor/geolocation',
    '@capacitor/google-maps',
    '@capacitor/haptics',
    '@capacitor/keyboard',
    '@capacitor/local-notifications',
    '@capacitor/motion',
    '@capacitor/network',
    '@capacitor/preferences',
    '@capacitor/push-notifications',
    '@capacitor/screen-reader',
    '@capacitor/screen-orientation',
    '@capacitor/share',
    '@capacitor/splash-screen',
    '@capacitor/status-bar',
    '@capacitor/text-zoom',
    '@capacitor/toast',
];
const coreVersion = '^5.0.0';
const pluginVersion = '^5.0.0';
const gradleVersion = '8.0.2';
let installFailed = false;
async function migrateCommand(config, noprompt, packagemanager) {
    if (config === null) {
        (0, errors_1.fatal)('Config data missing');
    }
    const capMajor = await checkCapacitorMajorVersion(config);
    if (capMajor < 4) {
        (0, errors_1.fatal)('Migrate can only be used on capacitor 4 and above, please use the CLI in Capacitor 4 to upgrade to 4 first');
    }
    const jdkMajor = await (0, common_2.checkJDKMajorVersion)();
    if (jdkMajor < 17) {
        log_1.logger.warn('Capacitor 5 requires JDK 17 or higher. Some steps may fail.');
    }
    const variablesAndClasspaths = await getAndroidVariablesAndClasspaths(config);
    if (!variablesAndClasspaths) {
        (0, errors_1.fatal)('Variable and Classpath info could not be read.');
    }
    allDependencies = {
        ...config.app.package.dependencies,
        ...config.app.package.devDependencies,
    };
    const monorepoWarning = 'Please note this tool is not intended for use in a mono-repo enviroment, please check out the Ionic vscode extension for this functionality.';
    log_1.logger.info(monorepoWarning);
    const { migrateconfirm } = noprompt
        ? { migrateconfirm: 'y' }
        : await (0, log_1.logPrompt)(`Capacitor 5 sets a deployment target of iOS 13 and Android 13 (SDK 33). \n`, {
            type: 'text',
            name: 'migrateconfirm',
            message: `Are you sure you want to migrate? (Y/n)`,
            initial: 'y',
        });
    if (typeof migrateconfirm === 'string' &&
        migrateconfirm.toLowerCase() === 'y') {
        try {
            const { depInstallConfirm } = noprompt
                ? { depInstallConfirm: 'y' }
                : await (0, log_1.logPrompt)(`Would you like the migrator to run npm, yarn, or pnpm install to install the latest versions of capacitor packages? (Those using other package managers should answer N)`, {
                    type: 'text',
                    name: 'depInstallConfirm',
                    message: `Run Dependency Install? (Y/n)`,
                    initial: 'y',
                });
            const runNpmInstall = typeof depInstallConfirm === 'string' &&
                depInstallConfirm.toLowerCase() === 'y';
            let installerType = 'npm';
            if (runNpmInstall) {
                const { manager } = packagemanager
                    ? { manager: packagemanager }
                    : await (0, log_1.logPrompt)('What dependency manager do you use?', {
                        type: 'select',
                        name: 'manager',
                        message: `Dependency Management Tool`,
                        choices: [
                            { title: 'NPM', value: 'npm' },
                            { title: 'Yarn', value: 'yarn' },
                            { title: 'PNPM', value: 'pnpm' },
                        ],
                        initial: 0,
                    });
                installerType = manager;
            }
            try {
                await (0, common_2.runTask)(`Installing Latest Modules using ${installerType}.`, () => {
                    return installLatestLibs(installerType, runNpmInstall, config);
                });
            }
            catch (ex) {
                log_1.logger.error(`${installerType} install failed. Try deleting node_modules folder and running ${colors_1.default.input(`${installerType} install --force`)} manually.`);
                installFailed = true;
            }
            // Update iOS Projects
            if (allDependencies['@capacitor/ios'] &&
                (0, utils_fs_1.existsSync)(config.ios.platformDirAbs)) {
                //Update icon to single 1024 x 1024 icon
                await (0, common_2.runTask)('Update App Icon to only 1024 x 1024', () => {
                    return updateAppIcons(config);
                });
                //Remove Podfile.lock from .gitignore
                await (0, common_2.runTask)('Remove Podfile.lock from iOS .gitignore', () => {
                    return updateIosGitIgnore((0, path_1.join)(config.ios.platformDirAbs, '.gitignore'));
                });
            }
            if (allDependencies['@capacitor/android'] &&
                (0, utils_fs_1.existsSync)(config.android.platformDirAbs)) {
                await (0, common_2.runTask)(`Migrating build.gradle file.`, () => {
                    return updateBuildGradle((0, path_1.join)(config.android.platformDirAbs, 'build.gradle'), variablesAndClasspaths);
                });
                // Remove enableJetifier
                await (0, common_2.runTask)('Remove android.enableJetifier=true from gradle.properties', () => {
                    return updateGradleProperties((0, path_1.join)(config.android.platformDirAbs, 'gradle.properties'));
                });
                // Move package from android manifest
                await (0, common_2.runTask)('Migrating package from Manifest to build.gradle', () => {
                    return movePackageFromManifestToBuildGradle((0, path_1.join)(config.android.platformDirAbs, 'app', 'src', 'main', 'AndroidManifest.xml'), (0, path_1.join)(config.android.platformDirAbs, 'app', 'build.gradle'));
                });
                // Update gradle-wrapper.properties
                await (0, common_2.runTask)(`Migrating gradle-wrapper.properties by updating gradle version to ${gradleVersion}.`, () => {
                    return updateGradleWrapper((0, path_1.join)(config.android.platformDirAbs, 'gradle', 'wrapper', 'gradle-wrapper.properties'));
                });
                // Variables gradle
                await (0, common_2.runTask)(`Migrating variables.gradle file.`, () => {
                    return (async () => {
                        const variablesPath = (0, path_1.join)(config.android.platformDirAbs, 'variables.gradle');
                        let txt = readFile(variablesPath);
                        if (!txt) {
                            return;
                        }
                        txt = txt.replace(/= {2}'/g, `= '`);
                        (0, utils_fs_1.writeFileSync)(variablesPath, txt, { encoding: 'utf-8' });
                        for (const variable of Object.keys(variablesAndClasspaths.variables)) {
                            if (!(await updateFile(config, variablesPath, `${variable} = '`, `'`, variablesAndClasspaths.variables[variable].toString(), true))) {
                                const didWork = await updateFile(config, variablesPath, `${variable} = `, `\n`, variablesAndClasspaths.variables[variable].toString(), true);
                                if (!didWork) {
                                    let file = readFile(variablesPath);
                                    if (file) {
                                        file = file.replace('}', `    ${variable} = '${variablesAndClasspaths.variables[variable].toString()}'\n}`);
                                        (0, utils_fs_1.writeFileSync)(variablesPath, file);
                                    }
                                }
                            }
                        }
                        const pluginVariables = {
                            firebaseMessagingVersion: '23.1.2',
                            playServicesLocationVersion: '21.0.1',
                            androidxBrowserVersion: '1.5.0',
                            androidxMaterialVersion: '1.8.0',
                            androidxExifInterfaceVersion: '1.3.6',
                            androidxCoreKTXVersion: '1.10.0',
                            googleMapsPlayServicesVersion: '18.1.0',
                            googleMapsUtilsVersion: '3.4.0',
                            googleMapsKtxVersion: '3.4.0',
                            googleMapsUtilsKtxVersion: '3.4.0',
                            kotlinxCoroutinesVersion: '1.6.4',
                        };
                        for (const variable of Object.keys(pluginVariables)) {
                            await updateFile(config, variablesPath, `${variable} = '`, `'`, pluginVariables[variable], true);
                        }
                    })();
                });
                rimraf_1.default.sync((0, path_1.join)(config.android.appDirAbs, 'build'));
                if (!installFailed) {
                    await (0, common_2.runTask)('Migrating package from Manifest to build.gradle in Capacitor plugins', () => {
                        return patchOldCapacitorPlugins(config);
                    });
                }
                else {
                    log_1.logger.warn('Skipped migrating package from Manifest to build.gradle in Capacitor plugins');
                }
            }
            if (!installFailed) {
                // Run Cap Sync
                await (0, common_2.runTask)(`Running cap sync.`, () => {
                    return (0, subprocess_1.getCommandOutput)('npx', ['cap', 'sync']);
                });
            }
            else {
                log_1.logger.warn('Skipped Running cap sync.');
            }
            if (allDependencies['@capacitor/android'] &&
                (0, utils_fs_1.existsSync)(config.android.platformDirAbs)) {
                if (!installFailed) {
                    try {
                        await (0, common_2.runTask)(`Upgrading gradle wrapper files`, () => {
                            return updateGradleWrapperFiles(config.android.platformDirAbs);
                        });
                    }
                    catch (e) {
                        if (e.includes('EACCES')) {
                            log_1.logger.error(`gradlew file does not have executable permissions. This can happen if the Android platform was added on a Windows machine. Please run ${colors_1.default.input(`chmod +x ./${config.android.platformDir}/gradlew`)} and ${colors_1.default.input(`cd ${config.android.platformDir} && ./gradlew wrapper --distribution-type all --gradle-version ${gradleVersion} --warning-mode all`)} to update the files manually`);
                        }
                        else {
                            log_1.logger.error(`gradle wrapper files were not updated`);
                        }
                    }
                }
                else {
                    log_1.logger.warn('Skipped upgrading gradle wrapper files');
                }
            }
            // Write all breaking changes
            await (0, common_2.runTask)(`Writing breaking changes.`, () => {
                return writeBreakingChanges();
            });
            if (!installFailed) {
                (0, log_1.logSuccess)(`Migration to Capacitor ${coreVersion} is complete. Run and test your app!`);
            }
            else {
                log_1.logger.warn(`Migration to Capacitor ${coreVersion} is incomplete. Check the log messages for more information.`);
            }
        }
        catch (err) {
            (0, errors_1.fatal)(`Failed to migrate: ${err}`);
        }
    }
    else {
        (0, errors_1.fatal)(`User canceled migration.`);
    }
}
exports.migrateCommand = migrateCommand;
async function checkCapacitorMajorVersion(config) {
    var _a;
    const capacitorVersion = await (0, common_2.getCoreVersion)(config);
    const versionArray = (_a = capacitorVersion.match(/([0-9]+)\.([0-9]+)\.([0-9]+)/)) !== null && _a !== void 0 ? _a : [];
    const majorVersion = parseInt(versionArray[1]);
    return majorVersion;
}
async function installLatestLibs(dependencyManager, runInstall, config) {
    const pkgJsonPath = (0, path_1.join)(config.app.rootDir, 'package.json');
    const pkgJsonFile = readFile(pkgJsonPath);
    if (!pkgJsonFile) {
        return;
    }
    const pkgJson = JSON.parse(pkgJsonFile);
    for (const devDepKey of Object.keys(pkgJson['devDependencies'] || {})) {
        if (libs.includes(devDepKey)) {
            pkgJson['devDependencies'][devDepKey] = coreVersion;
        }
        else if (plugins.includes(devDepKey)) {
            pkgJson['devDependencies'][devDepKey] = pluginVersion;
        }
    }
    for (const depKey of Object.keys(pkgJson['dependencies'] || {})) {
        if (libs.includes(depKey)) {
            pkgJson['dependencies'][depKey] = coreVersion;
        }
        else if (plugins.includes(depKey)) {
            pkgJson['dependencies'][depKey] = pluginVersion;
        }
    }
    (0, utils_fs_1.writeFileSync)(pkgJsonPath, JSON.stringify(pkgJson, null, 2), {
        encoding: 'utf-8',
    });
    if (runInstall) {
        rimraf_1.default.sync((0, path_1.join)(config.app.rootDir, 'node_modules/@capacitor/!(cli)'));
        await (0, subprocess_1.runCommand)(dependencyManager, ['install']);
        if (dependencyManager == 'yarn') {
            await (0, subprocess_1.runCommand)(dependencyManager, ['upgrade']);
        }
        else {
            await (0, subprocess_1.runCommand)(dependencyManager, ['update']);
        }
    }
    else {
        log_1.logger.info(`Please run an install command with your package manager of choice. (ex: yarn install)`);
    }
}
async function writeBreakingChanges() {
    const breaking = [
        '@capacitor/camera',
        '@capacitor/device',
        '@capacitor/local-notifications',
        '@capacitor/push-notifications',
    ];
    const broken = [];
    for (const lib of breaking) {
        if (allDependencies[lib]) {
            broken.push(lib);
        }
    }
    if (broken.length > 0) {
        log_1.logger.info(`IMPORTANT: Review https://capacitorjs.com/docs/updating/5-0#plugins for breaking changes in these plugins that you use: ${broken.join(', ')}.`);
    }
}
async function getAndroidVariablesAndClasspaths(config) {
    const tempAndroidTemplateFolder = (0, path_1.join)(config.cli.assetsDirAbs, 'tempAndroidTemplate');
    await (0, template_1.extractTemplate)(config.cli.assets.android.platformTemplateArchiveAbs, tempAndroidTemplateFolder);
    const variablesGradleFile = readFile((0, path_1.join)(tempAndroidTemplateFolder, 'variables.gradle'));
    const buildGradleFile = readFile((0, path_1.join)(tempAndroidTemplateFolder, 'build.gradle'));
    if (!variablesGradleFile || !buildGradleFile) {
        return;
    }
    (0, fs_1.deleteFolderRecursive)(tempAndroidTemplateFolder);
    const firstIndxOfCATBGV = buildGradleFile.indexOf(`classpath 'com.android.tools.build:gradle:`) + 42;
    const firstIndxOfCGGGS = buildGradleFile.indexOf(`com.google.gms:google-services:`) + 31;
    const comAndroidToolsBuildGradleVersion = '' +
        buildGradleFile.substring(firstIndxOfCATBGV, buildGradleFile.indexOf("'", firstIndxOfCATBGV));
    const comGoogleGmsGoogleServices = '' +
        buildGradleFile.substring(firstIndxOfCGGGS, buildGradleFile.indexOf("'", firstIndxOfCGGGS));
    const variablesGradleAsJSON = JSON.parse(variablesGradleFile
        .replace('ext ', '')
        .replace(/=/g, ':')
        .replace(/\n/g, ',')
        .replace(/,([^:]+):/g, function (_k, p1) {
        return `,"${p1}":`;
    })
        .replace('{,', '{')
        .replace(',}', '}')
        .replace(/\s/g, '')
        .replace(/'/g, '"'));
    return {
        'variables': variablesGradleAsJSON,
        'com.android.tools.build:gradle': comAndroidToolsBuildGradleVersion,
        'com.google.gms:google-services': comGoogleGmsGoogleServices,
    };
}
function readFile(filename) {
    try {
        if (!(0, utils_fs_1.existsSync)(filename)) {
            log_1.logger.error(`Unable to find ${filename}. Try updating it manually`);
            return;
        }
        return (0, utils_fs_1.readFileSync)(filename, 'utf-8');
    }
    catch (err) {
        log_1.logger.error(`Unable to read ${filename}. Verify it is not already open. ${err}`);
    }
}
async function updateGradleWrapper(filename) {
    const txt = readFile(filename);
    if (!txt) {
        return;
    }
    const replaced = setAllStringIn(txt, 'distributionUrl=', '\n', 
    // eslint-disable-next-line no-useless-escape
    `https\\://services.gradle.org/distributions/gradle-${gradleVersion}-all.zip`);
    (0, utils_fs_1.writeFileSync)(filename, replaced, 'utf-8');
}
async function updateGradleWrapperFiles(platformDir) {
    await (0, subprocess_1.runCommand)(`./gradlew`, [
        'wrapper',
        '--distribution-type',
        'all',
        '--gradle-version',
        gradleVersion,
        '--warning-mode',
        'all',
    ], {
        cwd: platformDir,
    });
}
async function updateIosGitIgnore(filename) {
    const txt = readFile(filename);
    if (!txt) {
        return;
    }
    const lines = txt.split('\n');
    let linesToKeep = '';
    for (const line of lines) {
        // check for enableJetifier
        const podfileMatch = line.match(/.+Podfile\.lock/) || [];
        if (podfileMatch.length == 0) {
            linesToKeep += line + '\n';
        }
    }
    (0, utils_fs_1.writeFileSync)(filename, linesToKeep, { encoding: 'utf-8' });
}
async function updateAppIcons(config) {
    const iconToKeep = 'AppIcon-512@2x.png';
    const contentsFile = 'Contents.json';
    const newContentsFileContents = `{
    "images" : [
      {
        "filename" : "${iconToKeep}",
        "idiom" : "universal",
        "platform" : "ios",
        "size" : "1024x1024"
      }
    ],
    "info" : {
      "author" : "xcode",
      "version" : 1
    }
}`;
    const path = (0, path_1.join)(config.ios.platformDirAbs, 'App', 'App', 'Assets.xcassets', 'AppIcon.appiconset');
    if (!(0, utils_fs_1.existsSync)(path)) {
        log_1.logger.error(`Unable to find ${path}. Try updating it manually`);
        return;
    }
    if (!(0, utils_fs_1.existsSync)((0, path_1.join)(path, iconToKeep))) {
        log_1.logger.error(`Unable to find ${iconToKeep}. Try updating it manually`);
        return;
    }
    if (!(0, utils_fs_1.existsSync)((0, path_1.join)(path, contentsFile))) {
        log_1.logger.error(`Unable to find ${path}. Try updating it manually`);
        return;
    }
    const filenames = (0, utils_fs_1.readdirSync)(path);
    for (const filename of filenames) {
        if (filename != iconToKeep && filename != contentsFile) {
            (0, utils_fs_1.removeSync)((0, path_1.join)(path, filename));
        }
    }
    (0, utils_fs_1.writeFileSync)((0, path_1.join)(path, contentsFile), newContentsFileContents);
}
async function updateGradleProperties(filename) {
    const txt = readFile(filename);
    if (!txt) {
        return;
    }
    const lines = txt.split('\n');
    let linesToKeep = '';
    for (const line of lines) {
        // check for enableJetifier
        const jetifierMatch = line.match(/android\.enableJetifier\s*=\s*true/) || [];
        const commentMatch = line.match(/# Automatically convert third-party libraries to use AndroidX/) || [];
        if (jetifierMatch.length == 0 && commentMatch.length == 0) {
            linesToKeep += line + '\n';
        }
    }
    (0, utils_fs_1.writeFileSync)(filename, linesToKeep, { encoding: 'utf-8' });
}
async function movePackageFromManifestToBuildGradle(manifestFilename, buildGradleFilename) {
    const manifestText = readFile(manifestFilename);
    const buildGradleText = readFile(buildGradleFilename);
    if (!manifestText) {
        log_1.logger.error(`Could not read ${manifestFilename}. Check its permissions and if it exists.`);
        return;
    }
    if (!buildGradleText) {
        log_1.logger.error(`Could not read ${buildGradleFilename}. Check its permissions and if it exists.`);
        return;
    }
    const namespaceExists = new RegExp(/\s+namespace\s+/).test(buildGradleText);
    if (namespaceExists) {
        log_1.logger.error('Found namespace in build.gradle already, skipping migration');
        return;
    }
    let packageName;
    const manifestRegEx = new RegExp(/package="([^"]+)"/);
    const manifestResults = manifestRegEx.exec(manifestText);
    if (manifestResults === null) {
        log_1.logger.error(`Unable to update Android Manifest. Package not found.`);
        return;
    }
    else {
        packageName = manifestResults[1];
    }
    let manifestReplaced = manifestText;
    manifestReplaced = manifestReplaced.replace(manifestRegEx, '');
    if (manifestText == manifestReplaced) {
        log_1.logger.error(`Unable to update Android Manifest: no changes were detected in Android Manifest file`);
        return;
    }
    let buildGradleReplaced = buildGradleText;
    buildGradleReplaced = setAllStringIn(buildGradleText, 'android {', '\n', `\n    namespace "${packageName}"`);
    if (buildGradleText == buildGradleReplaced) {
        log_1.logger.error(`Unable to update buildGradleText: no changes were detected in Android Manifest file`);
        return;
    }
    (0, utils_fs_1.writeFileSync)(manifestFilename, manifestReplaced, 'utf-8');
    (0, utils_fs_1.writeFileSync)(buildGradleFilename, buildGradleReplaced, 'utf-8');
}
async function updateBuildGradle(filename, variablesAndClasspaths) {
    // In build.gradle add dependencies:
    // classpath 'com.android.tools.build:gradle:8.0.0'
    // classpath 'com.google.gms:google-services:4.3.15'
    const txt = readFile(filename);
    if (!txt) {
        return;
    }
    const neededDeps = {
        'com.android.tools.build:gradle': variablesAndClasspaths['com.android.tools.build:gradle'],
        'com.google.gms:google-services': variablesAndClasspaths['com.google.gms:google-services'],
    };
    let replaced = txt;
    for (const dep of Object.keys(neededDeps)) {
        if (replaced.includes(`classpath '${dep}`)) {
            const semver = await Promise.resolve().then(() => tslib_1.__importStar(require('semver')));
            const firstIndex = replaced.indexOf(dep) + dep.length + 1;
            const existingVersion = '' + replaced.substring(firstIndex, replaced.indexOf("'", firstIndex));
            if (semver.gte(neededDeps[dep], existingVersion)) {
                replaced = setAllStringIn(replaced, `classpath '${dep}:`, `'`, neededDeps[dep]);
                log_1.logger.info(`Set ${dep} = ${neededDeps[dep]}.`);
            }
        }
    }
    (0, utils_fs_1.writeFileSync)(filename, replaced, 'utf-8');
}
async function updateFile(config, filename, textStart, textEnd, replacement, skipIfNotFound) {
    if (config === null) {
        return false;
    }
    const path = filename;
    let txt = readFile(path);
    if (!txt) {
        return false;
    }
    if (txt.includes(textStart)) {
        if (replacement) {
            txt = setAllStringIn(txt, textStart, textEnd, replacement);
            (0, utils_fs_1.writeFileSync)(path, txt, { encoding: 'utf-8' });
        }
        else {
            // Replacing in code so we need to count the number of brackets to find the end of the function in swift
            const lines = txt.split('\n');
            let replaced = '';
            let keep = true;
            let brackets = 0;
            for (const line of lines) {
                if (line.includes(textStart)) {
                    keep = false;
                }
                if (!keep) {
                    brackets += (line.match(/{/g) || []).length;
                    brackets -= (line.match(/}/g) || []).length;
                    if (brackets == 0) {
                        keep = true;
                    }
                }
                else {
                    replaced += line + '\n';
                }
            }
            (0, utils_fs_1.writeFileSync)(path, replaced, { encoding: 'utf-8' });
        }
        return true;
    }
    else if (!skipIfNotFound) {
        log_1.logger.error(`Unable to find "${textStart}" in ${filename}. Try updating it manually`);
    }
    return false;
}
function setAllStringIn(data, start, end, replacement) {
    let position = 0;
    let result = data;
    let replaced = true;
    while (replaced) {
        const foundIdx = result.indexOf(start, position);
        if (foundIdx == -1) {
            replaced = false;
        }
        else {
            const idx = foundIdx + start.length;
            position = idx + replacement.length;
            result =
                result.substring(0, idx) +
                    replacement +
                    result.substring(result.indexOf(end, idx));
        }
    }
    return result;
}
async function patchOldCapacitorPlugins(config) {
    const allPlugins = await (0, plugin_1.getPlugins)(config, 'android');
    const androidPlugins = await (0, common_1.getAndroidPlugins)(allPlugins);
    return await Promise.all(androidPlugins.map(async (p) => {
        var _a, _b;
        if ((_b = (_a = p.manifest) === null || _a === void 0 ? void 0 : _a.android) === null || _b === void 0 ? void 0 : _b.src) {
            const buildGradlePath = (0, node_1.resolveNode)(config.app.rootDir, p.id, p.manifest.android.src, 'build.gradle');
            const manifestPath = (0, node_1.resolveNode)(config.app.rootDir, p.id, p.manifest.android.src, 'src', 'main', 'AndroidManifest.xml');
            if (buildGradlePath && manifestPath) {
                const gradleContent = readFile(buildGradlePath);
                if (!(gradleContent === null || gradleContent === void 0 ? void 0 : gradleContent.includes('namespace'))) {
                    if (plugins.includes(p.id)) {
                        log_1.logger.warn(`You are using an outdated version of ${p.id}, update the plugin to version ${pluginVersion}`);
                    }
                    else {
                        log_1.logger.warn(`${p.id}@${p.version} doesn't officially support Capacitor ${coreVersion} yet, doing our best moving it's package to build.gradle so it builds`);
                    }
                    movePackageFromManifestToBuildGradle(manifestPath, buildGradlePath);
                }
            }
        }
    }));
}
exports.patchOldCapacitorPlugins = patchOldCapacitorPlugins;
