From 389aa019075685f167840966a44e20b52f711e23 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Fri, 27 Nov 2026 16:58:02 -0300 Subject: [PATCH 1/4] fix(android): give plugins with clashing short names unique aar names The CLI names a plugin's aar, its temp build project and the `org.nativescript.` namespace fallback after the plugin's short name, which drops the npm scope. Two scoped plugins with the same name, such as `@foo/plugin-x` and `@bar/plugin-x`, therefore both build `plugin_x.aar`, share `platforms/tempPlugin/plugin_x` and get the same fallback namespace. Which plugin's code ends up linked depends on the order they are built in. Each native Android plugin now gets an aar name that is unique in the project. A plugin whose short name no other native plugin shares keeps it, so projects without a clash build exactly as before: same dependencies.json, same aar names and paths. Within a group of plugins that share a short name, scoped plugins get `_` (the scope without `@`, with characters other than [A-Za-z0-9_] replaced by `_`), an unscoped plugin keeps its short name, and a name that would start with a digit gets a leading `_`. The result does not depend on the order of the dependencies. If two plugins still end up with the same name, prepare fails and names both packages. `ns plugin build` is unchanged. Old Gradle templates add every *.aar in a plugin's platforms/android to the app, so an aar the CLI built under the plugin's previous name would add duplicate classes. When the CLI builds a plugin (it has a manifest or Android sources), each aar in its platforms/android named after another of its candidate names is handled as follows: - the plain short name: earlier CLIs always copied the built aar to `.aar`, overwriting anything the package shipped under that name, so the file is a leftover and is deleted; - the scope-qualified name: only this CLI builds it, so the file is a leftover only when `//build.gradle` sets `project.ext.PLUGIN_NAME` to this plugin's npm name and the temp project has a build output at `//build/outputs/aar/-release.aar`. If the file is byte-identical to that output it is deleted; if it differs, prepare fails with both paths and asks to delete it or run `ns clean`. Otherwise the package ships it and it is left alone. Aars of plugins the CLI does not build are never deleted or flagged. The Android project service reports a plugin for reprepare while its aar is missing under the new name or a leftover is still there, so upgrading the CLI on a project with a clash rebuilds the renamed aars and deletes the old `.aar` in each clashing plugin. --- lib/common/helpers.ts | 65 ++++ lib/common/test/unit-tests/helpers.ts | 125 +++++++ lib/definitions/android-plugin-migrator.d.ts | 10 + lib/services/android-plugin-build-service.ts | 182 ++++++++-- lib/services/android-project-service.ts | 107 +++++- test/services/android-plugin-build-service.ts | 312 +++++++++++++++++- test/services/android-project-service.ts | 260 ++++++++++++++- test/stubs.ts | 4 + 8 files changed, 1006 insertions(+), 59 deletions(-) diff --git a/lib/common/helpers.ts b/lib/common/helpers.ts index 095743db5e..c73ca2eee2 100644 --- a/lib/common/helpers.ts +++ b/lib/common/helpers.ts @@ -125,6 +125,71 @@ function sanitizePluginName(pluginName: string): string { return pluginName.split("/").pop(); } +function getScopeQualifiedPluginName(pluginName: string): string | null { + const parts = pluginName.split("/"); + if (parts.length < 2 || !parts[0].startsWith("@")) { + return null; + } + + const scope = parts[0].slice(1).replace(/[^A-Za-z0-9_]/g, "_"); + return `${scope}_${getShortPluginName(pluginName)}`; +} + +// The aar name doubles as a Java package segment (the `org.nativescript.` +// namespace fallback), which cannot start with a digit. +function withoutLeadingDigit(name: string): string { + return /^[0-9]/.test(name) ? `_${name}` : name; +} + +/** + * Maps each plugin name to a file-system and Java-package safe name for its aar + * that is unique among `pluginNames`. A plugin whose short name is not shared + * keeps `getShortPluginName(name)`, so projects without clashes keep their names. + * Throws if two plugins still end up with the same name. + */ +export function getUniqueShortPluginNames( + pluginNames: string[], +): Map { + const sortedNames = _.sortBy(_.uniq(pluginNames)); + const namesByShortName = _.groupBy(sortedNames, getShortPluginName); + const result = new Map(); + const owners = new Map(); + + for (const pluginName of sortedNames) { + const shortName = getShortPluginName(pluginName); + const aarName = + namesByShortName[shortName].length === 1 + ? shortName + : withoutLeadingDigit( + getScopeQualifiedPluginName(pluginName) ?? shortName, + ); + + const owner = owners.get(aarName); + if (owner !== undefined) { + throw new Error( + `The plugins "${owner}" and "${pluginName}" both need the Android aar name "${aarName}". Remove one of them from the project.`, + ); + } + + owners.set(aarName, pluginName); + result.set(pluginName, aarName); + } + + return result; +} + +/** + * Every aar name `getUniqueShortPluginNames` can give this plugin, depending on + * which other plugins are installed. + */ +export function getCandidateAarNames(pluginName: string): string[] { + const shortName = getShortPluginName(pluginName); + return _.uniq([ + shortName, + withoutLeadingDigit(getScopeQualifiedPluginName(pluginName) ?? shortName), + ]); +} + export async function executeActionByChunks( initialData: T[] | IDictionary, chunkSize: number, diff --git a/lib/common/test/unit-tests/helpers.ts b/lib/common/test/unit-tests/helpers.ts index 39db1dbdf2..ee5aa542f3 100644 --- a/lib/common/test/unit-tests/helpers.ts +++ b/lib/common/test/unit-tests/helpers.ts @@ -1111,4 +1111,129 @@ const test = require("./test");`, assert.deepStrictEqual(seen.sink, ["kept"]); }); }); + + describe("getUniqueShortPluginNames", () => { + const toObject = (names: string[]) => + Object.fromEntries(helpers.getUniqueShortPluginNames(names)); + + it("keeps the short name of plugins without a clash", () => { + assert.deepStrictEqual( + toObject([ + "@nativescript/core", + "nativescript-plugin", + "@scope/my-plugin", + "9-lives", + ]), + { + "@nativescript/core": "core", + "nativescript-plugin": "nativescript_plugin", + "@scope/my-plugin": "my_plugin", + "9-lives": "9_lives", + }, + ); + }); + + it("qualifies clashing scoped plugins with their scope", () => { + assert.deepStrictEqual( + toObject(["@foo/plugin-x", "@bar/plugin-x", "@nativescript/core"]), + { + "@foo/plugin-x": "foo_plugin_x", + "@bar/plugin-x": "bar_plugin_x", + "@nativescript/core": "core", + }, + ); + }); + + it("lets an unscoped plugin keep its name when it clashes with a scoped one", () => { + assert.deepStrictEqual(toObject(["plugin-x", "@foo/plugin-x"]), { + "plugin-x": "plugin_x", + "@foo/plugin-x": "foo_plugin_x", + }); + }); + + it("replaces characters a scope may contain but a name may not", () => { + assert.deepStrictEqual(toObject(["@my.org~x/plugin", "@a/plugin"]), { + "@my.org~x/plugin": "my_org_x_plugin", + "@a/plugin": "a_plugin", + }); + }); + + it("prefixes clashing names that would start with a digit", () => { + assert.deepStrictEqual(toObject(["@1password/plugin", "@a/plugin"]), { + "@1password/plugin": "_1password_plugin", + "@a/plugin": "a_plugin", + }); + assert.deepStrictEqual(toObject(["9-lives", "@a/9-lives"]), { + "9-lives": "_9_lives", + "@a/9-lives": "a_9_lives", + }); + }); + + it("fails when two plugins still share a name", () => { + assert.throws( + () => + helpers.getUniqueShortPluginNames(["@foo/plugin-x", "@foo/plugin_x"]), + /"@foo\/plugin-x" and "@foo\/plugin_x"/, + ); + assert.throws( + () => + helpers.getUniqueShortPluginNames([ + "foo-plugin-x", + "@foo/plugin-x", + "@bar/plugin-x", + ]), + /"@foo\/plugin-x" and "foo-plugin-x".*"foo_plugin_x"/, + ); + }); + + it("does not depend on the order of the plugins", () => { + const names = ["@foo/plugin-x", "plugin-x", "@bar/plugin-x", "other"]; + const expected = toObject(names); + assert.deepStrictEqual(toObject([...names].reverse()), expected); + assert.deepStrictEqual( + toObject([names[2], names[0], names[3], names[1]]), + expected, + ); + assert.throws( + () => + helpers.getUniqueShortPluginNames(["@foo/plugin_x", "@foo/plugin-x"]), + /"@foo\/plugin-x" and "@foo\/plugin_x"/, + ); + }); + }); + + describe("getCandidateAarNames", () => { + it("lists the short and the scope-qualified name of a scoped plugin", () => { + assert.deepStrictEqual(helpers.getCandidateAarNames("@foo/plugin-x"), [ + "plugin_x", + "foo_plugin_x", + ]); + }); + + it("lists the short name of an unscoped plugin", () => { + assert.deepStrictEqual(helpers.getCandidateAarNames("plugin-x"), [ + "plugin_x", + ]); + assert.deepStrictEqual(helpers.getCandidateAarNames("9-lives"), [ + "9_lives", + "_9_lives", + ]); + }); + + it("covers every name getUniqueShortPluginNames gives", () => { + const projects = [ + ["@foo/plugin-x"], + ["@foo/plugin-x", "@bar/plugin-x"], + ["plugin-x", "@foo/plugin-x"], + ["@1a/plugin", "@b/plugin", "plugin", "9-lives", "@c/9-lives"], + ]; + for (const project of projects) { + for (const [name, aarName] of helpers.getUniqueShortPluginNames( + project, + )) { + assert.include(helpers.getCandidateAarNames(name), aarName); + } + } + }); + }); }); diff --git a/lib/definitions/android-plugin-migrator.d.ts b/lib/definitions/android-plugin-migrator.d.ts index f5ad873307..b787557e7e 100644 --- a/lib/definitions/android-plugin-migrator.d.ts +++ b/lib/definitions/android-plugin-migrator.d.ts @@ -3,6 +3,11 @@ import { IProjectDir } from "../common/declarations"; interface IPluginBuildOptions extends IAndroidBuildOptions { projectDir?: string; + /** + * File name (without extension) of the built aar and of its temp build dir. + * Defaults to the plugin's short name. + */ + aarName?: string; } interface IAndroidBuildOptions { @@ -17,6 +22,11 @@ interface IAndroidBuildOptions { interface IAndroidPluginBuildService { buildAar(options: IPluginBuildOptions): Promise; migrateIncludeGradle(options: IPluginBuildOptions): boolean; + /** + * Whether the plugin has sources to build but `aarOutputDir` lacks its aar + * or still holds one the CLI built under another of its candidate names. + */ + hasOutdatedAar(options: IPluginBuildOptions): boolean; } /** diff --git a/lib/services/android-plugin-build-service.ts b/lib/services/android-plugin-build-service.ts index 88098d55b0..901a06bcbb 100644 --- a/lib/services/android-plugin-build-service.ts +++ b/lib/services/android-plugin-build-service.ts @@ -8,7 +8,12 @@ import { PLUGIN_BUILD_DATA_FILENAME, SCOPED_ANDROID_RUNTIME_NAME, } from "../constants"; -import { getShortPluginName, hook, quoteString } from "../common/helpers"; +import { + getCandidateAarNames, + getShortPluginName, + hook, + quoteString, +} from "../common/helpers"; import { Builder, parseString } from "xml2js"; import { IRuntimeGradleVersions, @@ -39,6 +44,15 @@ import * as _ from "lodash"; import { resolvePackageJSONPath } from "@rigor789/resolve-package-path"; import { cwd } from "process"; +interface IStaleAar { + aarPath: string; + /** + * The CLI's earlier build output the aar must match to be deleted. Absent + * when the aar is deleted whatever its content. + */ + previousOutputPath?: string; +} + export class AndroidPluginBuildService implements IAndroidPluginBuildService { private get $platformsDataService(): IPlatformsDataService { return this.$injector.resolve("platformsDataService"); @@ -226,19 +240,26 @@ export class AndroidPluginBuildService implements IAndroidPluginBuildService { const androidSourceDirectories = this.getAndroidSourceDirectories( options.platformsAndroidDirPath, ); - const shortPluginName = getShortPluginName(options.pluginName); - const pluginTempDir = path.join(options.tempPluginDirPath, shortPluginName); + const aarName = this.getAarName(options); + const pluginTempDir = path.join(options.tempPluginDirPath, aarName); + const staleAars = + options.aarName && (manifestFilePath || androidSourceDirectories.length) + ? this.getStaleAars(options, aarName) + : []; const pluginSourceFileHashesInfo = await this.getSourceFilesHashes( options.platformsAndroidDirPath, - shortPluginName, + [ + path.join(options.platformsAndroidDirPath, `${aarName}.aar`), + ...staleAars.map((staleAar) => staleAar.aarPath), + ], ); + this.removeStaleAars(options.pluginName, staleAars); const shouldBuildAar = await this.shouldBuildAar({ manifestFilePath, androidSourceDirectories, pluginTempDir, - pluginSourceDir: options.platformsAndroidDirPath, - shortPluginName, + aarPath: path.join(this.getAarOutputDir(options), `${aarName}.aar`), fileHashesInfo: pluginSourceFileHashesInfo, }); @@ -249,7 +270,7 @@ export class AndroidPluginBuildService implements IAndroidPluginBuildService { await this.updateManifest( manifestFilePath, pluginTempMainSrcDir, - shortPluginName, + aarName, ); this.copySourceSetDirectories( androidSourceDirectories, @@ -260,6 +281,7 @@ export class AndroidPluginBuildService implements IAndroidPluginBuildService { options.platformsAndroidDirPath, options.projectDir, options.pluginName, + aarName, ); await this.buildPlugin({ gradlePath: options.gradlePath, @@ -269,15 +291,134 @@ export class AndroidPluginBuildService implements IAndroidPluginBuildService { projectDir: options.projectDir, }); this.$watchIgnoreListService.addFileToIgnoreList( - path.join(options.aarOutputDir, `${shortPluginName}.aar`), + path.join(options.aarOutputDir, `${aarName}.aar`), ); - this.copyAar(shortPluginName, pluginTempDir, options.aarOutputDir); + this.copyAar(aarName, pluginTempDir, options.aarOutputDir); this.writePluginHashInfo(pluginSourceFileHashesInfo, pluginTempDir); } return shouldBuildAar; } + public hasOutdatedAar(options: IPluginBuildOptions): boolean { + if ( + !this.$fs.exists(options.platformsAndroidDirPath) || + (!this.getManifest(options.platformsAndroidDirPath) && + !this.getAndroidSourceDirectories(options.platformsAndroidDirPath) + .length) + ) { + return false; + } + + const aarName = this.getAarName(options); + return ( + !this.$fs.exists( + path.join(this.getAarOutputDir(options), `${aarName}.aar`), + ) || this.getStaleAars(options, aarName).length > 0 + ); + } + + private getAarName(options: IPluginBuildOptions): string { + return options.aarName ?? getShortPluginName(options.pluginName); + } + + private getAarOutputDir(options: IPluginBuildOptions): string { + return options.aarOutputDir || options.platformsAndroidDirPath; + } + + /** + * Aars in `aarOutputDir` under another of the plugin's candidate names that + * the CLI built. Earlier CLIs copied every built plugin's aar to + * `.aar`, overwriting any file the package shipped under that + * name, so that file is always a leftover. A scope-qualified name is only + * ever built by this plugin, so that file is a leftover only if the temp + * project for the name was set up for this plugin and has a build output to + * compare it with; otherwise the package ships it. + */ + private getStaleAars( + options: IPluginBuildOptions, + aarName: string, + ): IStaleAar[] { + const aarOutputDir = this.getAarOutputDir(options); + const shortName = getShortPluginName(options.pluginName); + const staleAars: IStaleAar[] = []; + for (const candidate of getCandidateAarNames(options.pluginName)) { + const aarPath = path.join(aarOutputDir, `${candidate}.aar`); + if (candidate === aarName || !this.$fs.exists(aarPath)) { + continue; + } + + if (candidate === shortName) { + staleAars.push({ aarPath }); + continue; + } + + const tempProjectDir = path.join(options.tempPluginDirPath, candidate); + const previousOutputPath = path.join( + tempProjectDir, + "build", + "outputs", + "aar", + `${candidate}-release.aar`, + ); + if ( + this.$fs.exists(previousOutputPath) && + this.getTempProjectPluginName(tempProjectDir) === options.pluginName + ) { + staleAars.push({ aarPath, previousOutputPath }); + } + } + + return staleAars; + } + + /** + * The npm name setupGradle substituted into the temp project's build.gradle. + */ + private getTempProjectPluginName(tempProjectDir: string): string | null { + try { + const buildGradle = this.$fs.readText( + path.join(tempProjectDir, "build.gradle"), + ); + return ( + buildGradle.match(/project\.ext\.PLUGIN_NAME\s*=\s*"([^"]*)"/)?.[1] ?? + null + ); + } catch (err) { + return null; + } + } + + /** + * Gradle templates add every aar in a plugin's platforms/android to the app, + * so an aar the CLI built for this plugin under another candidate name would + * duplicate its classes. + */ + private removeStaleAars(pluginName: string, staleAars: IStaleAar[]): void { + for (const { aarPath, previousOutputPath } of staleAars) { + if ( + previousOutputPath && + !this.isSameFileContent(aarPath, previousOutputPath) + ) { + this.$errors.fail( + `${aarPath} has a name the CLI built ${pluginName}'s aar under before, but differs from that build's output at ${previousOutputPath}. If it is an old build it would add duplicate classes to the app. Delete it or run \`ns clean\`.`, + ); + } + } + + for (const { aarPath } of staleAars) { + this.$watchIgnoreListService.addFileToIgnoreList(aarPath); + this.$logger.trace(`Removing stale plugin aar ${aarPath}`); + this.$fs.deleteFile(aarPath); + } + } + + private isSameFileContent(first: string, second: string): boolean { + const firstContent = this.$fs.readFile(first) as Buffer; + const secondContent = this.$fs.readFile(second) as Buffer; + return firstContent.equals(secondContent); + } + private cleanPluginDir(pluginTempDir: string): void { // In case plugin was already built in the current process, we need to clean the old sources as they may break the new build. this.$fs.deleteDirectory(pluginTempDir); @@ -286,15 +427,12 @@ export class AndroidPluginBuildService implements IAndroidPluginBuildService { private getSourceFilesHashes( pluginTempPlatformsAndroidDir: string, - shortPluginName: string, + excludedAarPaths: string[], ): Promise { - const pathToAar = path.join( - pluginTempPlatformsAndroidDir, - `${shortPluginName}.aar`, - ); + const excluded = new Set(excludedAarPaths); const pluginNativeDataFiles = this.$fs.enumerateFilesInDirectorySync( pluginTempPlatformsAndroidDir, - (file: string, stat: IFsStats) => file !== pathToAar, + (file: string, stat: IFsStats) => !excluded.has(file), ); return this.$filesHashService.generateHashes(pluginNativeDataFiles); } @@ -311,8 +449,7 @@ export class AndroidPluginBuildService implements IAndroidPluginBuildService { manifestFilePath: string; androidSourceDirectories: string[]; pluginTempDir: string; - pluginSourceDir: string; - shortPluginName: string; + aarPath: string; fileHashesInfo: IStringDictionary; }): Promise { let shouldBuildAar = @@ -321,9 +458,7 @@ export class AndroidPluginBuildService implements IAndroidPluginBuildService { if ( shouldBuildAar && this.$fs.exists(opts.pluginTempDir) && - this.$fs.exists( - path.join(opts.pluginSourceDir, `${opts.shortPluginName}.aar`), - ) + this.$fs.exists(opts.aarPath) ) { const buildDataFile = this.getPathToPluginBuildDataFile( opts.pluginTempDir, @@ -401,6 +536,7 @@ export class AndroidPluginBuildService implements IAndroidPluginBuildService { platformsAndroidDirPath: string, projectDir: string, pluginName: string, + aarName: string, ): Promise { const gradleTemplatePath = path.resolve( path.join(__dirname, "../../vendor/gradle-plugin"), @@ -424,9 +560,7 @@ export class AndroidPluginBuildService implements IAndroidPluginBuildService { this.replaceFileContent(buildGradlePath, "{{pluginName}}", pluginName); this.replaceFileContent(settingsGradlePath, "{{pluginName}}", pluginName); - // gets the package from the AndroidManifest to use as the namespace or fallback to the `org.nativescript.${shortPluginName}` - const shortPluginName = getShortPluginName(pluginName); - + // gets the package from the AndroidManifest to use as the namespace or fallback to the `org.nativescript.${aarName}` const manifestPath = path.join( pluginTempDir, "src", @@ -435,7 +569,7 @@ export class AndroidPluginBuildService implements IAndroidPluginBuildService { ); const manifestContent = this.$fs.readText(manifestPath); - let packageName = `org.nativescript.${shortPluginName}`; + let packageName = `org.nativescript.${aarName}`; const xml = await this.getXml(manifestContent); if (xml["manifest"]) { if (xml["manifest"]["$"]["package"]) { diff --git a/lib/services/android-project-service.ts b/lib/services/android-project-service.ts index d4ba573a08..2484de9b8c 100644 --- a/lib/services/android-project-service.ts +++ b/lib/services/android-project-service.ts @@ -6,7 +6,7 @@ import * as semver from "semver"; import * as projectServiceBaseLib from "./platform-project-service-base"; import { DeviceAndroidDebugBridge } from "../common/mobile/android/device-android-debug-bridge"; import { Configurations, LiveSyncPaths } from "../common/constants"; -import { hook } from "../common/helpers"; +import { getUniqueShortPluginNames, hook } from "../common/helpers"; import { performanceLog } from ".././common/decorators"; import { IProjectData, @@ -16,6 +16,7 @@ import { import { IPlatformData, IBuildOutputOptions, + INodeModulesDependenciesBuilder, IPlatformEnvironmentRequirements, IValidBuildOutputData, } from "../definitions/platform"; @@ -159,6 +160,11 @@ export class AndroidProjectService super($fs, $projectDataService); } + private pluginAarNames: { + projectDir: string; + names: Map; + } = null; + private _platformData: IPlatformData = null; public getPlatformData(projectData: IProjectData): IPlatformData { if (!projectData && !this._platformData) { @@ -695,15 +701,11 @@ export class AndroidProjectService AndroidProjectService.ANDROID_PLATFORM_NAME, ); if (this.$fs.exists(pluginPlatformsFolderPath)) { - const options: IPluginBuildOptions = { - gradlePath: this.$options.gradlePath, - gradleArgs: this.$options.gradleArgs, - projectDir: projectData.projectDir, - pluginName: pluginData.name, - platformsAndroidDirPath: pluginPlatformsFolderPath, - aarOutputDir: pluginPlatformsFolderPath, - tempPluginDirPath: path.join(projectData.platformsDir, "tempPlugin"), - }; + const options = this.getPluginBuildOptions( + pluginData, + pluginPlatformsFolderPath, + projectData, + ); if (await this.$androidPluginBuildService.buildAar(options)) { this.$logger.info(`Built aar for ${options.pluginName}`); @@ -713,6 +715,90 @@ export class AndroidProjectService } } + public shouldRepreparePlugin( + pluginData: IPluginData, + projectData: IProjectData, + ): boolean { + if (!this.getPluginAarNames(projectData).has(pluginData.name)) { + return false; + } + + return this.$androidPluginBuildService.hasOutdatedAar( + this.getPluginBuildOptions( + pluginData, + this.getPluginPlatformsFolderPath( + pluginData, + AndroidProjectService.ANDROID_PLATFORM_NAME, + ), + projectData, + ), + ); + } + + private getPluginBuildOptions( + pluginData: IPluginData, + pluginPlatformsFolderPath: string, + projectData: IProjectData, + ): IPluginBuildOptions { + const options: IPluginBuildOptions = { + gradlePath: this.$options.gradlePath, + gradleArgs: this.$options.gradleArgs, + projectDir: projectData.projectDir, + pluginName: pluginData.name, + platformsAndroidDirPath: pluginPlatformsFolderPath, + aarOutputDir: pluginPlatformsFolderPath, + tempPluginDirPath: path.join(projectData.platformsDir, "tempPlugin"), + }; + + const aarName = this.getPluginAarNames(projectData).get(pluginData.name); + if (aarName) { + options.aarName = aarName; + } + + return options; + } + + /** + * Normally computed by beforePrepareAllPlugins; computed here from the + * project's production dependencies when a plugin is prepared without it. + */ + private getPluginAarNames(projectData: IProjectData): Map { + if (this.pluginAarNames?.projectDir !== projectData.projectDir) { + const dependencies = this.$injector + .resolve( + "nodeModulesDependenciesBuilder", + ) + .getProductionDependencies( + projectData.projectDir, + projectData.ignoredDependencies, + ); + this.setPluginAarNames( + projectData, + this.filterUniqueDependencies(dependencies).filter( + AndroidProjectService.isNativeAndroidDependency, + ), + ); + } + + return this.pluginAarNames.names; + } + + private setPluginAarNames( + projectData: IProjectData, + nativeDependencyData: IDependencyData[], + ): void { + let names: Map; + try { + names = getUniqueShortPluginNames( + nativeDependencyData.map((dep) => dep.name), + ); + } catch (err) { + this.$errors.fail(err.message); + } + + this.pluginAarNames = { projectDir: projectData.projectDir, names }; + } + public async processConfigurationFilesFromAppResources(): Promise { return; } @@ -775,6 +861,7 @@ export class AndroidProjectService let nativeDependencyData = dependencies.filter( AndroidProjectService.isNativeAndroidDependency, ); + this.setPluginAarNames(projectData, nativeDependencyData); let nativeDependencies = nativeDependencyData.map( ({ name, directory, dependencies }) => { diff --git a/test/services/android-plugin-build-service.ts b/test/services/android-plugin-build-service.ts index c2107cf4c1..ee28d606e9 100644 --- a/test/services/android-plugin-build-service.ts +++ b/test/services/android-plugin-build-service.ts @@ -24,6 +24,8 @@ describe("androidPluginBuildService", () => { const pluginName = "my-plugin"; const shortPluginName = getShortPluginName(pluginName); let spawnFromEventCalled = false; + let ignoredFiles: string[] = []; + let hashedFiles: string[] = []; let fs: IFileSystem; let androidBuildPluginService: AndroidPluginBuildService; let tempFolder: string; @@ -75,15 +77,17 @@ describe("androidPluginBuildService", () => { const testInjector: IInjector = new stubs.InjectorStub(); testInjector.register("fs", FsLib.FileSystem); testInjector.register("childProcess", { - spawnFromEvent: async (command: string): Promise => { - const finalAarName = `${shortPluginName}-release.aar`; + spawnFromEvent: async ( + command: string, + args: string[], + ): Promise => { + const pluginDir = args[args.indexOf("-p") + 1]; const aar = path.join( - tempFolder, - shortPluginName, + pluginDir, "build", "outputs", "aar", - finalAarName, + `${path.basename(pluginDir)}-release.aar`, ); fs.writeFile(aar, ""); spawnFromEventCalled = command.indexOf("gradlew") !== -1; @@ -93,9 +97,10 @@ describe("androidPluginBuildService", () => { testInjector.register("packageManager", setupNpm(options)); testInjector.register("projectData", stubs.ProjectDataStub); testInjector.register("filesHashService", { - generateHashes: async ( - files: string[], - ): Promise => ({}), + generateHashes: async (files: string[]): Promise => { + hashedFiles = files; + return {}; + }, getChanges: async ( files: string[], oldHashes: IStringDictionary, @@ -106,8 +111,9 @@ describe("androidPluginBuildService", () => { ): boolean => !!options.hasChangesInShasums, }); + ignoredFiles = []; testInjector.register("watchIgnoreListService", { - addFileToIgnoreList: () => ({}), + addFileToIgnoreList: (file: string) => ignoredFiles.push(file), }); fs = testInjector.resolve("fs"); @@ -415,6 +421,294 @@ dependencies { }); }); + describe("aar names", () => { + const scopedPluginName = "@foo/my-plugin"; + const qualifiedName = "foo_my_plugin"; + + function setupScoped( + overrides?: Partial, + ): IPluginBuildOptions { + return { + ...setup({ addManifest: true }), + pluginName: scopedPluginName, + aarName: qualifiedName, + ...overrides, + }; + } + + function writePreviousOutput( + name: string, + content: string, + builtFor = scopedPluginName, + ) { + fs.writeFile( + path.join(tempFolder, name, "build.gradle"), + `android {\n project.ext.PLUGIN_NAME = "${builtFor}"\n}\n`, + ); + fs.writeFile( + path.join( + tempFolder, + name, + "build", + "outputs", + "aar", + `${name}-release.aar`, + ), + content, + ); + } + + it("uses aarName for the temp project, the aar and the namespace fallback", async () => { + const config = setupScoped(); + + assert.isTrue(await androidBuildPluginService.buildAar(config)); + + const buildGradle = fs.readText( + path.join(tempFolder, qualifiedName, "build.gradle"), + ); + assert.include( + buildGradle, + `namespace "org.nativescript.${qualifiedName}"`, + ); + assert.isTrue(fs.exists(path.join(pluginFolder, `${qualifiedName}.aar`))); + assert.isFalse(fs.exists(path.join(tempFolder, shortPluginName))); + assert.isFalse( + fs.exists(path.join(pluginFolder, `${shortPluginName}.aar`)), + ); + assert.deepStrictEqual(ignoredFiles, [ + path.join(pluginFolder, `${qualifiedName}.aar`), + ]); + }); + + it("does not hash the aar it builds or one it built under its other name", async () => { + const config = setupScoped(); + for (const name of [shortPluginName, qualifiedName, "unrelated"]) { + fs.writeFile(path.join(pluginFolder, `${name}.aar`), name); + } + + await androidBuildPluginService.buildAar(config); + + assert.include(hashedFiles, path.join(pluginFolder, "unrelated.aar")); + assert.notInclude( + hashedFiles, + path.join(pluginFolder, `${shortPluginName}.aar`), + ); + assert.notInclude( + hashedFiles, + path.join(pluginFolder, `${qualifiedName}.aar`), + ); + }); + + it("deletes an aar under the plugin's short name whatever its content", async () => { + const config = setupScoped(); + const staleAar = path.join(pluginFolder, `${shortPluginName}.aar`); + fs.writeFile(staleAar, "not like any build output"); + assert.isTrue(androidBuildPluginService.hasOutdatedAar(config)); + + await androidBuildPluginService.buildAar(config); + + assert.isFalse(fs.exists(staleAar)); + assert.include(ignoredFiles, staleAar); + assert.isTrue(fs.exists(path.join(pluginFolder, `${qualifiedName}.aar`))); + assert.isFalse(androidBuildPluginService.hasOutdatedAar(config)); + }); + + it("deletes the old short-name aars of clashing plugins built by an older CLI", async () => { + const foo = setupScoped({ + pluginName: "@foo/plugin-x", + aarName: "foo_plugin_x", + }); + const barFolder = mkdtempSync( + path.join(tmpdir(), "androidPluginBuildService-plugin-"), + ); + fs.copyFile( + path.join(pluginFolder, "AndroidManifest.xml"), + path.join(barFolder, "AndroidManifest.xml"), + ); + const bar: IPluginBuildOptions = { + ...foo, + pluginName: "@bar/plugin-x", + aarName: "bar_plugin_x", + platformsAndroidDirPath: barFolder, + aarOutputDir: barFolder, + }; + const fooOldAar = path.join(pluginFolder, "plugin_x.aar"); + const barOldAar = path.join(barFolder, "plugin_x.aar"); + fs.writeFile(fooOldAar, "foo build"); + fs.writeFile(barOldAar, "bar build"); + writePreviousOutput("plugin_x", "bar build", "@bar/plugin-x"); + + assert.isTrue(await androidBuildPluginService.buildAar(foo)); + assert.isTrue(await androidBuildPluginService.buildAar(bar)); + + assert.isFalse(fs.exists(fooOldAar)); + assert.isFalse(fs.exists(barOldAar)); + assert.isTrue(fs.exists(path.join(pluginFolder, "foo_plugin_x.aar"))); + assert.isTrue(fs.exists(path.join(barFolder, "bar_plugin_x.aar"))); + }); + + it("deletes a short-name aar that a plugin with sources ships when another plugin now owns that name", async () => { + const config = setupScoped({ + pluginName: "@foo/plugin-x", + aarName: "foo_plugin_x", + }); + const shippedAar = path.join(pluginFolder, "plugin_x.aar"); + fs.writeFile(shippedAar, "shipped"); + writePreviousOutput("plugin_x", "built for plugin-x", "plugin-x"); + + assert.isTrue(await androidBuildPluginService.buildAar(config)); + + assert.isFalse(fs.exists(shippedAar)); + assert.isTrue(fs.exists(path.join(pluginFolder, "foo_plugin_x.aar"))); + assert.equal( + fs.readText( + path.join( + tempFolder, + "plugin_x", + "build", + "outputs", + "aar", + "plugin_x-release.aar", + ), + ), + "built for plugin-x", + ); + }); + + it("keeps the aars of a plugin without sources to build", async () => { + const config: IPluginBuildOptions = { + ...setup(), + pluginName: "@foo/plugin-x", + aarName: "foo_plugin_x", + }; + const shippedAar = path.join(pluginFolder, "plugin_x.aar"); + fs.writeFile(shippedAar, "shipped"); + + assert.isFalse(await androidBuildPluginService.buildAar(config)); + + assert.equal(fs.readText(shippedAar), "shipped"); + assert.notInclude(ignoredFiles, shippedAar); + assert.isFalse(androidBuildPluginService.hasOutdatedAar(config)); + }); + + it("deletes a scope-qualified aar the CLI built for the plugin", async () => { + const config = setupScoped({ aarName: shortPluginName }); + const staleAar = path.join(pluginFolder, `${qualifiedName}.aar`); + fs.writeFile(staleAar, "previous build"); + writePreviousOutput(qualifiedName, "previous build"); + assert.isTrue(androidBuildPluginService.hasOutdatedAar(config)); + + await androidBuildPluginService.buildAar(config); + + assert.isFalse(fs.exists(staleAar)); + assert.include(ignoredFiles, staleAar); + assert.isTrue( + fs.exists(path.join(pluginFolder, `${shortPluginName}.aar`)), + ); + assert.isFalse(androidBuildPluginService.hasOutdatedAar(config)); + }); + + it("fails on a scope-qualified aar that differs from the CLI's build of the plugin under that name", async () => { + const config = setupScoped({ aarName: shortPluginName }); + const staleAar = path.join(pluginFolder, `${qualifiedName}.aar`); + fs.writeFile(staleAar, "shipped"); + writePreviousOutput(qualifiedName, "something else"); + assert.isTrue(androidBuildPluginService.hasOutdatedAar(config)); + + let error: Error = null; + try { + await androidBuildPluginService.buildAar(config); + } catch (err) { + error = err; + } + + assert.include(error?.message, staleAar); + assert.include( + error?.message, + path.join( + tempFolder, + qualifiedName, + "build", + "outputs", + "aar", + `${qualifiedName}-release.aar`, + ), + ); + assert.include(error?.message, "Delete it or run `ns clean`"); + assert.isTrue(fs.exists(staleAar)); + assert.isFalse(spawnFromEventCalled); + }); + + it("keeps a scope-qualified aar the CLI never built", async () => { + const config = setupScoped({ aarName: shortPluginName }); + const shippedAar = path.join(pluginFolder, `${qualifiedName}.aar`); + fs.writeFile(shippedAar, "shipped"); + + assert.isTrue(await androidBuildPluginService.buildAar(config)); + + assert.equal(fs.readText(shippedAar), "shipped"); + assert.notInclude(ignoredFiles, shippedAar); + assert.include(hashedFiles, shippedAar); + assert.isTrue( + fs.exists(path.join(pluginFolder, `${shortPluginName}.aar`)), + ); + assert.isFalse(androidBuildPluginService.hasOutdatedAar(config)); + }); + + it("keeps a scope-qualified aar whose temp project was not set up for the plugin", async () => { + const config = setupScoped({ aarName: shortPluginName }); + const shippedAar = path.join(pluginFolder, `${qualifiedName}.aar`); + fs.writeFile(shippedAar, "shipped"); + writePreviousOutput(qualifiedName, "something else", "@other/my-plugin"); + + assert.isTrue(await androidBuildPluginService.buildAar(config)); + assert.equal(fs.readText(shippedAar), "shipped"); + + assert.notInclude(ignoredFiles, shippedAar); + assert.isFalse(androidBuildPluginService.hasOutdatedAar(config)); + + fs.deleteFile(path.join(tempFolder, qualifiedName, "build.gradle")); + assert.isFalse(androidBuildPluginService.hasOutdatedAar(config)); + await androidBuildPluginService.buildAar(config); + assert.equal(fs.readText(shippedAar), "shipped"); + }); + + it("leaves other candidate aars alone when no aarName is given", async () => { + const config: IPluginBuildOptions = { + ...setup({ addManifest: true }), + pluginName: scopedPluginName, + }; + const otherAar = path.join(pluginFolder, `${qualifiedName}.aar`); + fs.writeFile(otherAar, "kept"); + writePreviousOutput(qualifiedName, "kept"); + + await androidBuildPluginService.buildAar(config); + + assert.isTrue(fs.exists(otherAar)); + assert.isTrue( + fs.exists(path.join(pluginFolder, `${shortPluginName}.aar`)), + ); + }); + + describe("hasOutdatedAar", () => { + it("is false for a plugin without sources to build", () => { + const config: IPluginBuildOptions = { + ...setup({ addIncludeGradle: true }), + aarName: shortPluginName, + }; + assert.isFalse(androidBuildPluginService.hasOutdatedAar(config)); + }); + + it("is true while the aar is missing", () => { + const config = setupScoped(); + assert.isTrue(androidBuildPluginService.hasOutdatedAar(config)); + + fs.writeFile(path.join(pluginFolder, `${qualifiedName}.aar`), ""); + assert.isFalse(androidBuildPluginService.hasOutdatedAar(config)); + }); + }); + }); + describe("migrateIncludeGradle", () => { it("if there is a legacy include.gradle file", async () => { const config: IPluginBuildOptions = setup({ diff --git a/test/services/android-project-service.ts b/test/services/android-project-service.ts index 1961548012..7f758ecad3 100644 --- a/test/services/android-project-service.ts +++ b/test/services/android-project-service.ts @@ -4,6 +4,9 @@ import * as stubs from "../stubs"; import { assert } from "chai"; import * as sinon from "sinon"; import * as path from "path"; +import { mkdtempSync, realpathSync } from "fs"; +import { tmpdir } from "os"; +import { FileSystem } from "../../lib/common/file-system"; import { GradleCommandService } from "../../lib/services/android/gradle-command-service"; import { GradleBuildService } from "../../lib/services/android/gradle-build-service"; import { GradleBuildArgsService } from "../../lib/services/android/gradle-build-args-service"; @@ -12,7 +15,10 @@ import { IAndroidToolsInfo, IAndroidToolsInfoData, IAndroidResourcesMigrationService, + IDependencyData, } from "../../lib/declarations"; +import { IPluginData } from "../../lib/definitions/plugins"; +import { IPluginBuildOptions } from "../../lib/definitions/android-plugin-migrator"; import { IInjector } from "../../lib/common/definitions/yok"; import { IDictionary, @@ -102,7 +108,7 @@ describe("androidProjectService", () => { childProcess = injector.resolve("childProcess"); const getPlatformDataStub: sinon.SinonStub = sandbox.stub( androidProjectService, - "getPlatformData" + "getPlatformData", ); getPlatformDataStub.callsFake(() => { return { @@ -120,7 +126,7 @@ describe("androidProjectService", () => { await androidProjectService.buildProject( "local/local", projectData, - buildConfig + buildConfig, ); //assert @@ -136,7 +142,7 @@ describe("androidProjectService", () => { await androidProjectService.buildProject( "local/local", projectData, - buildConfig + buildConfig, ); //assert @@ -152,7 +158,7 @@ describe("androidProjectService", () => { await androidProjectService.buildProject( "local/local", projectData, - buildConfig + buildConfig, ); //assert @@ -169,7 +175,7 @@ describe("androidProjectService", () => { await androidProjectService.buildProject( "local/local", projectData, - buildConfig + buildConfig, ); //assert @@ -182,30 +188,30 @@ describe("androidProjectService", () => { const pathToAppResourcesDir = path.join(projectDir, "app", "App_Resources"); const pathToAppResourcesAndroid = path.join( pathToAppResourcesDir, - "Android" + "Android", ); const pathToPlatformsAndroid = path.join( projectDir, "platforms", - "android" + "android", ); const pathToResDirInPlatforms = path.join( pathToPlatformsAndroid, "app", "src", "main", - "res" + "res", ); const valuesV27Path = path.join(pathToResDirInPlatforms, "values-v27"); const valuesV28Path = path.join(pathToResDirInPlatforms, "values-v28"); const libsPath = path.join(pathToResDirInPlatforms, "libs"); const drawableHdpiPath = path.join( pathToResDirInPlatforms, - "drawable-hdpi" + "drawable-hdpi", ); const drawableLdpiPath = path.join( pathToResDirInPlatforms, - "drawable-ldpi" + "drawable-ldpi", ); let deletedDirs: string[] = []; let copiedFiles: { @@ -232,7 +238,7 @@ describe("androidProjectService", () => { }; fs.copyFile = ( sourceFileName: string, - destinationFileName: string + destinationFileName: string, ): void => { copiedFiles.push({ sourceFileName, destinationFileName }); }; @@ -245,7 +251,7 @@ describe("androidProjectService", () => { const androidToolsInfo = injector.resolve("androidToolsInfo"); androidToolsInfo.getToolsInfo = ( - config?: IProjectDir + config?: IProjectDir, ): IAndroidToolsInfoData => { return { compileSdkVersion, @@ -256,12 +262,12 @@ describe("androidProjectService", () => { describe("when new Android App_Resources structure is detected (post {N} 4.0 structure)", () => { const pathToSrcDirInAppResources = path.join( pathToAppResourcesAndroid, - "src" + "src", ); beforeEach(() => { const androidResourcesMigrationService = injector.resolve( - "androidResourcesMigrationService" + "androidResourcesMigrationService", ); androidResourcesMigrationService.hasMigrated = () => true; }); @@ -277,7 +283,7 @@ describe("androidProjectService", () => { "platforms", "android", "app", - "src" + "src", ), }, ]); @@ -333,7 +339,7 @@ describe("androidProjectService", () => { beforeEach(() => { const androidResourcesMigrationService = injector.resolve( - "androidResourcesMigrationService" + "androidResourcesMigrationService", ); androidResourcesMigrationService.hasMigrated = () => false; }); @@ -404,3 +410,225 @@ describe("androidProjectService", () => { }); }); }); + +describe("androidProjectService plugin aar names", () => { + let fs: IFileSystem; + let service: AndroidProjectService; + let projectDir: string; + let platformDir: string; + let dependencies: IDependencyData[]; + let buildAarCalls: IPluginBuildOptions[]; + let outdatedAar: boolean; + + function createProjectData(): IProjectData { + return ({ + projectDir, + platformsDir: path.join(projectDir, "platforms"), + ignoredDependencies: [], + }); + } + + function addPlugin(plugin: { + name: string; + dependencies?: string[]; + native?: boolean; + }): void { + const directory = path.join(projectDir, "node_modules", plugin.name); + const nativescript = + plugin.native === false ? {} : { platforms: { android: "8.0.0" } }; + fs.writeFile( + path.join(directory, "platforms", "android", "AndroidManifest.xml"), + "", + ); + dependencies.push({ + name: plugin.name, + directory, + depth: 0, + version: "1.0.0", + nativescript, + dependencies: plugin.dependencies ?? [], + }); + } + + function pluginData(name: string): IPluginData { + const directory = path.join(projectDir, "node_modules", name); + return ({ + name, + fullPath: directory, + pluginPlatformsFolderPath: (platform: string) => + path.join(directory, "platforms", platform), + }); + } + + function addClashingPlugins(): void { + addPlugin({ name: "@nativescript/core" }); + addPlugin({ name: "@foo/plugin-x", dependencies: ["@nativescript/core"] }); + addPlugin({ name: "@bar/plugin-x" }); + } + + beforeEach(() => { + projectDir = realpathSync( + mkdtempSync(path.join(tmpdir(), "android-aar-names-")), + ); + platformDir = path.join(projectDir, "platforms", "android"); + dependencies = []; + buildAarCalls = []; + outdatedAar = false; + + const testInjector = new Yok(); + testInjector.register("injector", testInjector); + testInjector.register("fs", FileSystem); + testInjector.register("logger", stubs.LoggerStub); + testInjector.register("errors", stubs.ErrorsStub); + testInjector.register("options", {}); + testInjector.register("projectDataService", {}); + testInjector.register("nodeModulesDependenciesBuilder", { + getProductionDependencies: () => dependencies, + }); + testInjector.register("androidPluginBuildService", { + buildAar: async (options: IPluginBuildOptions) => { + buildAarCalls.push(options); + return false; + }, + migrateIncludeGradle: () => false, + hasOutdatedAar: () => outdatedAar, + }); + for (const unused of [ + "androidToolsInfo", + "devicePlatformsConstants", + "platformEnvironmentRequirements", + "androidResourcesMigrationService", + "filesHashService", + "gradleCommandService", + "gradleBuildService", + "analyticsService", + ]) { + testInjector.register(unused, {}); + } + testInjector.register("androidProjectService", AndroidProjectService); + + fs = testInjector.resolve("fs"); + service = testInjector.resolve("androidProjectService"); + }); + + it("writes the same dependencies.json when no short names clash", async () => { + addPlugin({ + name: "nativescript-plugin", + dependencies: ["@nativescript/core", "lodash"], + }); + addPlugin({ name: "@nativescript/core" }); + addPlugin({ name: "lodash", native: false }); + + await service.beforePrepareAllPlugins(createProjectData(), dependencies); + + const relative = (name: string) => + path.relative(platformDir, path.join(projectDir, "node_modules", name)); + assert.equal( + fs.readText(path.join(platformDir, "dependencies.json")), + JSON.stringify( + [ + { + name: "@nativescript/core", + directory: relative("@nativescript/core"), + dependencies: [], + }, + { + name: "nativescript-plugin", + directory: relative("nativescript-plugin"), + dependencies: ["@nativescript/core"], + }, + ], + null, + 4, + ), + ); + }); + + it("builds plugins without a clash under their short name", async () => { + addClashingPlugins(); + const projectData = createProjectData(); + await service.beforePrepareAllPlugins(projectData, dependencies); + + await service.preparePluginNativeCode( + pluginData("@nativescript/core"), + projectData, + ); + + const nativeDir = path.join( + projectDir, + "node_modules", + "@nativescript", + "core", + "platforms", + "android", + ); + assert.deepStrictEqual(buildAarCalls, [ + { + gradlePath: undefined, + gradleArgs: undefined, + projectDir, + pluginName: "@nativescript/core", + platformsAndroidDirPath: nativeDir, + aarOutputDir: nativeDir, + tempPluginDirPath: path.join(projectDir, "platforms", "tempPlugin"), + aarName: "core", + }, + ]); + }); + + it("builds clashing plugins under scope-qualified names", async () => { + addClashingPlugins(); + const projectData = createProjectData(); + await service.beforePrepareAllPlugins(projectData, dependencies); + + await service.preparePluginNativeCode( + pluginData("@foo/plugin-x"), + projectData, + ); + await service.preparePluginNativeCode( + pluginData("@bar/plugin-x"), + projectData, + ); + + assert.deepStrictEqual( + buildAarCalls.map((options) => options.aarName), + ["foo_plugin_x", "bar_plugin_x"], + ); + }); + + it("works out the aar names when plugins are prepared on their own", async () => { + addClashingPlugins(); + + await service.preparePluginNativeCode( + pluginData("@bar/plugin-x"), + createProjectData(), + ); + + assert.equal(buildAarCalls[0].aarName, "bar_plugin_x"); + }); + + it("asks for a reprepare when the plugin's aar is outdated", async () => { + addClashingPlugins(); + const projectData = createProjectData(); + await service.beforePrepareAllPlugins(projectData, dependencies); + + assert.isFalse( + service.shouldRepreparePlugin(pluginData("@foo/plugin-x"), projectData), + ); + outdatedAar = true; + assert.isTrue( + service.shouldRepreparePlugin(pluginData("@foo/plugin-x"), projectData), + ); + }); + + it("fails prepare when two plugins cannot get distinct aar names", async () => { + addPlugin({ name: "@foo/plugin-x" }); + addPlugin({ name: "@foo/plugin_x" }); + + await assert.isRejected( + service.beforePrepareAllPlugins(createProjectData(), dependencies), + /"@foo\/plugin-x" and "@foo\/plugin_x"/, + ); + assert.isFalse(fs.exists(path.join(platformDir, "dependencies.json"))); + }); +}); diff --git a/test/stubs.ts b/test/stubs.ts index c21b07ce22..35baf6cc3a 100644 --- a/test/stubs.ts +++ b/test/stubs.ts @@ -750,6 +750,10 @@ export class AndroidPluginBuildServiceStub implements IAndroidPluginBuildService migrateIncludeGradle(options: IPluginBuildOptions): boolean { return true; } + + hasOutdatedAar(options: IPluginBuildOptions): boolean { + return false; + } } export class PlatformProjectServiceStub From b0af0fc03bfd6770d272e32330346dbcf9ac4146 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Mon, 30 Nov 2026 09:01:07 -0300 Subject: [PATCH 2/4] fix(android): address review of unique aar names Only names the CLI creates get the leading `_` for a leading digit. An unscoped plugin keeps its exact short name even when it clashes, so `9-lives` next to `@a/9-lives` stays `9_lives` (and its `9_lives.aar` is no longer deleted), while `@9a/x` next to `x` becomes `_9a_x`. Short names are never prefixed, as that would rename aars in existing projects. Two plugins that still end up with the same name keep failing prepare. Aar names are now unique among every package prepare builds an aar for: native Android dependencies plus any package with a `nativescript` key whose platforms/android directory exists, since those share platforms/tempPlugin too. Such packages could otherwise still build in the same temp project as a clashing plugin. dependencies.json and the names in projects without a clash are unchanged. The Android project service gets $nodeModulesDependenciesBuilder through its constructor. getUniqueShortPluginNames is renamed to getUniqueAarNames, and copyAar/updateManifest take an `aarName`. --- lib/common/helpers.ts | 42 ++++++------ lib/common/test/unit-tests/helpers.ts | 42 ++++++++---- lib/services/android-plugin-build-service.ts | 20 +++--- lib/services/android-project-service.ts | 45 ++++++++----- test/services/android-project-service.ts | 68 ++++++++++++++++++-- 5 files changed, 146 insertions(+), 71 deletions(-) diff --git a/lib/common/helpers.ts b/lib/common/helpers.ts index c73ca2eee2..403f3c8631 100644 --- a/lib/common/helpers.ts +++ b/lib/common/helpers.ts @@ -125,31 +125,27 @@ function sanitizePluginName(pluginName: string): string { return pluginName.split("/").pop(); } -function getScopeQualifiedPluginName(pluginName: string): string | null { +// The aar name doubles as a Java package segment (the `org.nativescript.` +// namespace fallback), which cannot start with a digit. Short names are used +// as is, since changing them would rename aars in existing projects. +function getScopeQualifiedAarName(pluginName: string): string | null { const parts = pluginName.split("/"); if (parts.length < 2 || !parts[0].startsWith("@")) { return null; } const scope = parts[0].slice(1).replace(/[^A-Za-z0-9_]/g, "_"); - return `${scope}_${getShortPluginName(pluginName)}`; -} - -// The aar name doubles as a Java package segment (the `org.nativescript.` -// namespace fallback), which cannot start with a digit. -function withoutLeadingDigit(name: string): string { + const name = `${scope}_${getShortPluginName(pluginName)}`; return /^[0-9]/.test(name) ? `_${name}` : name; } /** - * Maps each plugin name to a file-system and Java-package safe name for its aar - * that is unique among `pluginNames`. A plugin whose short name is not shared - * keeps `getShortPluginName(name)`, so projects without clashes keep their names. - * Throws if two plugins still end up with the same name. + * Maps each plugin name to a name for its aar that is unique among + * `pluginNames`. A plugin whose short name is not shared, or that is unscoped, + * keeps `getShortPluginName(name)`, so projects without clashes keep their + * names. Throws if two plugins still end up with the same name. */ -export function getUniqueShortPluginNames( - pluginNames: string[], -): Map { +export function getUniqueAarNames(pluginNames: string[]): Map { const sortedNames = _.sortBy(_.uniq(pluginNames)); const namesByShortName = _.groupBy(sortedNames, getShortPluginName); const result = new Map(); @@ -160,9 +156,7 @@ export function getUniqueShortPluginNames( const aarName = namesByShortName[shortName].length === 1 ? shortName - : withoutLeadingDigit( - getScopeQualifiedPluginName(pluginName) ?? shortName, - ); + : (getScopeQualifiedAarName(pluginName) ?? shortName); const owner = owners.get(aarName); if (owner !== undefined) { @@ -179,15 +173,15 @@ export function getUniqueShortPluginNames( } /** - * Every aar name `getUniqueShortPluginNames` can give this plugin, depending on - * which other plugins are installed. + * Every aar name `getUniqueAarNames` can give this plugin, depending on which + * other plugins are installed. */ export function getCandidateAarNames(pluginName: string): string[] { - const shortName = getShortPluginName(pluginName); - return _.uniq([ - shortName, - withoutLeadingDigit(getScopeQualifiedPluginName(pluginName) ?? shortName), - ]); + const scopeQualifiedName = getScopeQualifiedAarName(pluginName); + return [ + getShortPluginName(pluginName), + ...(scopeQualifiedName ? [scopeQualifiedName] : []), + ]; } export async function executeActionByChunks( diff --git a/lib/common/test/unit-tests/helpers.ts b/lib/common/test/unit-tests/helpers.ts index ee5aa542f3..2d548dbf92 100644 --- a/lib/common/test/unit-tests/helpers.ts +++ b/lib/common/test/unit-tests/helpers.ts @@ -1112,9 +1112,9 @@ const test = require("./test");`, }); }); - describe("getUniqueShortPluginNames", () => { + describe("getUniqueAarNames", () => { const toObject = (names: string[]) => - Object.fromEntries(helpers.getUniqueShortPluginNames(names)); + Object.fromEntries(helpers.getUniqueAarNames(names)); it("keeps the short name of plugins without a clash", () => { assert.deepStrictEqual( @@ -1158,32 +1158,42 @@ const test = require("./test");`, }); }); - it("prefixes clashing names that would start with a digit", () => { + it("prefixes scope-qualified names that would start with a digit", () => { assert.deepStrictEqual(toObject(["@1password/plugin", "@a/plugin"]), { "@1password/plugin": "_1password_plugin", "@a/plugin": "a_plugin", }); + assert.deepStrictEqual(toObject(["@9a/x", "@b/x"]), { + "@9a/x": "_9a_x", + "@b/x": "b_x", + }); + }); + + it("lets an unscoped plugin starting with a digit keep its name in a clash", () => { assert.deepStrictEqual(toObject(["9-lives", "@a/9-lives"]), { - "9-lives": "_9_lives", + "9-lives": "9_lives", "@a/9-lives": "a_9_lives", }); }); it("fails when two plugins still share a name", () => { assert.throws( - () => - helpers.getUniqueShortPluginNames(["@foo/plugin-x", "@foo/plugin_x"]), + () => helpers.getUniqueAarNames(["@foo/plugin-x", "@foo/plugin_x"]), /"@foo\/plugin-x" and "@foo\/plugin_x"/, ); assert.throws( () => - helpers.getUniqueShortPluginNames([ + helpers.getUniqueAarNames([ "foo-plugin-x", "@foo/plugin-x", "@bar/plugin-x", ]), /"@foo\/plugin-x" and "foo-plugin-x".*"foo_plugin_x"/, ); + assert.throws( + () => helpers.getUniqueAarNames(["_9a_x", "@9a/x", "x"]), + /"@9a\/x" and "_9a_x".*"_9a_x"/, + ); }); it("does not depend on the order of the plugins", () => { @@ -1195,8 +1205,7 @@ const test = require("./test");`, expected, ); assert.throws( - () => - helpers.getUniqueShortPluginNames(["@foo/plugin_x", "@foo/plugin-x"]), + () => helpers.getUniqueAarNames(["@foo/plugin_x", "@foo/plugin-x"]), /"@foo\/plugin-x" and "@foo\/plugin_x"/, ); }); @@ -1216,21 +1225,26 @@ const test = require("./test");`, ]); assert.deepStrictEqual(helpers.getCandidateAarNames("9-lives"), [ "9_lives", - "_9_lives", ]); }); - it("covers every name getUniqueShortPluginNames gives", () => { + it("prefixes a scope-qualified name that would start with a digit", () => { + assert.deepStrictEqual(helpers.getCandidateAarNames("@9a/x"), [ + "x", + "_9a_x", + ]); + }); + + it("covers every name getUniqueAarNames gives", () => { const projects = [ ["@foo/plugin-x"], ["@foo/plugin-x", "@bar/plugin-x"], ["plugin-x", "@foo/plugin-x"], ["@1a/plugin", "@b/plugin", "plugin", "9-lives", "@c/9-lives"], + ["@9a/x", "x"], ]; for (const project of projects) { - for (const [name, aarName] of helpers.getUniqueShortPluginNames( - project, - )) { + for (const [name, aarName] of helpers.getUniqueAarNames(project)) { assert.include(helpers.getCandidateAarNames(name), aarName); } } diff --git a/lib/services/android-plugin-build-service.ts b/lib/services/android-plugin-build-service.ts index 901a06bcbb..7d165abc6c 100644 --- a/lib/services/android-plugin-build-service.ts +++ b/lib/services/android-plugin-build-service.ts @@ -327,13 +327,9 @@ export class AndroidPluginBuildService implements IAndroidPluginBuildService { } /** - * Aars in `aarOutputDir` under another of the plugin's candidate names that - * the CLI built. Earlier CLIs copied every built plugin's aar to - * `.aar`, overwriting any file the package shipped under that - * name, so that file is always a leftover. A scope-qualified name is only - * ever built by this plugin, so that file is a leftover only if the temp - * project for the name was set up for this plugin and has a build output to - * compare it with; otherwise the package ships it. + * `.aar` is always CLI output, since earlier CLIs overwrote it on + * every build. A package may ship a scope-qualified name itself, so that one + * only counts when its temp project was built for this plugin. */ private getStaleAars( options: IPluginBuildOptions, @@ -482,11 +478,11 @@ export class AndroidPluginBuildService implements IAndroidPluginBuildService { private async updateManifest( manifestFilePath: string, pluginTempMainSrcDir: string, - shortPluginName: string, + aarName: string, ): Promise { let updatedManifestContent; this.$fs.ensureDirectoryExists(pluginTempMainSrcDir); - const defaultPackageName = "org.nativescript." + shortPluginName; + const defaultPackageName = "org.nativescript." + aarName; if (manifestFilePath) { let androidManifestContent; try { @@ -851,11 +847,11 @@ export class AndroidPluginBuildService implements IAndroidPluginBuildService { } private copyAar( - shortPluginName: string, + aarName: string, pluginTempDir: string, aarOutputDir: string, ): void { - const finalAarName = `${shortPluginName}-release.aar`; + const finalAarName = `${aarName}-release.aar`; const pathToBuiltAar = path.join( pluginTempDir, "build", @@ -869,7 +865,7 @@ export class AndroidPluginBuildService implements IAndroidPluginBuildService { if (aarOutputDir) { this.$fs.copyFile( pathToBuiltAar, - path.join(aarOutputDir, `${shortPluginName}.aar`), + path.join(aarOutputDir, `${aarName}.aar`), ); } } catch (e) { diff --git a/lib/services/android-project-service.ts b/lib/services/android-project-service.ts index 2484de9b8c..d2412ac67e 100644 --- a/lib/services/android-project-service.ts +++ b/lib/services/android-project-service.ts @@ -6,7 +6,7 @@ import * as semver from "semver"; import * as projectServiceBaseLib from "./platform-project-service-base"; import { DeviceAndroidDebugBridge } from "../common/mobile/android/device-android-debug-bridge"; import { Configurations, LiveSyncPaths } from "../common/constants"; -import { getUniqueShortPluginNames, hook } from "../common/helpers"; +import { getUniqueAarNames, hook } from "../common/helpers"; import { performanceLog } from ".././common/decorators"; import { IProjectData, @@ -156,6 +156,7 @@ export class AndroidProjectService private $gradleCommandService: IGradleCommandService, private $gradleBuildService: IGradleBuildService, private $analyticsService: IAnalyticsService, + private $nodeModulesDependenciesBuilder: INodeModulesDependenciesBuilder, ) { super($fs, $projectDataService); } @@ -764,18 +765,13 @@ export class AndroidProjectService */ private getPluginAarNames(projectData: IProjectData): Map { if (this.pluginAarNames?.projectDir !== projectData.projectDir) { - const dependencies = this.$injector - .resolve( - "nodeModulesDependenciesBuilder", - ) - .getProductionDependencies( - projectData.projectDir, - projectData.ignoredDependencies, - ); this.setPluginAarNames( projectData, - this.filterUniqueDependencies(dependencies).filter( - AndroidProjectService.isNativeAndroidDependency, + this.filterUniqueDependencies( + this.$nodeModulesDependenciesBuilder.getProductionDependencies( + projectData.projectDir, + projectData.ignoredDependencies, + ), ), ); } @@ -783,15 +779,32 @@ export class AndroidProjectService return this.pluginAarNames.names; } + /** + * Names must be unique among every package preparePluginNativeCode builds, + * not only those in dependencies.json, since they share platforms/tempPlugin. + */ private setPluginAarNames( projectData: IProjectData, - nativeDependencyData: IDependencyData[], + dependencies: IDependencyData[], ): void { + const aarPluginNames = dependencies + .filter( + (dep) => + AndroidProjectService.isNativeAndroidDependency(dep) || + (dep.nativescript && + this.$fs.exists( + path.join( + dep.directory, + constants.PLATFORMS_DIR_NAME, + AndroidProjectService.ANDROID_PLATFORM_NAME, + ), + )), + ) + .map((dep) => dep.name); + let names: Map; try { - names = getUniqueShortPluginNames( - nativeDependencyData.map((dep) => dep.name), - ); + names = getUniqueAarNames(aarPluginNames); } catch (err) { this.$errors.fail(err.message); } @@ -816,6 +829,7 @@ export class AndroidProjectService ): Promise { if (dependencies) { dependencies = this.filterUniqueDependencies(dependencies); + this.setPluginAarNames(projectData, dependencies); return this.provideDependenciesJson(projectData, dependencies); } } @@ -861,7 +875,6 @@ export class AndroidProjectService let nativeDependencyData = dependencies.filter( AndroidProjectService.isNativeAndroidDependency, ); - this.setPluginAarNames(projectData, nativeDependencyData); let nativeDependencies = nativeDependencyData.map( ({ name, directory, dependencies }) => { diff --git a/test/services/android-project-service.ts b/test/services/android-project-service.ts index 7f758ecad3..cdcce49722 100644 --- a/test/services/android-project-service.ts +++ b/test/services/android-project-service.ts @@ -65,6 +65,7 @@ const createTestInjector = (): IInjector => { testInjector.register("gradleBuildService", GradleBuildService); testInjector.register("gradleBuildArgsService", GradleBuildArgsService); testInjector.register("analyticsService", stubs.AnalyticsService); + testInjector.register("nodeModulesDependenciesBuilder", {}); testInjector.register("staticConfig", { TRACK_FEATURE_USAGE_SETTING_NAME: "TrackFeatureUsage", }); @@ -432,14 +433,17 @@ describe("androidProjectService plugin aar names", () => { name: string; dependencies?: string[]; native?: boolean; + androidDir?: boolean; }): void { const directory = path.join(projectDir, "node_modules", plugin.name); const nativescript = plugin.native === false ? {} : { platforms: { android: "8.0.0" } }; - fs.writeFile( - path.join(directory, "platforms", "android", "AndroidManifest.xml"), - "", - ); + if (plugin.androidDir !== false) { + fs.writeFile( + path.join(directory, "platforms", "android", "AndroidManifest.xml"), + "", + ); + } dependencies.push({ name: plugin.name, directory, @@ -518,8 +522,9 @@ describe("androidProjectService plugin aar names", () => { }); addPlugin({ name: "@nativescript/core" }); addPlugin({ name: "lodash", native: false }); + const projectData = createProjectData(); - await service.beforePrepareAllPlugins(createProjectData(), dependencies); + await service.beforePrepareAllPlugins(projectData, dependencies); const relative = (name: string) => path.relative(platformDir, path.join(projectDir, "node_modules", name)); @@ -542,6 +547,18 @@ describe("androidProjectService plugin aar names", () => { 4, ), ); + + for (const name of [ + "nativescript-plugin", + "@nativescript/core", + "lodash", + ]) { + await service.preparePluginNativeCode(pluginData(name), projectData); + } + assert.deepStrictEqual( + buildAarCalls.map((options) => options.aarName), + ["nativescript_plugin", "core", "lodash"], + ); }); it("builds plugins without a clash under their short name", async () => { @@ -596,6 +613,47 @@ describe("androidProjectService plugin aar names", () => { ); }); + it("gives unique names to packages built without declaring Android", async () => { + addPlugin({ name: "@foo/plugin-x" }); + addPlugin({ name: "@bar/plugin-x", native: false }); + const projectData = createProjectData(); + await service.beforePrepareAllPlugins(projectData, dependencies); + + await service.preparePluginNativeCode( + pluginData("@foo/plugin-x"), + projectData, + ); + await service.preparePluginNativeCode( + pluginData("@bar/plugin-x"), + projectData, + ); + + assert.deepStrictEqual( + buildAarCalls.map((options) => options.aarName), + ["foo_plugin_x", "bar_plugin_x"], + ); + assert.deepStrictEqual( + JSON.parse(fs.readText(path.join(platformDir, "dependencies.json"))).map( + (dep: { name: string }) => dep.name, + ), + ["@foo/plugin-x"], + ); + }); + + it("ignores packages without platforms/android when naming aars", async () => { + addPlugin({ name: "@foo/plugin-x" }); + addPlugin({ name: "@bar/plugin-x", native: false, androidDir: false }); + const projectData = createProjectData(); + await service.beforePrepareAllPlugins(projectData, dependencies); + + await service.preparePluginNativeCode( + pluginData("@foo/plugin-x"), + projectData, + ); + + assert.equal(buildAarCalls[0].aarName, "plugin_x"); + }); + it("works out the aar names when plugins are prepared on their own", async () => { addClashingPlugins(); From c6a117efd4cf31887e2d5641596a04a2c42e3c33 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Mon, 30 Nov 2026 09:33:09 -0300 Subject: [PATCH 3/4] fix(android): only name aars for packages the CLI builds Aar names were allocated among every package with a `nativescript` key and a platforms/android directory, including packages that only ship prebuilt aars. Those never run the aar build or use tempPlugin, yet could make prepare fail: `@foo/plugin-x` (with sources) next to `@foo/plugin_x` (only platforms/android/vendor.aar) both mapped to `foo_plugin_x`. Names are now allocated only among packages buildAar builds: a `nativescript` package whose platforms/android has an AndroidManifest.xml or Android source directories. Plugins that declare Android but only ship prebuilt aars are left out too and get no aar name. AndroidPluginBuildService exposes that condition as hasAarSources, which buildAar and hasOutdatedAar use as well. Two packages that both build still clash and get renamed or rejected as before. --- lib/definitions/android-plugin-migrator.d.ts | 5 +++ lib/services/android-plugin-build-service.ts | 27 +++++++------- lib/services/android-project-service.ts | 22 +++++------ test/services/android-plugin-build-service.ts | 32 ++++++++++++++++ test/services/android-project-service.ts | 37 +++++++++++++++---- test/stubs.ts | 4 ++ 6 files changed, 96 insertions(+), 31 deletions(-) diff --git a/lib/definitions/android-plugin-migrator.d.ts b/lib/definitions/android-plugin-migrator.d.ts index b787557e7e..be3acf3a7d 100644 --- a/lib/definitions/android-plugin-migrator.d.ts +++ b/lib/definitions/android-plugin-migrator.d.ts @@ -22,6 +22,11 @@ interface IAndroidBuildOptions { interface IAndroidPluginBuildService { buildAar(options: IPluginBuildOptions): Promise; migrateIncludeGradle(options: IPluginBuildOptions): boolean; + /** + * Whether `buildAar` builds an aar from this platforms/android directory, + * i.e. it has an AndroidManifest.xml or Android source directories. + */ + hasAarSources(platformsAndroidDirPath: string): boolean; /** * Whether the plugin has sources to build but `aarOutputDir` lacks its aar * or still holds one the CLI built under another of its candidate names. diff --git a/lib/services/android-plugin-build-service.ts b/lib/services/android-plugin-build-service.ts index 7d165abc6c..a0ac29c2eb 100644 --- a/lib/services/android-plugin-build-service.ts +++ b/lib/services/android-plugin-build-service.ts @@ -240,10 +240,11 @@ export class AndroidPluginBuildService implements IAndroidPluginBuildService { const androidSourceDirectories = this.getAndroidSourceDirectories( options.platformsAndroidDirPath, ); + const hasAarSources = this.hasAarSources(options.platformsAndroidDirPath); const aarName = this.getAarName(options); const pluginTempDir = path.join(options.tempPluginDirPath, aarName); const staleAars = - options.aarName && (manifestFilePath || androidSourceDirectories.length) + options.aarName && hasAarSources ? this.getStaleAars(options, aarName) : []; const pluginSourceFileHashesInfo = await this.getSourceFilesHashes( @@ -256,8 +257,7 @@ export class AndroidPluginBuildService implements IAndroidPluginBuildService { this.removeStaleAars(options.pluginName, staleAars); const shouldBuildAar = await this.shouldBuildAar({ - manifestFilePath, - androidSourceDirectories, + hasAarSources, pluginTempDir, aarPath: path.join(this.getAarOutputDir(options), `${aarName}.aar`), fileHashesInfo: pluginSourceFileHashesInfo, @@ -300,13 +300,16 @@ export class AndroidPluginBuildService implements IAndroidPluginBuildService { return shouldBuildAar; } + public hasAarSources(platformsAndroidDirPath: string): boolean { + return ( + this.$fs.exists(platformsAndroidDirPath) && + (!!this.getManifest(platformsAndroidDirPath) || + this.getAndroidSourceDirectories(platformsAndroidDirPath).length > 0) + ); + } + public hasOutdatedAar(options: IPluginBuildOptions): boolean { - if ( - !this.$fs.exists(options.platformsAndroidDirPath) || - (!this.getManifest(options.platformsAndroidDirPath) && - !this.getAndroidSourceDirectories(options.platformsAndroidDirPath) - .length) - ) { + if (!this.hasAarSources(options.platformsAndroidDirPath)) { return false; } @@ -442,14 +445,12 @@ export class AndroidPluginBuildService implements IAndroidPluginBuildService { } private async shouldBuildAar(opts: { - manifestFilePath: string; - androidSourceDirectories: string[]; + hasAarSources: boolean; pluginTempDir: string; aarPath: string; fileHashesInfo: IStringDictionary; }): Promise { - let shouldBuildAar = - !!opts.manifestFilePath || !!opts.androidSourceDirectories.length; + let shouldBuildAar = opts.hasAarSources; if ( shouldBuildAar && diff --git a/lib/services/android-project-service.ts b/lib/services/android-project-service.ts index d2412ac67e..d44dcf8f9d 100644 --- a/lib/services/android-project-service.ts +++ b/lib/services/android-project-service.ts @@ -780,8 +780,9 @@ export class AndroidProjectService } /** - * Names must be unique among every package preparePluginNativeCode builds, - * not only those in dependencies.json, since they share platforms/tempPlugin. + * Names must be unique among every package preparePluginNativeCode builds + * an aar for, not only those in dependencies.json, since they share + * platforms/tempPlugin. Packages that only ship prebuilt aars take no name. */ private setPluginAarNames( projectData: IProjectData, @@ -790,15 +791,14 @@ export class AndroidProjectService const aarPluginNames = dependencies .filter( (dep) => - AndroidProjectService.isNativeAndroidDependency(dep) || - (dep.nativescript && - this.$fs.exists( - path.join( - dep.directory, - constants.PLATFORMS_DIR_NAME, - AndroidProjectService.ANDROID_PLATFORM_NAME, - ), - )), + dep.nativescript && + this.$androidPluginBuildService.hasAarSources( + path.join( + dep.directory, + constants.PLATFORMS_DIR_NAME, + AndroidProjectService.ANDROID_PLATFORM_NAME, + ), + ), ) .map((dep) => dep.name); diff --git a/test/services/android-plugin-build-service.ts b/test/services/android-plugin-build-service.ts index ee28d606e9..583b72686c 100644 --- a/test/services/android-plugin-build-service.ts +++ b/test/services/android-plugin-build-service.ts @@ -690,6 +690,38 @@ dependencies { ); }); + describe("hasAarSources", () => { + it("is true for a manifest or Android source directories", () => { + const withManifest = setup({ addManifest: true }); + assert.isTrue( + androidBuildPluginService.hasAarSources( + withManifest.platformsAndroidDirPath, + ), + ); + const withResources = setup({ addResFolder: true }); + assert.isTrue( + androidBuildPluginService.hasAarSources( + withResources.platformsAndroidDirPath, + ), + ); + }); + + it("is false for prebuilt aars only or a missing directory", () => { + const config = setup({ addIncludeGradle: true }); + fs.writeFile(path.join(pluginFolder, "vendor.aar"), ""); + assert.isFalse( + androidBuildPluginService.hasAarSources( + config.platformsAndroidDirPath, + ), + ); + assert.isFalse( + androidBuildPluginService.hasAarSources( + path.join(pluginFolder, "missing"), + ), + ); + }); + }); + describe("hasOutdatedAar", () => { it("is false for a plugin without sources to build", () => { const config: IPluginBuildOptions = { diff --git a/test/services/android-project-service.ts b/test/services/android-project-service.ts index cdcce49722..4cd34ceb24 100644 --- a/test/services/android-project-service.ts +++ b/test/services/android-project-service.ts @@ -433,16 +433,16 @@ describe("androidProjectService plugin aar names", () => { name: string; dependencies?: string[]; native?: boolean; - androidDir?: boolean; + android?: "sources" | "prebuilt" | "none"; }): void { const directory = path.join(projectDir, "node_modules", plugin.name); const nativescript = plugin.native === false ? {} : { platforms: { android: "8.0.0" } }; - if (plugin.androidDir !== false) { - fs.writeFile( - path.join(directory, "platforms", "android", "AndroidManifest.xml"), - "", - ); + const androidDir = path.join(directory, "platforms", "android"); + if (plugin.android === "prebuilt") { + fs.writeFile(path.join(androidDir, "vendor.aar"), ""); + } else if (plugin.android !== "none") { + fs.writeFile(path.join(androidDir, "AndroidManifest.xml"), ""); } dependencies.push({ name: plugin.name, @@ -496,6 +496,8 @@ describe("androidProjectService plugin aar names", () => { }, migrateIncludeGradle: () => false, hasOutdatedAar: () => outdatedAar, + hasAarSources: (platformsAndroidDirPath: string) => + fs.exists(path.join(platformsAndroidDirPath, "AndroidManifest.xml")), }); for (const unused of [ "androidToolsInfo", @@ -642,7 +644,7 @@ describe("androidProjectService plugin aar names", () => { it("ignores packages without platforms/android when naming aars", async () => { addPlugin({ name: "@foo/plugin-x" }); - addPlugin({ name: "@bar/plugin-x", native: false, androidDir: false }); + addPlugin({ name: "@bar/plugin-x", native: false, android: "none" }); const projectData = createProjectData(); await service.beforePrepareAllPlugins(projectData, dependencies); @@ -654,6 +656,27 @@ describe("androidProjectService plugin aar names", () => { assert.equal(buildAarCalls[0].aarName, "plugin_x"); }); + it("ignores packages that only ship prebuilt aars when naming aars", async () => { + addPlugin({ name: "@foo/plugin-x" }); + addPlugin({ name: "@foo/plugin_x", native: false, android: "prebuilt" }); + addPlugin({ name: "@bar/plugin-x", android: "prebuilt" }); + const projectData = createProjectData(); + await service.beforePrepareAllPlugins(projectData, dependencies); + + for (const name of ["@foo/plugin-x", "@foo/plugin_x", "@bar/plugin-x"]) { + await service.preparePluginNativeCode(pluginData(name), projectData); + } + + assert.deepStrictEqual( + buildAarCalls.map((options) => [options.pluginName, options.aarName]), + [ + ["@foo/plugin-x", "plugin_x"], + ["@foo/plugin_x", undefined], + ["@bar/plugin-x", undefined], + ], + ); + }); + it("works out the aar names when plugins are prepared on their own", async () => { addClashingPlugins(); diff --git a/test/stubs.ts b/test/stubs.ts index 35baf6cc3a..de7d9a9f60 100644 --- a/test/stubs.ts +++ b/test/stubs.ts @@ -754,6 +754,10 @@ export class AndroidPluginBuildServiceStub implements IAndroidPluginBuildService hasOutdatedAar(options: IPluginBuildOptions): boolean { return false; } + + hasAarSources(platformsAndroidDirPath: string): boolean { + return false; + } } export class PlatformProjectServiceStub From 0e44f9a87614bef8f4f0ce4d4fe396622b23c1fd Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Mon, 30 Nov 2026 09:49:24 -0300 Subject: [PATCH 4/4] fix(android): delete leftover aars only after the new aar exists buildAar deleted a plugin's leftover aars (the old `.aar`, or a scope-qualified aar the CLI built for it) before running Gradle. When the build failed, for example offline, the plugin was left with no aar at all. The leftovers are still identified before the build, and a scope-qualified aar that differs from the CLI's earlier output still stops prepare before Gradle runs. They are now deleted only after the new aar has been copied, or when no rebuild is needed and the aar under the current name is already there. A failed build keeps the old aar, and hasOutdatedAar keeps reporting the plugin so the next prepare retries. --- lib/services/android-plugin-build-service.ts | 22 ++++--- test/services/android-plugin-build-service.ts | 57 +++++++++++++++++++ 2 files changed, 72 insertions(+), 7 deletions(-) diff --git a/lib/services/android-plugin-build-service.ts b/lib/services/android-plugin-build-service.ts index a0ac29c2eb..c557ac410c 100644 --- a/lib/services/android-plugin-build-service.ts +++ b/lib/services/android-plugin-build-service.ts @@ -254,7 +254,7 @@ export class AndroidPluginBuildService implements IAndroidPluginBuildService { ...staleAars.map((staleAar) => staleAar.aarPath), ], ); - this.removeStaleAars(options.pluginName, staleAars); + this.ensureStaleAarsAreBuildOutputs(options.pluginName, staleAars); const shouldBuildAar = await this.shouldBuildAar({ hasAarSources, @@ -297,6 +297,8 @@ export class AndroidPluginBuildService implements IAndroidPluginBuildService { this.writePluginHashInfo(pluginSourceFileHashesInfo, pluginTempDir); } + this.removeStaleAars(staleAars); + return shouldBuildAar; } @@ -388,12 +390,10 @@ export class AndroidPluginBuildService implements IAndroidPluginBuildService { } } - /** - * Gradle templates add every aar in a plugin's platforms/android to the app, - * so an aar the CLI built for this plugin under another candidate name would - * duplicate its classes. - */ - private removeStaleAars(pluginName: string, staleAars: IStaleAar[]): void { + private ensureStaleAarsAreBuildOutputs( + pluginName: string, + staleAars: IStaleAar[], + ): void { for (const { aarPath, previousOutputPath } of staleAars) { if ( previousOutputPath && @@ -404,7 +404,15 @@ export class AndroidPluginBuildService implements IAndroidPluginBuildService { ); } } + } + /** + * Gradle templates add every aar in a plugin's platforms/android to the app, + * so an aar the CLI built for this plugin under another candidate name would + * duplicate its classes. Only call once the aar under the current name + * exists, so a failed build leaves the plugin with its previous aar. + */ + private removeStaleAars(staleAars: IStaleAar[]): void { for (const { aarPath } of staleAars) { this.$watchIgnoreListService.addFileToIgnoreList(aarPath); this.$logger.trace(`Removing stale plugin aar ${aarPath}`); diff --git a/test/services/android-plugin-build-service.ts b/test/services/android-plugin-build-service.ts index 583b72686c..8600a390df 100644 --- a/test/services/android-plugin-build-service.ts +++ b/test/services/android-plugin-build-service.ts @@ -24,6 +24,7 @@ describe("androidPluginBuildService", () => { const pluginName = "my-plugin"; const shortPluginName = getShortPluginName(pluginName); let spawnFromEventCalled = false; + let failGradleBuild = false; let ignoredFiles: string[] = []; let hashedFiles: string[] = []; let fs: IFileSystem; @@ -75,12 +76,16 @@ describe("androidPluginBuildService", () => { hasChangesInShasums?: boolean; }): void { const testInjector: IInjector = new stubs.InjectorStub(); + failGradleBuild = false; testInjector.register("fs", FsLib.FileSystem); testInjector.register("childProcess", { spawnFromEvent: async ( command: string, args: string[], ): Promise => { + if (failGradleBuild) { + throw new Error("Gradle build failed"); + } const pluginDir = args[args.indexOf("-p") + 1]; const aar = path.join( pluginDir, @@ -513,6 +518,58 @@ dependencies { assert.isFalse(androidBuildPluginService.hasOutdatedAar(config)); }); + it("keeps the short-name aar when the build fails", async () => { + const config = setupScoped(); + const staleAar = path.join(pluginFolder, `${shortPluginName}.aar`); + fs.writeFile(staleAar, "previous build"); + failGradleBuild = true; + + await assert.isRejected( + androidBuildPluginService.buildAar(config), + /Gradle build failed/, + ); + + assert.equal(fs.readText(staleAar), "previous build"); + assert.isFalse( + fs.exists(path.join(pluginFolder, `${qualifiedName}.aar`)), + ); + assert.isTrue(androidBuildPluginService.hasOutdatedAar(config)); + }); + + it("deletes the short-name aar only once the new aar is in place", async () => { + const config = setupScoped(); + const newAar = path.join(pluginFolder, `${qualifiedName}.aar`); + const staleAar = path.join(pluginFolder, `${shortPluginName}.aar`); + fs.writeFile(staleAar, "previous build"); + const deleteFile = fs.deleteFile.bind(fs); + const newAarExistedOnDelete: boolean[] = []; + fs.deleteFile = (file: string) => { + if (file === staleAar) { + newAarExistedOnDelete.push(fs.exists(newAar)); + } + deleteFile(file); + }; + + assert.isTrue(await androidBuildPluginService.buildAar(config)); + + assert.deepStrictEqual(newAarExistedOnDelete, [true]); + assert.isFalse(fs.exists(staleAar)); + }); + + it("deletes a short-name aar that appears when no rebuild is needed", async () => { + const config = setupScoped(); + assert.isTrue(await androidBuildPluginService.buildAar(config)); + const staleAar = path.join(pluginFolder, `${shortPluginName}.aar`); + fs.writeFile(staleAar, "previous build"); + assert.isTrue(androidBuildPluginService.hasOutdatedAar(config)); + + assert.isFalse(await androidBuildPluginService.buildAar(config)); + + assert.isFalse(fs.exists(staleAar)); + assert.include(ignoredFiles, staleAar); + assert.isFalse(androidBuildPluginService.hasOutdatedAar(config)); + }); + it("deletes the old short-name aars of clashing plugins built by an older CLI", async () => { const foo = setupScoped({ pluginName: "@foo/plugin-x",