From cfa86f3040bb05e702da1c2704246777f1848c69 Mon Sep 17 00:00:00 2001 From: rosen-vladimirov Date: Fri, 25 Aug 2017 13:19:35 +0300 Subject: [PATCH] Add prefer-const rule to tslint Enable `prefer-const` rule in tslint and fix the errors: The rule requires that variable declarations use const instead of let and var if possible. If a variable is only assigned to once when it is declared, it should be declared using `const` Add new npm script for automatic fix of tslint: `npm run tslint-fix`. NOTE: In case you have 3 errors that the script can fix, when you execute `npm run tslint-fix`, it will fix them, but will print them as errors again. Run the command again to verify everything is ok. --- lib/android-tools-info.ts | 56 ++-- lib/commands/add-platform.ts | 2 +- lib/commands/appstore-list.ts | 8 +- lib/commands/appstore-upload.ts | 24 +- lib/commands/build.ts | 2 +- lib/commands/clean-app.ts | 4 +- lib/commands/debug.ts | 4 +- lib/commands/install.ts | 8 +- lib/commands/list-platforms.ts | 6 +- lib/commands/platform-clean.ts | 2 +- lib/commands/plugin/add-plugin.ts | 4 +- lib/commands/plugin/list-plugins.ts | 16 +- lib/commands/plugin/remove-plugin.ts | 4 +- lib/commands/plugin/update-plugin.ts | 10 +- lib/commands/remove-platform.ts | 2 +- lib/commands/run.ts | 2 +- lib/commands/test-init.ts | 22 +- lib/commands/update-platform.ts | 2 +- lib/commands/update.ts | 26 +- lib/common | 2 +- lib/config.ts | 2 +- lib/device-path-provider.ts | 2 +- lib/device-sockets/ios/packet-stream.ts | 4 +- .../ios/socket-proxy-factory.ts | 16 +- lib/dynamic-help-provider.ts | 2 +- lib/node-package-manager.ts | 24 +- lib/npm-installation-manager.ts | 24 +- lib/options.ts | 6 +- lib/providers/project-files-provider.ts | 12 +- lib/services/analytics-settings-service.ts | 2 +- lib/services/android-debug-service.ts | 14 +- .../android-project-properties-manager.ts | 18 +- lib/services/android-project-service.ts | 104 +++---- lib/services/app-files-updater.ts | 6 +- lib/services/cocoapods-service.ts | 18 +- lib/services/doctor-service.ts | 28 +- lib/services/emulator-platform-service.ts | 50 ++-- lib/services/emulator-settings-service.ts | 4 +- lib/services/info-service.ts | 4 +- lib/services/init-service.ts | 34 +-- lib/services/ios-debug-service.ts | 22 +- lib/services/ios-entitlements-service.ts | 16 +- lib/services/ios-log-filter.ts | 28 +- lib/services/ios-project-service.ts | 280 +++++++++--------- lib/services/itmstransporter-service.ts | 26 +- lib/services/karma-execution.ts | 2 +- .../android-device-livesync-service.ts | 8 +- .../livesync/ios-device-livesync-service.ts | 12 +- lib/services/livesync/livesync-service.ts | 18 +- .../platform-livesync-service-base.ts | 2 +- lib/services/platform-project-service-base.ts | 6 +- lib/services/platform-service.ts | 172 +++++------ lib/services/plugin-variables-service.ts | 20 +- lib/services/plugins-service.ts | 74 ++--- lib/services/project-changes-service.ts | 40 +-- lib/services/project-data-service.ts | 6 +- lib/services/project-name-service.ts | 6 +- lib/services/project-service.ts | 36 +-- lib/services/project-templates-service.ts | 2 +- lib/services/subscription-service.ts | 10 +- lib/services/test-execution-service.ts | 42 +-- lib/services/user-settings-service.ts | 2 +- lib/services/versions-service.ts | 46 +-- lib/services/xcconfig-service.ts | 4 +- lib/services/xcproj-service.ts | 12 +- lib/sys-info.ts | 2 +- .../node-modules-dependencies-builder.ts | 6 +- .../node-modules/node-modules-dest-copy.ts | 28 +- lib/xml-validator.ts | 12 +- package.json | 3 +- test/android-project-properties-manager.ts | 72 ++--- test/cocoapods-service.ts | 8 +- test/debug.ts | 10 +- test/ios-entitlements-service.ts | 40 +-- test/ios-project-service.ts | 214 ++++++------- test/npm-installation-manager.ts | 12 +- test/npm-support.ts | 102 +++---- test/platform-commands.ts | 8 +- test/platform-service.ts | 188 ++++++------ test/plugin-variables-service.ts | 196 ++++++------ test/plugins-service.ts | 178 +++++------ test/post-install.ts | 2 +- test/project-changes-service.ts | 16 +- test/project-commands.ts | 4 +- test/project-files-provider.ts | 32 +- test/project-name-service.ts | 18 +- test/project-service.ts | 150 +++++----- test/project-templates-service.ts | 18 +- test/services/extensibility-service.ts | 4 +- test/services/project-data-service.ts | 6 +- test/services/subscription-service.ts | 2 +- test/stubs.ts | 12 +- test/tns-appstore-upload.ts | 4 +- .../node-modules-dependencies-builder.ts | 10 +- test/xcconfig-service.ts | 58 ++-- tslint.json | 1 + 96 files changed, 1445 insertions(+), 1443 deletions(-) diff --git a/lib/android-tools-info.ts b/lib/android-tools-info.ts index 32667f66b4..020b1b3dcd 100644 --- a/lib/android-tools-info.ts +++ b/lib/android-tools-info.ts @@ -29,7 +29,7 @@ export class AndroidToolsInfo implements IAndroidToolsInfo { @cache() public getToolsInfo(): IAndroidToolsInfoData { if (!this.toolsInfo) { - let infoData: IAndroidToolsInfoData = Object.create(null); + const infoData: IAndroidToolsInfoData = Object.create(null); infoData.androidHomeEnvVar = this.androidHome; infoData.compileSdkVersion = this.getCompileSdkVersion(); infoData.buildToolsVersion = this.getBuildToolsVersion(); @@ -46,8 +46,8 @@ export class AndroidToolsInfo implements IAndroidToolsInfo { public validateInfo(options?: { showWarningsAsErrors: boolean, validateTargetSdk: boolean }): boolean { let detectedErrors = false; this.showWarningsAsErrors = options && options.showWarningsAsErrors; - let toolsInfoData = this.getToolsInfo(); - let isAndroidHomeValid = this.validateAndroidHomeEnvVariable(); + const toolsInfoData = this.getToolsInfo(); + const isAndroidHomeValid = this.validateAndroidHomeEnvVariable(); if (!toolsInfoData.compileSdkVersion) { this.printMessage(`Cannot find a compatible Android SDK for compilation. To be able to build for Android, install Android SDK ${AndroidToolsInfo.MIN_REQUIRED_COMPILE_TARGET} or later.`, `Run \`\$ ${this.getPathToSdkManagementTool()}\` to manage your Android SDK versions.`); @@ -55,8 +55,8 @@ export class AndroidToolsInfo implements IAndroidToolsInfo { } if (!toolsInfoData.buildToolsVersion) { - let buildToolsRange = this.getBuildToolsRange(); - let versionRangeMatches = buildToolsRange.match(/^.*?([\d\.]+)\s+.*?([\d\.]+)$/); + const buildToolsRange = this.getBuildToolsRange(); + const versionRangeMatches = buildToolsRange.match(/^.*?([\d\.]+)\s+.*?([\d\.]+)$/); let message = `You can install any version in the following range: '${buildToolsRange}'.`; // Improve message in case buildToolsRange is something like: ">=22.0.0 <=22.0.0" - same numbers on both sides @@ -83,11 +83,11 @@ export class AndroidToolsInfo implements IAndroidToolsInfo { } if (options && options.validateTargetSdk) { - let targetSdk = toolsInfoData.targetSdkVersion; - let newTarget = `${AndroidToolsInfo.ANDROID_TARGET_PREFIX}-${targetSdk}`; + const targetSdk = toolsInfoData.targetSdkVersion; + const newTarget = `${AndroidToolsInfo.ANDROID_TARGET_PREFIX}-${targetSdk}`; if (!_.includes(AndroidToolsInfo.SUPPORTED_TARGETS, newTarget)) { - let supportedVersions = AndroidToolsInfo.SUPPORTED_TARGETS.sort(); - let minSupportedVersion = this.parseAndroidSdkString(_.first(supportedVersions)); + const supportedVersions = AndroidToolsInfo.SUPPORTED_TARGETS.sort(); + const minSupportedVersion = this.parseAndroidSdkString(_.first(supportedVersions)); if (targetSdk && (targetSdk < minSupportedVersion)) { this.printMessage(`The selected Android target SDK ${newTarget} is not supported. You must target ${minSupportedVersion} or later.`); @@ -107,10 +107,10 @@ export class AndroidToolsInfo implements IAndroidToolsInfo { this.showWarningsAsErrors = options.showWarningsAsErrors; } - let additionalMessage = "You will not be able to build your projects for Android." + EOL + const additionalMessage = "You will not be able to build your projects for Android." + EOL + "To be able to build for Android, verify that you have installed The Java Development Kit (JDK) and configured it according to system requirements as" + EOL + " described in " + this.$staticConfig.SYS_REQUIREMENTS_LINK; - let matchingVersion = (installedJavaVersion || "").match(AndroidToolsInfo.VERSION_REGEX); + const matchingVersion = (installedJavaVersion || "").match(AndroidToolsInfo.VERSION_REGEX); if (matchingVersion && matchingVersion[1]) { if (semver.lt(matchingVersion[1], AndroidToolsInfo.MIN_JAVA_VERSION)) { hasProblemWithJavaVersion = true; @@ -126,7 +126,7 @@ export class AndroidToolsInfo implements IAndroidToolsInfo { public async getPathToAdbFromAndroidHome(): Promise { if (this.androidHome) { - let pathToAdb = path.join(this.androidHome, "platform-tools", "adb"); + const pathToAdb = path.join(this.androidHome, "platform-tools", "adb"); try { await this.$childProcess.execFile(pathToAdb, ["help"]); return pathToAdb; @@ -212,19 +212,19 @@ export class AndroidToolsInfo implements IAndroidToolsInfo { private getCompileSdkVersion(): number { if (!this.selectedCompileSdk) { - let userSpecifiedCompileSdk = this.$options.compileSdk; + const userSpecifiedCompileSdk = this.$options.compileSdk; if (userSpecifiedCompileSdk) { - let installedTargets = this.getInstalledTargets(); - let androidCompileSdk = `${AndroidToolsInfo.ANDROID_TARGET_PREFIX}-${userSpecifiedCompileSdk}`; + const installedTargets = this.getInstalledTargets(); + const androidCompileSdk = `${AndroidToolsInfo.ANDROID_TARGET_PREFIX}-${userSpecifiedCompileSdk}`; if (!_.includes(installedTargets, androidCompileSdk)) { this.$errors.failWithoutHelp(`You have specified '${userSpecifiedCompileSdk}' for compile sdk, but it is not installed on your system.`); } this.selectedCompileSdk = userSpecifiedCompileSdk; } else { - let latestValidAndroidTarget = this.getLatestValidAndroidTarget(); + const latestValidAndroidTarget = this.getLatestValidAndroidTarget(); if (latestValidAndroidTarget) { - let integerVersion = this.parseAndroidSdkString(latestValidAndroidTarget); + const integerVersion = this.parseAndroidSdkString(latestValidAndroidTarget); if (integerVersion && integerVersion >= AndroidToolsInfo.MIN_REQUIRED_COMPILE_TARGET) { this.selectedCompileSdk = integerVersion; @@ -237,7 +237,7 @@ export class AndroidToolsInfo implements IAndroidToolsInfo { } private getTargetSdk(): number { - let targetSdk = this.$options.sdk ? parseInt(this.$options.sdk) : this.getCompileSdkVersion(); + const targetSdk = this.$options.sdk ? parseInt(this.$options.sdk) : this.getCompileSdkVersion(); this.$logger.trace(`Selected targetSdk is: ${targetSdk}`); return targetSdk; } @@ -245,12 +245,12 @@ export class AndroidToolsInfo implements IAndroidToolsInfo { private getMatchingDir(pathToDir: string, versionRange: string): string { let selectedVersion: string; if (this.$fs.exists(pathToDir)) { - let subDirs = this.$fs.readDirectory(pathToDir); + const subDirs = this.$fs.readDirectory(pathToDir); this.$logger.trace(`Directories found in ${pathToDir} are ${subDirs.join(", ")}`); - let subDirsVersions = subDirs + const subDirsVersions = subDirs .map(dirName => { - let dirNameGroups = dirName.match(AndroidToolsInfo.VERSION_REGEX); + const dirNameGroups = dirName.match(AndroidToolsInfo.VERSION_REGEX); if (dirNameGroups) { return dirNameGroups[1]; } @@ -259,7 +259,7 @@ export class AndroidToolsInfo implements IAndroidToolsInfo { }) .filter(dirName => !!dirName); this.$logger.trace(`Versions found in ${pathToDir} are ${subDirsVersions.join(", ")}`); - let version = semver.maxSatisfying(subDirsVersions, versionRange); + const version = semver.maxSatisfying(subDirsVersions, versionRange); if (version) { selectedVersion = _.find(subDirs, dir => dir.indexOf(version) !== -1); } @@ -275,8 +275,8 @@ export class AndroidToolsInfo implements IAndroidToolsInfo { private getBuildToolsVersion(): string { let buildToolsVersion: string; if (this.androidHome) { - let pathToBuildTools = path.join(this.androidHome, "build-tools"); - let buildToolsRange = this.getBuildToolsRange(); + const pathToBuildTools = path.join(this.androidHome, "build-tools"); + const buildToolsRange = this.getBuildToolsRange(); buildToolsVersion = this.getMatchingDir(pathToBuildTools, buildToolsRange); } @@ -284,7 +284,7 @@ export class AndroidToolsInfo implements IAndroidToolsInfo { } private getAppCompatRange(): string { - let compileSdkVersion = this.getCompileSdkVersion(); + const compileSdkVersion = this.getCompileSdkVersion(); let requiredAppCompatRange: string; if (compileSdkVersion) { requiredAppCompatRange = `>=${compileSdkVersion} <${compileSdkVersion + 1}`; @@ -295,9 +295,9 @@ export class AndroidToolsInfo implements IAndroidToolsInfo { private getAndroidSupportRepositoryVersion(): string { let selectedAppCompatVersion: string; - let requiredAppCompatRange = this.getAppCompatRange(); + const requiredAppCompatRange = this.getAppCompatRange(); if (this.androidHome && requiredAppCompatRange) { - let pathToAppCompat = path.join(this.androidHome, "extras", "android", "m2repository", "com", "android", "support", "appcompat-v7"); + const pathToAppCompat = path.join(this.androidHome, "extras", "android", "m2repository", "com", "android", "support", "appcompat-v7"); selectedAppCompatVersion = this.getMatchingDir(pathToAppCompat, requiredAppCompatRange); } @@ -306,7 +306,7 @@ export class AndroidToolsInfo implements IAndroidToolsInfo { } private getLatestValidAndroidTarget(): string { - let installedTargets = this.getInstalledTargets(); + const installedTargets = this.getInstalledTargets(); return _.findLast(AndroidToolsInfo.SUPPORTED_TARGETS.sort(), supportedTarget => _.includes(installedTargets, supportedTarget)); } diff --git a/lib/commands/add-platform.ts b/lib/commands/add-platform.ts index ddb6156c9f..5a597c5d6f 100644 --- a/lib/commands/add-platform.ts +++ b/lib/commands/add-platform.ts @@ -18,7 +18,7 @@ export class AddPlatformCommand implements ICommand { this.$errors.fail("No platform specified. Please specify a platform to add"); } - for (let arg of args) { + for (const arg of args) { this.$platformService.validatePlatform(arg, this.$projectData); const platformData = this.$platformsData.getPlatformData(arg, this.$projectData); const platformProjectService = platformData.platformProjectService; diff --git a/lib/commands/appstore-list.ts b/lib/commands/appstore-list.ts index 379508f538..6313a2f64b 100644 --- a/lib/commands/appstore-list.ts +++ b/lib/commands/appstore-list.ts @@ -20,8 +20,8 @@ export class ListiOSApps implements ICommand { this.$errors.fail(`Applications for platform ${this.$devicePlatformsConstants.iOS} can not be built on this OS`); } - let username = args[0], - password = args[1]; + let username = args[0]; + let password = args[1]; if (!username) { username = await this.$prompter.getString("Apple ID", { allowEmpty: false }); @@ -31,12 +31,12 @@ export class ListiOSApps implements ICommand { password = await this.$prompter.getPassword("Apple ID password"); } - let iOSApplications = await this.$itmsTransporterService.getiOSApplications({ username, password }); + const iOSApplications = await this.$itmsTransporterService.getiOSApplications({ username, password }); if (!iOSApplications || !iOSApplications.length) { this.$logger.out("Seems you don't have any applications yet."); } else { - let table: any = createTable(["Application Name", "Bundle Identifier", "Version"], iOSApplications.map(element => { + const table: any = createTable(["Application Name", "Bundle Identifier", "Version"], iOSApplications.map(element => { return [element.name, element.bundleId, element.version]; })); diff --git a/lib/commands/appstore-upload.ts b/lib/commands/appstore-upload.ts index 48671fea98..9968d0faf3 100644 --- a/lib/commands/appstore-upload.ts +++ b/lib/commands/appstore-upload.ts @@ -28,12 +28,12 @@ export class PublishIOS implements ICommand { } public async execute(args: string[]): Promise { - let username = args[0], - password = args[1], - mobileProvisionIdentifier = args[2], - codeSignIdentity = args[3], - teamID = this.$options.teamId, - ipaFilePath = this.$options.ipa ? path.resolve(this.$options.ipa) : null; + let username = args[0]; + let password = args[1]; + const mobileProvisionIdentifier = args[2]; + const codeSignIdentity = args[3]; + const teamID = this.$options.teamId; + let ipaFilePath = this.$options.ipa ? path.resolve(this.$options.ipa) : null; if (!username) { username = await this.$prompter.getString("Apple ID", { allowEmpty: false }); @@ -54,11 +54,11 @@ export class PublishIOS implements ICommand { this.$options.release = true; if (!ipaFilePath) { - let platform = this.$devicePlatformsConstants.iOS; + const platform = this.$devicePlatformsConstants.iOS; // No .ipa path provided, build .ipa on out own. const appFilesUpdaterOptions: IAppFilesUpdaterOptions = { bundle: this.$options.bundle, release: this.$options.release }; if (mobileProvisionIdentifier || codeSignIdentity) { - let iOSBuildConfig: IBuildConfig = { + const iOSBuildConfig: IBuildConfig = { projectDir: this.$options.path, release: this.$options.release, device: this.$options.device, @@ -77,13 +77,13 @@ export class PublishIOS implements ICommand { this.$logger.info("No .ipa, mobile provision or certificate set. Perfect! Now we'll build .xcarchive and let Xcode pick the distribution certificate and provisioning profile for you when exporting .ipa for AppStore submission."); await this.$platformService.preparePlatform(platform, appFilesUpdaterOptions, this.$options.platformTemplate, this.$projectData, this.$options); - let platformData = this.$platformsData.getPlatformData(platform, this.$projectData); - let iOSProjectService = platformData.platformProjectService; + const platformData = this.$platformsData.getPlatformData(platform, this.$projectData); + const iOSProjectService = platformData.platformProjectService; - let archivePath = await iOSProjectService.archive(this.$projectData); + const archivePath = await iOSProjectService.archive(this.$projectData); this.$logger.info("Archive at: " + archivePath); - let exportPath = await iOSProjectService.exportArchive(this.$projectData, { archivePath, teamID, provision: mobileProvisionIdentifier || this.$options.provision }); + const exportPath = await iOSProjectService.exportArchive(this.$projectData, { archivePath, teamID, provision: mobileProvisionIdentifier || this.$options.provision }); this.$logger.info("Export at: " + exportPath); ipaFilePath = exportPath; diff --git a/lib/commands/build.ts b/lib/commands/build.ts index 04b86c12e4..f03710a2b6 100644 --- a/lib/commands/build.ts +++ b/lib/commands/build.ts @@ -9,7 +9,7 @@ export class BuildCommandBase { } public async executeCore(args: string[]): Promise { - let platform = args[0].toLowerCase(); + const platform = args[0].toLowerCase(); const appFilesUpdaterOptions: IAppFilesUpdaterOptions = { bundle: this.$options.bundle, release: this.$options.release }; await this.$platformService.preparePlatform(platform, appFilesUpdaterOptions, this.$options.platformTemplate, this.$projectData, this.$options); this.$options.clean = true; diff --git a/lib/commands/clean-app.ts b/lib/commands/clean-app.ts index f948b4bfe8..b32718804d 100644 --- a/lib/commands/clean-app.ts +++ b/lib/commands/clean-app.ts @@ -23,8 +23,8 @@ export class CleanAppCommandBase implements ICommand { this.$errors.fail(`Applications for platform ${this.platform} can not be built on this OS`); } - let platformData = this.$platformsData.getPlatformData(this.platform, this.$projectData); - let platformProjectService = platformData.platformProjectService; + const platformData = this.$platformsData.getPlatformData(this.platform, this.$projectData); + const platformProjectService = platformData.platformProjectService; await platformProjectService.validate(this.$projectData); return true; } diff --git a/lib/commands/debug.ts b/lib/commands/debug.ts index 6ac49ad201..3b5d4ef9d8 100644 --- a/lib/commands/debug.ts +++ b/lib/commands/debug.ts @@ -1,4 +1,4 @@ -import { CONNECTED_STATUS } from "../common/constants"; +import { CONNECTED_STATUS } from "../common/constants"; import { isInteractive } from "../common/helpers"; import { cache } from "../common/decorators"; import { DebugCommandErrors } from "../constants"; @@ -24,7 +24,7 @@ export class DebugPlatformCommand implements ICommand { public async execute(args: string[]): Promise { const debugOptions = _.cloneDeep(this.$options.argv); - let debugData = this.$debugDataService.createDebugData(this.$projectData, this.$options); + const debugData = this.$debugDataService.createDebugData(this.$projectData, this.$options); await this.$platformService.trackProjectType(this.$projectData); const selectedDeviceForDebug = await this.getDeviceForDebug(); diff --git a/lib/commands/install.ts b/lib/commands/install.ts index 798eed654b..69be170ea7 100644 --- a/lib/commands/install.ts +++ b/lib/commands/install.ts @@ -26,8 +26,8 @@ export class InstallCommand implements ICommand { await this.$pluginsService.ensureAllDependenciesAreInstalled(this.$projectData); - for (let platform of this.$platformsData.platformsNames) { - let platformData = this.$platformsData.getPlatformData(platform, this.$projectData); + for (const platform of this.$platformsData.platformsNames) { + const platformData = this.$platformsData.getPlatformData(platform, this.$projectData); const frameworkPackageData = this.$projectDataService.getNSValue(this.$projectData.projectDir, platformData.frameworkPackageName); if (frameworkPackageData && frameworkPackageData.version) { try { @@ -47,9 +47,9 @@ export class InstallCommand implements ICommand { } private async installModule(moduleName: string): Promise { - let projectDir = this.$projectData.projectDir; + const projectDir = this.$projectData.projectDir; - let devPrefix = 'nativescript-dev-'; + const devPrefix = 'nativescript-dev-'; if (!this.$fs.exists(moduleName) && moduleName.indexOf(devPrefix) !== 0) { moduleName = devPrefix + moduleName; } diff --git a/lib/commands/list-platforms.ts b/lib/commands/list-platforms.ts index a90326b717..7210609be8 100644 --- a/lib/commands/list-platforms.ts +++ b/lib/commands/list-platforms.ts @@ -10,10 +10,10 @@ export class ListPlatformsCommand implements ICommand { } public async execute(args: string[]): Promise { - let installedPlatforms = this.$platformService.getInstalledPlatforms(this.$projectData); + const installedPlatforms = this.$platformService.getInstalledPlatforms(this.$projectData); if (installedPlatforms.length > 0) { - let preparedPlatforms = this.$platformService.getPreparedPlatforms(this.$projectData); + const preparedPlatforms = this.$platformService.getPreparedPlatforms(this.$projectData); if (preparedPlatforms.length > 0) { this.$logger.out("The project is prepared for: ", helpers.formatListOfNames(preparedPlatforms, "and")); } else { @@ -22,7 +22,7 @@ export class ListPlatformsCommand implements ICommand { this.$logger.out("Installed platforms: ", helpers.formatListOfNames(installedPlatforms, "and")); } else { - let formattedPlatformsList = helpers.formatListOfNames(this.$platformService.getAvailablePlatforms(this.$projectData), "and"); + const formattedPlatformsList = helpers.formatListOfNames(this.$platformService.getAvailablePlatforms(this.$projectData), "and"); this.$logger.out("Available platforms for this OS: ", formattedPlatformsList); this.$logger.out("No installed platforms found. Use $ tns platform add"); } diff --git a/lib/commands/platform-clean.ts b/lib/commands/platform-clean.ts index 046ece328b..5542372de9 100644 --- a/lib/commands/platform-clean.ts +++ b/lib/commands/platform-clean.ts @@ -18,7 +18,7 @@ export class CleanCommand implements ICommand { this.$errors.fail("No platform specified. Please specify a platform to clean"); } - for (let platform of args) { + for (const platform of args) { this.$platformService.validatePlatformInstalled(platform, this.$projectData); const platformData = this.$platformsData.getPlatformData(platform, this.$projectData); diff --git a/lib/commands/plugin/add-plugin.ts b/lib/commands/plugin/add-plugin.ts index ed9fd44d3d..a2830b007d 100644 --- a/lib/commands/plugin/add-plugin.ts +++ b/lib/commands/plugin/add-plugin.ts @@ -16,8 +16,8 @@ export class AddPluginCommand implements ICommand { this.$errors.fail("You must specify plugin name."); } - let installedPlugins = await this.$pluginsService.getAllInstalledPlugins(this.$projectData); - let pluginName = args[0].toLowerCase(); + const installedPlugins = await this.$pluginsService.getAllInstalledPlugins(this.$projectData); + const pluginName = args[0].toLowerCase(); if (_.some(installedPlugins, (plugin: IPluginData) => plugin.name.toLowerCase() === pluginName)) { this.$errors.failWithoutHelp(`Plugin "${pluginName}" is already installed.`); } diff --git a/lib/commands/plugin/list-plugins.ts b/lib/commands/plugin/list-plugins.ts index cc5d52e480..f9afa9c316 100644 --- a/lib/commands/plugin/list-plugins.ts +++ b/lib/commands/plugin/list-plugins.ts @@ -10,19 +10,19 @@ export class ListPluginsCommand implements ICommand { } public async execute(args: string[]): Promise { - let installedPlugins: IPackageJsonDepedenciesResult = this.$pluginsService.getDependenciesFromPackageJson(this.$projectData.projectDir); + const installedPlugins: IPackageJsonDepedenciesResult = this.$pluginsService.getDependenciesFromPackageJson(this.$projectData.projectDir); - let headers: string[] = ["Plugin", "Version"]; - let dependenciesData: string[][] = this.createTableCells(installedPlugins.dependencies); + const headers: string[] = ["Plugin", "Version"]; + const dependenciesData: string[][] = this.createTableCells(installedPlugins.dependencies); - let dependenciesTable: any = createTable(headers, dependenciesData); + const dependenciesTable: any = createTable(headers, dependenciesData); this.$logger.out("Dependencies:"); this.$logger.out(dependenciesTable.toString()); if (installedPlugins.devDependencies && installedPlugins.devDependencies.length) { - let devDependenciesData: string[][] = this.createTableCells(installedPlugins.devDependencies); + const devDependenciesData: string[][] = this.createTableCells(installedPlugins.devDependencies); - let devDependenciesTable: any = createTable(headers, devDependenciesData); + const devDependenciesTable: any = createTable(headers, devDependenciesData); this.$logger.out("Dev Dependencies:"); this.$logger.out(devDependenciesTable.toString()); @@ -30,8 +30,8 @@ export class ListPluginsCommand implements ICommand { this.$logger.out("There are no dev dependencies."); } - let viewDependenciesCommand: string = "npm view grep dependencies".cyan.toString(); - let viewDevDependenciesCommand: string = "npm view grep devDependencies".cyan.toString(); + const viewDependenciesCommand: string = "npm view grep dependencies".cyan.toString(); + const viewDevDependenciesCommand: string = "npm view grep devDependencies".cyan.toString(); this.$logger.warn("NOTE:"); this.$logger.warn(`If you want to check the dependencies of installed plugin use ${viewDependenciesCommand}`); diff --git a/lib/commands/plugin/remove-plugin.ts b/lib/commands/plugin/remove-plugin.ts index 9bd07e9a28..9edd83df22 100644 --- a/lib/commands/plugin/remove-plugin.ts +++ b/lib/commands/plugin/remove-plugin.ts @@ -20,14 +20,14 @@ export class RemovePluginCommand implements ICommand { let pluginNames: string[] = []; try { // try installing the plugins, so we can get information from node_modules about their native code, libs, etc. - let installedPlugins = await this.$pluginsService.getAllInstalledPlugins(this.$projectData); + const installedPlugins = await this.$pluginsService.getAllInstalledPlugins(this.$projectData); pluginNames = installedPlugins.map(pl => pl.name); } catch (err) { this.$logger.trace("Error while installing plugins. Error is:", err); pluginNames = _.keys(this.$projectData.dependencies); } - let pluginName = args[0].toLowerCase(); + const pluginName = args[0].toLowerCase(); if (!_.some(pluginNames, name => name.toLowerCase() === pluginName)) { this.$errors.failWithoutHelp(`Plugin "${pluginName}" is not installed.`); } diff --git a/lib/commands/plugin/update-plugin.ts b/lib/commands/plugin/update-plugin.ts index b0d03d1941..d0b9db4f83 100644 --- a/lib/commands/plugin/update-plugin.ts +++ b/lib/commands/plugin/update-plugin.ts @@ -9,11 +9,11 @@ export class UpdatePluginCommand implements ICommand { let pluginNames = args; if (!pluginNames || args.length === 0) { - let installedPlugins = await this.$pluginsService.getAllInstalledPlugins(this.$projectData); + const installedPlugins = await this.$pluginsService.getAllInstalledPlugins(this.$projectData); pluginNames = installedPlugins.map(p => p.name); } - for (let pluginName of pluginNames) { + for (const pluginName of pluginNames) { await this.$pluginsService.remove(pluginName, this.$projectData); await this.$pluginsService.add(pluginName, this.$projectData); } @@ -24,10 +24,10 @@ export class UpdatePluginCommand implements ICommand { return true; } - let installedPlugins = await this.$pluginsService.getAllInstalledPlugins(this.$projectData); - let installedPluginNames: string[] = installedPlugins.map(pl => pl.name); + const installedPlugins = await this.$pluginsService.getAllInstalledPlugins(this.$projectData); + const installedPluginNames: string[] = installedPlugins.map(pl => pl.name); - let pluginName = args[0].toLowerCase(); + const pluginName = args[0].toLowerCase(); if (!_.some(installedPluginNames, name => name.toLowerCase() === pluginName)) { this.$errors.failWithoutHelp(`Plugin "${pluginName}" is not installed.`); } diff --git a/lib/commands/remove-platform.ts b/lib/commands/remove-platform.ts index 38b7ca016d..e6132e14bf 100644 --- a/lib/commands/remove-platform.ts +++ b/lib/commands/remove-platform.ts @@ -17,7 +17,7 @@ export class RemovePlatformCommand implements ICommand { this.$errors.fail("No platform specified. Please specify a platform to remove"); } - for (let platform of args) { + for (const platform of args) { this.$platformService.validatePlatformInstalled(platform, this.$projectData); const platformData = this.$platformsData.getPlatformData(platform, this.$projectData); const platformProjectService = platformData.platformProjectService; diff --git a/lib/commands/run.ts b/lib/commands/run.ts index 28b76c92de..da4da5148b 100644 --- a/lib/commands/run.ts +++ b/lib/commands/run.ts @@ -34,7 +34,7 @@ export class RunCommandBase implements ICommand { } const availablePlatforms = this.$liveSyncCommandHelper.getPlatformsForOperation(this.platform); - for (let platform of availablePlatforms) { + for (const platform of availablePlatforms) { const platformData = this.$platformsData.getPlatformData(platform, this.$projectData); const platformProjectService = platformData.platformProjectService; await platformProjectService.validate(this.$projectData); diff --git a/lib/commands/test-init.ts b/lib/commands/test-init.ts index b04a261e0f..2cf77223a5 100644 --- a/lib/commands/test-init.ts +++ b/lib/commands/test-init.ts @@ -21,18 +21,18 @@ class TestInitCommand implements ICommand { } public async execute(args: string[]): Promise { - let projectDir = this.$projectData.projectDir; + const projectDir = this.$projectData.projectDir; - let frameworkToInstall = this.$options.framework || + const frameworkToInstall = this.$options.framework || await this.$prompter.promptForChoice('Select testing framework:', TESTING_FRAMEWORKS); if (TESTING_FRAMEWORKS.indexOf(frameworkToInstall) === -1) { this.$errors.fail(`Unknown or unsupported unit testing framework: ${frameworkToInstall}`); } - let dependencies = this.frameworkDependencies[frameworkToInstall] || []; - let modulesToInstall = ['karma', 'karma-' + frameworkToInstall, 'karma-nativescript-launcher'].concat(dependencies.map(f => 'karma-' + f)); + const dependencies = this.frameworkDependencies[frameworkToInstall] || []; + const modulesToInstall = ['karma', 'karma-' + frameworkToInstall, 'karma-nativescript-launcher'].concat(dependencies.map(f => 'karma-' + f)); - for (let mod of modulesToInstall) { + for (const mod of modulesToInstall) { await this.$npm.install(mod, projectDir, { 'save-dev': true, optional: false, @@ -47,8 +47,8 @@ class TestInitCommand implements ICommand { const modulePackageJsonContent = this.$fs.readJson(modulePackageJsonPath); const modulePeerDependencies = modulePackageJsonContent.peerDependencies || {}; - for (let peerDependency in modulePeerDependencies) { - let dependencyVersion = modulePeerDependencies[peerDependency] || "*"; + for (const peerDependency in modulePeerDependencies) { + const dependencyVersion = modulePeerDependencies[peerDependency] || "*"; // catch errors when a peerDependency is already installed // e.g karma is installed; karma-jasmine depends on karma and will try to install it again @@ -68,7 +68,7 @@ class TestInitCommand implements ICommand { await this.$pluginsService.add('nativescript-unit-test-runner', this.$projectData); - let testsDir = path.join(projectDir, 'app/tests'); + const testsDir = path.join(projectDir, 'app/tests'); let shouldCreateSampleTests = true; if (this.$fs.exists(testsDir)) { this.$logger.info('app/tests/ directory already exists, will not create an example test project.'); @@ -77,8 +77,8 @@ class TestInitCommand implements ICommand { this.$fs.ensureDirectoryExists(testsDir); - let karmaConfTemplate = this.$resources.readText('test/karma.conf.js'); - let karmaConf = _.template(karmaConfTemplate)({ + const karmaConfTemplate = this.$resources.readText('test/karma.conf.js'); + const karmaConf = _.template(karmaConfTemplate)({ frameworks: [frameworkToInstall].concat(dependencies) .map(fw => `'${fw}'`) .join(', ') @@ -86,7 +86,7 @@ class TestInitCommand implements ICommand { this.$fs.writeFile(path.join(projectDir, 'karma.conf.js'), karmaConf); - let exampleFilePath = this.$resources.resolvePath(`test/example.${frameworkToInstall}.js`); + const exampleFilePath = this.$resources.resolvePath(`test/example.${frameworkToInstall}.js`); if (shouldCreateSampleTests && this.$fs.exists(exampleFilePath)) { this.$fs.copyFile(exampleFilePath, path.join(testsDir, 'example.js')); diff --git a/lib/commands/update-platform.ts b/lib/commands/update-platform.ts index 78975d546e..7dc8c1dae3 100644 --- a/lib/commands/update-platform.ts +++ b/lib/commands/update-platform.ts @@ -18,7 +18,7 @@ export class UpdatePlatformCommand implements ICommand { this.$errors.fail("No platform specified. Please specify platforms to update."); } - for (let arg of args) { + for (const arg of args) { const platform = arg.split("@")[0]; this.$platformService.validatePlatform(platform, this.$projectData); const platformData = this.$platformsData.getPlatformData(platform, this.$projectData); diff --git a/lib/commands/update.ts b/lib/commands/update.ts index ca5ba7e888..2669740cca 100644 --- a/lib/commands/update.ts +++ b/lib/commands/update.ts @@ -16,15 +16,15 @@ export class UpdateCommand implements ICommand { } public async execute(args: string[]): Promise { - let folders = ["lib", "hooks", "platforms", "node_modules"]; - let tmpDir = path.join(this.$projectData.projectDir, ".tmp_backup"); + const folders = ["lib", "hooks", "platforms", "node_modules"]; + const tmpDir = path.join(this.$projectData.projectDir, ".tmp_backup"); try { shelljs.rm("-fr", tmpDir); shelljs.mkdir(tmpDir); shelljs.cp(path.join(this.$projectData.projectDir, "package.json"), tmpDir); - for (let folder of folders) { - let folderToCopy = path.join(this.$projectData.projectDir, folder); + for (const folder of folders) { + const folderToCopy = path.join(this.$projectData.projectDir, folder); if (this.$fs.exists(folderToCopy)) { shelljs.cp("-rf", folderToCopy, tmpDir); } @@ -38,10 +38,10 @@ export class UpdateCommand implements ICommand { await this.executeCore(args, folders); } catch (error) { shelljs.cp("-f", path.join(tmpDir, "package.json"), this.$projectData.projectDir); - for (let folder of folders) { + for (const folder of folders) { shelljs.rm("-rf", path.join(this.$projectData.projectDir, folder)); - let folderToCopy = path.join(tmpDir, folder); + const folderToCopy = path.join(tmpDir, folder); if (this.$fs.exists(folderToCopy)) { shelljs.cp("-fr", folderToCopy, this.$projectData.projectDir); @@ -55,7 +55,7 @@ export class UpdateCommand implements ICommand { } public async canExecute(args: string[]): Promise { - for (let arg of args) { + for (const arg of args) { const platform = arg.split("@")[0]; this.$platformService.validatePlatformInstalled(platform, this.$projectData); const platformData = this.$platformsData.getPlatformData(platform, this.$projectData); @@ -68,11 +68,11 @@ export class UpdateCommand implements ICommand { private async executeCore(args: string[], folders: string[]): Promise { let platforms = this.$platformService.getInstalledPlatforms(this.$projectData); - let availablePlatforms = this.$platformService.getAvailablePlatforms(this.$projectData); - let packagePlatforms: string[] = []; + const availablePlatforms = this.$platformService.getAvailablePlatforms(this.$projectData); + const packagePlatforms: string[] = []; - for (let platform of availablePlatforms) { - let platformData = this.$platformsData.getPlatformData(platform, this.$projectData); + for (const platform of availablePlatforms) { + const platformData = this.$platformsData.getPlatformData(platform, this.$projectData); const platformVersion = this.$projectDataService.getNSValue(this.$projectData.projectDir, platformData.frameworkPackageName); if (platformVersion) { packagePlatforms.push(platform); @@ -84,13 +84,13 @@ export class UpdateCommand implements ICommand { await this.$pluginsService.remove("tns-core-modules", this.$projectData); await this.$pluginsService.remove("tns-core-modules-widgets", this.$projectData); - for (let folder of folders) { + for (const folder of folders) { shelljs.rm("-fr", folder); } platforms = platforms.concat(packagePlatforms); if (args.length === 1) { - for (let platform of platforms) { + for (const platform of platforms) { await this.$platformService.addPlatforms([platform + "@" + args[0]], this.$options.platformTemplate, this.$projectData, this.$options, this.$options.frameworkPath); } diff --git a/lib/common b/lib/common index ef87c15950..5b4c6da25c 160000 --- a/lib/common +++ b/lib/common @@ -1 +1 @@ -Subproject commit ef87c15950c43c8ebf6c217f3ec192cf9e18af94 +Subproject commit 5b4c6da25ca015f52756431ddc63b5a7fbd8a995 diff --git a/lib/config.ts b/lib/config.ts index 52265023cb..247c721ede 100644 --- a/lib/config.ts +++ b/lib/config.ts @@ -78,7 +78,7 @@ export class StaticConfig extends StaticConfigBase implements IStaticConfig { public async getAdbFilePath(): Promise { if (!this._adbFilePath) { - let androidToolsInfo: IAndroidToolsInfo = this.$injector.resolve("androidToolsInfo"); + const androidToolsInfo: IAndroidToolsInfo = this.$injector.resolve("androidToolsInfo"); this._adbFilePath = await androidToolsInfo.getPathToAdbFromAndroidHome() || await super.getAdbFilePath(); } diff --git a/lib/device-path-provider.ts b/lib/device-path-provider.ts index ee360590ec..dba30ee452 100644 --- a/lib/device-path-provider.ts +++ b/lib/device-path-provider.ts @@ -13,7 +13,7 @@ export class DevicePathProvider implements IDevicePathProvider { let projectRoot = ""; if (this.$mobileHelper.isiOSPlatform(device.deviceInfo.platform)) { if (device.isEmulator) { - let applicationPath = this.$iOSSimResolver.iOSSim.getApplicationPath(device.deviceInfo.identifier, options.appIdentifier); + const applicationPath = this.$iOSSimResolver.iOSSim.getApplicationPath(device.deviceInfo.identifier, options.appIdentifier); projectRoot = path.join(applicationPath); } else { projectRoot = LiveSyncPaths.IOS_DEVICE_PROJECT_ROOT_PATH; diff --git a/lib/device-sockets/ios/packet-stream.ts b/lib/device-sockets/ios/packet-stream.ts index accbbfb9ca..7a4fbbe2f6 100644 --- a/lib/device-sockets/ios/packet-stream.ts +++ b/lib/device-sockets/ios/packet-stream.ts @@ -12,14 +12,14 @@ export class PacketStream extends stream.Transform { while (packet.length > 0) { if (!this.buffer) { // read length - let length = packet.readInt32BE(0); + const length = packet.readInt32BE(0); this.buffer = new Buffer(length); this.offset = 0; packet = packet.slice(4); } packet.copy(this.buffer, this.offset); - let copied = Math.min(this.buffer.length - this.offset, packet.length); + const copied = Math.min(this.buffer.length - this.offset, packet.length); this.offset += copied; packet = packet.slice(copied); diff --git a/lib/device-sockets/ios/socket-proxy-factory.ts b/lib/device-sockets/ios/socket-proxy-factory.ts index 7cace33215..33a75b7b03 100644 --- a/lib/device-sockets/ios/socket-proxy-factory.ts +++ b/lib/device-sockets/ios/socket-proxy-factory.ts @@ -19,7 +19,7 @@ export class SocketProxyFactory extends EventEmitter implements ISocketProxyFact this.$logger.info("\nSetting up proxy...\nPress Ctrl + C to terminate, or disconnect.\n"); - let server = net.createServer({ + const server = net.createServer({ allowHalfOpen: true }); @@ -63,7 +63,7 @@ export class SocketProxyFactory extends EventEmitter implements ISocketProxyFact }); }); - let socketFileLocation = temp.path({ suffix: ".sock" }); + const socketFileLocation = temp.path({ suffix: ".sock" }); server.listen(socketFileLocation); if (!this.$options.client) { this.$logger.info("socket-file-location: " + socketFileLocation); @@ -83,7 +83,7 @@ export class SocketProxyFactory extends EventEmitter implements ISocketProxyFact // We store the socket that connects us to the device in the upgrade request object itself and later on retrieve it // in the connection callback. - let server = new ws.Server({ + const server = new ws.Server({ port: localPort, verifyClient: async (info: any, callback: Function) => { this.$logger.info("Frontend client connected."); @@ -102,10 +102,10 @@ export class SocketProxyFactory extends EventEmitter implements ISocketProxyFact } }); server.on("connection", (webSocket) => { - let encoding = "utf16le"; + const encoding = "utf16le"; - let deviceSocket: net.Socket = (webSocket.upgradeReq)["__deviceSocket"]; - let packets = new PacketStream(); + const deviceSocket: net.Socket = (webSocket.upgradeReq)["__deviceSocket"]; + const packets = new PacketStream(); deviceSocket.pipe(packets); packets.on("data", (buffer: Buffer) => { @@ -121,8 +121,8 @@ export class SocketProxyFactory extends EventEmitter implements ISocketProxyFact }); webSocket.on("message", (message, flags) => { - let length = Buffer.byteLength(message, encoding); - let payload = new Buffer(length + 4); + const length = Buffer.byteLength(message, encoding); + const payload = new Buffer(length + 4); payload.writeInt32BE(length, 0); payload.write(message, 4, length, encoding); deviceSocket.write(payload); diff --git a/lib/dynamic-help-provider.ts b/lib/dynamic-help-provider.ts index 84aa255f27..ab8c43d3b0 100644 --- a/lib/dynamic-help-provider.ts +++ b/lib/dynamic-help-provider.ts @@ -6,7 +6,7 @@ export class DynamicHelpProvider implements IDynamicHelpProvider { } public getLocalVariables(options: { isHtml: boolean }): IDictionary { - let localVariables: IDictionary = { + const localVariables: IDictionary = { constants: constants }; return localVariables; diff --git a/lib/node-package-manager.ts b/lib/node-package-manager.ts index f3b5a39ba4..60ca9c9d54 100644 --- a/lib/node-package-manager.ts +++ b/lib/node-package-manager.ts @@ -21,10 +21,10 @@ export class NodePackageManager implements INodePackageManager { config["ignore-scripts"] = true; } - let packageJsonPath = path.join(pathToSave, "package.json"); - let jsonContentBefore = this.$fs.readJson(packageJsonPath); + const packageJsonPath = path.join(pathToSave, "package.json"); + const jsonContentBefore = this.$fs.readJson(packageJsonPath); - let flags = this.getFlagsString(config, true); + const flags = this.getFlagsString(config, true); let params = ["install"]; const isInstallingAllDependencies = packageName === pathToSave; if (!isInstallingAllDependencies) { @@ -32,7 +32,7 @@ export class NodePackageManager implements INodePackageManager { } params = params.concat(flags); - let cwd = pathToSave; + const cwd = pathToSave; // Npm creates `etc` directory in installation dir when --prefix is passed // https://github.com/npm/npm/issues/11486 // we should delete it if it was created because of us @@ -51,7 +51,7 @@ export class NodePackageManager implements INodePackageManager { } try { - let spawnResult: ISpawnResult = await this.getNpmInstallResult(params, cwd); + const spawnResult: ISpawnResult = await this.getNpmInstallResult(params, cwd); // Whenever calling npm install without any arguments (hence installing all dependencies) no output is emitted on stdout // Luckily, whenever you call npm install to install all dependencies chances are you won't need the name/version of the package you're installing because there is none. @@ -64,7 +64,7 @@ export class NodePackageManager implements INodePackageManager { // We cannot use the actual install with --json to get the information because of post-install scripts which may print on stdout // dry-run install is quite fast when the dependencies are already installed even for many dependencies (e.g. angular) so we can live with this approach // We need the --prefix here because without it no output is emitted on stdout because all the dependencies are already installed. - let spawnNpmDryRunResult = await this.$childProcess.spawnFromEvent(this.getNpmExecutableName(), params, "close"); + const spawnNpmDryRunResult = await this.$childProcess.spawnFromEvent(this.getNpmExecutableName(), params, "close"); return this.parseNpmInstallResult(spawnNpmDryRunResult.stdout, spawnResult.stdout, packageName); } catch (err) { if (err.message && err.message.indexOf("EPEERINVALID") !== -1) { @@ -100,7 +100,7 @@ export class NodePackageManager implements INodePackageManager { public async view(packageName: string, config: Object): Promise { const wrappedConfig = _.extend({}, config, { json: true }); // always require view response as JSON - let flags = this.getFlagsString(wrappedConfig, false); + const flags = this.getFlagsString(wrappedConfig, false); let viewResult: any; try { viewResult = await this.$childProcess.exec(`npm view ${packageName} ${flags}`); @@ -121,8 +121,8 @@ export class NodePackageManager implements INodePackageManager { } private getFlagsString(config: any, asArray: boolean): any { - let array: Array = []; - for (let flag in config) { + const array: Array = []; + for (const flag in config) { if (flag === "global") { array.push(`--${flag}`); array.push(`${config[flag]}`); @@ -176,7 +176,7 @@ export class NodePackageManager implements INodePackageManager { this.$logger.trace(`Unable to parse result of npm --dry-run operation. Output is: ${npmDryRunInstallOutput}.`); this.$logger.trace("Now we'll try to parse the real output of npm install command."); - let npmOutputMatchRegExp = /^.--\s+(?!UNMET)(.*)@((?:\d+\.){2}\d+)/m; + const npmOutputMatchRegExp = /^.--\s+(?!UNMET)(.*)@((?:\d+\.){2}\d+)/m; const match = npmInstallOutput.match(npmOutputMatchRegExp); if (match) { return { @@ -192,8 +192,8 @@ export class NodePackageManager implements INodePackageManager { private getDependencyInformation(dependency: string): INpmInstallResultInfo { const scopeDependencyMatch = dependency.match(NodePackageManager.SCOPED_DEPENDENCY_REGEXP); - let name: string = null, - version: string = null; + let name: string = null; + let version: string = null; if (scopeDependencyMatch) { name = scopeDependencyMatch[1]; diff --git a/lib/npm-installation-manager.ts b/lib/npm-installation-manager.ts index 7a4728912c..0911fcecd5 100644 --- a/lib/npm-installation-manager.ts +++ b/lib/npm-installation-manager.ts @@ -41,10 +41,10 @@ export class NpmInstallationManager implements INpmInstallationManager { public async install(packageName: string, projectDir: string, opts?: INpmInstallOptions): Promise { try { - let packageToInstall = this.$options.frameworkPath || packageName; - let pathToSave = projectDir; - let version = (opts && opts.version) || null; - let dependencyType = (opts && opts.dependencyType) || null; + const packageToInstall = this.$options.frameworkPath || packageName; + const pathToSave = projectDir; + const version = (opts && opts.version) || null; + const dependencyType = (opts && opts.dependencyType) || null; return await this.installCore(packageToInstall, pathToSave, version, dependencyType); } catch (error) { @@ -55,7 +55,7 @@ export class NpmInstallationManager implements INpmInstallationManager { } public async getInspectorFromCache(inspectorNpmPackageName: string, projectDir: string): Promise { - let inspectorPath = path.join(projectDir, constants.NODE_MODULES_FOLDER_NAME, inspectorNpmPackageName); + const inspectorPath = path.join(projectDir, constants.NODE_MODULES_FOLDER_NAME, inspectorNpmPackageName); // local installation takes precedence over cache if (!this.inspectorAlreadyInstalled(inspectorPath)) { @@ -107,10 +107,10 @@ export class NpmInstallationManager implements INpmInstallationManager { version = version || await this.getLatestCompatibleVersion(packageName); } - let installResultInfo = await this.npmInstall(packageName, pathToSave, version, dependencyType); - let installedPackageName = installResultInfo.name; + const installResultInfo = await this.npmInstall(packageName, pathToSave, version, dependencyType); + const installedPackageName = installResultInfo.name; - let pathToInstalledPackage = path.join(pathToSave, "node_modules", installedPackageName); + const pathToInstalledPackage = path.join(pathToSave, "node_modules", installedPackageName); return pathToInstalledPackage; } @@ -119,8 +119,8 @@ export class NpmInstallationManager implements INpmInstallationManager { } private isURL(str: string): boolean { - let urlRegex = '^(?!mailto:)(?:(?:http|https|ftp)://)(?:\\S+(?::\\S*)?@)?(?:(?:(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[0-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)(?:\\.(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)*(?:\\.(?:[a-z\\u00a1-\\uffff]{2,})))|localhost)(?::\\d{2,5})?(?:(/|\\?|#)[^\\s]*)?$'; - let url = new RegExp(urlRegex, 'i'); + const urlRegex = '^(?!mailto:)(?:(?:http|https|ftp)://)(?:\\S+(?::\\S*)?@)?(?:(?:(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[0-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)(?:\\.(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)*(?:\\.(?:[a-z\\u00a1-\\uffff]{2,})))|localhost)(?::\\d{2,5})?(?:(/|\\?|#)[^\\s]*)?$'; + const url = new RegExp(urlRegex, 'i'); return str.length < 2083 && url.test(str); } @@ -129,7 +129,7 @@ export class NpmInstallationManager implements INpmInstallationManager { packageName = packageName + (version ? `@${version}` : ""); - let npmOptions: any = { silent: true, "save-exact": true }; + const npmOptions: any = { silent: true, "save-exact": true }; if (dependencyType) { npmOptions[dependencyType] = true; @@ -143,7 +143,7 @@ export class NpmInstallationManager implements INpmInstallationManager { * because npm view doens't work with those */ private async getVersion(packageName: string, version: string): Promise { - let data: any = await this.$npm.view(packageName, { "dist-tags": true }); + const data: any = await this.$npm.view(packageName, { "dist-tags": true }); this.$logger.trace("Using version %s. ", data[version]); return data[version]; diff --git a/lib/options.ts b/lib/options.ts index a5c960007a..4d73db3e4c 100644 --- a/lib/options.ts +++ b/lib/options.ts @@ -2,7 +2,7 @@ import * as commonOptionsLibPath from "./common/options"; import * as osenv from "osenv"; import * as path from "path"; -let OptionType = commonOptionsLibPath.OptionType; +const OptionType = commonOptionsLibPath.OptionType; export class Options extends commonOptionsLibPath.OptionsBase { constructor($errors: IErrors, @@ -48,7 +48,7 @@ export class Options extends commonOptionsLibPath.OptionsBase { // I guess we can remove this code after some grace period, say after 1.7 is out if ($hostInfo.isWindows) { try { - let shelljs = require("shelljs"), + const shelljs = require("shelljs"), oldSettings = path.join(process.env.LocalAppData, ".nativescript-cli", "user-settings.json"), newSettings = path.join(process.env.AppData, ".nativescript-cli", "user-settings.json"); if (shelljs.test("-e", oldSettings) && !shelljs.test("-e", newSettings)) { @@ -60,7 +60,7 @@ export class Options extends commonOptionsLibPath.OptionsBase { } } - let that = (this); + const that = (this); // if justlaunch is set, it takes precedence over the --watch flag and the default true value if (that.justlaunch) { that.watch = false; diff --git a/lib/providers/project-files-provider.ts b/lib/providers/project-files-provider.ts index 6a70fb2592..89917e1da0 100644 --- a/lib/providers/project-files-provider.ts +++ b/lib/providers/project-files-provider.ts @@ -13,24 +13,24 @@ export class ProjectFilesProvider extends ProjectFilesProviderBase { private static INTERNAL_NONPROJECT_FILES = [ "**/*.ts" ]; public mapFilePath(filePath: string, platform: string, projectData: IProjectData, projectFilesConfig: IProjectFilesConfig): string { - let platformData = this.$platformsData.getPlatformData(platform.toLowerCase(), projectData); - let parsedFilePath = this.getPreparedFilePath(filePath, projectFilesConfig); + const platformData = this.$platformsData.getPlatformData(platform.toLowerCase(), projectData); + const parsedFilePath = this.getPreparedFilePath(filePath, projectFilesConfig); let mappedFilePath = ""; if (parsedFilePath.indexOf(constants.NODE_MODULES_FOLDER_NAME) > -1) { - let relativePath = path.relative(path.join(projectData.projectDir, constants.NODE_MODULES_FOLDER_NAME), parsedFilePath); + const relativePath = path.relative(path.join(projectData.projectDir, constants.NODE_MODULES_FOLDER_NAME), parsedFilePath); mappedFilePath = path.join(platformData.appDestinationDirectoryPath, constants.APP_FOLDER_NAME, constants.TNS_MODULES_FOLDER_NAME, relativePath); } else { mappedFilePath = path.join(platformData.appDestinationDirectoryPath, path.relative(projectData.projectDir, parsedFilePath)); } - let appResourcesDirectoryPath = path.join(constants.APP_FOLDER_NAME, constants.APP_RESOURCES_FOLDER_NAME); - let platformSpecificAppResourcesDirectoryPath = path.join(appResourcesDirectoryPath, platformData.normalizedPlatformName); + const appResourcesDirectoryPath = path.join(constants.APP_FOLDER_NAME, constants.APP_RESOURCES_FOLDER_NAME); + const platformSpecificAppResourcesDirectoryPath = path.join(appResourcesDirectoryPath, platformData.normalizedPlatformName); if (parsedFilePath.indexOf(appResourcesDirectoryPath) > -1 && parsedFilePath.indexOf(platformSpecificAppResourcesDirectoryPath) === -1) { return null; } if (parsedFilePath.indexOf(platformSpecificAppResourcesDirectoryPath) > -1) { - let appResourcesRelativePath = path.relative(path.join(projectData.projectDir, constants.APP_FOLDER_NAME, constants.APP_RESOURCES_FOLDER_NAME, + const appResourcesRelativePath = path.relative(path.join(projectData.projectDir, constants.APP_FOLDER_NAME, constants.APP_RESOURCES_FOLDER_NAME, platformData.normalizedPlatformName), parsedFilePath); mappedFilePath = path.join(platformData.platformProjectService.getAppResourcesDestinationDirectoryPath(projectData), appResourcesRelativePath); } diff --git a/lib/services/analytics-settings-service.ts b/lib/services/analytics-settings-service.ts index ef21d53a36..2147bbd273 100644 --- a/lib/services/analytics-settings-service.ts +++ b/lib/services/analytics-settings-service.ts @@ -33,7 +33,7 @@ class AnalyticsSettingsService implements IAnalyticsSettingsService { } public async getUserSessionsCount(projectName: string): Promise { - let oldSessionCount = await this.$userSettingsService.getSettingValue(AnalyticsSettingsService.SESSIONS_STARTED_OBSOLETE_KEY); + const oldSessionCount = await this.$userSettingsService.getSettingValue(AnalyticsSettingsService.SESSIONS_STARTED_OBSOLETE_KEY); if (oldSessionCount) { // remove the old property for sessions count diff --git a/lib/services/android-debug-service.ts b/lib/services/android-debug-service.ts index 65b3cd25d7..a161179e93 100644 --- a/lib/services/android-debug-service.ts +++ b/lib/services/android-debug-service.ts @@ -58,13 +58,13 @@ export class AndroidDebugService extends DebugServiceBase implements IPlatformDe private async getForwardedLocalDebugPortForPackageName(deviceId: string, packageName: string): Promise { let port = -1; - let forwardsResult = await this.device.adb.executeCommand(["forward", "--list"]); + const forwardsResult = await this.device.adb.executeCommand(["forward", "--list"]); - let unixSocketName = `${packageName}-inspectorServer`; + const unixSocketName = `${packageName}-inspectorServer`; //matches 123a188909e6czzc tcp:40001 localabstract:org.nativescript.testUnixSockets-debug - let regexp = new RegExp(`(?:${deviceId} tcp:)([\\d]+)(?= localabstract:${unixSocketName})`, "g"); - let match = regexp.exec(forwardsResult); + const regexp = new RegExp(`(?:${deviceId} tcp:)([\\d]+)(?= localabstract:${unixSocketName})`, "g"); + const match = regexp.exec(forwardsResult); if (match) { port = parseInt(match[1]); @@ -112,7 +112,7 @@ export class AndroidDebugService extends DebugServiceBase implements IPlatformDe } private async printDebugPort(deviceId: string, packageName: string): Promise { - let port = await this.getForwardedLocalDebugPortForPackageName(deviceId, packageName); + const port = await this.getForwardedLocalDebugPortForPackageName(deviceId, packageName); this.$logger.info("device: " + deviceId + " debug port: " + port + "\n"); } @@ -145,11 +145,11 @@ export class AndroidDebugService extends DebugServiceBase implements IPlatformDe } private async waitForDebugger(packageName: String): Promise { - let waitText: string = `0 /data/local/tmp/${packageName}-debugger-started`; + const waitText: string = `0 /data/local/tmp/${packageName}-debugger-started`; let maxWait = 12; let debuggerStarted: boolean = false; while (maxWait > 0 && !debuggerStarted) { - let forwardsResult = await this.device.adb.executeShellCommand(["ls", "-s", `/data/local/tmp/${packageName}-debugger-started`]); + const forwardsResult = await this.device.adb.executeShellCommand(["ls", "-s", `/data/local/tmp/${packageName}-debugger-started`]); maxWait--; diff --git a/lib/services/android-project-properties-manager.ts b/lib/services/android-project-properties-manager.ts index 2d1b250779..71a1338b61 100644 --- a/lib/services/android-project-properties-manager.ts +++ b/lib/services/android-project-properties-manager.ts @@ -14,8 +14,8 @@ export class AndroidProjectPropertiesManager implements IAndroidProjectPropertie public async getProjectReferences(): Promise { if (!this.projectReferences || this.dirty) { - let allProjectProperties = await this.getAllProjectProperties(); - let allProjectPropertiesKeys = _.keys(allProjectProperties); + const allProjectProperties = await this.getAllProjectProperties(); + const allProjectPropertiesKeys = _.keys(allProjectProperties); this.projectReferences = _(allProjectPropertiesKeys) .filter(key => _.startsWith(key, "android.library.reference.")) .map(key => this.createLibraryReference(key, allProjectProperties[key])) @@ -26,16 +26,16 @@ export class AndroidProjectPropertiesManager implements IAndroidProjectPropertie } public async addProjectReference(referencePath: string): Promise { - let references = await this.getProjectReferences(); - let libRefExists = _.some(references, r => path.normalize(r.path) === path.normalize(referencePath)); + const references = await this.getProjectReferences(); + const libRefExists = _.some(references, r => path.normalize(r.path) === path.normalize(referencePath)); if (!libRefExists) { await this.addToPropertyList("android.library.reference", referencePath); } } public async removeProjectReference(referencePath: string): Promise { - let references = await this.getProjectReferences(); - let libRefExists = _.some(references, r => path.normalize(r.path) === path.normalize(referencePath)); + const references = await this.getProjectReferences(); + const libRefExists = _.some(references, r => path.normalize(r.path) === path.normalize(referencePath)); if (libRefExists) { await this.removeFromPropertyList("android.library.reference", referencePath); } else { @@ -65,7 +65,7 @@ export class AndroidProjectPropertiesManager implements IAndroidProjectPropertie } private async addToPropertyList(key: string, value: string): Promise { - let editor = await this.createEditor(); + const editor = await this.createEditor(); let i = 1; while (editor.get(this.buildKeyName(key, i))) { i++; @@ -77,8 +77,8 @@ export class AndroidProjectPropertiesManager implements IAndroidProjectPropertie } private async removeFromPropertyList(key: string, value: string): Promise { - let editor = await this.createEditor(); - let valueLowerCase = value.toLowerCase(); + const editor = await this.createEditor(); + const valueLowerCase = value.toLowerCase(); let i = 1; let currentValue: any; while (currentValue = editor.get(this.buildKeyName(key, i))) { diff --git a/lib/services/android-project-service.ts b/lib/services/android-project-service.ts index 4406bf8064..f8ef8c412a 100644 --- a/lib/services/android-project-service.ts +++ b/lib/services/android-project-service.ts @@ -49,8 +49,8 @@ export class AndroidProjectService extends projectServiceBaseLib.PlatformProject if (projectData && projectData.platformsDir && this._platformsDirCache !== projectData.platformsDir) { this._platformsDirCache = projectData.platformsDir; - let projectRoot = path.join(projectData.platformsDir, "android"); - let packageName = this.getProjectNameFromId(projectData); + const projectRoot = path.join(projectData.platformsDir, "android"); + const packageName = this.getProjectNameFromId(projectData); this._platformData = { frameworkPackageName: "tns-android", normalizedPlatformName: "Android", @@ -97,7 +97,7 @@ export class AndroidProjectService extends projectServiceBaseLib.PlatformProject this.$androidToolsInfo.validateAndroidHomeEnvVariable({ showWarningsAsErrors: true }); - let javaCompilerVersion = await this.$sysInfo.getJavaCompilerVersion(); + const javaCompilerVersion = await this.$sysInfo.getJavaCompilerVersion(); await this.$androidToolsInfo.validateJavacVersion(javaCompilerVersion, { showWarningsAsErrors: true }); @@ -114,13 +114,13 @@ export class AndroidProjectService extends projectServiceBaseLib.PlatformProject } this.$fs.ensureDirectoryExists(this.getPlatformData(projectData).projectRoot); - let androidToolsInfo = this.$androidToolsInfo.getToolsInfo(); - let targetSdkVersion = androidToolsInfo && androidToolsInfo.targetSdkVersion; + const androidToolsInfo = this.$androidToolsInfo.getToolsInfo(); + const targetSdkVersion = androidToolsInfo && androidToolsInfo.targetSdkVersion; this.$logger.trace(`Using Android SDK '${targetSdkVersion}'.`); this.copy(this.getPlatformData(projectData).projectRoot, frameworkDir, "libs", "-R"); if (config.pathToTemplate) { - let mainPath = path.join(this.getPlatformData(projectData).projectRoot, "src", "main"); + const mainPath = path.join(this.getPlatformData(projectData).projectRoot, "src", "main"); this.$fs.createDirectory(mainPath); shell.cp("-R", path.join(path.resolve(config.pathToTemplate), "*"), mainPath); } else { @@ -139,7 +139,7 @@ export class AndroidProjectService extends projectServiceBaseLib.PlatformProject this.cleanResValues(targetSdkVersion, projectData, frameworkVersion); - let npmConfig: INodePackageManagerInstallOptions = { + const npmConfig: INodePackageManagerInstallOptions = { save: true, "save-dev": true, "save-exact": true, @@ -149,20 +149,20 @@ export class AndroidProjectService extends projectServiceBaseLib.PlatformProject ignoreScripts: config.ignoreScripts }; - let projectPackageJson: any = this.$fs.readJson(projectData.projectFilePath); + const projectPackageJson: any = this.$fs.readJson(projectData.projectFilePath); - for (let dependency of AndroidProjectService.REQUIRED_DEV_DEPENDENCIES) { + for (const dependency of AndroidProjectService.REQUIRED_DEV_DEPENDENCIES) { let dependencyVersionInProject = (projectPackageJson.dependencies && projectPackageJson.dependencies[dependency.name]) || (projectPackageJson.devDependencies && projectPackageJson.devDependencies[dependency.name]); if (!dependencyVersionInProject) { await this.$npm.install(`${dependency.name}@${dependency.version}`, projectData.projectDir, npmConfig); } else { - let cleanedVerson = semver.clean(dependencyVersionInProject); + const cleanedVerson = semver.clean(dependencyVersionInProject); // The plugin version is not valid. Check node_modules for the valid version. if (!cleanedVerson) { - let pathToPluginPackageJson = path.join(projectData.projectDir, constants.NODE_MODULES_FOLDER_NAME, dependency.name, constants.PACKAGE_JSON_FILE_NAME); + const pathToPluginPackageJson = path.join(projectData.projectDir, constants.NODE_MODULES_FOLDER_NAME, dependency.name, constants.PACKAGE_JSON_FILE_NAME); dependencyVersionInProject = this.$fs.exists(pathToPluginPackageJson) && this.$fs.readJson(pathToPluginPackageJson).version; } @@ -174,9 +174,9 @@ export class AndroidProjectService extends projectServiceBaseLib.PlatformProject } private cleanResValues(targetSdkVersion: number, projectData: IProjectData, frameworkVersion: string): void { - let resDestinationDir = this.getAppResourcesDestinationDirectoryPath(projectData, frameworkVersion); - let directoriesInResFolder = this.$fs.readDirectory(resDestinationDir); - let directoriesToClean = directoriesInResFolder + const resDestinationDir = this.getAppResourcesDestinationDirectoryPath(projectData, frameworkVersion); + const directoriesInResFolder = this.$fs.readDirectory(resDestinationDir); + const directoriesToClean = directoriesInResFolder .map(dir => { return { dirName: dir, @@ -199,15 +199,15 @@ export class AndroidProjectService extends projectServiceBaseLib.PlatformProject // Interpolate the apilevel and package this.interpolateConfigurationFile(projectData, platformSpecificData); - let stringsFilePath = path.join(this.getAppResourcesDestinationDirectoryPath(projectData), 'values', 'strings.xml'); + const stringsFilePath = path.join(this.getAppResourcesDestinationDirectoryPath(projectData), 'values', 'strings.xml'); shell.sed('-i', /__NAME__/, projectData.projectName, stringsFilePath); shell.sed('-i', /__TITLE_ACTIVITY__/, projectData.projectName, stringsFilePath); - let gradleSettingsFilePath = path.join(this.getPlatformData(projectData).projectRoot, "settings.gradle"); + const gradleSettingsFilePath = path.join(this.getPlatformData(projectData).projectRoot, "settings.gradle"); shell.sed('-i', /__PROJECT_NAME__/, this.getProjectNameFromId(projectData), gradleSettingsFilePath); // will replace applicationId in app/App_Resources/Android/app.gradle if it has not been edited by the user - let userAppGradleFilePath = path.join(projectData.appResourcesDirectoryPath, this.$devicePlatformsConstants.Android, "app.gradle"); + const userAppGradleFilePath = path.join(projectData.appResourcesDirectoryPath, this.$devicePlatformsConstants.Android, "app.gradle"); try { shell.sed('-i', /__PACKAGE__/, projectData.projectId, userAppGradleFilePath); @@ -217,7 +217,7 @@ export class AndroidProjectService extends projectServiceBaseLib.PlatformProject } public interpolateConfigurationFile(projectData: IProjectData, platformSpecificData: IPlatformSpecificData): void { - let manifestPath = this.getPlatformData(projectData).configurationFilePath; + const manifestPath = this.getPlatformData(projectData).configurationFilePath; shell.sed('-i', /__PACKAGE__/, projectData.projectId, manifestPath); if (this.$androidToolsInfo.getToolsInfo().androidHomeEnvVar) { const sdk = (platformSpecificData && platformSpecificData.sdk) || (this.$androidToolsInfo.getToolsInfo().compileSdkVersion || "").toString(); @@ -228,7 +228,7 @@ export class AndroidProjectService extends projectServiceBaseLib.PlatformProject private getProjectNameFromId(projectData: IProjectData): string { let id: string; if (projectData && projectData.projectId) { - let idParts = projectData.projectId.split("."); + const idParts = projectData.projectId.split("."); id = idParts[idParts.length - 1]; } @@ -245,7 +245,7 @@ export class AndroidProjectService extends projectServiceBaseLib.PlatformProject public async updatePlatform(currentVersion: string, newVersion: string, canUpdate: boolean, projectData: IProjectData, addPlatform?: Function, removePlatforms?: (platforms: string[]) => Promise): Promise { if (semver.eq(newVersion, AndroidProjectService.MIN_RUNTIME_VERSION_WITH_GRADLE)) { - let platformLowercase = this.getPlatformData(projectData).normalizedPlatformName.toLowerCase(); + const platformLowercase = this.getPlatformData(projectData).normalizedPlatformName.toLowerCase(); await removePlatforms([platformLowercase.split("@")[0]]); await addPlatform(platformLowercase); return false; @@ -256,7 +256,7 @@ export class AndroidProjectService extends projectServiceBaseLib.PlatformProject public async buildProject(projectRoot: string, projectData: IProjectData, buildConfig: IBuildConfig): Promise { if (this.canUseGradle(projectData)) { - let buildOptions = this.getBuildOptions(buildConfig, projectData); + const buildOptions = this.getBuildOptions(buildConfig, projectData); if (this.$logger.getLevel() === "TRACE") { buildOptions.unshift("--stacktrace"); buildOptions.unshift("--debug"); @@ -284,13 +284,13 @@ export class AndroidProjectService extends projectServiceBaseLib.PlatformProject private getBuildOptions(settings: IAndroidBuildOptionsSettings, projectData: IProjectData): Array { this.$androidToolsInfo.validateInfo({ showWarningsAsErrors: true, validateTargetSdk: true }); - let androidToolsInfo = this.$androidToolsInfo.getToolsInfo(); - let compileSdk = androidToolsInfo.compileSdkVersion; - let targetSdk = this.getTargetFromAndroidManifest(projectData) || compileSdk; - let buildToolsVersion = androidToolsInfo.buildToolsVersion; - let appCompatVersion = androidToolsInfo.supportRepositoryVersion; - let generateTypings = androidToolsInfo.generateTypings; - let buildOptions = [ + const androidToolsInfo = this.$androidToolsInfo.getToolsInfo(); + const compileSdk = androidToolsInfo.compileSdkVersion; + const targetSdk = this.getTargetFromAndroidManifest(projectData) || compileSdk; + const buildToolsVersion = androidToolsInfo.buildToolsVersion; + const appCompatVersion = androidToolsInfo.supportRepositoryVersion; + const generateTypings = androidToolsInfo.generateTypings; + const buildOptions = [ `-PcompileSdk=android-${compileSdk}`, `-PtargetSdk=${targetSdk}`, `-PbuildToolsVersion=${buildToolsVersion}`, @@ -326,9 +326,9 @@ export class AndroidProjectService extends projectServiceBaseLib.PlatformProject } public ensureConfigurationFileInAppResources(projectData: IProjectData): void { - let originalAndroidManifestFilePath = path.join(projectData.appResourcesDirectoryPath, this.$devicePlatformsConstants.Android, this.getPlatformData(projectData).configurationFileName); + const originalAndroidManifestFilePath = path.join(projectData.appResourcesDirectoryPath, this.$devicePlatformsConstants.Android, this.getPlatformData(projectData).configurationFileName); - let manifestExists = this.$fs.exists(originalAndroidManifestFilePath); + const manifestExists = this.$fs.exists(originalAndroidManifestFilePath); if (!manifestExists) { this.$logger.warn('No manifest found in ' + originalAndroidManifestFilePath); @@ -339,16 +339,16 @@ export class AndroidProjectService extends projectServiceBaseLib.PlatformProject } public prepareAppResources(appResourcesDirectoryPath: string, projectData: IProjectData): void { - let resourcesDirPath = path.join(appResourcesDirectoryPath, this.getPlatformData(projectData).normalizedPlatformName); - let valuesDirRegExp = /^values/; - let resourcesDirs = this.$fs.readDirectory(resourcesDirPath).filter(resDir => !resDir.match(valuesDirRegExp)); + const resourcesDirPath = path.join(appResourcesDirectoryPath, this.getPlatformData(projectData).normalizedPlatformName); + const valuesDirRegExp = /^values/; + const resourcesDirs = this.$fs.readDirectory(resourcesDirPath).filter(resDir => !resDir.match(valuesDirRegExp)); _.each(resourcesDirs, resourceDir => { this.$fs.deleteDirectory(path.join(this.getAppResourcesDestinationDirectoryPath(projectData), resourceDir)); }); } public async preparePluginNativeCode(pluginData: IPluginData, projectData: IProjectData): Promise { - let pluginPlatformsFolderPath = this.getPluginPlatformsFolderPath(pluginData, AndroidProjectService.ANDROID_PLATFORM_NAME); + const pluginPlatformsFolderPath = this.getPluginPlatformsFolderPath(pluginData, AndroidProjectService.ANDROID_PLATFORM_NAME); await this.processResourcesFromPlugin(pluginData, pluginPlatformsFolderPath, projectData); } @@ -357,30 +357,30 @@ export class AndroidProjectService extends projectServiceBaseLib.PlatformProject } private async processResourcesFromPlugin(pluginData: IPluginData, pluginPlatformsFolderPath: string, projectData: IProjectData): Promise { - let configurationsDirectoryPath = path.join(this.getPlatformData(projectData).projectRoot, "configurations"); + const configurationsDirectoryPath = path.join(this.getPlatformData(projectData).projectRoot, "configurations"); this.$fs.ensureDirectoryExists(configurationsDirectoryPath); - let pluginConfigurationDirectoryPath = path.join(configurationsDirectoryPath, pluginData.name); + const pluginConfigurationDirectoryPath = path.join(configurationsDirectoryPath, pluginData.name); if (this.$fs.exists(pluginPlatformsFolderPath)) { this.$fs.ensureDirectoryExists(pluginConfigurationDirectoryPath); - let isScoped = pluginData.name.indexOf("@") === 0; - let flattenedDependencyName = isScoped ? pluginData.name.replace("/", "_") : pluginData.name; + const isScoped = pluginData.name.indexOf("@") === 0; + const flattenedDependencyName = isScoped ? pluginData.name.replace("/", "_") : pluginData.name; // Copy all resources from plugin - let resourcesDestinationDirectoryPath = path.join(this.getPlatformData(projectData).projectRoot, "src", flattenedDependencyName); + const resourcesDestinationDirectoryPath = path.join(this.getPlatformData(projectData).projectRoot, "src", flattenedDependencyName); this.$fs.ensureDirectoryExists(resourcesDestinationDirectoryPath); shell.cp("-Rf", path.join(pluginPlatformsFolderPath, "*"), resourcesDestinationDirectoryPath); const filesForInterpolation = this.$fs.enumerateFilesInDirectorySync(resourcesDestinationDirectoryPath, file => this.$fs.getFsStats(file).isDirectory() || path.extname(file) === constants.XML_FILE_EXTENSION) || []; - for (let file of filesForInterpolation) { + for (const file of filesForInterpolation) { this.$logger.trace(`Interpolate data for plugin file: ${file}`); await this.$pluginVariablesService.interpolate(pluginData, file, projectData); } } // Copy include.gradle file - let includeGradleFilePath = path.join(pluginPlatformsFolderPath, "include.gradle"); + const includeGradleFilePath = path.join(pluginPlatformsFolderPath, "include.gradle"); if (this.$fs.exists(includeGradleFilePath)) { shell.cp("-f", includeGradleFilePath, pluginConfigurationDirectoryPath); } @@ -389,7 +389,7 @@ export class AndroidProjectService extends projectServiceBaseLib.PlatformProject public async removePluginNativeCode(pluginData: IPluginData, projectData: IProjectData): Promise { try { // check whether the dependency that's being removed has native code - let pluginConfigDir = path.join(this.getPlatformData(projectData).projectRoot, "configurations", pluginData.name); + const pluginConfigDir = path.join(this.getPlatformData(projectData).projectRoot, "configurations", pluginData.name); if (this.$fs.exists(pluginConfigDir)) { await this.cleanProject(this.getPlatformData(projectData).projectRoot, projectData); } @@ -408,11 +408,11 @@ export class AndroidProjectService extends projectServiceBaseLib.PlatformProject public async beforePrepareAllPlugins(projectData: IProjectData, dependencies?: IDependencyData[]): Promise { if (dependencies) { - let platformDir = path.join(projectData.platformsDir, "android"); - let buildDir = path.join(platformDir, "build-tools"); - let checkV8dependants = path.join(buildDir, "check-v8-dependants.js"); + const platformDir = path.join(projectData.platformsDir, "android"); + const buildDir = path.join(platformDir, "build-tools"); + const checkV8dependants = path.join(buildDir, "check-v8-dependants.js"); if (this.$fs.exists(checkV8dependants)) { - let stringifiedDependencies = JSON.stringify(dependencies); + const stringifiedDependencies = JSON.stringify(dependencies); try { await this.spawn('node', [checkV8dependants, stringifiedDependencies, projectData.platformsDir], { stdio: "inherit" }); } catch (e) { @@ -421,7 +421,7 @@ export class AndroidProjectService extends projectServiceBaseLib.PlatformProject } } - let projectRoot = this.getPlatformData(projectData).projectRoot; + const projectRoot = this.getPlatformData(projectData).projectRoot; await this.cleanProject(projectRoot, projectData); } @@ -439,8 +439,8 @@ export class AndroidProjectService extends projectServiceBaseLib.PlatformProject } public async cleanDeviceTempFolder(deviceIdentifier: string, projectData: IProjectData): Promise { - let adb = this.$injector.resolve(DeviceAndroidDebugBridge, { identifier: deviceIdentifier }); - let deviceRootPath = `/data/local/tmp/${projectData.projectId}`; + const adb = this.$injector.resolve(DeviceAndroidDebugBridge, { identifier: deviceIdentifier }); + const deviceRootPath = `/data/local/tmp/${projectData.projectId}`; await adb.executeShellCommand(["rm", "-rf", deviceRootPath]); } @@ -463,7 +463,7 @@ export class AndroidProjectService extends projectServiceBaseLib.PlatformProject } private copy(projectRoot: string, frameworkDir: string, files: string, cpArg: string): void { - let paths = files.split(' ').map(p => path.join(frameworkDir, p)); + const paths = files.split(' ').map(p => path.join(frameworkDir, p)); shell.cp(cpArg, paths, projectRoot); } @@ -498,9 +498,9 @@ export class AndroidProjectService extends projectServiceBaseLib.PlatformProject private getTargetFromAndroidManifest(projectData: IProjectData): string { let versionInManifest: string; if (this.$fs.exists(this.getPlatformData(projectData).configurationFilePath)) { - let targetFromAndroidManifest: string = this.$fs.readText(this.getPlatformData(projectData).configurationFilePath); + const targetFromAndroidManifest: string = this.$fs.readText(this.getPlatformData(projectData).configurationFilePath); if (targetFromAndroidManifest) { - let match = targetFromAndroidManifest.match(/.*?android:targetSdkVersion=\"(.*?)\"/); + const match = targetFromAndroidManifest.match(/.*?android:targetSdkVersion=\"(.*?)\"/); if (match && match[1]) { versionInManifest = match[1]; } diff --git a/lib/services/app-files-updater.ts b/lib/services/app-files-updater.ts index dde5831ce4..f7de291a29 100644 --- a/lib/services/app-files-updater.ts +++ b/lib/services/app-files-updater.ts @@ -50,7 +50,7 @@ export class AppFilesUpdater { } protected readSourceDir(): string[] { - let tnsDir = path.join(this.appSourceDirectoryPath, constants.TNS_MODULES_FOLDER_NAME); + const tnsDir = path.join(this.appSourceDirectoryPath, constants.TNS_MODULES_FOLDER_NAME); return this.fs.enumerateFilesInDirectorySync(this.appSourceDirectoryPath, null, { includeEmptyDirectories: true }).filter(dirName => dirName !== tnsDir); } @@ -59,7 +59,7 @@ export class AppFilesUpdater { let sourceFiles = this.readSourceDir(); if (this.options.release) { - let testsFolderPath = path.join(this.appSourceDirectoryPath, 'tests'); + const testsFolderPath = path.join(this.appSourceDirectoryPath, 'tests'); sourceFiles = sourceFiles.filter(source => source.indexOf(testsFolderPath) === -1); } @@ -76,7 +76,7 @@ export class AppFilesUpdater { protected copyAppSourceFiles(sourceFiles: string[]): void { sourceFiles.map(source => { - let destinationPath = path.join(this.appDestinationDirectoryPath, path.relative(this.appSourceDirectoryPath, source)); + const destinationPath = path.join(this.appDestinationDirectoryPath, path.relative(this.appSourceDirectoryPath, source)); let exists = fs.lstatSync(source); if (exists.isSymbolicLink()) { diff --git a/lib/services/cocoapods-service.ts b/lib/services/cocoapods-service.ts index c07d49bf1a..e9f8dfc117 100644 --- a/lib/services/cocoapods-service.ts +++ b/lib/services/cocoapods-service.ts @@ -21,18 +21,18 @@ export class CocoaPodsService implements ICocoaPodsService { throw new Error(`The Podfile ${pathToPodfile} does not exist.`); } - let podfileContent = this.$fs.readText(pathToPodfile); - let hookStart = `${hookName} do`; + const podfileContent = this.$fs.readText(pathToPodfile); + const hookStart = `${hookName} do`; - let hookDefinitionRegExp = new RegExp(`${hookStart} *(\\|(\\w+)\\|)?`, "g"); + const hookDefinitionRegExp = new RegExp(`${hookStart} *(\\|(\\w+)\\|)?`, "g"); let newFunctionNameIndex = 1; - let newFunctions: IRubyFunction[] = []; + const newFunctions: IRubyFunction[] = []; - let replacedContent = podfileContent.replace(hookDefinitionRegExp, (substring: string, firstGroup: string, secondGroup: string, index: number): string => { - let newFunctionName = `${hookName}${newFunctionNameIndex++}`; + const replacedContent = podfileContent.replace(hookDefinitionRegExp, (substring: string, firstGroup: string, secondGroup: string, index: number): string => { + const newFunctionName = `${hookName}${newFunctionNameIndex++}`; let newDefinition = `def ${newFunctionName}`; - let rubyFunction: IRubyFunction = { functionName: newFunctionName }; + const rubyFunction: IRubyFunction = { functionName: newFunctionName }; // firstGroup is the block parameter, secondGroup is the block parameter name. if (firstGroup && secondGroup) { newDefinition = `${newDefinition} (${secondGroup})`; @@ -45,7 +45,7 @@ export class CocoaPodsService implements ICocoaPodsService { if (newFunctions.length > 1) { // Execute all methods in the hook and pass the parameter to them. - let blokParameterName = "installer"; + const blokParameterName = "installer"; let mergedHookContent = `${hookStart} |${blokParameterName}|${EOL}`; _.each(newFunctions, (rubyFunction: IRubyFunction) => { @@ -59,7 +59,7 @@ export class CocoaPodsService implements ICocoaPodsService { mergedHookContent = `${mergedHookContent}end`; - let newPodfileContent = `${replacedContent}${EOL}${mergedHookContent}`; + const newPodfileContent = `${replacedContent}${EOL}${mergedHookContent}`; this.$fs.writeFile(pathToPodfile, newPodfileContent); } } diff --git a/lib/services/doctor-service.ts b/lib/services/doctor-service.ts index 5b8df741a6..b2ceb4eba6 100644 --- a/lib/services/doctor-service.ts +++ b/lib/services/doctor-service.ts @@ -2,7 +2,7 @@ import { EOL } from "os"; import * as semver from "semver"; import * as path from "path"; import * as helpers from "../common/helpers"; -let clui = require("clui"); +const clui = require("clui"); class DoctorService implements IDoctorService { private static PROJECT_NAME_PLACEHOLDER = "__PROJECT_NAME__"; @@ -33,7 +33,7 @@ class DoctorService implements IDoctorService { public async printWarnings(configOptions?: { trackResult: boolean }): Promise { let result = false; - let sysInfo = await this.$sysInfo.getSysInfo(this.$staticConfig.pathToPackageJson); + const sysInfo = await this.$sysInfo.getSysInfo(this.$staticConfig.pathToPackageJson); if (!sysInfo.adbVer) { this.$logger.warn("WARNING: adb from the Android SDK is not installed or is not configured properly."); @@ -80,7 +80,7 @@ class DoctorService implements IDoctorService { } if (sysInfo.xcodeVer && sysInfo.cocoapodVer) { - let problemWithCocoaPods = await this.verifyCocoaPods(); + const problemWithCocoaPods = await this.verifyCocoaPods(); if (problemWithCocoaPods) { this.$logger.warn("WARNING: There was a problem with CocoaPods"); this.$logger.out("Verify that CocoaPods are configured properly."); @@ -103,10 +103,10 @@ class DoctorService implements IDoctorService { this.$logger.out("To be able to work with iOS devices and projects, you need Mac OS X Mavericks or later." + EOL); } - let androidToolsIssues = this.$androidToolsInfo.validateInfo(); - let javaVersionIssue = await this.$androidToolsInfo.validateJavacVersion(sysInfo.javacVersion); - let pythonIssues = await this.validatePythonPackages(); - let doctorResult = result || androidToolsIssues || javaVersionIssue || pythonIssues; + const androidToolsIssues = this.$androidToolsInfo.validateInfo(); + const javaVersionIssue = await this.$androidToolsInfo.validateJavacVersion(sysInfo.javacVersion); + const pythonIssues = await this.validatePythonPackages(); + const doctorResult = result || androidToolsIssues || javaVersionIssue || pythonIssues; if (!configOptions || configOptions.trackResult) { await this.$analyticsService.track("DoctorEnvironmentSetup", doctorResult ? "incorrect" : "correct"); @@ -157,16 +157,16 @@ class DoctorService implements IDoctorService { private async verifyCocoaPods(): Promise { this.$logger.out("Verifying CocoaPods. This may take more than a minute, please be patient."); - let temp = require("temp"); + const temp = require("temp"); temp.track(); - let projDir = temp.mkdirSync("nativescript-check-cocoapods"); - let packageJsonData = { + const projDir = temp.mkdirSync("nativescript-check-cocoapods"); + const packageJsonData = { "name": "nativescript-check-cocoapods", "version": "0.0.1" }; this.$fs.writeJson(path.join(projDir, "package.json"), packageJsonData); - let spinner = new clui.Spinner("Installing iOS runtime."); + const spinner = new clui.Spinner("Installing iOS runtime."); try { spinner.start(); await this.$npm.install("tns-ios", projDir, { @@ -178,7 +178,7 @@ class DoctorService implements IDoctorService { ignoreScripts: true }); spinner.stop(); - let iosDir = path.join(projDir, "node_modules", "tns-ios", "framework"); + const iosDir = path.join(projDir, "node_modules", "tns-ios", "framework"); this.$fs.writeFile( path.join(iosDir, "Podfile"), `${this.$cocoapodsService.getPodfileHeader(DoctorService.PROJECT_NAME_PLACEHOLDER)}pod 'AFNetworking', '~> 1.0'${this.$cocoapodsService.getPodfileFooter()}` @@ -186,7 +186,7 @@ class DoctorService implements IDoctorService { spinner.message("Verifying CocoaPods. This may take some time, please be patient."); spinner.start(); - let future = this.$childProcess.spawnFromEvent( + const future = this.$childProcess.spawnFromEvent( this.$config.USE_POD_SANDBOX ? "sandbox-pod" : "pod", ["install"], "exit", @@ -194,7 +194,7 @@ class DoctorService implements IDoctorService { { throwError: false } ); - let result = await this.$progressIndicator.showProgressIndicator(future, 5000); + const result = await this.$progressIndicator.showProgressIndicator(future, 5000); if (result.exitCode) { this.$logger.out(result.stdout, result.stderr); return true; diff --git a/lib/services/emulator-platform-service.ts b/lib/services/emulator-platform-service.ts index ead601fa6d..b2a9af9e83 100644 --- a/lib/services/emulator-platform-service.ts +++ b/lib/services/emulator-platform-service.ts @@ -16,9 +16,9 @@ export class EmulatorPlatformService implements IEmulatorPlatformService { if (this.$mobileHelper.isAndroidPlatform(info.platform)) { this.$options.avd = this.$options.device; this.$options.device = null; - let platformsData: IPlatformsData = $injector.resolve("platformsData"); - let platformData = platformsData.getPlatformData(info.platform, projectData); - let emulatorServices = platformData.emulatorServices; + const platformsData: IPlatformsData = $injector.resolve("platformsData"); + const platformData = platformsData.getPlatformData(info.platform, projectData); + const emulatorServices = platformData.emulatorServices; emulatorServices.checkAvailability(); await emulatorServices.checkDependencies(); await emulatorServices.startEmulator(); @@ -28,13 +28,13 @@ export class EmulatorPlatformService implements IEmulatorPlatformService { if (this.$mobileHelper.isiOSPlatform(info.platform)) { await this.stopEmulator(info.platform); - let deferred = deferPromise(); + const deferred = deferPromise(); await this.$childProcess.exec(`open -a Simulator --args -CurrentDeviceUDID ${info.id}`); - let timeoutFunc = async () => { + const timeoutFunc = async () => { info = await this.getEmulatorInfo("ios", info.id); if (info.isRunning) { await this.$devicesService.initialize({ platform: info.platform, deviceId: info.id }); - let device = this.$devicesService.getDeviceByIdentifier(info.id); + const device = this.$devicesService.getDeviceByIdentifier(info.id); await device.applicationManager.checkForApplicationUpdates(); deferred.resolve(); return; @@ -56,15 +56,15 @@ export class EmulatorPlatformService implements IEmulatorPlatformService { public async getEmulatorInfo(platform: string, idOrName: string): Promise { if (this.$mobileHelper.isAndroidPlatform(platform)) { - let androidEmulators = this.getAndroidEmulators(); - let found = androidEmulators.filter((info: IEmulatorInfo) => info.id === idOrName); + const androidEmulators = this.getAndroidEmulators(); + const found = androidEmulators.filter((info: IEmulatorInfo) => info.id === idOrName); if (found.length > 0) { return found[0]; } await this.$devicesService.initialize({ platform: platform, deviceId: null, skipInferPlatform: true }); let info: IEmulatorInfo = null; - let action = async (device: Mobile.IDevice) => { + const action = async (device: Mobile.IDevice) => { if (device.deviceInfo.identifier === idOrName) { info = { id: device.deviceInfo.identifier, @@ -81,15 +81,15 @@ export class EmulatorPlatformService implements IEmulatorPlatformService { } if (this.$mobileHelper.isiOSPlatform(platform)) { - let emulators = await this.getiOSEmulators(); + const emulators = await this.getiOSEmulators(); let sdk: string = null; - let versionStart = idOrName.indexOf("("); + const versionStart = idOrName.indexOf("("); if (versionStart > 0) { sdk = idOrName.substring(versionStart + 1, idOrName.indexOf(")", versionStart)).trim(); idOrName = idOrName.substring(0, versionStart - 1).trim(); } - let found = emulators.filter((info: IEmulatorInfo) => { - let sdkMatch = sdk ? info.version === sdk : true; + const found = emulators.filter((info: IEmulatorInfo) => { + const sdkMatch = sdk ? info.version === sdk : true; return sdkMatch && info.id === idOrName || info.name === idOrName; }); return found.length > 0 ? found[0] : null; @@ -102,14 +102,14 @@ export class EmulatorPlatformService implements IEmulatorPlatformService { public async listAvailableEmulators(platform: string): Promise { let emulators: IEmulatorInfo[] = []; if (!platform || this.$mobileHelper.isiOSPlatform(platform)) { - let iosEmulators = await this.getiOSEmulators(); + const iosEmulators = await this.getiOSEmulators(); if (iosEmulators) { emulators = emulators.concat(iosEmulators); } } if (!platform || this.$mobileHelper.isAndroidPlatform(platform)) { - let androidEmulators = this.getAndroidEmulators(); + const androidEmulators = this.getAndroidEmulators(); if (androidEmulators) { emulators = emulators.concat(androidEmulators); } @@ -119,20 +119,20 @@ export class EmulatorPlatformService implements IEmulatorPlatformService { } public async getiOSEmulators(): Promise { - let output = await this.$childProcess.exec("xcrun simctl list --json"); - let list = JSON.parse(output); - let emulators: IEmulatorInfo[] = []; - for (let osName in list["devices"]) { + const output = await this.$childProcess.exec("xcrun simctl list --json"); + const list = JSON.parse(output); + const emulators: IEmulatorInfo[] = []; + for (const osName in list["devices"]) { if (osName.indexOf("iOS") === -1) { continue; } - let os = list["devices"][osName]; - let version = this.parseiOSVersion(osName); - for (let device of os) { + const os = list["devices"][osName]; + const version = this.parseiOSVersion(osName); + for (const device of os) { if (device["availability"] !== "(available)") { continue; } - let emulatorInfo: IEmulatorInfo = { + const emulatorInfo: IEmulatorInfo = { id: device["udid"], name: device["name"], isRunning: device["state"] === "Booted", @@ -167,8 +167,8 @@ export class EmulatorPlatformService implements IEmulatorPlatformService { private outputEmulators(title: string, emulators: IEmulatorInfo[]) { this.$logger.out(title); - let table: any = createTable(["Device Name", "Platform", "Version", "Device Identifier"], []); - for (let info of emulators) { + const table: any = createTable(["Device Name", "Platform", "Version", "Device Identifier"], []); + for (const info of emulators) { table.push([info.name, info.platform, info.version, info.id]); } diff --git a/lib/services/emulator-settings-service.ts b/lib/services/emulator-settings-service.ts index 806d0139bb..d9bd1b6f26 100644 --- a/lib/services/emulator-settings-service.ts +++ b/lib/services/emulator-settings-service.ts @@ -4,9 +4,9 @@ export class EmulatorSettingsService implements Mobile.IEmulatorSettingsService constructor(private $injector: IInjector) { } public canStart(platform: string): boolean { - let platformService = this.$injector.resolve("platformService"); // this should be resolved here due to cyclic dependency + const platformService = this.$injector.resolve("platformService"); // this should be resolved here due to cyclic dependency - let installedPlatforms = platformService.getInstalledPlatforms(); + const installedPlatforms = platformService.getInstalledPlatforms(); return _.includes(installedPlatforms, platform.toLowerCase()); } diff --git a/lib/services/info-service.ts b/lib/services/info-service.ts index 40eb96a1b3..e7cb63c8ac 100644 --- a/lib/services/info-service.ts +++ b/lib/services/info-service.ts @@ -3,9 +3,9 @@ export class InfoService implements IInfoService { private $logger: ILogger) { } public async printComponentsInfo(): Promise { - let allComponentsInfo = await this.$versionsService.getAllComponentsVersions(); + const allComponentsInfo = await this.$versionsService.getAllComponentsVersions(); - let table: any = this.$versionsService.createTableWithVersionsInformation(allComponentsInfo); + const table: any = this.$versionsService.createTableWithVersionsInformation(allComponentsInfo); this.$logger.out("All NativeScript components versions information"); this.$logger.out(table.toString()); diff --git a/lib/services/init-service.ts b/lib/services/init-service.ts index 84358a67e9..4017d29863 100644 --- a/lib/services/init-service.ts +++ b/lib/services/init-service.ts @@ -31,7 +31,7 @@ export class InitService implements IInitService { projectData = this.$fs.readJson(this.projectFilePath); } - let projectDataBackup = _.extend({}, projectData); + const projectDataBackup = _.extend({}, projectData); if (!projectData[this.$staticConfig.CLIENT_NAME_KEY_IN_PROJECT_FILE]) { projectData[this.$staticConfig.CLIENT_NAME_KEY_IN_PROJECT_FILE] = {}; @@ -42,30 +42,30 @@ export class InitService implements IInitService { projectData[this.$staticConfig.CLIENT_NAME_KEY_IN_PROJECT_FILE]["id"] = await this.getProjectId(); if (this.$options.frameworkName && this.$options.frameworkVersion) { - let currentPlatformData = projectData[this.$staticConfig.CLIENT_NAME_KEY_IN_PROJECT_FILE][this.$options.frameworkName] || {}; + const currentPlatformData = projectData[this.$staticConfig.CLIENT_NAME_KEY_IN_PROJECT_FILE][this.$options.frameworkName] || {}; projectData[this.$staticConfig.CLIENT_NAME_KEY_IN_PROJECT_FILE][this.$options.frameworkName] = _.extend(currentPlatformData, this.buildVersionData(this.$options.frameworkVersion)); } else { - let $platformsData = this.$injector.resolve("platformsData"); - let $projectData = this.$injector.resolve("projectData"); + const $platformsData = this.$injector.resolve("platformsData"); + const $projectData = this.$injector.resolve("projectData"); $projectData.initializeProjectData(path.dirname(this.projectFilePath)); - for (let platform of $platformsData.platformsNames) { - let platformData: IPlatformData = $platformsData.getPlatformData(platform, $projectData); + for (const platform of $platformsData.platformsNames) { + const platformData: IPlatformData = $platformsData.getPlatformData(platform, $projectData); if (!platformData.targetedOS || (platformData.targetedOS && _.includes(platformData.targetedOS, process.platform))) { - let currentPlatformData = projectData[this.$staticConfig.CLIENT_NAME_KEY_IN_PROJECT_FILE][platformData.frameworkPackageName] || {}; + const currentPlatformData = projectData[this.$staticConfig.CLIENT_NAME_KEY_IN_PROJECT_FILE][platformData.frameworkPackageName] || {}; projectData[this.$staticConfig.CLIENT_NAME_KEY_IN_PROJECT_FILE][platformData.frameworkPackageName] = _.extend(currentPlatformData, await this.getVersionData(platformData.frameworkPackageName)); } } } - let dependencies = projectData.dependencies; + const dependencies = projectData.dependencies; if (!dependencies) { projectData.dependencies = Object.create(null); } // In case console is interactive and --force is not specified, do not read the version from package.json, show all available versions to the user. - let tnsCoreModulesVersionInPackageJson = this.useDefaultValue ? projectData.dependencies[constants.TNS_CORE_MODULES_NAME] : null; + const tnsCoreModulesVersionInPackageJson = this.useDefaultValue ? projectData.dependencies[constants.TNS_CORE_MODULES_NAME] : null; projectData.dependencies[constants.TNS_CORE_MODULES_NAME] = tnsCoreModulesVersionInPackageJson || (await this.getVersionData(constants.TNS_CORE_MODULES_NAME))["version"]; this.$fs.writeJson(this.projectFilePath, projectData); @@ -79,7 +79,7 @@ export class InitService implements IInitService { private get projectFilePath(): string { if (!this._projectFilePath) { - let projectDir = path.resolve(this.$options.path || "."); + const projectDir = path.resolve(this.$options.path || "."); this._projectFilePath = path.join(projectDir, constants.PACKAGE_JSON_FILE_NAME); } @@ -91,7 +91,7 @@ export class InitService implements IInitService { return this.$options.appid; } - let defaultAppId = this.$projectHelper.generateDefaultAppId(path.basename(path.dirname(this.projectFilePath)), constants.DEFAULT_APP_IDENTIFIER_PREFIX); + const defaultAppId = this.$projectHelper.generateDefaultAppId(path.basename(path.dirname(this.projectFilePath)), constants.DEFAULT_APP_IDENTIFIER_PREFIX); if (this.useDefaultValue) { return defaultAppId; } @@ -100,26 +100,26 @@ export class InitService implements IInitService { } private async getVersionData(packageName: string): Promise { - let latestVersion = await this.$npmInstallationManager.getLatestCompatibleVersion(packageName); + const latestVersion = await this.$npmInstallationManager.getLatestCompatibleVersion(packageName); if (this.useDefaultValue) { return this.buildVersionData(latestVersion); } - let allVersions: any = await this.$npm.view(packageName, { "versions": true }); - let versions = _.filter(allVersions, (version: string) => semver.gte(version, InitService.MIN_SUPPORTED_FRAMEWORK_VERSIONS[packageName])); + const allVersions: any = await this.$npm.view(packageName, { "versions": true }); + const versions = _.filter(allVersions, (version: string) => semver.gte(version, InitService.MIN_SUPPORTED_FRAMEWORK_VERSIONS[packageName])); if (versions.length === 1) { this.$logger.info(`Only ${versions[0]} version is available for ${packageName}.`); return this.buildVersionData(versions[0]); } - let sortedVersions = versions.sort(helpers.versionCompare).reverse(); + const sortedVersions = versions.sort(helpers.versionCompare).reverse(); //TODO: plamen5kov: don't offer versions from next (they are not available) - let version = await this.$prompter.promptForChoice(`${packageName} version:`, sortedVersions); + const version = await this.$prompter.promptForChoice(`${packageName} version:`, sortedVersions); return this.buildVersionData(version); } private buildVersionData(version: string): IStringDictionary { - let result: IStringDictionary = {}; + const result: IStringDictionary = {}; result[InitService.VERSION_KEY_NAME] = version; diff --git a/lib/services/ios-debug-service.ts b/lib/services/ios-debug-service.ts index 03fa2f651a..a7adaf468e 100644 --- a/lib/services/ios-debug-service.ts +++ b/lib/services/ios-debug-service.ts @@ -113,8 +113,8 @@ export class IOSDebugService extends DebugServiceBase implements IPlatformDebugS } private async emulatorDebugBrk(debugData: IDebugData, debugOptions: IDebugOptions): Promise { - let args = debugOptions.debugBrk ? "--nativescript-debug-brk" : "--nativescript-debug-start"; - let child_process = await this.$iOSEmulatorServices.runApplicationOnEmulator(debugData.pathToAppPackage, { + const args = debugOptions.debugBrk ? "--nativescript-debug-brk" : "--nativescript-debug-start"; + const child_process = await this.$iOSEmulatorServices.runApplicationOnEmulator(debugData.pathToAppPackage, { waitForDebugger: true, captureStdin: true, args: args, @@ -122,11 +122,11 @@ export class IOSDebugService extends DebugServiceBase implements IPlatformDebugS skipInstall: true }); - let lineStream = byline(child_process.stdout); + const lineStream = byline(child_process.stdout); this._childProcess = child_process; lineStream.on('data', (line: NodeBuffer) => { - let lineText = line.toString(); + const lineText = line.toString(); if (lineText && _.startsWith(lineText, debugData.applicationIdentifier)) { const pid = getPidFromiOSSimulatorLogs(debugData.applicationIdentifier, lineText); if (!pid) { @@ -151,9 +151,9 @@ export class IOSDebugService extends DebugServiceBase implements IPlatformDebugS private async emulatorStart(debugData: IDebugData, debugOptions: IDebugOptions): Promise { const result = await this.wireDebuggerClient(debugData, debugOptions); - let attachRequestMessage = this.$iOSNotification.getAttachRequest(debugData.applicationIdentifier); + const attachRequestMessage = this.$iOSNotification.getAttachRequest(debugData.applicationIdentifier); - let iOSEmulator = this.$iOSEmulatorServices; + const iOSEmulator = this.$iOSEmulatorServices; await iOSEmulator.postDarwinNotification(attachRequestMessage); return result; } @@ -171,7 +171,7 @@ export class IOSDebugService extends DebugServiceBase implements IPlatformDebugS justlaunch: debugOptions.justlaunch }; // we intentionally do not wait on this here, because if we did, we'd miss the AppLaunching notification - let startApplicationAction = this.$platformService.startApplication(this.platform, runOptions, debugData.applicationIdentifier); + const startApplicationAction = this.$platformService.startApplication(this.platform, runOptions, debugData.applicationIdentifier); const result = await this.debugBrkCore(device, debugData, debugOptions); @@ -215,12 +215,12 @@ export class IOSDebugService extends DebugServiceBase implements IPlatformDebugS private async openAppInspector(fileDescriptor: string, debugData: IDebugData, debugOptions: IDebugOptions): Promise { if (debugOptions.client) { - let inspectorPath = await this.$npmInstallationManager.getInspectorFromCache(inspectorNpmPackageName, debugData.projectDir); + const inspectorPath = await this.$npmInstallationManager.getInspectorFromCache(inspectorNpmPackageName, debugData.projectDir); - let inspectorSourceLocation = path.join(inspectorPath, inspectorUiDir, "Main.html"); - let inspectorApplicationPath = path.join(inspectorPath, inspectorAppName); + const inspectorSourceLocation = path.join(inspectorPath, inspectorUiDir, "Main.html"); + const inspectorApplicationPath = path.join(inspectorPath, inspectorAppName); - let cmd = `open -a '${inspectorApplicationPath}' --args '${inspectorSourceLocation}' '${debugData.projectName}' '${fileDescriptor}'`; + const cmd = `open -a '${inspectorApplicationPath}' --args '${inspectorSourceLocation}' '${debugData.projectName}' '${fileDescriptor}'`; await this.$childProcess.exec(cmd); } else { this.$logger.info("Suppressing debugging client."); diff --git a/lib/services/ios-entitlements-service.ts b/lib/services/ios-entitlements-service.ts index 74662bea78..0f749e31cf 100644 --- a/lib/services/ios-entitlements-service.ts +++ b/lib/services/ios-entitlements-service.ts @@ -30,10 +30,10 @@ export class IOSEntitlementsService { } public async merge(projectData: IProjectData): Promise { - let session = new PlistSession({ log: (txt: string) => this.$logger.trace("App.entitlements: " + txt) }); + const session = new PlistSession({ log: (txt: string) => this.$logger.trace("App.entitlements: " + txt) }); - let projectDir = projectData.projectDir; - let makePatch = (plistPath: string) => { + const projectDir = projectData.projectDir; + const makePatch = (plistPath: string) => { if (!this.$fs.exists(plistPath)) { this.$logger.trace("No plist found at: " + plistPath); return; @@ -46,19 +46,19 @@ export class IOSEntitlementsService { }); }; - let allPlugins = await this.getAllInstalledPlugins(projectData); - for (let plugin of allPlugins) { - let pluginInfoPlistPath = path.join(plugin.pluginPlatformsFolderPath(this.$devicePlatformsConstants.iOS), + const allPlugins = await this.getAllInstalledPlugins(projectData); + for (const plugin of allPlugins) { + const pluginInfoPlistPath = path.join(plugin.pluginPlatformsFolderPath(this.$devicePlatformsConstants.iOS), IOSEntitlementsService.DefaultEntitlementsName); makePatch(pluginInfoPlistPath); } - let appEntitlementsPath = this.getDefaultAppEntitlementsPath(projectData); + const appEntitlementsPath = this.getDefaultAppEntitlementsPath(projectData); if (this.$fs.exists(appEntitlementsPath)) { makePatch(appEntitlementsPath); } - let plistContent = session.build(); + const plistContent = session.build(); this.$logger.trace("App.entitlements: Write to: " + this.getPlatformsEntitlementsPath(projectData)); this.$fs.writeFile(this.getPlatformsEntitlementsPath(projectData), plistContent); return; diff --git a/lib/services/ios-log-filter.ts b/lib/services/ios-log-filter.ts index 713122e1ea..fde1997d3a 100644 --- a/lib/services/ios-log-filter.ts +++ b/lib/services/ios-log-filter.ts @@ -1,4 +1,4 @@ -let sourcemap = require("source-map"); +const sourcemap = require("source-map"); import * as path from "path"; import { cache } from "../common/decorators"; import * as iOSLogFilterBase from "../common/mobile/ios/ios-log-filter"; @@ -21,8 +21,8 @@ export class IOSLogFilter extends iOSLogFilterBase.IOSLogFilter implements Mobil } if (data) { - let skipLastLine = data[data.length - 1] !== "\n"; - let lines = data.split("\n"); + const skipLastLine = data[data.length - 1] !== "\n"; + const lines = data.split("\n"); let result = ""; for (let i = 0; i < lines.length; i++) { let line = lines[i]; @@ -41,8 +41,8 @@ export class IOSLogFilter extends iOSLogFilterBase.IOSLogFilter implements Mobil // This code removes unnecessary information from log messages. The output looks like: // CONSOLE LOG file:///location:row:column: if (pid) { - let searchString = "[" + pid + "]: "; - let pidIndex = line.indexOf(searchString); + const searchString = "[" + pid + "]: "; + const pidIndex = line.indexOf(searchString); if (pidIndex > 0) { line = line.substring(pidIndex + searchString.length, line.length); this.getOriginalFileLocation(line); @@ -68,17 +68,17 @@ export class IOSLogFilter extends iOSLogFilterBase.IOSLogFilter implements Mobil const projectDir = this.getProjectDir(); if (fileIndex >= 0 && projectDir) { - let parts = data.substring(fileIndex + fileString.length).split(":"); + const parts = data.substring(fileIndex + fileString.length).split(":"); if (parts.length >= 4) { - let file = parts[0]; - let sourceMapFile = path.join(projectDir, file + ".map"); - let row = parseInt(parts[1]); - let column = parseInt(parts[2]); + const file = parts[0]; + const sourceMapFile = path.join(projectDir, file + ".map"); + const row = parseInt(parts[1]); + const column = parseInt(parts[2]); if (this.$fs.exists(sourceMapFile)) { - let sourceMap = this.$fs.readText(sourceMapFile); - let smc = new sourcemap.SourceMapConsumer(sourceMap); - let originalPosition = smc.originalPositionFor({ line: row, column: column }); - let sourceFile = smc.sources.length > 0 ? file.replace(smc.file, smc.sources[0]) : file; + const sourceMap = this.$fs.readText(sourceMapFile); + const smc = new sourcemap.SourceMapConsumer(sourceMap); + const originalPosition = smc.originalPositionFor({ line: row, column: column }); + const sourceFile = smc.sources.length > 0 ? file.replace(smc.file, smc.sources[0]) : file; data = data.substring(0, fileIndex + fileString.length) + sourceFile + ":" + originalPosition.line + ":" diff --git a/lib/services/ios-project-service.ts b/lib/services/ios-project-service.ts index 65c2fe47d3..3ecfcd4162 100644 --- a/lib/services/ios-project-service.ts +++ b/lib/services/ios-project-service.ts @@ -61,7 +61,7 @@ export class IOSProjectService extends projectServiceBaseLib.PlatformProjectServ } if (projectData && projectData.platformsDir && this._platformsDirCache !== projectData.platformsDir) { - let projectRoot = path.join(projectData.platformsDir, this.$devicePlatformsConstants.iOS.toLowerCase()); + const projectRoot = path.join(projectData.platformsDir, this.$devicePlatformsConstants.iOS.toLowerCase()); this._platformData = { frameworkPackageName: "tns-ios", @@ -114,7 +114,7 @@ export class IOSProjectService extends projectServiceBaseLib.PlatformProjectServ } public getAppResourcesDestinationDirectoryPath(projectData: IProjectData): string { - let frameworkVersion = this.getFrameworkVersion(this.getPlatformData(projectData).frameworkPackageName, projectData.projectDir); + const frameworkVersion = this.getFrameworkVersion(this.getPlatformData(projectData).frameworkPackageName, projectData.projectDir); if (semver.lt(frameworkVersion, "1.3.0")) { return path.join(this.getPlatformData(projectData).projectRoot, projectData.projectName, "Resources", "icons"); @@ -134,7 +134,7 @@ export class IOSProjectService extends projectServiceBaseLib.PlatformProjectServ this.$errors.fail("Xcode is not installed. Make sure you have Xcode installed and added to your PATH"); } - let xcodeBuildVersion = await this.getXcodeVersion(); + const xcodeBuildVersion = await this.getXcodeVersion(); if (helpers.versionCompare(xcodeBuildVersion, IOSProjectService.XCODEBUILD_MIN_VERSION) < 0) { this.$errors.fail("NativeScript can only run in Xcode version %s or greater", IOSProjectService.XCODEBUILD_MIN_VERSION); } @@ -157,7 +157,7 @@ export class IOSProjectService extends projectServiceBaseLib.PlatformProjectServ //TODO: plamen5kov: revisit this method, might have unnecessary/obsolete logic public async interpolateData(projectData: IProjectData, platformSpecificData: IPlatformSpecificData): Promise { - let projectRootFilePath = path.join(this.getPlatformData(projectData).projectRoot, IOSProjectService.IOS_PROJECT_NAME_PLACEHOLDER); + const projectRootFilePath = path.join(this.getPlatformData(projectData).projectRoot, IOSProjectService.IOS_PROJECT_NAME_PLACEHOLDER); // Starting with NativeScript for iOS 1.6.0, the project Info.plist file resides not in the platform project, // but in the hello-world app template as a platform specific resource. if (this.$fs.exists(path.join(projectRootFilePath, IOSProjectService.IOS_PROJECT_NAME_PLACEHOLDER + "-Info.plist"))) { @@ -165,8 +165,8 @@ export class IOSProjectService extends projectServiceBaseLib.PlatformProjectServ } this.replaceFileName("-Prefix.pch", projectRootFilePath, projectData); - let xcschemeDirPath = path.join(this.getPlatformData(projectData).projectRoot, IOSProjectService.IOS_PROJECT_NAME_PLACEHOLDER + IOSProjectService.XCODE_PROJECT_EXT_NAME, "xcshareddata/xcschemes"); - let xcschemeFilePath = path.join(xcschemeDirPath, IOSProjectService.IOS_PROJECT_NAME_PLACEHOLDER + IOSProjectService.XCODE_SCHEME_EXT_NAME); + const xcschemeDirPath = path.join(this.getPlatformData(projectData).projectRoot, IOSProjectService.IOS_PROJECT_NAME_PLACEHOLDER + IOSProjectService.XCODE_PROJECT_EXT_NAME, "xcshareddata/xcschemes"); + const xcschemeFilePath = path.join(xcschemeDirPath, IOSProjectService.IOS_PROJECT_NAME_PLACEHOLDER + IOSProjectService.XCODE_SCHEME_EXT_NAME); if (this.$fs.exists(xcschemeFilePath)) { this.$logger.debug("Found shared scheme at xcschemeFilePath, renaming to match project name."); @@ -181,7 +181,7 @@ export class IOSProjectService extends projectServiceBaseLib.PlatformProjectServ this.replaceFileName(IOSProjectService.XCODE_PROJECT_EXT_NAME, this.getPlatformData(projectData).projectRoot, projectData); - let pbxprojFilePath = this.getPbxProjPath(projectData); + const pbxprojFilePath = this.getPbxProjPath(projectData); this.replaceFileContent(pbxprojFilePath, projectData); } @@ -199,9 +199,9 @@ export class IOSProjectService extends projectServiceBaseLib.PlatformProjectServ * Returns the path to the .xcarchive. */ public async archive(projectData: IProjectData, buildConfig?: IBuildConfig, options?: { archivePath?: string }): Promise { - let projectRoot = this.getPlatformData(projectData).projectRoot; - let archivePath = options && options.archivePath ? path.resolve(options.archivePath) : path.join(projectRoot, "/build/archive/", projectData.projectName + ".xcarchive"); - let args = ["archive", "-archivePath", archivePath, "-configuration", + const projectRoot = this.getPlatformData(projectData).projectRoot; + const archivePath = options && options.archivePath ? path.resolve(options.archivePath) : path.join(projectRoot, "/build/archive/", projectData.projectName + ".xcarchive"); + const args = ["archive", "-archivePath", archivePath, "-configuration", (!buildConfig || buildConfig.release) ? "Release" : "Debug"] .concat(this.xcbuildProjectArgs(projectRoot, projectData, "scheme")); await this.xcodebuild(args, projectRoot, buildConfig && buildConfig.buildOutputStdio); @@ -265,11 +265,11 @@ export class IOSProjectService extends projectServiceBaseLib.PlatformProjectServ * Exports .xcarchive for a development device. */ private async exportDevelopmentArchive(projectData: IProjectData, buildConfig: IBuildConfig, options: { archivePath: string, exportDir?: string, teamID?: string, provision?: string }): Promise { - let platformData = this.getPlatformData(projectData); - let projectRoot = platformData.projectRoot; - let archivePath = options.archivePath; - let buildOutputPath = path.join(projectRoot, "build", "device"); - let exportOptionsMethod = await this.getExportOptionsMethod(projectData); + const platformData = this.getPlatformData(projectData); + const projectRoot = platformData.projectRoot; + const archivePath = options.archivePath; + const buildOutputPath = path.join(projectRoot, "build", "device"); + const exportOptionsMethod = await this.getExportOptionsMethod(projectData); let plistTemplate = ` @@ -291,12 +291,12 @@ export class IOSProjectService extends projectServiceBaseLib.PlatformProjectServ // Save the options... temp.track(); - let exportOptionsPlist = temp.path({ prefix: "export-", suffix: ".plist" }); + const exportOptionsPlist = temp.path({ prefix: "export-", suffix: ".plist" }); this.$fs.writeFile(exportOptionsPlist, plistTemplate); // The xcodebuild exportPath expects directory and writes the .ipa at that directory. - let exportPath = path.resolve(options.exportDir || buildOutputPath); - let exportFile = path.join(exportPath, projectData.projectName + ".ipa"); + const exportPath = path.resolve(options.exportDir || buildOutputPath); + const exportFile = path.join(exportPath, projectData.projectName + ".ipa"); await this.xcodebuild( [ @@ -310,11 +310,11 @@ export class IOSProjectService extends projectServiceBaseLib.PlatformProjectServ } private xcbuildProjectArgs(projectRoot: string, projectData: IProjectData, product?: "scheme" | "target"): string[] { - let xcworkspacePath = path.join(projectRoot, projectData.projectName + ".xcworkspace"); + const xcworkspacePath = path.join(projectRoot, projectData.projectName + ".xcworkspace"); if (this.$fs.exists(xcworkspacePath)) { return ["-workspace", xcworkspacePath, product ? "-" + product : "-scheme", projectData.projectName]; } else { - let xcodeprojPath = path.join(projectRoot, projectData.projectName + ".xcodeproj"); + const xcodeprojPath = path.join(projectRoot, projectData.projectName + ".xcodeproj"); return ["-project", xcodeprojPath, product ? "-" + product : "-target", projectData.projectName]; } } @@ -328,7 +328,7 @@ export class IOSProjectService extends projectServiceBaseLib.PlatformProjectServ basicArgs = basicArgs.concat(this.xcbuildProjectArgs(projectRoot, projectData)); // Starting from tns-ios 1.4 the xcconfig file is referenced in the project template - let frameworkVersion = this.getFrameworkVersion(this.getPlatformData(projectData).frameworkPackageName, projectData.projectDir); + const frameworkVersion = this.getFrameworkVersion(this.getPlatformData(projectData).frameworkPackageName, projectData.projectDir); if (semver.lt(frameworkVersion, "1.4.0")) { basicArgs.push("-xcconfig", path.join(projectRoot, projectData.projectName, "build.xcconfig")); } @@ -360,10 +360,10 @@ export class IOSProjectService extends projectServiceBaseLib.PlatformProjectServ } public async validatePlugins(projectData: IProjectData): Promise { - let installedPlugins = await (this.$injector.resolve("pluginsService")).getAllInstalledPlugins(projectData); - for (let pluginData of installedPlugins) { - let pluginsFolderExists = this.$fs.exists(path.join(pluginData.pluginPlatformsFolderPath(this.$devicePlatformsConstants.iOS.toLowerCase()), "Podfile")); - let cocoaPodVersion = await this.$sysInfo.getCocoapodVersion(); + const installedPlugins = await (this.$injector.resolve("pluginsService")).getAllInstalledPlugins(projectData); + for (const pluginData of installedPlugins) { + const pluginsFolderExists = this.$fs.exists(path.join(pluginData.pluginPlatformsFolderPath(this.$devicePlatformsConstants.iOS.toLowerCase()), "Podfile")); + const cocoaPodVersion = await this.$sysInfo.getCocoapodVersion(); if (pluginsFolderExists && !cocoaPodVersion) { this.$errors.failWithoutHelp(`${pluginData.name} has Podfile and you don't have Cocoapods installed or it is not configured correctly. Please verify Cocoapods can work on your machine.`); } @@ -372,7 +372,7 @@ export class IOSProjectService extends projectServiceBaseLib.PlatformProjectServ } private async buildForDevice(projectRoot: string, args: string[], buildConfig: IBuildConfig, projectData: IProjectData): Promise { - let defaultArchitectures = [ + const defaultArchitectures = [ 'ARCHS=armv7 arm64', 'VALID_ARCHS=armv7 arm64' ]; @@ -383,14 +383,14 @@ export class IOSProjectService extends projectServiceBaseLib.PlatformProjectServ platform: this.$devicePlatformsConstants.iOS.toLowerCase(), deviceId: buildConfig.device, skipEmulatorStart: true }); - let instances = this.$devicesService.getDeviceInstances(); - let devicesArchitectures = _(instances) + const instances = this.$devicesService.getDeviceInstances(); + const devicesArchitectures = _(instances) .filter(d => this.$mobileHelper.isiOSPlatform(d.deviceInfo.platform) && d.deviceInfo.activeArchitecture) .map(d => d.deviceInfo.activeArchitecture) .uniq() .value(); if (devicesArchitectures.length > 0) { - let architectures = [ + const architectures = [ `ARCHS=${devicesArchitectures.join(" ")}`, `VALID_ARCHS=${devicesArchitectures.join(" ")}` ]; @@ -408,7 +408,7 @@ export class IOSProjectService extends projectServiceBaseLib.PlatformProjectServ "CONFIGURATION_BUILD_DIR=" + path.join(projectRoot, "build", "device") ]); - let xcodeBuildVersion = await this.getXcodeVersion(); + const xcodeBuildVersion = await this.getXcodeVersion(); if (helpers.versionCompare(xcodeBuildVersion, "8.0") >= 0) { await this.setupSigningForDevice(projectRoot, buildConfig, projectData); } @@ -478,8 +478,8 @@ export class IOSProjectService extends projectServiceBaseLib.PlatformProjectServ let shouldUpdateXcode = false; if (signing && signing.style === "Manual") { - for (let config in signing.configurations) { - let options = signing.configurations[config]; + for (const config in signing.configurations) { + const options = signing.configurations[config]; if (options.name !== provision && options.uuid !== provision) { shouldUpdateXcode = true; break; @@ -565,17 +565,17 @@ export class IOSProjectService extends projectServiceBaseLib.PlatformProjectServ if (!this.$hostInfo.isWindows) { this.validateFramework(frameworkPath); - let project = this.createPbxProj(projectData); - let frameworkName = path.basename(frameworkPath, path.extname(frameworkPath)); - let frameworkBinaryPath = path.join(frameworkPath, frameworkName); - let isDynamic = _.includes((await this.$childProcess.spawnFromEvent("file", [frameworkBinaryPath], "close")).stdout, "dynamically linked"); - let frameworkAddOptions: IXcode.Options = { customFramework: true }; + const project = this.createPbxProj(projectData); + const frameworkName = path.basename(frameworkPath, path.extname(frameworkPath)); + const frameworkBinaryPath = path.join(frameworkPath, frameworkName); + const isDynamic = _.includes((await this.$childProcess.spawnFromEvent("file", [frameworkBinaryPath], "close")).stdout, "dynamically linked"); + const frameworkAddOptions: IXcode.Options = { customFramework: true }; if (isDynamic) { frameworkAddOptions["embed"] = true; } - let frameworkRelativePath = '$(SRCROOT)/' + this.getLibSubpathRelativeToProjectPath(frameworkPath, projectData); + const frameworkRelativePath = '$(SRCROOT)/' + this.getLibSubpathRelativeToProjectPath(frameworkPath, projectData); project.addFramework(frameworkRelativePath, frameworkAddOptions); this.savePbxProj(project, projectData); } @@ -584,15 +584,15 @@ export class IOSProjectService extends projectServiceBaseLib.PlatformProjectServ private async addStaticLibrary(staticLibPath: string, projectData: IProjectData): Promise { await this.validateStaticLibrary(staticLibPath); // Copy files to lib folder. - let libraryName = path.basename(staticLibPath, ".a"); - let headersSubpath = path.join(path.dirname(staticLibPath), "include", libraryName); + const libraryName = path.basename(staticLibPath, ".a"); + const headersSubpath = path.join(path.dirname(staticLibPath), "include", libraryName); // Add static library to project file and setup header search paths - let project = this.createPbxProj(projectData); - let relativeStaticLibPath = this.getLibSubpathRelativeToProjectPath(staticLibPath, projectData); + const project = this.createPbxProj(projectData); + const relativeStaticLibPath = this.getLibSubpathRelativeToProjectPath(staticLibPath, projectData); project.addFramework(relativeStaticLibPath); - let relativeHeaderSearchPath = path.join(this.getLibSubpathRelativeToProjectPath(headersSubpath, projectData)); + const relativeHeaderSearchPath = path.join(this.getLibSubpathRelativeToProjectPath(headersSubpath, projectData)); project.addToHeaderSearchPaths({ relativePath: relativeHeaderSearchPath }); this.generateModulemap(headersSubpath, libraryName); @@ -600,14 +600,14 @@ export class IOSProjectService extends projectServiceBaseLib.PlatformProjectServ } public canUpdatePlatform(installedModuleDir: string, projectData: IProjectData): boolean { - let currentXcodeProjectFile = this.buildPathToCurrentXcodeProjectFile(projectData); - let currentXcodeProjectFileContent = this.$fs.readFile(currentXcodeProjectFile); + const currentXcodeProjectFile = this.buildPathToCurrentXcodeProjectFile(projectData); + const currentXcodeProjectFileContent = this.$fs.readFile(currentXcodeProjectFile); - let newXcodeProjectFile = this.buildPathToNewXcodeProjectFile(installedModuleDir); + const newXcodeProjectFile = this.buildPathToNewXcodeProjectFile(installedModuleDir); this.replaceFileContent(newXcodeProjectFile, projectData); - let newXcodeProjectFileContent = this.$fs.readFile(newXcodeProjectFile); + const newXcodeProjectFileContent = this.$fs.readFile(newXcodeProjectFile); - let contentIsTheSame = currentXcodeProjectFileContent.toString() === newXcodeProjectFileContent.toString(); + const contentIsTheSame = currentXcodeProjectFileContent.toString() === newXcodeProjectFileContent.toString(); if (!contentIsTheSame) { this.$logger.warn(`The content of the current project file: ${currentXcodeProjectFile} and the new project file: ${newXcodeProjectFile} is different.`); @@ -628,18 +628,18 @@ export class IOSProjectService extends projectServiceBaseLib.PlatformProjectServ private provideLaunchScreenIfMissing(projectData: IProjectData): void { try { this.$logger.trace("Checking if we need to provide compatability LaunchScreen.xib"); - let platformData = this.getPlatformData(projectData); - let projectPath = path.join(platformData.projectRoot, projectData.projectName); - let projectPlist = this.getInfoPlistPath(projectData); - let plistContent = plist.parse(this.$fs.readText(projectPlist)); - let storyName = plistContent["UILaunchStoryboardName"]; + const platformData = this.getPlatformData(projectData); + const projectPath = path.join(platformData.projectRoot, projectData.projectName); + const projectPlist = this.getInfoPlistPath(projectData); + const plistContent = plist.parse(this.$fs.readText(projectPlist)); + const storyName = plistContent["UILaunchStoryboardName"]; this.$logger.trace(`Examining ${projectPlist} UILaunchStoryboardName: "${storyName}".`); if (storyName !== "LaunchScreen") { this.$logger.trace("The project has its UILaunchStoryboardName set to " + storyName + " which is not the pre v2.1.0 default LaunchScreen, probably the project is migrated so we are good to go."); return; } - let expectedStoryPath = path.join(projectPath, "Resources", "LaunchScreen.storyboard"); + const expectedStoryPath = path.join(projectPath, "Resources", "LaunchScreen.storyboard"); if (this.$fs.exists(expectedStoryPath)) { // Found a LaunchScreen on expected path this.$logger.trace("LaunchScreen.storyboard was found. Project is up to date."); @@ -647,28 +647,28 @@ export class IOSProjectService extends projectServiceBaseLib.PlatformProjectServ } this.$logger.trace("LaunchScreen file not found at: " + expectedStoryPath); - let expectedXibPath = path.join(projectPath, "en.lproj", "LaunchScreen.xib"); + const expectedXibPath = path.join(projectPath, "en.lproj", "LaunchScreen.xib"); if (this.$fs.exists(expectedXibPath)) { this.$logger.trace("Obsolete LaunchScreen.xib was found. It'k OK, we are probably running with iOS runtime from pre v2.1.0."); return; } this.$logger.trace("LaunchScreen file not found at: " + expectedXibPath); - let isTheLaunchScreenFile = (fileName: string) => fileName === "LaunchScreen.xib" || fileName === "LaunchScreen.storyboard"; - let matches = this.$fs.enumerateFilesInDirectorySync(projectPath, isTheLaunchScreenFile, { enumerateDirectories: false }); + const isTheLaunchScreenFile = (fileName: string) => fileName === "LaunchScreen.xib" || fileName === "LaunchScreen.storyboard"; + const matches = this.$fs.enumerateFilesInDirectorySync(projectPath, isTheLaunchScreenFile, { enumerateDirectories: false }); if (matches.length > 0) { this.$logger.trace("Found LaunchScreen by slowly traversing all files here: " + matches + "\nConsider moving the LaunchScreen so it could be found at: " + expectedStoryPath); return; } - let compatabilityXibPath = path.join(projectPath, "Resources", "LaunchScreen.xib"); + const compatabilityXibPath = path.join(projectPath, "Resources", "LaunchScreen.xib"); this.$logger.warn(`Failed to find LaunchScreen.storyboard but it was specified in the Info.plist. Consider updating the resources in app/App_Resources/iOS/. A good starting point would be to create a new project and diff the changes with your current one. Also the following repo may be helpful: https://github.com/NativeScript/template-hello-world/tree/master/App_Resources/iOS We will now place an empty obsolete compatability white screen LauncScreen.xib for you in ${path.relative(projectData.projectDir, compatabilityXibPath)} so your app may appear as it did in pre v2.1.0 versions of the ios runtime.`); - let content = ` + const content = ` @@ -709,28 +709,28 @@ We will now place an empty obsolete compatability white screen LauncScreen.xib f await this.setupSigningFromTeam(projectRoot, projectData, teamId); } - let project = this.createPbxProj(projectData); + const project = this.createPbxProj(projectData); this.provideLaunchScreenIfMissing(projectData); - let resources = project.pbxGroupByName("Resources"); + const resources = project.pbxGroupByName("Resources"); if (resources) { - let references = project.pbxFileReferenceSection(); + const references = project.pbxFileReferenceSection(); - let xcodeProjectImages = _.map(resources.children, resource => this.replace(references[resource.value].name)); + const xcodeProjectImages = _.map(resources.children, resource => this.replace(references[resource.value].name)); this.$logger.trace("Images from Xcode project"); this.$logger.trace(xcodeProjectImages); - let appResourcesImages = this.$fs.readDirectory(this.getAppResourcesDestinationDirectoryPath(projectData)); + const appResourcesImages = this.$fs.readDirectory(this.getAppResourcesDestinationDirectoryPath(projectData)); this.$logger.trace("Current images from App_Resources"); this.$logger.trace(appResourcesImages); - let imagesToAdd = _.difference(appResourcesImages, xcodeProjectImages); + const imagesToAdd = _.difference(appResourcesImages, xcodeProjectImages); this.$logger.trace(`New images to add into xcode project: ${imagesToAdd.join(", ")}`); _.each(imagesToAdd, image => project.addResourceFile(path.relative(this.getPlatformData(projectData).projectRoot, path.join(this.getAppResourcesDestinationDirectoryPath(projectData), image)))); - let imagesToRemove = _.difference(xcodeProjectImages, appResourcesImages); + const imagesToRemove = _.difference(xcodeProjectImages, appResourcesImages); this.$logger.trace(`Images to remove from xcode project: ${imagesToRemove.join(", ")}`); _.each(imagesToRemove, image => project.removeResourceFile(path.join(this.getAppResourcesDestinationDirectoryPath(projectData), image))); @@ -739,8 +739,8 @@ We will now place an empty obsolete compatability white screen LauncScreen.xib f } public prepareAppResources(appResourcesDirectoryPath: string, projectData: IProjectData): void { - let platformFolder = path.join(appResourcesDirectoryPath, this.getPlatformData(projectData).normalizedPlatformName); - let filterFile = (filename: string) => this.$fs.deleteFile(path.join(platformFolder, filename)); + const platformFolder = path.join(appResourcesDirectoryPath, this.getPlatformData(projectData).normalizedPlatformName); + const filterFile = (filename: string) => this.$fs.deleteFile(path.join(platformFolder, filename)); filterFile(this.getPlatformData(projectData).configurationFileName); @@ -751,7 +751,7 @@ We will now place an empty obsolete compatability white screen LauncScreen.xib f await this.mergeInfoPlists({ release }, projectData); await this.$iOSEntitlementsService.merge(projectData); await this.mergeProjectXcconfigFiles(release, projectData); - for (let pluginData of await this.getAllInstalledPlugins(projectData)) { + for (const pluginData of await this.getAllInstalledPlugins(projectData)) { await this.$pluginVariablesService.interpolatePluginVariables(pluginData, this.getPlatformData(projectData).configurationFilePath, projectData); } @@ -781,8 +781,8 @@ We will now place an empty obsolete compatability white screen LauncScreen.xib f } private async mergeInfoPlists(buildOptions: IRelease, projectData: IProjectData): Promise { - let projectDir = projectData.projectDir; - let infoPlistPath = path.join(projectDir, constants.APP_FOLDER_NAME, constants.APP_RESOURCES_FOLDER_NAME, this.getPlatformData(projectData).normalizedPlatformName, this.getPlatformData(projectData).configurationFileName); + const projectDir = projectData.projectDir; + const infoPlistPath = path.join(projectDir, constants.APP_FOLDER_NAME, constants.APP_RESOURCES_FOLDER_NAME, this.getPlatformData(projectData).normalizedPlatformName, this.getPlatformData(projectData).configurationFileName); this.ensureConfigurationFileInAppResources(); if (!this.$fs.exists(infoPlistPath)) { @@ -796,8 +796,8 @@ We will now place an empty obsolete compatability white screen LauncScreen.xib f warn: (txt: string) => this.$logger.warn(`${reporterTraceMessage} ${txt}`) }; - let session = new PlistSession(reporter); - let makePatch = (plistPath: string) => { + const session = new PlistSession(reporter); + const makePatch = (plistPath: string) => { if (!this.$fs.exists(plistPath)) { this.$logger.trace("No plist found at: " + plistPath); return; @@ -810,9 +810,9 @@ We will now place an empty obsolete compatability white screen LauncScreen.xib f }); }; - let allPlugins = await this.getAllInstalledPlugins(projectData); - for (let plugin of allPlugins) { - let pluginInfoPlistPath = path.join(plugin.pluginPlatformsFolderPath(IOSProjectService.IOS_PLATFORM_NAME), this.getPlatformData(projectData).configurationFileName); + const allPlugins = await this.getAllInstalledPlugins(projectData); + for (const plugin of allPlugins) { + const pluginInfoPlistPath = path.join(plugin.pluginPlatformsFolderPath(IOSProjectService.IOS_PLATFORM_NAME), this.getPlatformData(projectData).configurationFileName); makePatch(pluginInfoPlistPath); } @@ -857,7 +857,7 @@ We will now place an empty obsolete compatability white screen LauncScreen.xib f }); } - let plistContent = session.build(); + const plistContent = session.build(); this.$logger.trace("Info.plist: Write to: " + this.getPlatformData(projectData).configurationFilePath); this.$fs.writeFile(this.getPlatformData(projectData).configurationFilePath, plistContent); @@ -892,7 +892,7 @@ We will now place an empty obsolete compatability white screen LauncScreen.xib f } private getLibSubpathRelativeToProjectPath(targetPath: string, projectData: IProjectData): string { - let frameworkPath = path.relative(this.getPlatformData(projectData).projectRoot, targetPath); + const frameworkPath = path.relative(this.getPlatformData(projectData).projectRoot, targetPath); return frameworkPath; } @@ -901,7 +901,7 @@ We will now place an empty obsolete compatability white screen LauncScreen.xib f } private createPbxProj(projectData: IProjectData): any { - let project = new this.$xcode.project(this.getPbxProjPath(projectData)); + const project = new this.$xcode.project(this.getPbxProjPath(projectData)); project.parseSync(); return project; @@ -912,7 +912,7 @@ We will now place an empty obsolete compatability white screen LauncScreen.xib f } public async preparePluginNativeCode(pluginData: IPluginData, projectData: IProjectData, opts?: any): Promise { - let pluginPlatformsFolderPath = pluginData.pluginPlatformsFolderPath(IOSProjectService.IOS_PLATFORM_NAME); + const pluginPlatformsFolderPath = pluginData.pluginPlatformsFolderPath(IOSProjectService.IOS_PLATFORM_NAME); await this.prepareFrameworks(pluginPlatformsFolderPath, pluginData, projectData); await this.prepareStaticLibs(pluginPlatformsFolderPath, pluginData, projectData); @@ -920,7 +920,7 @@ We will now place an empty obsolete compatability white screen LauncScreen.xib f } public async removePluginNativeCode(pluginData: IPluginData, projectData: IProjectData): Promise { - let pluginPlatformsFolderPath = pluginData.pluginPlatformsFolderPath(IOSProjectService.IOS_PLATFORM_NAME); + const pluginPlatformsFolderPath = pluginData.pluginPlatformsFolderPath(IOSProjectService.IOS_PLATFORM_NAME); this.removeFrameworks(pluginPlatformsFolderPath, pluginData, projectData); this.removeStaticLibs(pluginPlatformsFolderPath, pluginData, projectData); @@ -929,23 +929,23 @@ We will now place an empty obsolete compatability white screen LauncScreen.xib f public async afterPrepareAllPlugins(projectData: IProjectData): Promise { if (this.$fs.exists(this.getProjectPodFilePath(projectData))) { - let projectPodfileContent = this.$fs.readText(this.getProjectPodFilePath(projectData)); + const projectPodfileContent = this.$fs.readText(this.getProjectPodFilePath(projectData)); this.$logger.trace("Project Podfile content"); this.$logger.trace(projectPodfileContent); - let firstPostInstallIndex = projectPodfileContent.indexOf(IOSProjectService.PODFILE_POST_INSTALL_SECTION_NAME); + const firstPostInstallIndex = projectPodfileContent.indexOf(IOSProjectService.PODFILE_POST_INSTALL_SECTION_NAME); if (firstPostInstallIndex !== -1 && firstPostInstallIndex !== projectPodfileContent.lastIndexOf(IOSProjectService.PODFILE_POST_INSTALL_SECTION_NAME)) { this.$cocoapodsService.mergePodfileHookContent(IOSProjectService.PODFILE_POST_INSTALL_SECTION_NAME, this.getProjectPodFilePath(projectData)); } - let xcuserDataPath = path.join(this.getXcodeprojPath(projectData), "xcuserdata"); - let sharedDataPath = path.join(this.getXcodeprojPath(projectData), "xcshareddata"); + const xcuserDataPath = path.join(this.getXcodeprojPath(projectData), "xcuserdata"); + const sharedDataPath = path.join(this.getXcodeprojPath(projectData), "xcshareddata"); if (!this.$fs.exists(xcuserDataPath) && !this.$fs.exists(sharedDataPath)) { this.$logger.info("Creating project scheme..."); await this.checkIfXcodeprojIsRequired(); - let createSchemeRubyScript = `ruby -e "require 'xcodeproj'; xcproj = Xcodeproj::Project.open('${projectData.projectName}.xcodeproj'); xcproj.recreate_user_schemes; xcproj.save"`; + const createSchemeRubyScript = `ruby -e "require 'xcodeproj'; xcproj = Xcodeproj::Project.open('${projectData.projectName}.xcodeproj'); xcproj.recreate_user_schemes; xcproj.save"`; await this.$childProcess.exec(createSchemeRubyScript, { cwd: this.getPlatformData(projectData).projectRoot }); } @@ -1005,7 +1005,7 @@ We will now place an empty obsolete compatability white screen LauncScreen.xib f } private getAllLibsForPluginWithFileExtension(pluginData: IPluginData, fileExtension: string): string[] { - let filterCallback = (fileName: string, pluginPlatformsFolderPath: string) => path.extname(fileName) === fileExtension; + const filterCallback = (fileName: string, pluginPlatformsFolderPath: string) => path.extname(fileName) === fileExtension; return this.getAllNativeLibrariesForPlugin(pluginData, IOSProjectService.IOS_PLATFORM_NAME, filterCallback); } @@ -1036,8 +1036,8 @@ We will now place an empty obsolete compatability white screen LauncScreen.xib f this.$errors.failWithoutHelp(`The bundle at ${libraryPath} does not contain a valid static library in the '.a' file format.`); } - let expectedArchs = ["armv7", "arm64", "i386"]; - let archsInTheFatFile = await this.$childProcess.exec("lipo -i " + libraryPath); + const expectedArchs = ["armv7", "arm64", "i386"]; + const archsInTheFatFile = await this.$childProcess.exec("lipo -i " + libraryPath); expectedArchs.forEach(expectedArch => { if (archsInTheFatFile.indexOf(expectedArch) < 0) { @@ -1047,14 +1047,14 @@ We will now place an empty obsolete compatability white screen LauncScreen.xib f } private replaceFileContent(file: string, projectData: IProjectData): void { - let fileContent = this.$fs.readText(file); - let replacedContent = helpers.stringReplaceAll(fileContent, IOSProjectService.IOS_PROJECT_NAME_PLACEHOLDER, projectData.projectName); + const fileContent = this.$fs.readText(file); + const replacedContent = helpers.stringReplaceAll(fileContent, IOSProjectService.IOS_PROJECT_NAME_PLACEHOLDER, projectData.projectName); this.$fs.writeFile(file, replacedContent); } private replaceFileName(fileNamePart: string, fileRootLocation: string, projectData: IProjectData): void { - let oldFileName = IOSProjectService.IOS_PROJECT_NAME_PLACEHOLDER + fileNamePart; - let newFileName = projectData.projectName + fileNamePart; + const oldFileName = IOSProjectService.IOS_PROJECT_NAME_PLACEHOLDER + fileNamePart; + const newFileName = projectData.projectName + fileNamePart; this.$fs.rename(path.join(fileRootLocation, oldFileName), path.join(fileRootLocation, newFileName)); } @@ -1071,10 +1071,10 @@ We will now place an empty obsolete compatability white screen LauncScreen.xib f await this.$xcprojService.verifyXcproj(true); this.$logger.info("Installing pods..."); - let podTool = this.$config.USE_POD_SANDBOX ? "sandbox-pod" : "pod"; - let childProcess = await this.$childProcess.spawnFromEvent(podTool, ["install"], "close", { cwd: this.getPlatformData(projectData).projectRoot, stdio: ['pipe', process.stdout, 'pipe'] }); + const podTool = this.$config.USE_POD_SANDBOX ? "sandbox-pod" : "pod"; + const childProcess = await this.$childProcess.spawnFromEvent(podTool, ["install"], "close", { cwd: this.getPlatformData(projectData).projectRoot, stdio: ['pipe', process.stdout, 'pipe'] }); if (childProcess.stderr) { - let warnings = childProcess.stderr.match(/(\u001b\[(?:\d*;){0,5}\d*m[\s\S]+?\u001b\[(?:\d*;){0,5}\d*m)|(\[!\].*?\n)|(.*?warning.*)/gi); + const warnings = childProcess.stderr.match(/(\u001b\[(?:\d*;){0,5}\d*m[\s\S]+?\u001b\[(?:\d*;){0,5}\d*m)|(\[!\].*?\n)|(.*?warning.*)/gi); _.each(warnings, (warning: string) => { this.$logger.warnWithLabel(warning.replace("\n", "")); }); @@ -1097,26 +1097,26 @@ We will now place an empty obsolete compatability white screen LauncScreen.xib f } private async prepareFrameworks(pluginPlatformsFolderPath: string, pluginData: IPluginData, projectData: IProjectData): Promise { - for (let fileName of this.getAllLibsForPluginWithFileExtension(pluginData, ".framework")) { + for (const fileName of this.getAllLibsForPluginWithFileExtension(pluginData, ".framework")) { await this.addFramework(path.join(pluginPlatformsFolderPath, fileName), projectData); } } private async prepareStaticLibs(pluginPlatformsFolderPath: string, pluginData: IPluginData, projectData: IProjectData): Promise { - for (let fileName of this.getAllLibsForPluginWithFileExtension(pluginData, ".a")) { + for (const fileName of this.getAllLibsForPluginWithFileExtension(pluginData, ".a")) { await this.addStaticLibrary(path.join(pluginPlatformsFolderPath, fileName), projectData); } } private async prepareCocoapods(pluginPlatformsFolderPath: string, projectData: IProjectData, opts?: any): Promise { - let pluginPodFilePath = path.join(pluginPlatformsFolderPath, "Podfile"); + const pluginPodFilePath = path.join(pluginPlatformsFolderPath, "Podfile"); if (this.$fs.exists(pluginPodFilePath)) { - let pluginPodFileContent = this.$fs.readText(pluginPodFilePath), - pluginPodFilePreparedContent = this.buildPodfileContent(pluginPodFilePath, pluginPodFileContent), - projectPodFileContent = this.$fs.exists(this.getProjectPodFilePath(projectData)) ? this.$fs.readText(this.getProjectPodFilePath(projectData)) : ""; + const pluginPodFileContent = this.$fs.readText(pluginPodFilePath); + const pluginPodFilePreparedContent = this.buildPodfileContent(pluginPodFilePath, pluginPodFileContent); + let projectPodFileContent = this.$fs.exists(this.getProjectPodFilePath(projectData)) ? this.$fs.readText(this.getProjectPodFilePath(projectData)) : ""; if (!~projectPodFileContent.indexOf(pluginPodFilePreparedContent)) { - let podFileHeader = this.$cocoapodsService.getPodfileHeader(projectData.projectName), + const podFileHeader = this.$cocoapodsService.getPodfileHeader(projectData.projectName), podFileFooter = this.$cocoapodsService.getPodfileFooter(); if (_.startsWith(projectPodFileContent, podFileHeader)) { @@ -1127,10 +1127,10 @@ We will now place an empty obsolete compatability white screen LauncScreen.xib f projectPodFileContent = projectPodFileContent.substr(0, projectPodFileContent.length - podFileFooter.length); } - let contentToWrite = `${podFileHeader}${projectPodFileContent}${pluginPodFilePreparedContent}${podFileFooter}`; + const contentToWrite = `${podFileHeader}${projectPodFileContent}${pluginPodFilePreparedContent}${podFileFooter}`; this.$fs.writeFile(this.getProjectPodFilePath(projectData), contentToWrite); - let project = this.createPbxProj(projectData); + const project = this.createPbxProj(projectData); this.savePbxProj(project, projectData); } } @@ -1141,9 +1141,9 @@ We will now place an empty obsolete compatability white screen LauncScreen.xib f } private removeFrameworks(pluginPlatformsFolderPath: string, pluginData: IPluginData, projectData: IProjectData): void { - let project = this.createPbxProj(projectData); + const project = this.createPbxProj(projectData); _.each(this.getAllLibsForPluginWithFileExtension(pluginData, ".framework"), fileName => { - let relativeFrameworkPath = this.getLibSubpathRelativeToProjectPath(fileName, projectData); + const relativeFrameworkPath = this.getLibSubpathRelativeToProjectPath(fileName, projectData); project.removeFramework(relativeFrameworkPath, { customFramework: true, embed: true }); }); @@ -1151,15 +1151,15 @@ We will now place an empty obsolete compatability white screen LauncScreen.xib f } private removeStaticLibs(pluginPlatformsFolderPath: string, pluginData: IPluginData, projectData: IProjectData): void { - let project = this.createPbxProj(projectData); + const project = this.createPbxProj(projectData); _.each(this.getAllLibsForPluginWithFileExtension(pluginData, ".a"), fileName => { - let staticLibPath = path.join(pluginPlatformsFolderPath, fileName); - let relativeStaticLibPath = this.getLibSubpathRelativeToProjectPath(path.basename(staticLibPath), projectData); + const staticLibPath = path.join(pluginPlatformsFolderPath, fileName); + const relativeStaticLibPath = this.getLibSubpathRelativeToProjectPath(path.basename(staticLibPath), projectData); project.removeFramework(relativeStaticLibPath); - let headersSubpath = path.join("include", path.basename(staticLibPath, ".a")); - let relativeHeaderSearchPath = path.join(this.getLibSubpathRelativeToProjectPath(headersSubpath, projectData)); + const headersSubpath = path.join("include", path.basename(staticLibPath, ".a")); + const relativeHeaderSearchPath = path.join(this.getLibSubpathRelativeToProjectPath(headersSubpath, projectData)); project.removeFromHeaderSearchPaths({ relativePath: relativeHeaderSearchPath }); }); @@ -1167,12 +1167,12 @@ We will now place an empty obsolete compatability white screen LauncScreen.xib f } private removeCocoapods(pluginPlatformsFolderPath: string, projectData: IProjectData): void { - let pluginPodFilePath = path.join(pluginPlatformsFolderPath, "Podfile"); + const pluginPodFilePath = path.join(pluginPlatformsFolderPath, "Podfile"); if (this.$fs.exists(pluginPodFilePath) && this.$fs.exists(this.getProjectPodFilePath(projectData))) { - let pluginPodFileContent = this.$fs.readText(pluginPodFilePath); + const pluginPodFileContent = this.$fs.readText(pluginPodFilePath); let projectPodFileContent = this.$fs.readText(this.getProjectPodFilePath(projectData)); - let contentToRemove = this.buildPodfileContent(pluginPodFilePath, pluginPodFileContent); + const contentToRemove = this.buildPodfileContent(pluginPodFilePath, pluginPodFileContent); projectPodFileContent = helpers.stringReplaceAll(projectPodFileContent, contentToRemove, ""); if (projectPodFileContent.trim() === `use_frameworks!${os.EOL}${os.EOL}target "${projectData.projectName}" do${os.EOL}${os.EOL}end`) { this.$fs.deleteFile(this.getProjectPodFilePath(projectData)); @@ -1187,8 +1187,8 @@ We will now place an empty obsolete compatability white screen LauncScreen.xib f } private generateModulemap(headersFolderPath: string, libraryName: string): void { - let headersFilter = (fileName: string, containingFolderPath: string) => (path.extname(fileName) === ".h" && this.$fs.getFsStats(path.join(containingFolderPath, fileName)).isFile()); - let headersFolderContents = this.$fs.readDirectory(headersFolderPath); + const headersFilter = (fileName: string, containingFolderPath: string) => (path.extname(fileName) === ".h" && this.$fs.getFsStats(path.join(containingFolderPath, fileName)).isFile()); + const headersFolderContents = this.$fs.readDirectory(headersFolderPath); let headers = _(headersFolderContents).filter(item => headersFilter(item, headersFolderPath)).value(); if (!headers.length) { @@ -1198,7 +1198,7 @@ We will now place an empty obsolete compatability white screen LauncScreen.xib f headers = _.map(headers, value => `header "${value}"`); - let modulemap = `module ${libraryName} { explicit module ${libraryName} { ${headers.join(" ")} } }`; + const modulemap = `module ${libraryName} { explicit module ${libraryName} { ${headers.join(" ")} } }`; this.$fs.writeFile(path.join(headersFolderPath, "module.modulemap"), modulemap); } @@ -1208,32 +1208,32 @@ We will now place an empty obsolete compatability white screen LauncScreen.xib f } await this.checkIfXcodeprojIsRequired(); - let escapedProjectFile = projectFile.replace(/'/g, "\\'"), + const escapedProjectFile = projectFile.replace(/'/g, "\\'"), escapedPluginFile = pluginFile.replace(/'/g, "\\'"), mergeScript = `require 'xcodeproj'; Xcodeproj::Config.new('${escapedProjectFile}').merge(Xcodeproj::Config.new('${escapedPluginFile}')).save_as(Pathname.new('${escapedProjectFile}'))`; await this.$childProcess.exec(`ruby -e "${mergeScript}"`); } private async mergeProjectXcconfigFiles(release: boolean, projectData: IProjectData): Promise { - let pluginsXcconfigFilePath = release ? this.getPluginsReleaseXcconfigFilePath(projectData) : this.getPluginsDebugXcconfigFilePath(projectData); + const pluginsXcconfigFilePath = release ? this.getPluginsReleaseXcconfigFilePath(projectData) : this.getPluginsDebugXcconfigFilePath(projectData); this.$fs.deleteFile(pluginsXcconfigFilePath); - let allPlugins: IPluginData[] = await (this.$injector.resolve("pluginsService")).getAllInstalledPlugins(projectData); - for (let plugin of allPlugins) { - let pluginPlatformsFolderPath = plugin.pluginPlatformsFolderPath(IOSProjectService.IOS_PLATFORM_NAME); - let pluginXcconfigFilePath = path.join(pluginPlatformsFolderPath, "build.xcconfig"); + const allPlugins: IPluginData[] = await (this.$injector.resolve("pluginsService")).getAllInstalledPlugins(projectData); + for (const plugin of allPlugins) { + const pluginPlatformsFolderPath = plugin.pluginPlatformsFolderPath(IOSProjectService.IOS_PLATFORM_NAME); + const pluginXcconfigFilePath = path.join(pluginPlatformsFolderPath, "build.xcconfig"); if (this.$fs.exists(pluginXcconfigFilePath)) { await this.mergeXcconfigFiles(pluginXcconfigFilePath, pluginsXcconfigFilePath); } } - let appResourcesXcconfigPath = path.join(projectData.projectDir, constants.APP_FOLDER_NAME, constants.APP_RESOURCES_FOLDER_NAME, this.getPlatformData(projectData).normalizedPlatformName, "build.xcconfig"); + const appResourcesXcconfigPath = path.join(projectData.projectDir, constants.APP_FOLDER_NAME, constants.APP_RESOURCES_FOLDER_NAME, this.getPlatformData(projectData).normalizedPlatformName, "build.xcconfig"); if (this.$fs.exists(appResourcesXcconfigPath)) { await this.mergeXcconfigFiles(appResourcesXcconfigPath, pluginsXcconfigFilePath); } // Set Entitlements Property to point to default file if not set explicitly by the user. - let entitlementsPropertyValue = this.$xCConfigService.readPropertyValue(pluginsXcconfigFilePath, constants.CODE_SIGN_ENTITLEMENTS); + const entitlementsPropertyValue = this.$xCConfigService.readPropertyValue(pluginsXcconfigFilePath, constants.CODE_SIGN_ENTITLEMENTS); if (entitlementsPropertyValue === null) { temp.track(); const tempEntitlementsDir = temp.mkdirSync("entitlements"); @@ -1244,8 +1244,8 @@ We will now place an empty obsolete compatability white screen LauncScreen.xib f await this.mergeXcconfigFiles(tempEntitlementsFilePath, pluginsXcconfigFilePath); } - let podFilesRootDirName = path.join("Pods", "Target Support Files", `Pods-${projectData.projectName}`); - let podFolder = path.join(this.getPlatformData(projectData).projectRoot, podFilesRootDirName); + const podFilesRootDirName = path.join("Pods", "Target Support Files", `Pods-${projectData.projectName}`); + const podFolder = path.join(this.getPlatformData(projectData).projectRoot, podFilesRootDirName); if (this.$fs.exists(podFolder)) { if (release) { await this.mergeXcconfigFiles(path.join(this.getPlatformData(projectData).projectRoot, podFilesRootDirName, `Pods-${projectData.projectName}.release.xcconfig`), this.getPluginsReleaseXcconfigFilePath(projectData)); @@ -1256,9 +1256,9 @@ We will now place an empty obsolete compatability white screen LauncScreen.xib f } private async checkIfXcodeprojIsRequired(): Promise { - let xcprojInfo = await this.$xcprojService.getXcprojInfo(); + const xcprojInfo = await this.$xcprojService.getXcprojInfo(); if (xcprojInfo.shouldUseXcproj && !xcprojInfo.xcprojAvailable) { - let errorMessage = `You are using CocoaPods version ${xcprojInfo.cocoapodVer} which does not support Xcode ${xcprojInfo.xcodeVersion.major}.${xcprojInfo.xcodeVersion.minor} yet.${EOL}${EOL}You can update your cocoapods by running $sudo gem install cocoapods from a terminal.${EOL}${EOL}In order for the NativeScript CLI to be able to work correctly with this setup you need to install xcproj command line tool and add it to your PATH. Xcproj can be installed with homebrew by running $ brew install xcproj from the terminal`; + const errorMessage = `You are using CocoaPods version ${xcprojInfo.cocoapodVer} which does not support Xcode ${xcprojInfo.xcodeVersion.major}.${xcprojInfo.xcodeVersion.minor} yet.${EOL}${EOL}You can update your cocoapods by running $sudo gem install cocoapods from a terminal.${EOL}${EOL}In order for the NativeScript CLI to be able to work correctly with this setup you need to install xcproj command line tool and add it to your PATH. Xcproj can be installed with homebrew by running $ brew install xcproj from the terminal`; this.$errors.failWithoutHelp(errorMessage); @@ -1275,14 +1275,14 @@ We will now place an empty obsolete compatability white screen LauncScreen.xib f this.$errors.fail("xcodebuild execution failed. Make sure that you have latest Xcode and tools installed."); } - let splitedXcodeBuildVersion = xcodeBuildVersion.split("."); + const splitedXcodeBuildVersion = xcodeBuildVersion.split("."); xcodeBuildVersion = `${splitedXcodeBuildVersion[0] || 0}.${splitedXcodeBuildVersion[1] || 0}`; return xcodeBuildVersion; } private getBuildXCConfigFilePath(projectData: IProjectData): string { - let buildXCConfig = path.join(projectData.appResourcesDirectoryPath, + const buildXCConfig = path.join(projectData.appResourcesDirectoryPath, this.getPlatformData(projectData).normalizedPlatformName, "build.xcconfig"); return buildXCConfig; } @@ -1290,7 +1290,7 @@ We will now place an empty obsolete compatability white screen LauncScreen.xib f private readTeamId(projectData: IProjectData): string { let teamId = this.$xCConfigService.readPropertyValue(this.getBuildXCConfigFilePath(projectData), "DEVELOPMENT_TEAM"); - let fileName = path.join(this.getPlatformData(projectData).projectRoot, "teamid"); + const fileName = path.join(this.getPlatformData(projectData).projectRoot, "teamid"); if (this.$fs.exists(fileName)) { teamId = this.$fs.readText(fileName); } @@ -1318,7 +1318,7 @@ We will now place an empty obsolete compatability white screen LauncScreen.xib f teamId = teamId || this.readTeamId(projectData); if (!teamId) { - let teams = await this.$iOSProvisionService.getDevelopmentTeams(); + const teams = await this.$iOSProvisionService.getDevelopmentTeams(); this.$logger.warn("Xcode 8 requires a team id to be specified when building for device."); this.$logger.warn("You can specify the team id by setting the DEVELOPMENT_TEAM setting in build.xcconfig file located in App_Resources folder of your app, or by using the --teamId option when calling run, debug or livesync commands."); if (teams.length === 1) { @@ -1329,22 +1329,22 @@ We will now place an empty obsolete compatability white screen LauncScreen.xib f this.$errors.failWithoutHelp(`Unable to determine default development team. Available development teams are: ${_.map(teams, team => team.id)}. Specify team in app/App_Resources/iOS/build.xcconfig file in the following way: DEVELOPMENT_TEAM = `); } - let choices: string[] = []; - for (let team of teams) { + const choices: string[] = []; + for (const team of teams) { choices.push(team.name + " (" + team.id + ")"); } - let choice = await this.$prompter.promptForChoice('Found multiple development teams, select one:', choices); + const choice = await this.$prompter.promptForChoice('Found multiple development teams, select one:', choices); teamId = teams[choices.indexOf(choice)].id; - let choicesPersist = [ + const choicesPersist = [ "Yes, set the DEVELOPMENT_TEAM setting in build.xcconfig file.", "Yes, persist the team id in platforms folder.", "No, don't persist this setting." ]; - let choicePersist = await this.$prompter.promptForChoice("Do you want to make teamId: " + teamId + " a persistent choice for your app?", choicesPersist); + const choicePersist = await this.$prompter.promptForChoice("Do you want to make teamId: " + teamId + " a persistent choice for your app?", choicesPersist); switch (choicesPersist.indexOf(choicePersist)) { case 0: - let xcconfigFile = path.join(projectData.appResourcesDirectoryPath, this.getPlatformData(projectData).normalizedPlatformName, "build.xcconfig"); + const xcconfigFile = path.join(projectData.appResourcesDirectoryPath, this.getPlatformData(projectData).normalizedPlatformName, "build.xcconfig"); this.$fs.appendFile(xcconfigFile, "\nDEVELOPMENT_TEAM = " + teamId + "\n"); break; case 1: diff --git a/lib/services/itmstransporter-service.ts b/lib/services/itmstransporter-service.ts index 7405e3f29a..83dbbf3698 100644 --- a/lib/services/itmstransporter-service.ts +++ b/lib/services/itmstransporter-service.ts @@ -30,7 +30,7 @@ export class ITMSTransporterService implements IITMSTransporterService { } temp.track(); - let itmsTransporterPath = await this.getITMSTransporterPath(), + const itmsTransporterPath = await this.getITMSTransporterPath(), ipaFileName = "app.ipa", itmsDirectory = temp.mkdirSync("itms-"), innerDirectory = path.join(itmsDirectory, "mybundle.itmsp"), @@ -43,7 +43,7 @@ export class ITMSTransporterService implements IITMSTransporterService { this.$fs.copyFile(data.ipaFilePath, ipaFileLocation); - let ipaFileHash = await this.$fs.getFileShasum(ipaFileLocation, { algorithm: "md5" }), + const ipaFileHash = await this.$fs.getFileShasum(ipaFileLocation, { algorithm: "md5" }), ipaFileSize = this.$fs.getFileSize(ipaFileLocation), metadata = this.getITMSMetadataXml(iOSApplication.adamId, ipaFileName, ipaFileHash, ipaFileSize); @@ -54,7 +54,7 @@ export class ITMSTransporterService implements IITMSTransporterService { public async getiOSApplications(credentials: ICredentials): Promise { if (!this._itunesConnectApplications) { - let requestBody = this.getContentDeliveryRequestBody(credentials), + const requestBody = this.getContentDeliveryRequestBody(credentials), contentDeliveryResponse = await this.$httpClient.httpRequest({ url: "https://contentdelivery.itunes.apple.com/WebObjects/MZLabelService.woa/json/MZITunesProducerService", method: "POST", @@ -88,12 +88,12 @@ export class ITMSTransporterService implements IITMSTransporterService { * @return {IFuture} The iTunes Connect application. */ private async getiOSApplication(username: string, password: string, bundleId: string): Promise { - let iOSApplications = await this.getiOSApplications({ username, password }); + const iOSApplications = await this.getiOSApplications({ username, password }); if (!iOSApplications || !iOSApplications.length) { this.$errors.failWithoutHelp(`Cannot find any registered applications for Apple ID ${username} in iTunes Connect.`); } - let iOSApplication = _.find(iOSApplications, app => app.bundleId === bundleId); + const iOSApplication = _.find(iOSApplications, app => app.bundleId === bundleId); if (!iOSApplication) { this.$errors.failWithoutHelp(`Cannot find registered applications that match the specified identifier ${bundleId} in iTunes Connect.`); @@ -118,10 +118,10 @@ export class ITMSTransporterService implements IITMSTransporterService { this.$logger.trace("--ipa set - extracting .ipa file to get app's bundle identifier"); temp.track(); - let destinationDir = temp.mkdirSync("ipa-"); + const destinationDir = temp.mkdirSync("ipa-"); await this.$fs.unzip(ipaFileFullPath, destinationDir); - let payloadDir = path.join(destinationDir, "Payload"); + const payloadDir = path.join(destinationDir, "Payload"); let allApps = this.$fs.readDirectory(payloadDir); this.$logger.debug("ITMSTransporter .ipa Payload files:"); @@ -133,10 +133,10 @@ export class ITMSTransporterService implements IITMSTransporterService { } else if (allApps.length <= 0) { this.$errors.failWithoutHelp("In the .ipa the ITMSTransporter is uploading there must be at least one .app file."); } - let appFile = path.join(payloadDir, allApps[0]); + const appFile = path.join(payloadDir, allApps[0]); - let plistObject = await this.$bplistParser.parseFile(path.join(appFile, "Info.plist")); - let bundleId = plistObject && plistObject[0] && plistObject[0].CFBundleIdentifier; + const plistObject = await this.$bplistParser.parseFile(path.join(appFile, "Info.plist")); + const bundleId = plistObject && plistObject[0] && plistObject[0].CFBundleIdentifier; if (!bundleId) { this.$errors.failWithoutHelp(`Unable to determine bundle identifier from ${ipaFileFullPath}.`); } @@ -151,9 +151,9 @@ export class ITMSTransporterService implements IITMSTransporterService { private async getITMSTransporterPath(): Promise { if (!this._itmsTransporterPath) { - let xcodePath = await this.$xcodeSelectService.getContentsDirectoryPath(), - xcodeVersion = await this.$xcodeSelectService.getXcodeVersion(), - result = path.join(xcodePath, "Applications", "Application Loader.app", "Contents"); + const xcodePath = await this.$xcodeSelectService.getContentsDirectoryPath(); + const xcodeVersion = await this.$xcodeSelectService.getXcodeVersion(); + let result = path.join(xcodePath, "Applications", "Application Loader.app", "Contents"); xcodeVersion.patch = xcodeVersion.patch || "0"; // iTMS Transporter's path has been modified in Xcode 6.3 diff --git a/lib/services/karma-execution.ts b/lib/services/karma-execution.ts index 2223bef675..728bffcf71 100644 --- a/lib/services/karma-execution.ts +++ b/lib/services/karma-execution.ts @@ -2,7 +2,7 @@ import * as path from "path"; process.on("message", (data: any) => { if (data.karmaConfig) { - let pathToKarma = path.join(data.karmaConfig.projectDir, 'node_modules/karma'), + const pathToKarma = path.join(data.karmaConfig.projectDir, 'node_modules/karma'), KarmaServer = require(path.join(pathToKarma, 'lib/server')), karma = new KarmaServer(data.karmaConfig, (exitCode: number) => { //Exit with the correct exit code and signal the manager process. diff --git a/lib/services/livesync/android-device-livesync-service.ts b/lib/services/livesync/android-device-livesync-service.ts index 985a5f347e..b19cc0d7ad 100644 --- a/lib/services/livesync/android-device-livesync-service.ts +++ b/lib/services/livesync/android-device-livesync-service.ts @@ -58,8 +58,8 @@ export class AndroidDeviceLiveSyncService extends DeviceLiveSyncServiceBase impl } private async restartApplication(deviceAppData: Mobile.IDeviceAppData): Promise { - let devicePathRoot = `/data/data/${deviceAppData.appIdentifier}/files`; - let devicePath = this.$mobileHelper.buildDevicePath(devicePathRoot, "code_cache", "secondary_dexes", "proxyThumb"); + const devicePathRoot = `/data/data/${deviceAppData.appIdentifier}/files`; + const devicePath = this.$mobileHelper.buildDevicePath(devicePathRoot, "code_cache", "secondary_dexes", "proxyThumb"); await this.device.adb.executeShellCommand(["rm", "-rf", devicePath]); await this.device.applicationManager.restartApplication(deviceAppData.appIdentifier); @@ -112,14 +112,14 @@ export class AndroidDeviceLiveSyncService extends DeviceLiveSyncServiceBase impl @cache() public getDeviceHashService(appIdentifier: string): Mobile.IAndroidDeviceHashService { - let adb = this.$injector.resolve(DeviceAndroidDebugBridge, { identifier: this.device.deviceInfo.identifier }); + const adb = this.$injector.resolve(DeviceAndroidDebugBridge, { identifier: this.device.deviceInfo.identifier }); return this.$injector.resolve(AndroidDeviceHashService, { adb, appIdentifier }); } private async awaitRuntimeReloadSuccessMessage(): Promise { return new Promise((resolve, reject) => { let isResolved = false; - let socket = new net.Socket(); + const socket = new net.Socket(); socket.connect(AndroidDeviceLiveSyncService.BACKEND_PORT, '127.0.0.1', () => { socket.write(new Buffer([0, 0, 0, 1, 1])); diff --git a/lib/services/livesync/ios-device-livesync-service.ts b/lib/services/livesync/ios-device-livesync-service.ts index 976376a39f..a29ed506ff 100644 --- a/lib/services/livesync/ios-device-livesync-service.ts +++ b/lib/services/livesync/ios-device-livesync-service.ts @@ -84,7 +84,7 @@ export class IOSDeviceLiveSyncService extends DeviceLiveSyncServiceBase implemen private async reloadPage(deviceAppData: Mobile.IDeviceAppData, localToDevicePaths: Mobile.ILocalToDevicePathData[]): Promise { if (localToDevicePaths.length) { - let message = JSON.stringify({ + const message = JSON.stringify({ method: "Page.reload", params: { ignoreCache: false @@ -97,9 +97,9 @@ export class IOSDeviceLiveSyncService extends DeviceLiveSyncServiceBase implemen } private async liveEdit(localToDevicePaths: Mobile.ILocalToDevicePathData[]): Promise { - for (let localToDevicePath of localToDevicePaths) { - let content = this.$fs.readText(localToDevicePath.getLocalPath()); - let message = JSON.stringify({ + for (const localToDevicePath of localToDevicePaths) { + const content = this.$fs.readText(localToDevicePath.getLocalPath()); + const message = JSON.stringify({ method: "Debugger.setScriptSource", params: { scriptUrl: localToDevicePath.getRelativeToProjectBasePath(), @@ -133,8 +133,8 @@ export class IOSDeviceLiveSyncService extends DeviceLiveSyncServiceBase implemen try { await new Promise((resolve, reject) => { let isResolved = false; - let length = Buffer.byteLength(message, "utf16le"); - let payload = new Buffer(length + 4); + const length = Buffer.byteLength(message, "utf16le"); + const payload = new Buffer(length + 4); payload.writeInt32BE(length, 0); payload.write(message, 4, length, "utf16le"); diff --git a/lib/services/livesync/livesync-service.ts b/lib/services/livesync/livesync-service.ts index 7b0d9379d8..d01f372d82 100644 --- a/lib/services/livesync/livesync-service.ts +++ b/lib/services/livesync/livesync-service.ts @@ -146,7 +146,7 @@ export class LiveSyncService extends EventEmitter implements IDebugLiveSyncServi const deviceIdentifier = liveSyncResultInfo.deviceAppData.device.deviceInfo.identifier; await this.$debugService.debugStop(deviceIdentifier); - let applicationId = deviceAppData.appIdentifier; + const applicationId = deviceAppData.appIdentifier; const attachDebuggerOptions: IAttachDebuggerOptions = { platform: liveSyncResultInfo.deviceAppData.device.deviceInfo.platform, isEmulator: liveSyncResultInfo.deviceAppData.device.isEmulator, @@ -194,7 +194,7 @@ export class LiveSyncService extends EventEmitter implements IDebugLiveSyncServi } const projectData = this.$projectDataService.getProjectData(settings.projectDir); - let debugData = this.$debugDataService.createDebugData(projectData, { device: settings.deviceIdentifier }); + const debugData = this.$debugDataService.createDebugData(projectData, { device: settings.deviceIdentifier }); // Of the properties below only `buildForDevice` and `release` are currently used. // Leaving the others with placeholder values so that they may not be forgotten in future implementations. @@ -473,14 +473,14 @@ export class LiveSyncService extends EventEmitter implements IDebugLiveSyncServi } private async startWatcher(projectData: IProjectData, liveSyncData: ILiveSyncInfo): Promise { - let pattern = [APP_FOLDER_NAME]; + const pattern = [APP_FOLDER_NAME]; if (liveSyncData.watchAllFiles) { const productionDependencies = this.$nodeModulesDependenciesBuilder.getProductionDependencies(projectData.projectDir); pattern.push(PACKAGE_JSON_FILE_NAME); // watch only production node_module/packages same one prepare uses - for (let index in productionDependencies) { + for (const index in productionDependencies) { pattern.push(productionDependencies[index].directory); } } @@ -492,8 +492,8 @@ export class LiveSyncService extends EventEmitter implements IDebugLiveSyncServi currentWatcherInfo.watcher.close(); } - let filesToSync: string[] = [], - filesToRemove: string[] = []; + let filesToSync: string[] = []; + let filesToRemove: string[] = []; let timeoutTimer: NodeJS.Timer; const startTimeout = () => { @@ -502,10 +502,10 @@ export class LiveSyncService extends EventEmitter implements IDebugLiveSyncServi await this.addActionToChain(projectData.projectDir, async () => { if (filesToSync.length || filesToRemove.length) { try { - let currentFilesToSync = _.cloneDeep(filesToSync); + const currentFilesToSync = _.cloneDeep(filesToSync); filesToSync = []; - let currentFilesToRemove = _.cloneDeep(filesToRemove); + const currentFilesToRemove = _.cloneDeep(filesToRemove); filesToRemove = []; const allModifiedFiles = [].concat(currentFilesToSync).concat(currentFilesToRemove); @@ -550,7 +550,7 @@ export class LiveSyncService extends EventEmitter implements IDebugLiveSyncServi const allErrors = (err).allErrors; if (allErrors && _.isArray(allErrors)) { - for (let deviceError of allErrors) { + for (const deviceError of allErrors) { this.$logger.warn(`Unable to apply changes for device: ${deviceError.deviceIdentifier}. Error is: ${deviceError.message}.`); this.emit(LiveSyncEvents.liveSyncError, { diff --git a/lib/services/livesync/platform-livesync-service-base.ts b/lib/services/livesync/platform-livesync-service-base.ts index bb25daf456..27500ab6d9 100644 --- a/lib/services/livesync/platform-livesync-service-base.ts +++ b/lib/services/livesync/platform-livesync-service-base.ts @@ -58,7 +58,7 @@ export abstract class PlatformLiveSyncServiceBase { const syncInfo = _.merge({ device, watch: true }, liveSyncInfo); const deviceAppData = await this.getAppData(syncInfo); - let modifiedLocalToDevicePaths: Mobile.ILocalToDevicePathData[] = []; + const modifiedLocalToDevicePaths: Mobile.ILocalToDevicePathData[] = []; if (liveSyncInfo.filesToSync.length) { const filesToSync = liveSyncInfo.filesToSync; const mappedFiles = _.map(filesToSync, filePath => this.$projectFilesProvider.mapFilePath(filePath, device.deviceInfo.platform, projectData)); diff --git a/lib/services/platform-project-service-base.ts b/lib/services/platform-project-service-base.ts index b2cb7f7805..6672516cb6 100644 --- a/lib/services/platform-project-service-base.ts +++ b/lib/services/platform-project-service-base.ts @@ -11,11 +11,11 @@ export class PlatformProjectServiceBase extends EventEmitter implements IPlatfor } protected getAllNativeLibrariesForPlugin(pluginData: IPluginData, platform: string, filter: (fileName: string, _pluginPlatformsFolderPath: string) => boolean): string[] { - let pluginPlatformsFolderPath = this.getPluginPlatformsFolderPath(pluginData, platform), - nativeLibraries: string[] = []; + const pluginPlatformsFolderPath = this.getPluginPlatformsFolderPath(pluginData, platform); + let nativeLibraries: string[] = []; if (pluginPlatformsFolderPath && this.$fs.exists(pluginPlatformsFolderPath)) { - let platformsContents = this.$fs.readDirectory(pluginPlatformsFolderPath); + const platformsContents = this.$fs.readDirectory(pluginPlatformsFolderPath); nativeLibraries = _(platformsContents) .filter(platformItemName => filter(platformItemName, pluginPlatformsFolderPath)) .value(); diff --git a/lib/services/platform-service.ts b/lib/services/platform-service.ts index e6b546e211..206fbcc2ec 100644 --- a/lib/services/platform-service.ts +++ b/lib/services/platform-service.ts @@ -8,7 +8,7 @@ import { AppFilesUpdater } from "./app-files-updater"; import { attachAwaitDetach } from "../common/helpers"; import * as temp from "temp"; temp.track(); -let clui = require("clui"); +const clui = require("clui"); const buildInfoFileName = ".nsbuildinfo"; @@ -44,8 +44,8 @@ export class PlatformService extends EventEmitter implements IPlatformService { } public async cleanPlatforms(platforms: string[], platformTemplate: string, projectData: IProjectData, config: IPlatformOptions, framworkPath?: string): Promise { - for (let platform of platforms) { - let version: string = this.getCurrentPlatformVersion(platform, projectData); + for (const platform of platforms) { + const version: string = this.getCurrentPlatformVersion(platform, projectData); let platformWithVersion: string = platform; if (version !== undefined) { @@ -61,7 +61,7 @@ export class PlatformService extends EventEmitter implements IPlatformService { const platformsDir = projectData.platformsDir; this.$fs.ensureDirectoryExists(platformsDir); - for (let platform of platforms) { + for (const platform of platforms) { this.validatePlatform(platform, projectData); const platformPath = path.join(projectData.platformsDir, platform); @@ -74,8 +74,8 @@ export class PlatformService extends EventEmitter implements IPlatformService { } private getCurrentPlatformVersion(platform: string, projectData: IProjectData): string { - let platformData = this.$platformsData.getPlatformData(platform, projectData); - let currentPlatformData: any = this.$projectDataService.getNSValue(projectData.projectDir, platformData.frameworkPackageName); + const platformData = this.$platformsData.getPlatformData(platform, projectData); + const currentPlatformData: any = this.$projectDataService.getNSValue(projectData.projectDir, platformData.frameworkPackageName); let version: string; if (currentPlatformData && currentPlatformData[constants.VERSION_STRING]) { version = currentPlatformData[constants.VERSION_STRING]; @@ -85,11 +85,11 @@ export class PlatformService extends EventEmitter implements IPlatformService { } private async addPlatform(platformParam: string, platformTemplate: string, projectData: IProjectData, config: IPlatformOptions, frameworkPath?: string, nativePrepare?: INativePrepare): Promise { - let data = platformParam.split("@"), - platform = data[0].toLowerCase(), - version = data[1]; + const data = platformParam.split("@"); + const platform = data[0].toLowerCase(); + let version = data[1]; - let platformData = this.$platformsData.getPlatformData(platform, projectData); + const platformData = this.$platformsData.getPlatformData(platform, projectData); if (version === undefined) { version = this.getCurrentPlatformVersion(platform, projectData); @@ -104,7 +104,7 @@ export class PlatformService extends EventEmitter implements IPlatformService { this.$logger.out("Copying template files..."); let packageToInstall = ""; - let npmOptions: IStringDictionary = { + const npmOptions: IStringDictionary = { pathToSave: path.join(projectData.platformsDir, platform), dependencyType: "save" }; @@ -120,7 +120,7 @@ export class PlatformService extends EventEmitter implements IPlatformService { try { spinner.start(); - let downloadedPackagePath = await this.$npmInstallationManager.install(packageToInstall, projectDir, npmOptions); + const downloadedPackagePath = await this.$npmInstallationManager.install(packageToInstall, projectDir, npmOptions); let frameworkDir = path.join(downloadedPackagePath, constants.PROJECT_FRAMEWORK_FOLDER_NAME); frameworkDir = path.resolve(frameworkDir); @@ -149,7 +149,7 @@ export class PlatformService extends EventEmitter implements IPlatformService { await this.addPlatformCoreNative(platformData, frameworkDir, installedVersion, projectData, config); } - let frameworkPackageNameData: any = { version: installedVersion }; + const frameworkPackageNameData: any = { version: installedVersion }; if (customTemplateOptions) { frameworkPackageNameData.template = customTemplateOptions.selectedTemplate; } @@ -177,7 +177,7 @@ export class PlatformService extends EventEmitter implements IPlatformService { } if (selectedTemplate) { - let tempDir = temp.mkdirSync("platform-template"); + const tempDir = temp.mkdirSync("platform-template"); this.$fs.writeJson(path.join(tempDir, constants.PACKAGE_JSON_FILE_NAME), {}); try { const npmInstallResult = await this.$npm.install(selectedTemplate, tempDir, { @@ -185,7 +185,7 @@ export class PlatformService extends EventEmitter implements IPlatformService { frameworkPath: null, ignoreScripts: false }); - let pathToTemplate = path.join(tempDir, constants.NODE_MODULES_FOLDER_NAME, npmInstallResult.name); + const pathToTemplate = path.join(tempDir, constants.NODE_MODULES_FOLDER_NAME, npmInstallResult.name); return { selectedTemplate, pathToTemplate }; } catch (err) { this.$logger.trace("Error while trying to install specified template: ", err); @@ -201,12 +201,12 @@ export class PlatformService extends EventEmitter implements IPlatformService { return []; } - let subDirs = this.$fs.readDirectory(projectData.platformsDir); + const subDirs = this.$fs.readDirectory(projectData.platformsDir); return _.filter(subDirs, p => this.$platformsData.platformsNames.indexOf(p) > -1); } public getAvailablePlatforms(projectData: IProjectData): string[] { - let installedPlatforms = this.getInstalledPlatforms(projectData); + const installedPlatforms = this.getInstalledPlatforms(projectData); return _.filter(this.$platformsData.platformsNames, p => { return installedPlatforms.indexOf(p) < 0 && this.isPlatformSupportedForOS(p, projectData); // Only those not already installed }); @@ -234,13 +234,13 @@ export class PlatformService extends EventEmitter implements IPlatformService { if (platform) { platform = this.$mobileHelper.normalizePlatformName(platform); this.$logger.trace("Validate options for platform: " + platform); - let platformData = this.$platformsData.getPlatformData(platform, projectData); + const platformData = this.$platformsData.getPlatformData(platform, projectData); return await platformData.platformProjectService.validateOptions(projectData.projectId, provision, teamId); } else { let valid = true; - for (let availablePlatform in this.$platformsData.availablePlatforms) { + for (const availablePlatform in this.$platformsData.availablePlatforms) { this.$logger.trace("Validate options for platform: " + availablePlatform); - let platformData = this.$platformsData.getPlatformData(availablePlatform, projectData); + const platformData = this.$platformsData.getPlatformData(availablePlatform, projectData); valid = valid && await platformData.platformProjectService.validateOptions(projectData.projectId, provision, teamId); } @@ -295,7 +295,7 @@ export class PlatformService extends EventEmitter implements IPlatformService { private async preparePlatformCore(platform: string, appFilesUpdaterOptions: IAppFilesUpdaterOptions, projectData: IProjectData, platformSpecificData: IPlatformSpecificData, changesInfo?: IProjectChangesInfo, filesToSync?: Array, nativePrepare?: INativePrepare): Promise { this.$logger.out("Preparing project..."); - let platformData = this.$platformsData.getPlatformData(platform, projectData); + const platformData = this.$platformsData.getPlatformData(platform, projectData); const projectFilesConfig = helpers.getProjectFilesConfig({ isReleaseBuild: appFilesUpdaterOptions.release }); await this.preparePlatformCoreJS(platform, platformData, appFilesUpdaterOptions, projectData, platformSpecificData, changesInfo, filesToSync, projectFilesConfig); @@ -303,8 +303,8 @@ export class PlatformService extends EventEmitter implements IPlatformService { await this.preparePlatformCoreNative(platform, platformData, appFilesUpdaterOptions, projectData, platformSpecificData, changesInfo, projectFilesConfig); } - let directoryPath = path.join(platformData.appDestinationDirectoryPath, constants.APP_FOLDER_NAME); - let excludedDirs = [constants.APP_RESOURCES_FOLDER_NAME]; + const directoryPath = path.join(platformData.appDestinationDirectoryPath, constants.APP_FOLDER_NAME); + const excludedDirs = [constants.APP_RESOURCES_FOLDER_NAME]; if (!changesInfo || !changesInfo.modulesChanged) { excludedDirs.push(constants.TNS_MODULES_FOLDER_NAME); } @@ -345,10 +345,10 @@ export class PlatformService extends EventEmitter implements IPlatformService { if (!changesInfo || changesInfo.modulesChanged || appFilesUpdaterOptions.bundle) { await this.$pluginsService.validate(platformData, projectData); - let appDestinationDirectoryPath = path.join(platformData.appDestinationDirectoryPath, constants.APP_FOLDER_NAME); - let lastModifiedTime = this.$fs.exists(appDestinationDirectoryPath) ? this.$fs.getFsStats(appDestinationDirectoryPath).mtime : null; + const appDestinationDirectoryPath = path.join(platformData.appDestinationDirectoryPath, constants.APP_FOLDER_NAME); + const lastModifiedTime = this.$fs.exists(appDestinationDirectoryPath) ? this.$fs.getFsStats(appDestinationDirectoryPath).mtime : null; - let tnsModulesDestinationPath = path.join(appDestinationDirectoryPath, constants.TNS_MODULES_FOLDER_NAME); + const tnsModulesDestinationPath = path.join(appDestinationDirectoryPath, constants.TNS_MODULES_FOLDER_NAME); // Process node_modules folder await this.$nodeModulesBuilder.prepareNodeModules(tnsModulesDestinationPath, platform, lastModifiedTime, projectData, projectFilesConfig); } @@ -364,11 +364,11 @@ export class PlatformService extends EventEmitter implements IPlatformService { private async copyAppFiles(platformData: IPlatformData, appFilesUpdaterOptions: IAppFilesUpdaterOptions, projectData: IProjectData): Promise { platformData.platformProjectService.ensureConfigurationFileInAppResources(projectData); - let appDestinationDirectoryPath = path.join(platformData.appDestinationDirectoryPath, constants.APP_FOLDER_NAME); + const appDestinationDirectoryPath = path.join(platformData.appDestinationDirectoryPath, constants.APP_FOLDER_NAME); // Copy app folder to native project this.$fs.ensureDirectoryExists(appDestinationDirectoryPath); - let appSourceDirectoryPath = path.join(projectData.projectDir, constants.APP_FOLDER_NAME); + const appSourceDirectoryPath = path.join(projectData.projectDir, constants.APP_FOLDER_NAME); const appUpdater = new AppFilesUpdater(appSourceDirectoryPath, appDestinationDirectoryPath, appFilesUpdaterOptions, this.$fs); appUpdater.updateApp(sourceFiles => { @@ -377,11 +377,11 @@ export class PlatformService extends EventEmitter implements IPlatformService { } private copyAppResources(platformData: IPlatformData, projectData: IProjectData): void { - let appDestinationDirectoryPath = path.join(platformData.appDestinationDirectoryPath, constants.APP_FOLDER_NAME); - let appResourcesDirectoryPath = path.join(appDestinationDirectoryPath, constants.APP_RESOURCES_FOLDER_NAME); + const appDestinationDirectoryPath = path.join(platformData.appDestinationDirectoryPath, constants.APP_FOLDER_NAME); + const appResourcesDirectoryPath = path.join(appDestinationDirectoryPath, constants.APP_RESOURCES_FOLDER_NAME); if (this.$fs.exists(appResourcesDirectoryPath)) { platformData.platformProjectService.prepareAppResources(appResourcesDirectoryPath, projectData); - let appResourcesDestination = platformData.platformProjectService.getAppResourcesDestinationDirectoryPath(projectData); + const appResourcesDestination = platformData.platformProjectService.getAppResourcesDestinationDirectoryPath(projectData); this.$fs.ensureDirectoryExists(appResourcesDestination); shell.cp("-Rf", path.join(appResourcesDirectoryPath, platformData.normalizedPlatformName, "*"), appResourcesDestination); this.$fs.deleteDirectory(appResourcesDirectoryPath); @@ -389,11 +389,11 @@ export class PlatformService extends EventEmitter implements IPlatformService { } private async copyTnsModules(platform: string, platformData: IPlatformData, projectData: IProjectData, projectFilesConfig?: IProjectFilesConfig): Promise { - let appDestinationDirectoryPath = path.join(platformData.appDestinationDirectoryPath, constants.APP_FOLDER_NAME); - let lastModifiedTime = this.$fs.exists(appDestinationDirectoryPath) ? this.$fs.getFsStats(appDestinationDirectoryPath).mtime : null; + const appDestinationDirectoryPath = path.join(platformData.appDestinationDirectoryPath, constants.APP_FOLDER_NAME); + const lastModifiedTime = this.$fs.exists(appDestinationDirectoryPath) ? this.$fs.getFsStats(appDestinationDirectoryPath).mtime : null; try { - let tnsModulesDestinationPath = path.join(appDestinationDirectoryPath, constants.TNS_MODULES_FOLDER_NAME); + const tnsModulesDestinationPath = path.join(appDestinationDirectoryPath, constants.TNS_MODULES_FOLDER_NAME); // Process node_modules folder await this.$nodeModulesBuilder.prepareJSNodeModules(tnsModulesDestinationPath, platform, lastModifiedTime, projectData, projectFilesConfig); } catch (error) { @@ -408,21 +408,21 @@ export class PlatformService extends EventEmitter implements IPlatformService { return true; } - let platformData = this.$platformsData.getPlatformData(platform, projectData); - let forDevice = !buildConfig || buildConfig.buildForDevice; + const platformData = this.$platformsData.getPlatformData(platform, projectData); + const forDevice = !buildConfig || buildConfig.buildForDevice; outputPath = outputPath || (forDevice ? platformData.deviceBuildOutputPath : platformData.emulatorBuildOutputPath || platformData.deviceBuildOutputPath); if (!this.$fs.exists(outputPath)) { return true; } - let packageNames = platformData.getValidPackageNames({ isForDevice: forDevice }); - let packages = this.getApplicationPackages(outputPath, packageNames); + const packageNames = platformData.getValidPackageNames({ isForDevice: forDevice }); + const packages = this.getApplicationPackages(outputPath, packageNames); if (packages.length === 0) { return true; } - let prepareInfo = this.$projectChangesService.getPrepareInfo(platform, projectData); - let buildInfo = this.getBuildInfo(platform, platformData, buildConfig, outputPath); + const prepareInfo = this.$projectChangesService.getPrepareInfo(platform, projectData); + const buildInfo = this.getBuildInfo(platform, platformData, buildConfig, outputPath); if (!prepareInfo || !buildInfo) { return true; } @@ -470,7 +470,7 @@ export class PlatformService extends EventEmitter implements IPlatformService { const isForDevice = this.$mobileHelper.isAndroidPlatform(platform) ? null : buildConfig && buildConfig.buildForDevice; await this.trackActionForPlatform({ action: "Build", platform, isForDevice }); - let platformData = this.$platformsData.getPlatformData(platform, projectData); + const platformData = this.$platformsData.getPlatformData(platform, projectData); const handler = (data: any) => { this.emit(constants.BUILD_OUTPUT_EVENT_NAME, data); this.$logger.printInfoMessageOnSameLine(data.data.toString()); @@ -485,10 +485,10 @@ export class PlatformService extends EventEmitter implements IPlatformService { } public saveBuildInfoFile(platform: string, projectDir: string, buildInfoFileDirname: string): void { - let buildInfoFile = path.join(buildInfoFileDirname, buildInfoFileName); + const buildInfoFile = path.join(buildInfoFileDirname, buildInfoFileName); - let prepareInfo = this.$projectChangesService.getPrepareInfo(platform, this.$projectDataService.getProjectData(projectDir)); - let buildInfo = { + const prepareInfo = this.$projectChangesService.getPrepareInfo(platform, this.$projectDataService.getProjectData(projectDir)); + const buildInfo = { prepareTime: prepareInfo.changesRequireBuildTime, buildTime: new Date().toString() }; @@ -497,20 +497,20 @@ export class PlatformService extends EventEmitter implements IPlatformService { } public async shouldInstall(device: Mobile.IDevice, projectData: IProjectData, outputPath?: string): Promise { - let platform = device.deviceInfo.platform; + const platform = device.deviceInfo.platform; if (!(await device.applicationManager.isApplicationInstalled(projectData.projectId))) { return true; } - let platformData = this.$platformsData.getPlatformData(platform, projectData); - let deviceBuildInfo: IBuildInfo = await this.getDeviceBuildInfo(device, projectData); - let localBuildInfo = this.getBuildInfo(platform, platformData, { buildForDevice: !device.isEmulator }, outputPath); + const platformData = this.$platformsData.getPlatformData(platform, projectData); + const deviceBuildInfo: IBuildInfo = await this.getDeviceBuildInfo(device, projectData); + const localBuildInfo = this.getBuildInfo(platform, platformData, { buildForDevice: !device.isEmulator }, outputPath); return !localBuildInfo || !deviceBuildInfo || deviceBuildInfo.buildTime !== localBuildInfo.buildTime; } public async installApplication(device: Mobile.IDevice, buildConfig: IBuildConfig, projectData: IProjectData, packageFile?: string, outputFilePath?: string): Promise { this.$logger.out("Installing..."); - let platformData = this.$platformsData.getPlatformData(device.deviceInfo.platform, projectData); + const platformData = this.$platformsData.getPlatformData(device.deviceInfo.platform, projectData); if (!packageFile) { if (this.$devicesService.isiOSSimulator(device)) { packageFile = this.getLatestApplicationPackageForEmulator(platformData, buildConfig, outputFilePath).packageName; @@ -524,9 +524,9 @@ export class PlatformService extends EventEmitter implements IPlatformService { await device.applicationManager.reinstallApplication(projectData.projectId, packageFile); if (!buildConfig.release) { - let deviceFilePath = await this.getDeviceBuildInfoFilePath(device, projectData); - let buildInfoFilePath = outputFilePath || this.getBuildOutputPath(device.deviceInfo.platform, platformData, { buildForDevice: !device.isEmulator }); - let appIdentifier = projectData.projectId; + const deviceFilePath = await this.getDeviceBuildInfoFilePath(device, projectData); + const buildInfoFilePath = outputFilePath || this.getBuildOutputPath(device.deviceInfo.platform, platformData, { buildForDevice: !device.isEmulator }); + const appIdentifier = projectData.projectId; await device.fileSystem.putFile(path.join(buildInfoFilePath, buildInfoFileName), deviceFilePath, appIdentifier); } @@ -536,12 +536,12 @@ export class PlatformService extends EventEmitter implements IPlatformService { public async deployPlatform(platform: string, appFilesUpdaterOptions: IAppFilesUpdaterOptions, deployOptions: IDeployPlatformOptions, projectData: IProjectData, config: IPlatformOptions): Promise { await this.preparePlatform(platform, appFilesUpdaterOptions, deployOptions.platformTemplate, projectData, config); - let options: Mobile.IDevicesServicesInitializationOptions = { + const options: Mobile.IDevicesServicesInitializationOptions = { platform: platform, deviceId: deployOptions.device, emulator: deployOptions.emulator }; await this.$devicesService.initialize(options); - let action = async (device: Mobile.IDevice): Promise => { - let buildConfig: IBuildConfig = { + const action = async (device: Mobile.IDevice): Promise => { + const buildConfig: IBuildConfig = { buildForDevice: !this.$devicesService.isiOSSimulator(device), projectDir: deployOptions.projectDir, release: deployOptions.release, @@ -554,7 +554,7 @@ export class PlatformService extends EventEmitter implements IPlatformService { keyStorePath: deployOptions.keyStorePath, clean: deployOptions.clean }; - let shouldBuild = await this.shouldBuild(platform, projectData, buildConfig); + const shouldBuild = await this.shouldBuild(platform, projectData, buildConfig); if (shouldBuild) { await this.buildPlatform(platform, buildConfig, projectData); } else { @@ -576,7 +576,7 @@ export class PlatformService extends EventEmitter implements IPlatformService { public async startApplication(platform: string, runOptions: IRunPlatformOptions, projectId: string): Promise { this.$logger.out("Starting..."); - let action = async (device: Mobile.IDevice) => { + const action = async (device: Mobile.IDevice) => { await device.applicationManager.startApplication(projectId); this.$logger.out(`Successfully started on device with identifier '${device.deviceInfo.identifier}'.`); }; @@ -602,7 +602,7 @@ export class PlatformService extends EventEmitter implements IPlatformService { } private async getDeviceBuildInfo(device: Mobile.IDevice, projectData: IProjectData): Promise { - let deviceFilePath = await this.getDeviceBuildInfoFilePath(device, projectData); + const deviceFilePath = await this.getDeviceBuildInfoFilePath(device, projectData); try { return JSON.parse(await this.readFile(device, deviceFilePath, projectData)); } catch (e) { @@ -612,10 +612,10 @@ export class PlatformService extends EventEmitter implements IPlatformService { private getBuildInfo(platform: string, platformData: IPlatformData, options: IBuildForDevice, buildOutputPath?: string): IBuildInfo { buildOutputPath = buildOutputPath || this.getBuildOutputPath(platform, platformData, options); - let buildInfoFile = path.join(buildOutputPath, buildInfoFileName); + const buildInfoFile = path.join(buildOutputPath, buildInfoFileName); if (this.$fs.exists(buildInfoFile)) { try { - let buildInfoTime = this.$fs.readJson(buildInfoFile); + const buildInfoTime = this.$fs.readJson(buildInfoFile); return buildInfoTime; } catch (e) { return null; @@ -629,15 +629,15 @@ export class PlatformService extends EventEmitter implements IPlatformService { await this.ensurePlatformInstalled(platform, platformTemplate, projectData, config); const appSourceDirectoryPath = path.join(projectData.projectDir, constants.APP_FOLDER_NAME); - let platformData = this.$platformsData.getPlatformData(platform, projectData); - let appDestinationDirectoryPath = path.join(platformData.appDestinationDirectoryPath, constants.APP_FOLDER_NAME); + const platformData = this.$platformsData.getPlatformData(platform, projectData); + const appDestinationDirectoryPath = path.join(platformData.appDestinationDirectoryPath, constants.APP_FOLDER_NAME); const appUpdater = new AppFilesUpdater(appSourceDirectoryPath, appDestinationDirectoryPath, appFilesUpdaterOptions, this.$fs); appUpdater.cleanDestinationApp(); } public lastOutputPath(platform: string, buildConfig: IBuildConfig, projectData: IProjectData, outputPath?: string): string { let packageFile: string; - let platformData = this.$platformsData.getPlatformData(platform, projectData); + const platformData = this.$platformsData.getPlatformData(platform, projectData); if (buildConfig.buildForDevice) { packageFile = this.getLatestApplicationPackageForDevice(platformData, buildConfig, outputPath).packageName; } else { @@ -653,12 +653,12 @@ export class PlatformService extends EventEmitter implements IPlatformService { platform = platform.toLowerCase(); targetPath = path.resolve(targetPath); - let packageFile = this.lastOutputPath(platform, buildConfig, projectData); + const packageFile = this.lastOutputPath(platform, buildConfig, projectData); this.$fs.ensureDirectoryExists(path.dirname(targetPath)); if (this.$fs.exists(targetPath) && this.$fs.getFsStats(targetPath).isDirectory()) { - let sourceFileName = path.basename(packageFile); + const sourceFileName = path.basename(packageFile); this.$logger.trace(`Specified target path: '${targetPath}' is directory. Same filename will be used: '${sourceFileName}'.`); targetPath = path.join(targetPath, sourceFileName); } @@ -667,13 +667,13 @@ export class PlatformService extends EventEmitter implements IPlatformService { } public async removePlatforms(platforms: string[], projectData: IProjectData): Promise { - for (let platform of platforms) { + for (const platform of platforms) { this.validatePlatformInstalled(platform, projectData); - let platformData = this.$platformsData.getPlatformData(platform, projectData); + const platformData = this.$platformsData.getPlatformData(platform, projectData); await platformData.platformProjectService.stopServices(platformData.projectRoot); - let platformDir = path.join(projectData.platformsDir, platform); + const platformDir = path.join(projectData.platformsDir, platform); this.$fs.deleteDirectory(platformDir); this.$projectDataService.removeNSProperty(projectData.projectDir, platformData.frameworkPackageName); @@ -682,8 +682,8 @@ export class PlatformService extends EventEmitter implements IPlatformService { } public async updatePlatforms(platforms: string[], platformTemplate: string, projectData: IProjectData, config: IPlatformOptions): Promise { - for (let platformParam of platforms) { - let data = platformParam.split("@"), + for (const platformParam of platforms) { + const data = platformParam.split("@"), platform = data[0], version = data[1]; @@ -696,9 +696,9 @@ export class PlatformService extends EventEmitter implements IPlatformService { } private getCanExecuteAction(platform: string, options: IDeviceEmulator): any { - let canExecute = (currentDevice: Mobile.IDevice): boolean => { + const canExecute = (currentDevice: Mobile.IDevice): boolean => { if (options.device && currentDevice && currentDevice.deviceInfo) { - let device = this.$devicesService.getDeviceByDeviceOption(); + const device = this.$devicesService.getDeviceByDeviceOption(); if (device && device.deviceInfo) { return currentDevice.deviceInfo.identifier === device.deviceInfo.identifier; } @@ -763,20 +763,20 @@ export class PlatformService extends EventEmitter implements IPlatformService { } public isPlatformSupportedForOS(platform: string, projectData: IProjectData): boolean { - let targetedOS = this.$platformsData.getPlatformData(platform, projectData).targetedOS; - let res = !targetedOS || targetedOS.indexOf("*") >= 0 || targetedOS.indexOf(process.platform) >= 0; + const targetedOS = this.$platformsData.getPlatformData(platform, projectData).targetedOS; + const res = !targetedOS || targetedOS.indexOf("*") >= 0 || targetedOS.indexOf(process.platform) >= 0; return res; } private isPlatformPrepared(platform: string, projectData: IProjectData): boolean { - let platformData = this.$platformsData.getPlatformData(platform, projectData); + const platformData = this.$platformsData.getPlatformData(platform, projectData); return platformData.platformProjectService.isPlatformPrepared(platformData.projectRoot, projectData); } private getApplicationPackages(buildOutputPath: string, validPackageNames: string[]): IApplicationPackage[] { // Get latest package` that is produced from build - let candidates = this.$fs.readDirectory(buildOutputPath); - let packages = _.filter(candidates, candidate => { + const candidates = this.$fs.readDirectory(buildOutputPath); + const packages = _.filter(candidates, candidate => { return _.includes(validPackageNames, candidate); }).map(currentPackage => { currentPackage = path.join(buildOutputPath, currentPackage); @@ -793,7 +793,7 @@ export class PlatformService extends EventEmitter implements IPlatformService { private getLatestApplicationPackage(buildOutputPath: string, validPackageNames: string[]): IApplicationPackage { let packages = this.getApplicationPackages(buildOutputPath, validPackageNames); if (packages.length === 0) { - let packageExtName = path.extname(validPackageNames[0]); + const packageExtName = path.extname(validPackageNames[0]); this.$errors.fail("No %s found in %s directory", packageExtName, buildOutputPath); } @@ -811,19 +811,19 @@ export class PlatformService extends EventEmitter implements IPlatformService { } private async updatePlatform(platform: string, version: string, platformTemplate: string, projectData: IProjectData, config: IPlatformOptions): Promise { - let platformData = this.$platformsData.getPlatformData(platform, projectData); + const platformData = this.$platformsData.getPlatformData(platform, projectData); - let data = this.$projectDataService.getNSValue(projectData.projectDir, platformData.frameworkPackageName); - let currentVersion = data && data.version ? data.version : "0.2.0"; + const data = this.$projectDataService.getNSValue(projectData.projectDir, platformData.frameworkPackageName); + const currentVersion = data && data.version ? data.version : "0.2.0"; let newVersion = version === constants.PackageVersion.NEXT ? await this.$npmInstallationManager.getNextVersion(platformData.frameworkPackageName) : version || await this.$npmInstallationManager.getLatestCompatibleVersion(platformData.frameworkPackageName); - let installedModuleDir = await this.$npmInstallationManager.install(platformData.frameworkPackageName, projectData.projectDir, { version: newVersion, dependencyType: "save" }); - let cachedPackageData = this.$fs.readJson(path.join(installedModuleDir, "package.json")); + const installedModuleDir = await this.$npmInstallationManager.install(platformData.frameworkPackageName, projectData.projectDir, { version: newVersion, dependencyType: "save" }); + const cachedPackageData = this.$fs.readJson(path.join(installedModuleDir, "package.json")); newVersion = (cachedPackageData && cachedPackageData.version) || newVersion; - let canUpdate = platformData.platformProjectService.canUpdatePlatform(installedModuleDir, projectData); + const canUpdate = platformData.platformProjectService.canUpdatePlatform(installedModuleDir, projectData); await this.$npm.uninstall(platformData.frameworkPackageName, { save: true }, projectData.projectDir); if (canUpdate) { if (!semver.valid(newVersion)) { @@ -854,7 +854,7 @@ export class PlatformService extends EventEmitter implements IPlatformService { // TODO: Remove this method from here. It has nothing to do with platform public async readFile(device: Mobile.IDevice, deviceFilePath: string, projectData: IProjectData): Promise { temp.track(); - let uniqueFilePath = temp.path({ suffix: ".tmp" }); + const uniqueFilePath = temp.path({ suffix: ".tmp" }); try { await device.fileSystem.getFile(deviceFilePath, projectData.projectId, uniqueFilePath); } catch (e) { @@ -862,7 +862,7 @@ export class PlatformService extends EventEmitter implements IPlatformService { } if (this.$fs.exists(uniqueFilePath)) { - let text = this.$fs.readText(uniqueFilePath); + const text = this.$fs.readText(uniqueFilePath); shell.rm(uniqueFilePath); return text; } diff --git a/lib/services/plugin-variables-service.ts b/lib/services/plugin-variables-service.ts index 2a85e515bc..ccb822fcc5 100644 --- a/lib/services/plugin-variables-service.ts +++ b/lib/services/plugin-variables-service.ts @@ -14,9 +14,9 @@ export class PluginVariablesService implements IPluginVariablesService { } public async savePluginVariablesInProjectFile(pluginData: IPluginData, projectData: IProjectData): Promise { - let values = Object.create(null); + const values = Object.create(null); await this.executeForAllPluginVariables(pluginData, async (pluginVariableData: IPluginVariableData) => { - let pluginVariableValue = await this.getPluginVariableValue(pluginVariableData); + const pluginVariableValue = await this.getPluginVariableValue(pluginVariableData); this.ensurePluginVariableValue(pluginVariableValue, `Unable to find value for ${pluginVariableData.name} plugin variable from ${pluginData.name} plugin. Ensure the --var option is specified or the plugin variable has default value.`); values[pluginVariableData.name] = pluginVariableValue; }, projectData); @@ -41,8 +41,8 @@ export class PluginVariablesService implements IPluginVariablesService { } public interpolateAppIdentifier(pluginConfigurationFilePath: string, projectData: IProjectData): void { - let pluginConfigurationFileContent = this.$fs.readText(pluginConfigurationFilePath); - let newContent = this.interpolateCore("nativescript.id", projectData.projectId, pluginConfigurationFileContent); + const pluginConfigurationFileContent = this.$fs.readText(pluginConfigurationFilePath); + const newContent = this.interpolateCore("nativescript.id", projectData.projectId, pluginConfigurationFileContent); this.$fs.writeFile(pluginConfigurationFilePath, newContent); } @@ -62,20 +62,20 @@ export class PluginVariablesService implements IPluginVariablesService { } private async getPluginVariableValue(pluginVariableData: IPluginVariableData): Promise { - let pluginVariableName = pluginVariableData.name; + const pluginVariableName = pluginVariableData.name; let value = this.$pluginVariablesHelper.getPluginVariableFromVarOption(pluginVariableName); if (value) { value = value[pluginVariableName]; } else { value = pluginVariableData.defaultValue; if (!value && helpers.isInteractive()) { - let promptSchema = { + const promptSchema = { name: pluginVariableName, type: "input", message: `Enter value for ${pluginVariableName} variable:`, validate: (val: string) => !!val ? true : 'Please enter a value!' }; - let promptData = await this.$prompter.get([promptSchema]); + const promptData = await this.$prompter.get([promptSchema]); value = promptData[pluginVariableName]; } } @@ -84,13 +84,13 @@ export class PluginVariablesService implements IPluginVariablesService { } private async executeForAllPluginVariables(pluginData: IPluginData, action: (pluginVariableData: IPluginVariableData) => Promise, projectData: IProjectData): Promise { - let pluginVariables = pluginData.pluginVariables; - let pluginVariablesNames = _.keys(pluginVariables); + const pluginVariables = pluginData.pluginVariables; + const pluginVariablesNames = _.keys(pluginVariables); await Promise.all(_.map(pluginVariablesNames, pluginVariableName => action(this.createPluginVariableData(pluginData, pluginVariableName, projectData)))); } private createPluginVariableData(pluginData: IPluginData, pluginVariableName: string, projectData: IProjectData): IPluginVariableData { - let variableData = pluginData.pluginVariables[pluginVariableName]; + const variableData = pluginData.pluginVariables[pluginVariableName]; variableData.name = pluginVariableName; diff --git a/lib/services/plugins-service.ts b/lib/services/plugins-service.ts index 0b460da5db..7cd9e5b280 100644 --- a/lib/services/plugins-service.ts +++ b/lib/services/plugins-service.ts @@ -45,15 +45,15 @@ export class PluginsService implements IPluginsService { plugin = possiblePackageName; } - let name = (await this.$npm.install(plugin, projectData.projectDir, this.npmInstallOptions)).name; - let pathToRealNpmPackageJson = path.join(projectData.projectDir, "node_modules", name, "package.json"); - let realNpmPackageJson = this.$fs.readJson(pathToRealNpmPackageJson); + const name = (await this.$npm.install(plugin, projectData.projectDir, this.npmInstallOptions)).name; + const pathToRealNpmPackageJson = path.join(projectData.projectDir, "node_modules", name, "package.json"); + const realNpmPackageJson = this.$fs.readJson(pathToRealNpmPackageJson); if (realNpmPackageJson.nativescript) { - let pluginData = this.convertToPluginData(realNpmPackageJson, projectData.projectDir); + const pluginData = this.convertToPluginData(realNpmPackageJson, projectData.projectDir); // Validate - let action = async (pluginDestinationPath: string, platform: string, platformData: IPlatformData): Promise => { + const action = async (pluginDestinationPath: string, platform: string, platformData: IPlatformData): Promise => { this.isPluginDataValidForPlatform(pluginData, platform, projectData); }; @@ -77,8 +77,8 @@ export class PluginsService implements IPluginsService { } public async remove(pluginName: string, projectData: IProjectData): Promise { - let removePluginNativeCodeAction = async (modulesDestinationPath: string, platform: string, platformData: IPlatformData): Promise => { - let pluginData = this.convertToPluginData(this.getNodeModuleData(pluginName, projectData.projectDir), projectData.projectDir); + const removePluginNativeCodeAction = async (modulesDestinationPath: string, platform: string, platformData: IPlatformData): Promise => { + const pluginData = this.convertToPluginData(this.getNodeModuleData(pluginName, projectData.projectDir), projectData.projectDir); await platformData.platformProjectService.removePluginNativeCode(pluginData, projectData); }; @@ -89,7 +89,7 @@ export class PluginsService implements IPluginsService { await this.executeNpmCommand(PluginsService.UNINSTALL_COMMAND_NAME, pluginName, projectData); let showMessage = true; - let action = async (modulesDestinationPath: string, platform: string, platformData: IPlatformData): Promise => { + const action = async (modulesDestinationPath: string, platform: string, platformData: IPlatformData): Promise => { shelljs.rm("-rf", path.join(modulesDestinationPath, pluginName)); this.$logger.out(`Successfully removed plugin ${pluginName} for ${platform}.`); @@ -109,10 +109,10 @@ export class PluginsService implements IPluginsService { public async prepare(dependencyData: IDependencyData, platform: string, projectData: IProjectData, projectFilesConfig: IProjectFilesConfig): Promise { platform = platform.toLowerCase(); - let platformData = this.$platformsData.getPlatformData(platform, projectData); - let pluginData = this.convertToPluginData(dependencyData, projectData.projectDir); + const platformData = this.$platformsData.getPlatformData(platform, projectData); + const pluginData = this.convertToPluginData(dependencyData, projectData.projectDir); - let appFolderExists = this.$fs.exists(path.join(platformData.appDestinationDirectoryPath, constants.APP_FOLDER_NAME)); + const appFolderExists = this.$fs.exists(path.join(platformData.appDestinationDirectoryPath, constants.APP_FOLDER_NAME)); if (appFolderExists) { this.preparePluginScripts(pluginData, platform, projectData, projectFilesConfig); await this.preparePluginNativeCode(pluginData, platform, projectData); @@ -123,9 +123,9 @@ export class PluginsService implements IPluginsService { } public preparePluginScripts(pluginData: IPluginData, platform: string, projectData: IProjectData, projectFilesConfig: IProjectFilesConfig): void { - let platformData = this.$platformsData.getPlatformData(platform, projectData); - let pluginScriptsDestinationPath = path.join(platformData.appDestinationDirectoryPath, constants.APP_FOLDER_NAME, "tns_modules"); - let scriptsDestinationExists = this.$fs.exists(pluginScriptsDestinationPath); + const platformData = this.$platformsData.getPlatformData(platform, projectData); + const pluginScriptsDestinationPath = path.join(platformData.appDestinationDirectoryPath, constants.APP_FOLDER_NAME, "tns_modules"); + const scriptsDestinationExists = this.$fs.exists(pluginScriptsDestinationPath); if (!scriptsDestinationExists) { //tns_modules/ doesn't exist. Assuming we're running a bundled prepare. return; @@ -140,7 +140,7 @@ export class PluginsService implements IPluginsService { } public async preparePluginNativeCode(pluginData: IPluginData, platform: string, projectData: IProjectData): Promise { - let platformData = this.$platformsData.getPlatformData(platform, projectData); + const platformData = this.$platformsData.getPlatformData(platform, projectData); pluginData.pluginPlatformsFolderPath = (_platform: string) => path.join(pluginData.fullPath, "platforms", _platform); await platformData.platformProjectService.preparePluginNativeCode(pluginData, projectData); @@ -154,13 +154,13 @@ export class PluginsService implements IPluginsService { _(installedDependencies) .filter(dependencyName => _.startsWith(dependencyName, "@")) .each(scopedDependencyDir => { - let contents = this.$fs.readDirectory(path.join(this.getNodeModulesPath(projectData.projectDir), scopedDependencyDir)); + const contents = this.$fs.readDirectory(path.join(this.getNodeModulesPath(projectData.projectDir), scopedDependencyDir)); installedDependencies = installedDependencies.concat(contents.map(dependencyName => `${scopedDependencyDir}/${dependencyName}`)); }); - let packageJsonContent = this.$fs.readJson(this.getPackageJsonFilePath(projectData.projectDir)); - let allDependencies = _.keys(packageJsonContent.dependencies).concat(_.keys(packageJsonContent.devDependencies)); - let notInstalledDependencies = _.difference(allDependencies, installedDependencies); + const packageJsonContent = this.$fs.readJson(this.getPackageJsonFilePath(projectData.projectDir)); + const allDependencies = _.keys(packageJsonContent.dependencies).concat(_.keys(packageJsonContent.devDependencies)); + const notInstalledDependencies = _.difference(allDependencies, installedDependencies); if (this.$options.force || notInstalledDependencies.length) { this.$logger.trace("Npm install will be called from CLI. Force option is: ", this.$options.force, " Not installed dependencies are: ", notInstalledDependencies); await this.$npm.install(projectData.projectDir, projectData.projectDir, { @@ -173,15 +173,15 @@ export class PluginsService implements IPluginsService { } public async getAllInstalledPlugins(projectData: IProjectData): Promise { - let nodeModules = (await this.getAllInstalledModules(projectData)).map(nodeModuleData => this.convertToPluginData(nodeModuleData, projectData.projectDir)); + const nodeModules = (await this.getAllInstalledModules(projectData)).map(nodeModuleData => this.convertToPluginData(nodeModuleData, projectData.projectDir)); return _.filter(nodeModules, nodeModuleData => nodeModuleData && nodeModuleData.isPlugin); } public getDependenciesFromPackageJson(projectDir: string): IPackageJsonDepedenciesResult { - let packageJson = this.$fs.readJson(this.getPackageJsonFilePath(projectDir)); - let dependencies: IBasePluginData[] = this.getBasicPluginInformation(packageJson.dependencies); + const packageJson = this.$fs.readJson(this.getPackageJsonFilePath(projectDir)); + const dependencies: IBasePluginData[] = this.getBasicPluginInformation(packageJson.dependencies); - let devDependencies: IBasePluginData[] = this.getBasicPluginInformation(packageJson.devDependencies); + const devDependencies: IBasePluginData[] = this.getBasicPluginInformation(packageJson.devDependencies); return { dependencies, @@ -209,7 +209,7 @@ export class PluginsService implements IPluginsService { } private getDependencies(projectDir: string): string[] { - let packageJsonFilePath = this.getPackageJsonFilePath(projectDir); + const packageJsonFilePath = this.getPackageJsonFilePath(projectDir); return _.keys(require(packageJsonFilePath).dependencies); } @@ -218,7 +218,7 @@ export class PluginsService implements IPluginsService { module = this.getPackageJsonFilePathForModule(module, projectDir); } - let data = this.$fs.readJson(module); + const data = this.$fs.readJson(module); return { name: data.name, version: data.version, @@ -229,13 +229,13 @@ export class PluginsService implements IPluginsService { } public convertToPluginData(cacheData: any, projectDir: string): IPluginData { - let pluginData: any = {}; + const pluginData: any = {}; pluginData.name = cacheData.name; pluginData.version = cacheData.version; pluginData.fullPath = cacheData.directory || path.dirname(this.getPackageJsonFilePathForModule(cacheData.name, projectDir)); pluginData.isPlugin = !!cacheData.nativescript || !!cacheData.moduleInfo; pluginData.pluginPlatformsFolderPath = (platform: string) => path.join(pluginData.fullPath, "platforms", platform); - let data = cacheData.nativescript || cacheData.moduleInfo; + const data = cacheData.nativescript || cacheData.moduleInfo; if (pluginData.isPlugin) { pluginData.platformsData = data.platforms; @@ -253,7 +253,7 @@ export class PluginsService implements IPluginsService { private async getAllInstalledModules(projectData: IProjectData): Promise { await this.ensure(projectData); - let nodeModules = this.getDependencies(projectData.projectDir); + const nodeModules = this.getDependencies(projectData.projectDir); return _.map(nodeModules, nodeModuleName => this.getNodeModuleData(nodeModuleName, projectData.projectDir)); } @@ -272,19 +272,19 @@ export class PluginsService implements IPluginsService { } private async executeForAllInstalledPlatforms(action: (_pluginDestinationPath: string, pl: string, _platformData: IPlatformData) => Promise, projectData: IProjectData): Promise { - let availablePlatforms = _.keys(this.$platformsData.availablePlatforms); - for (let platform of availablePlatforms) { - let isPlatformInstalled = this.$fs.exists(path.join(projectData.platformsDir, platform.toLowerCase())); + const availablePlatforms = _.keys(this.$platformsData.availablePlatforms); + for (const platform of availablePlatforms) { + const isPlatformInstalled = this.$fs.exists(path.join(projectData.platformsDir, platform.toLowerCase())); if (isPlatformInstalled) { - let platformData = this.$platformsData.getPlatformData(platform.toLowerCase(), projectData); - let pluginDestinationPath = path.join(platformData.appDestinationDirectoryPath, constants.APP_FOLDER_NAME, "tns_modules"); + const platformData = this.$platformsData.getPlatformData(platform.toLowerCase(), projectData); + const pluginDestinationPath = path.join(platformData.appDestinationDirectoryPath, constants.APP_FOLDER_NAME, "tns_modules"); await action(pluginDestinationPath, platform.toLowerCase(), platformData); } } } private getInstalledFrameworkVersion(platform: string, projectData: IProjectData): string { - let platformData = this.$platformsData.getPlatformData(platform, projectData); + const platformData = this.$platformsData.getPlatformData(platform, projectData); const frameworkData = this.$projectDataService.getNSValue(projectData.projectDir, platformData.frameworkPackageName); return frameworkData.version; } @@ -292,10 +292,10 @@ export class PluginsService implements IPluginsService { private isPluginDataValidForPlatform(pluginData: IPluginData, platform: string, projectData: IProjectData): boolean { let isValid = true; - let installedFrameworkVersion = this.getInstalledFrameworkVersion(platform, projectData); - let pluginPlatformsData = pluginData.platformsData; + const installedFrameworkVersion = this.getInstalledFrameworkVersion(platform, projectData); + const pluginPlatformsData = pluginData.platformsData; if (pluginPlatformsData) { - let pluginVersion = (pluginPlatformsData)[platform]; + const pluginVersion = (pluginPlatformsData)[platform]; if (!pluginVersion) { this.$logger.warn(`${pluginData.name} is not supported for ${platform}.`); isValid = false; diff --git a/lib/services/project-changes-service.ts b/lib/services/project-changes-service.ts index e9982cae43..1baafc517c 100644 --- a/lib/services/project-changes-service.ts +++ b/lib/services/project-changes-service.ts @@ -55,7 +55,7 @@ export class ProjectChangesService implements IProjectChangesService { } public async checkForChanges(platform: string, projectData: IProjectData, projectChangesOptions: IProjectChangesOptions): Promise { - let platformData = this.$platformsData.getPlatformData(platform, projectData); + const platformData = this.$platformsData.getPlatformData(platform, projectData); this._changesInfo = new ProjectChangesInfo(); if (!this.ensurePrepareInfo(platform, projectData, projectChangesOptions)) { this._newFiles = 0; @@ -72,7 +72,7 @@ export class ProjectChangesService implements IProjectChangesService { if (this._newFiles > 0) { this._changesInfo.modulesChanged = true; } - let platformResourcesDir = path.join(projectData.appResourcesDirectoryPath, platformData.normalizedPlatformName); + const platformResourcesDir = path.join(projectData.appResourcesDirectoryPath, platformData.normalizedPlatformName); if (platform === this.$devicePlatformsConstants.iOS.toLowerCase()) { this._changesInfo.configChanged = this.filesChanged([path.join(platformResourcesDir, platformData.configurationFileName), path.join(platformResourcesDir, "LaunchScreen.storyboard"), @@ -86,7 +86,7 @@ export class ProjectChangesService implements IProjectChangesService { } } - let projectService = platformData.platformProjectService; + const projectService = platformData.platformProjectService; await projectService.checkForChanges(this._changesInfo, projectChangesOptions, projectData); if (projectChangesOptions.bundle !== this._prepareInfo.bundle || projectChangesOptions.release !== this._prepareInfo.release) { @@ -119,13 +119,13 @@ export class ProjectChangesService implements IProjectChangesService { } public getPrepareInfoFilePath(platform: string, projectData: IProjectData): string { - let platformData = this.$platformsData.getPlatformData(platform, projectData); - let prepareInfoFilePath = path.join(platformData.projectRoot, prepareInfoFileName); + const platformData = this.$platformsData.getPlatformData(platform, projectData); + const prepareInfoFilePath = path.join(platformData.projectRoot, prepareInfoFileName); return prepareInfoFilePath; } public getPrepareInfo(platform: string, projectData: IProjectData): IPrepareInfo { - let prepareInfoFilePath = this.getPrepareInfoFilePath(platform, projectData); + const prepareInfoFilePath = this.getPrepareInfoFilePath(platform, projectData); let prepareInfo: IPrepareInfo = null; if (this.$fs.exists(prepareInfoFilePath)) { try { @@ -138,7 +138,7 @@ export class ProjectChangesService implements IProjectChangesService { } public savePrepareInfo(platform: string, projectData: IProjectData): void { - let prepareInfoFilePath = this.getPrepareInfoFilePath(platform, projectData); + const prepareInfoFilePath = this.getPrepareInfoFilePath(platform, projectData); this.$fs.writeJson(prepareInfoFilePath, this._prepareInfo); } @@ -157,8 +157,8 @@ export class ProjectChangesService implements IProjectChangesService { projectChangesOptions.nativePlatformStatus : this._prepareInfo.nativePlatformStatus || projectChangesOptions.nativePlatformStatus; - let platformData = this.$platformsData.getPlatformData(platform, projectData); - let prepareInfoFile = path.join(platformData.projectRoot, prepareInfoFileName); + const platformData = this.$platformsData.getPlatformData(platform, projectData); + const prepareInfoFile = path.join(platformData.projectRoot, prepareInfoFileName); this._outputProjectMtime = this.$fs.getFsStats(prepareInfoFile).mtime.getTime(); this._outputProjectCTime = this.$fs.getFsStats(prepareInfoFile).ctime.getTime(); return false; @@ -206,9 +206,9 @@ export class ProjectChangesService implements IProjectChangesService { } private filesChanged(files: string[]): boolean { - for (let file of files) { + for (const file of files) { if (this.$fs.exists(file)) { - let fileStats = this.$fs.getFsStats(file); + const fileStats = this.$fs.getFsStats(file); if (fileStats.mtime.getTime() >= this._outputProjectMtime || fileStats.ctime.getTime() >= this._outputProjectCTime) { return true; } @@ -224,20 +224,20 @@ export class ProjectChangesService implements IProjectChangesService { return true; } - let files = this.$fs.readDirectory(dir); - for (let file of files) { - let filePath = path.join(dir, file); + const files = this.$fs.readDirectory(dir); + for (const file of files) { + const filePath = path.join(dir, file); if (filePath === skipDir) { continue; } const fileStats = this.$fs.getFsStats(filePath); - let changed = this.isFileModified(fileStats, filePath); + const changed = this.isFileModified(fileStats, filePath); if (changed) { if (processFunc) { this._newFiles++; - let filePathRelative = path.relative(projectData.projectDir, filePath); + const filePathRelative = path.relative(projectData.projectDir, filePath); if (processFunc.call(this, filePathRelative, projectData)) { return true; } @@ -261,7 +261,7 @@ export class ProjectChangesService implements IProjectChangesService { filePathStat.ctime.getTime() >= this._outputProjectCTime; if (!changed) { - let lFileStats = this.$fs.getLsStats(filePath); + const lFileStats = this.$fs.getLsStats(filePath); changed = lFileStats.mtime.getTime() >= this._outputProjectMtime || lFileStats.ctime.getTime() >= this._outputProjectCTime; } @@ -273,7 +273,7 @@ export class ProjectChangesService implements IProjectChangesService { if (path.basename(file) === "package.json") { return true; } - let projectDir = projectData.projectDir; + const projectDir = projectData.projectDir; if (_.startsWith(path.join(projectDir, file), projectData.appResourcesDirectoryPath)) { return true; } @@ -281,9 +281,9 @@ export class ProjectChangesService implements IProjectChangesService { let filePath = file; while (filePath !== NODE_MODULES_FOLDER_NAME) { filePath = path.dirname(filePath); - let fullFilePath = path.join(projectDir, path.join(filePath, "package.json")); + const fullFilePath = path.join(projectDir, path.join(filePath, "package.json")); if (this.$fs.exists(fullFilePath)) { - let json = this.$fs.readJson(fullFilePath); + const json = this.$fs.readJson(fullFilePath); if (json["nativescript"] && _.startsWith(file, path.join(filePath, "platforms"))) { return true; } diff --git a/lib/services/project-data-service.ts b/lib/services/project-data-service.ts index 29f1f964c7..46703f552d 100644 --- a/lib/services/project-data-service.ts +++ b/lib/services/project-data-service.ts @@ -63,7 +63,7 @@ export class ProjectDataService implements IProjectDataService { const props = dottedPropertyName.split("."); let result = jsonData[props.shift()]; - for (let prop of props) { + for (const prop of props) { result = result[prop]; } @@ -74,7 +74,7 @@ export class ProjectDataService implements IProjectDataService { const projectFileInfo = this.getProjectFileData(projectDir); const props = key.split("."); - let data: any = projectFileInfo.projectData; + const data: any = projectFileInfo.projectData; let currentData = data; _.each(props, (prop, index: number) => { @@ -92,7 +92,7 @@ export class ProjectDataService implements IProjectDataService { private removeProperty(projectDir: string, propertyName: string): void { const projectFileInfo = this.getProjectFileData(projectDir); - let data: any = projectFileInfo.projectData; + const data: any = projectFileInfo.projectData; let currentData = data; const props = propertyName.split("."); const propertyToDelete = props.splice(props.length - 1, 1)[0]; diff --git a/lib/services/project-name-service.ts b/lib/services/project-name-service.ts index 3b685d9249..2346a52036 100644 --- a/lib/services/project-name-service.ts +++ b/lib/services/project-name-service.ts @@ -15,7 +15,7 @@ export class ProjectNameService implements IProjectNameService { return await this.promptForNewName("The project name is invalid.", projectName, validateOptions); } - let userCanInteract = isInteractive(); + const userCanInteract = isInteractive(); if (!this.checkIfNameStartsWithLetter(projectName)) { if (!userCanInteract) { @@ -37,7 +37,7 @@ export class ProjectNameService implements IProjectNameService { } private checkIfNameStartsWithLetter(projectName: string): boolean { - let startsWithLetterExpression = /^[a-zA-Z]/; + const startsWithLetterExpression = /^[a-zA-Z]/; return startsWithLetterExpression.test(projectName); } @@ -46,7 +46,7 @@ export class ProjectNameService implements IProjectNameService { return projectName; } - let newProjectName = await this.$prompter.getString("Enter the new project name:"); + const newProjectName = await this.$prompter.getString("Enter the new project name:"); return await this.ensureValidName(newProjectName, validateOptions); } diff --git a/lib/services/project-service.ts b/lib/services/project-service.ts index f75f5b1d57..fcb50d79ca 100644 --- a/lib/services/project-service.ts +++ b/lib/services/project-service.ts @@ -19,8 +19,8 @@ export class ProjectService implements IProjectService { @exported("projectService") public async createProject(projectOptions: IProjectSettings): Promise { - let projectName = projectOptions.projectName, - selectedTemplate = projectOptions.template; + let projectName = projectOptions.projectName; + let selectedTemplate = projectOptions.template; if (!projectName) { this.$errors.fail("You must specify when creating a new project."); @@ -37,7 +37,7 @@ export class ProjectService implements IProjectService { this.$errors.fail("Path already exists and is not empty %s", projectDir); } - let projectId = projectOptions.appId || this.$projectHelper.generateDefaultAppId(projectName, constants.DEFAULT_APP_IDENTIFIER_PREFIX); + const projectId = projectOptions.appId || this.$projectHelper.generateDefaultAppId(projectName, constants.DEFAULT_APP_IDENTIFIER_PREFIX); this.createPackageJson(projectDir, projectId); this.$logger.trace(`Creating a new NativeScript project with name ${projectName} and id ${projectId} at location ${projectDir}`); @@ -46,12 +46,12 @@ export class ProjectService implements IProjectService { } try { - let templatePath = await this.$projectTemplatesService.prepareTemplate(selectedTemplate, projectDir); + const templatePath = await this.$projectTemplatesService.prepareTemplate(selectedTemplate, projectDir); await this.extractTemplate(projectDir, templatePath); await this.ensureAppResourcesExist(projectDir); - let templatePackageJsonData = this.getDataFromJson(templatePath); + const templatePackageJsonData = this.getDataFromJson(templatePath); if (!(templatePackageJsonData && templatePackageJsonData.dependencies && templatePackageJsonData.dependencies[constants.TNS_CORE_MODULES_NAME])) { await this.$npmInstallationManager.install(constants.TNS_CORE_MODULES_NAME, projectDir, { dependencyType: "save" }); @@ -66,7 +66,7 @@ export class ProjectService implements IProjectService { ignoreScripts: projectOptions.ignoreScripts }); - let templatePackageJson = this.$fs.readJson(path.join(templatePath, "package.json")); + const templatePackageJson = this.$fs.readJson(path.join(templatePath, "package.json")); await this.$npm.uninstall(templatePackageJson.name, { save: true }, projectDir); } catch (err) { this.$fs.deleteDirectory(projectDir); @@ -87,9 +87,9 @@ export class ProjectService implements IProjectService { } private getDataFromJson(templatePath: string): any { - let templatePackageJsonPath = path.join(templatePath, constants.PACKAGE_JSON_FILE_NAME); + const templatePackageJsonPath = path.join(templatePath, constants.PACKAGE_JSON_FILE_NAME); if (this.$fs.exists(templatePackageJsonPath)) { - let templatePackageJsonData = this.$fs.readJson(templatePackageJsonPath); + const templatePackageJsonData = this.$fs.readJson(templatePackageJsonPath); return templatePackageJsonData; } else { this.$logger.trace(`Template ${templatePath} does not have ${constants.PACKAGE_JSON_FILE_NAME} file.`); @@ -101,7 +101,7 @@ export class ProjectService implements IProjectService { private async extractTemplate(projectDir: string, realTemplatePath: string): Promise { this.$fs.ensureDirectoryExists(projectDir); - let appDestinationPath = path.join(projectDir, constants.APP_FOLDER_NAME); + const appDestinationPath = path.join(projectDir, constants.APP_FOLDER_NAME); this.$fs.createDirectory(appDestinationPath); this.$logger.trace(`Copying application from '${realTemplatePath}' into '${appDestinationPath}'.`); @@ -111,14 +111,14 @@ export class ProjectService implements IProjectService { } private async ensureAppResourcesExist(projectDir: string): Promise { - let appPath = path.join(projectDir, constants.APP_FOLDER_NAME), + const appPath = path.join(projectDir, constants.APP_FOLDER_NAME), appResourcesDestinationPath = path.join(appPath, constants.APP_RESOURCES_FOLDER_NAME); if (!this.$fs.exists(appResourcesDestinationPath)) { this.$fs.createDirectory(appResourcesDestinationPath); // the template installed doesn't have App_Resources -> get from a default template - let defaultTemplateName = constants.RESERVED_TEMPLATE_NAMES["default"]; + const defaultTemplateName = constants.RESERVED_TEMPLATE_NAMES["default"]; await this.$npm.install(defaultTemplateName, projectDir, { save: true, disableNpmInstall: false, @@ -126,7 +126,7 @@ export class ProjectService implements IProjectService { ignoreScripts: false }); - let defaultTemplateAppResourcesPath = path.join(projectDir, constants.NODE_MODULES_FOLDER_NAME, + const defaultTemplateAppResourcesPath = path.join(projectDir, constants.NODE_MODULES_FOLDER_NAME, defaultTemplateName, constants.APP_RESOURCES_FOLDER_NAME); if (this.$fs.exists(defaultTemplateAppResourcesPath)) { @@ -138,8 +138,8 @@ export class ProjectService implements IProjectService { } private removeMergedDependencies(projectDir: string, templatePackageJsonData: any): void { - let extractedTemplatePackageJsonPath = path.join(projectDir, constants.APP_FOLDER_NAME, constants.PACKAGE_JSON_FILE_NAME); - for (let key in templatePackageJsonData) { + const extractedTemplatePackageJsonPath = path.join(projectDir, constants.APP_FOLDER_NAME, constants.PACKAGE_JSON_FILE_NAME); + for (const key in templatePackageJsonData) { if (constants.PackageJsonKeysToKeep.indexOf(key) === -1) { delete templatePackageJsonData[key]; } @@ -151,8 +151,8 @@ export class ProjectService implements IProjectService { private mergeProjectAndTemplateProperties(projectDir: string, templatePackageJsonData: any): void { if (templatePackageJsonData) { - let projectPackageJsonPath = path.join(projectDir, constants.PACKAGE_JSON_FILE_NAME); - let projectPackageJsonData = this.$fs.readJson(projectPackageJsonPath); + const projectPackageJsonPath = path.join(projectDir, constants.PACKAGE_JSON_FILE_NAME); + const projectPackageJsonData = this.$fs.readJson(projectPackageJsonPath); this.$logger.trace("Initial project package.json data: ", projectPackageJsonData); if (projectPackageJsonData.dependencies || templatePackageJsonData.dependencies) { projectPackageJsonData.dependencies = this.mergeDependencies(projectPackageJsonData.dependencies, templatePackageJsonData.dependencies); @@ -174,8 +174,8 @@ export class ProjectService implements IProjectService { this.$logger.trace("Merging dependencies, projectDependencies are: ", projectDependencies, " templateDependencies are: ", templateDependencies); projectDependencies = projectDependencies || {}; _.extend(projectDependencies, templateDependencies || {}); - let sortedDeps: IStringDictionary = {}; - let dependenciesNames = _.keys(projectDependencies).sort(); + const sortedDeps: IStringDictionary = {}; + const dependenciesNames = _.keys(projectDependencies).sort(); _.each(dependenciesNames, (key: string) => { sortedDeps[key] = projectDependencies[key]; }); diff --git a/lib/services/project-templates-service.ts b/lib/services/project-templates-service.ts index fb5292384d..d3cb0a0489 100644 --- a/lib/services/project-templates-service.ts +++ b/lib/services/project-templates-service.ts @@ -12,7 +12,7 @@ export class ProjectTemplatesService implements IProjectTemplatesService { public async prepareTemplate(originalTemplateName: string, projectDir: string): Promise { // support @ syntax - let data = originalTemplateName.split("@"), + const data = originalTemplateName.split("@"), name = data[0], version = data[1]; diff --git a/lib/services/subscription-service.ts b/lib/services/subscription-service.ts index 8a9e18a6cf..73778df593 100644 --- a/lib/services/subscription-service.ts +++ b/lib/services/subscription-service.ts @@ -12,7 +12,7 @@ export class SubscriptionService implements ISubscriptionService { public async subscribeForNewsletter(): Promise { if (await this.shouldAskForEmail()) { this.$logger.out("Leave your e-mail address here to subscribe for NativeScript newsletter and product updates, tips and tricks:"); - let email = await this.getEmail("(press Enter for blank)"); + const email = await this.getEmail("(press Enter for blank)"); await this.$userSettingsService.saveSetting("EMAIL_REGISTERED", true); await this.sendEmail(email); } @@ -28,7 +28,7 @@ export class SubscriptionService implements ISubscriptionService { } private async getEmail(prompt: string, options?: IPrompterOptions): Promise { - let schema: IPromptSchema = { + const schema: IPromptSchema = { message: prompt, type: "input", name: "inputEmail", @@ -41,20 +41,20 @@ export class SubscriptionService implements ISubscriptionService { } }; - let result = await this.$prompter.get([schema]); + const result = await this.$prompter.get([schema]); return result.inputEmail; } private async sendEmail(email: string): Promise { if (email) { - let postData = queryString.stringify({ + const postData = queryString.stringify({ 'elqFormName': "dev_uins_cli", 'elqSiteID': '1325', 'emailAddress': email, 'elqCookieWrite': '0' }); - let options = { + const options = { url: 'https://s1325.t.eloqua.com/e/f2', method: 'POST', headers: { diff --git a/lib/services/test-execution-service.ts b/lib/services/test-execution-service.ts index eaee3ee9cd..b3d4221d26 100644 --- a/lib/services/test-execution-service.ts +++ b/lib/services/test-execution-service.ts @@ -37,24 +37,24 @@ class TestExecutionService implements ITestExecutionService { await new Promise((resolve, reject) => { process.on('message', async (launcherConfig: any) => { try { - let platformData = this.$platformsData.getPlatformData(platform.toLowerCase(), projectData); - let projectDir = projectData.projectDir; + const platformData = this.$platformsData.getPlatformData(platform.toLowerCase(), projectData); + const projectDir = projectData.projectDir; await this.$devicesService.initialize({ platform: platform, deviceId: this.$options.device, emulator: this.$options.emulator }); await this.$devicesService.detectCurrentlyAttachedDevices(); - let projectFilesPath = path.join(platformData.appDestinationDirectoryPath, constants.APP_FOLDER_NAME); + const projectFilesPath = path.join(platformData.appDestinationDirectoryPath, constants.APP_FOLDER_NAME); - let configOptions: IKarmaConfigOptions = JSON.parse(launcherConfig); + const configOptions: IKarmaConfigOptions = JSON.parse(launcherConfig); this.$options.debugBrk = configOptions.debugBrk; this.$options.debugTransport = configOptions.debugTransport; - let configJs = this.generateConfig(this.$options.port.toString(), configOptions); + const configJs = this.generateConfig(this.$options.port.toString(), configOptions); this.$fs.writeFile(path.join(projectDir, TestExecutionService.CONFIG_FILE_NAME), configJs); - let socketIoJsUrl = `http://localhost:${this.$options.port}/socket.io/socket.io.js`; - let socketIoJs = (await this.$httpClient.httpRequest(socketIoJsUrl)).body; + const socketIoJsUrl = `http://localhost:${this.$options.port}/socket.io/socket.io.js`; + const socketIoJs = (await this.$httpClient.httpRequest(socketIoJsUrl)).body; this.$fs.writeFile(path.join(projectDir, TestExecutionService.SOCKETIO_JS_FILE_NAME), socketIoJs); const appFilesUpdaterOptions: IAppFilesUpdaterOptions = { bundle: this.$options.bundle, release: this.$options.release }; @@ -121,7 +121,7 @@ class TestExecutionService implements ITestExecutionService { if (this.$options.debugBrk) { this.$logger.info('Starting debugger...'); - let debugService: IPlatformDebugService = this.$injector.resolve(`${platform}DebugService`); + const debugService: IPlatformDebugService = this.$injector.resolve(`${platform}DebugService`); const debugData = this.getDebugData(platform, projectData, deployOptions); await debugService.debugStart(debugData, this.$options); } @@ -147,28 +147,28 @@ class TestExecutionService implements ITestExecutionService { // We need the dependencies installed here, so we can start the Karma server. await this.$pluginsService.ensureAllDependenciesAreInstalled(projectData); - let projectDir = projectData.projectDir; + const projectDir = projectData.projectDir; await this.$devicesService.initialize({ platform: platform, deviceId: this.$options.device, emulator: this.$options.emulator }); - let karmaConfig = this.getKarmaConfiguration(platform, projectData), + const karmaConfig = this.getKarmaConfiguration(platform, projectData), karmaRunner = this.$childProcess.fork(path.join(__dirname, "karma-execution.js")), launchKarmaTests = async (karmaData: any) => { this.$logger.trace("## Unit-testing: Parent process received message", karmaData); let port: string; if (karmaData.url) { port = karmaData.url.port; - let socketIoJsUrl = `http://${karmaData.url.host}/socket.io/socket.io.js`; - let socketIoJs = (await this.$httpClient.httpRequest(socketIoJsUrl)).body; + const socketIoJsUrl = `http://${karmaData.url.host}/socket.io/socket.io.js`; + const socketIoJs = (await this.$httpClient.httpRequest(socketIoJsUrl)).body; this.$fs.writeFile(path.join(projectDir, TestExecutionService.SOCKETIO_JS_FILE_NAME), socketIoJs); } if (karmaData.launcherConfig) { - let configOptions: IKarmaConfigOptions = JSON.parse(karmaData.launcherConfig); - let configJs = this.generateConfig(port, configOptions); + const configOptions: IKarmaConfigOptions = JSON.parse(karmaData.launcherConfig); + const configJs = this.generateConfig(port, configOptions); this.$fs.writeFile(path.join(projectDir, TestExecutionService.CONFIG_FILE_NAME), configJs); } @@ -263,20 +263,20 @@ class TestExecutionService implements ITestExecutionService { allowedParameters: ICommandParameter[] = []; private detourEntryPoint(projectFilesPath: string): void { - let packageJsonPath = path.join(projectFilesPath, 'package.json'); - let packageJson = this.$fs.readJson(packageJsonPath); + const packageJsonPath = path.join(projectFilesPath, 'package.json'); + const packageJson = this.$fs.readJson(packageJsonPath); packageJson.main = TestExecutionService.MAIN_APP_NAME; this.$fs.writeJson(packageJsonPath, packageJson); } private generateConfig(port: string, options: any): string { - let nics = os.networkInterfaces(); - let ips = Object.keys(nics) + const nics = os.networkInterfaces(); + const ips = Object.keys(nics) .map(nicName => nics[nicName].filter((binding: any) => binding.family === 'IPv4')[0]) .filter(binding => binding) .map(binding => binding.address); - let config = { + const config = { port, ips, options, @@ -286,7 +286,7 @@ class TestExecutionService implements ITestExecutionService { } private getKarmaConfiguration(platform: string, projectData: IProjectData): any { - let karmaConfig: any = { + const karmaConfig: any = { browsers: [platform], configFile: path.join(projectData.projectDir, 'karma.conf.js'), _NS: { @@ -323,7 +323,7 @@ class TestExecutionService implements ITestExecutionService { private getDebugData(platform: string, projectData: IProjectData, deployOptions: IDeployPlatformOptions): IDebugData { const buildConfig: IBuildConfig = _.merge({ buildForDevice: this.$options.forDevice }, deployOptions); - let debugData = this.$debugDataService.createDebugData(projectData, this.$options); + const debugData = this.$debugDataService.createDebugData(projectData, this.$options); debugData.pathToAppPackage = this.$platformService.lastOutputPath(platform, buildConfig, projectData); return debugData; diff --git a/lib/services/user-settings-service.ts b/lib/services/user-settings-service.ts index f42bf2cc63..07201c799f 100644 --- a/lib/services/user-settings-service.ts +++ b/lib/services/user-settings-service.ts @@ -4,7 +4,7 @@ import * as userSettingsServiceBaseLib from "../common/services/user-settings-se class UserSettingsService extends userSettingsServiceBaseLib.UserSettingsServiceBase { constructor($fs: IFileSystem, $options: IOptions) { - let userSettingsFilePath = path.join($options.profileDir, "user-settings.json"); + const userSettingsFilePath = path.join($options.profileDir, "user-settings.json"); super(userSettingsFilePath, $fs); } } diff --git a/lib/services/versions-service.ts b/lib/services/versions-service.ts index 03e39414a4..908a3eb289 100644 --- a/lib/services/versions-service.ts +++ b/lib/services/versions-service.ts @@ -21,8 +21,8 @@ class VersionsService implements IVersionsService { } public async getNativescriptCliVersion(): Promise { - let currentCliVersion = this.$staticConfig.version; - let latestCliVersion = await this.$npmInstallationManager.getLatestVersion(constants.NATIVESCRIPT_KEY_NAME); + const currentCliVersion = this.$staticConfig.version; + const latestCliVersion = await this.$npmInstallationManager.getLatestVersion(constants.NATIVESCRIPT_KEY_NAME); return { componentName: constants.NATIVESCRIPT_KEY_NAME, @@ -32,21 +32,21 @@ class VersionsService implements IVersionsService { } public async getTnsCoreModulesVersion(): Promise { - let latestTnsCoreModulesVersion = await this.$npmInstallationManager.getLatestVersion(constants.TNS_CORE_MODULES_NAME); - let nativescriptCoreModulesInfo: IVersionInformation = { + const latestTnsCoreModulesVersion = await this.$npmInstallationManager.getLatestVersion(constants.TNS_CORE_MODULES_NAME); + const nativescriptCoreModulesInfo: IVersionInformation = { componentName: constants.TNS_CORE_MODULES_NAME, latestVersion: latestTnsCoreModulesVersion }; if (this.projectData) { - let nodeModulesPath = path.join(this.projectData.projectDir, constants.NODE_MODULES_FOLDER_NAME); - let tnsCoreModulesPath = path.join(nodeModulesPath, constants.TNS_CORE_MODULES_NAME); + const nodeModulesPath = path.join(this.projectData.projectDir, constants.NODE_MODULES_FOLDER_NAME); + const tnsCoreModulesPath = path.join(nodeModulesPath, constants.TNS_CORE_MODULES_NAME); if (!this.$fs.exists(nodeModulesPath) || !this.$fs.exists(tnsCoreModulesPath)) { await this.$pluginsService.ensureAllDependenciesAreInstalled(this.projectData); } - let currentTnsCoreModulesVersion = this.$fs.readJson(path.join(tnsCoreModulesPath, constants.PACKAGE_JSON_FILE_NAME)).version; + const currentTnsCoreModulesVersion = this.$fs.readJson(path.join(tnsCoreModulesPath, constants.PACKAGE_JSON_FILE_NAME)).version; nativescriptCoreModulesInfo.currentVersion = currentTnsCoreModulesVersion; } @@ -54,7 +54,7 @@ class VersionsService implements IVersionsService { } public async getRuntimesVersions(): Promise { - let runtimes: string[] = [ + const runtimes: string[] = [ constants.TNS_ANDROID_RUNTIME_NAME, constants.TNS_IOS_RUNTIME_NAME ]; @@ -65,17 +65,17 @@ class VersionsService implements IVersionsService { projectConfig = this.$fs.readJson(this.projectData.projectFilePath); } - let runtimesVersions: IVersionInformation[] = await Promise.all(runtimes.map(async (runtime: string) => { - let latestRuntimeVersion = await this.$npmInstallationManager.getLatestVersion(runtime); - let runtimeInformation: IVersionInformation = { + const runtimesVersions: IVersionInformation[] = await Promise.all(runtimes.map(async (runtime: string) => { + const latestRuntimeVersion = await this.$npmInstallationManager.getLatestVersion(runtime); + const runtimeInformation: IVersionInformation = { componentName: runtime, latestVersion: latestRuntimeVersion }; if (projectConfig) { - let projectRuntimeInformation = projectConfig.nativescript && projectConfig.nativescript[runtime]; + const projectRuntimeInformation = projectConfig.nativescript && projectConfig.nativescript[runtime]; if (projectRuntimeInformation) { - let runtimeVersionInProject = projectRuntimeInformation.version; + const runtimeVersionInProject = projectRuntimeInformation.version; runtimeInformation.currentVersion = runtimeVersionInProject; } } @@ -87,8 +87,8 @@ class VersionsService implements IVersionsService { } public async checkComponentsForUpdate(): Promise { - let allComponents: IVersionInformation[] = await this.getAllComponentsVersions(); - let componentsForUpdate: IVersionInformation[] = []; + const allComponents: IVersionInformation[] = await this.getAllComponentsVersions(); + const componentsForUpdate: IVersionInformation[] = []; _.forEach(allComponents, (component: IVersionInformation) => { if (component.currentVersion && this.hasUpdate(component)) { @@ -101,7 +101,7 @@ class VersionsService implements IVersionsService { private printVersionsInformation(versionsInformation: IVersionInformation[], allComponents: IVersionInformation[]): void { if (versionsInformation && versionsInformation.length) { - let table: any = this.createTableWithVersionsInformation(versionsInformation); + const table: any = this.createTableWithVersionsInformation(versionsInformation); this.$logger.warn("Updates available"); this.$logger.out(table.toString() + EOL); @@ -113,17 +113,17 @@ class VersionsService implements IVersionsService { public async getAllComponentsVersions(): Promise { let allComponents: IVersionInformation[] = []; - let nativescriptCliInformation: IVersionInformation = await this.getNativescriptCliVersion(); + const nativescriptCliInformation: IVersionInformation = await this.getNativescriptCliVersion(); if (nativescriptCliInformation) { allComponents.push(nativescriptCliInformation); } - let nativescriptCoreModulesInformation: IVersionInformation = await this.getTnsCoreModulesVersion(); + const nativescriptCoreModulesInformation: IVersionInformation = await this.getTnsCoreModulesVersion(); if (nativescriptCoreModulesInformation) { allComponents.push(nativescriptCoreModulesInformation); } - let runtimesVersions: IVersionInformation[] = await this.getRuntimesVersions(); + const runtimesVersions: IVersionInformation[] = await this.getRuntimesVersions(); allComponents = allComponents.concat(runtimesVersions); @@ -131,11 +131,11 @@ class VersionsService implements IVersionsService { } public createTableWithVersionsInformation(versionsInformation: IVersionInformation[]): any { - let headers = ["Component", "Current version", "Latest version", "Information"]; - let data: string[][] = []; + const headers = ["Component", "Current version", "Latest version", "Information"]; + const data: string[][] = []; _.forEach(versionsInformation, (componentInformation: IVersionInformation) => { - let row: string[] = [ + const row: string[] = [ componentInformation.componentName, componentInformation.currentVersion, componentInformation.latestVersion @@ -155,7 +155,7 @@ class VersionsService implements IVersionsService { private getProjectData(): IProjectData { try { - let projectData: IProjectData = this.$injector.resolve("projectData"); + const projectData: IProjectData = this.$injector.resolve("projectData"); projectData.initializeProjectData(); return projectData; } catch (error) { diff --git a/lib/services/xcconfig-service.ts b/lib/services/xcconfig-service.ts index d6fcb658ea..f595d5332b 100644 --- a/lib/services/xcconfig-service.ts +++ b/lib/services/xcconfig-service.ts @@ -9,14 +9,14 @@ export class XCConfigService { */ public readPropertyValue(xcconfigFilePath: string, propertyName: string): string { if (this.$fs.exists(xcconfigFilePath)) { - let text = this.$fs.readText(xcconfigFilePath); + const text = this.$fs.readText(xcconfigFilePath); let property: string; let isPropertyParsed: boolean = false; text.split(/\r?\n/).forEach((line) => { line = line.replace(/\/(\/)[^\n]*$/, ""); if (line.indexOf(propertyName) >= 0) { - let parts = line.split("="); + const parts = line.split("="); if (parts.length > 1 && parts[1]) { property = parts[1].trim(); isPropertyParsed = true; diff --git a/lib/services/xcproj-service.ts b/lib/services/xcproj-service.ts index 0746d9fb65..a3894d8dbe 100644 --- a/lib/services/xcproj-service.ts +++ b/lib/services/xcproj-service.ts @@ -13,9 +13,9 @@ class XcprojService implements IXcprojService { } public async verifyXcproj(shouldFail: boolean): Promise { - let xcprojInfo = await this.getXcprojInfo(); + const xcprojInfo = await this.getXcprojInfo(); if (xcprojInfo.shouldUseXcproj && !xcprojInfo.xcprojAvailable) { - let errorMessage = `You are using CocoaPods version ${xcprojInfo.cocoapodVer} which does not support Xcode ${xcprojInfo.xcodeVersion.major}.${xcprojInfo.xcodeVersion.minor} yet.${EOL}${EOL}You can update your cocoapods by running $sudo gem install cocoapods from a terminal.${EOL}${EOL}In order for the NativeScript CLI to be able to work correctly with this setup you need to install xcproj command line tool and add it to your PATH. Xcproj can be installed with homebrew by running $ brew install xcproj from the terminal`; + const errorMessage = `You are using CocoaPods version ${xcprojInfo.cocoapodVer} which does not support Xcode ${xcprojInfo.xcodeVersion.major}.${xcprojInfo.xcodeVersion.minor} yet.${EOL}${EOL}You can update your cocoapods by running $sudo gem install cocoapods from a terminal.${EOL}${EOL}In order for the NativeScript CLI to be able to work correctly with this setup you need to install xcproj command line tool and add it to your PATH. Xcproj can be installed with homebrew by running $ brew install xcproj from the terminal`; if (shouldFail) { this.$errors.failWithoutHelp(errorMessage); } else { @@ -30,8 +30,8 @@ class XcprojService implements IXcprojService { public async getXcprojInfo(): Promise { if (!this.xcprojInfoCache) { - let cocoapodVer = await this.$sysInfo.getCocoapodVersion(), - xcodeVersion = await this.$xcodeSelectService.getXcodeVersion(); + let cocoapodVer = await this.$sysInfo.getCocoapodVersion(); + const xcodeVersion = await this.$xcodeSelectService.getXcodeVersion(); if (cocoapodVer && !semver.valid(cocoapodVer)) { // Cocoapods betas have names like 1.0.0.beta.8 @@ -44,8 +44,8 @@ class XcprojService implements IXcprojService { // CocoaPods with version lower than 1.0.0 don't support Xcode 7.3 yet // https://github.com/CocoaPods/CocoaPods/issues/2530#issuecomment-210470123 // as a result of this all .pbxprojects touched by CocoaPods get converted to XML plist format - let shouldUseXcproj = cocoapodVer && !!(semver.lt(cocoapodVer, "1.0.0") && ~helpers.versionCompare(xcodeVersion, "7.3.0")), - xcprojAvailable: boolean; + const shouldUseXcproj = cocoapodVer && !!(semver.lt(cocoapodVer, "1.0.0") && ~helpers.versionCompare(xcodeVersion, "7.3.0")); + let xcprojAvailable: boolean; if (shouldUseXcproj) { // if that's the case we can use xcproj gem to convert them back to ASCII plist format diff --git a/lib/sys-info.ts b/lib/sys-info.ts index 6f7fdd904a..d2ac752a47 100644 --- a/lib/sys-info.ts +++ b/lib/sys-info.ts @@ -13,7 +13,7 @@ export class SysInfo extends SysInfoBase { } public async getSysInfo(pathToPackageJson: string, androidToolsInfo?: { pathToAdb: string }): Promise { - let defaultAndroidToolsInfo = { + const defaultAndroidToolsInfo = { pathToAdb: await this.$androidToolsInfo.getPathToAdbFromAndroidHome() }; diff --git a/lib/tools/node-modules/node-modules-dependencies-builder.ts b/lib/tools/node-modules/node-modules-dependencies-builder.ts index 396eb7dc34..f2482819b5 100644 --- a/lib/tools/node-modules/node-modules-dependencies-builder.ts +++ b/lib/tools/node-modules/node-modules-dependencies-builder.ts @@ -16,9 +16,9 @@ export class NodeModulesDependenciesBuilder implements INodeModulesDependenciesB const packageJsonContent = this.$fs.readJson(projectPackageJsonPath); const dependencies = packageJsonContent && packageJsonContent.dependencies; - let resolvedDependencies: IDependencyData[] = []; + const resolvedDependencies: IDependencyData[] = []; - let queue: IDependencyDescription[] = _.keys(dependencies) + const queue: IDependencyDescription[] = _.keys(dependencies) .map(dependencyName => ({ parentDir: projectPath, name: dependencyName, @@ -83,7 +83,7 @@ export class NodeModulesDependenciesBuilder implements INodeModulesDependenciesB const packageJsonExists = this.$fs.getLsStats(packageJsonPath).isFile(); if (packageJsonExists) { - let packageJsonContents = this.$fs.readJson(packageJsonPath); + const packageJsonContents = this.$fs.readJson(packageJsonPath); if (!!packageJsonContents.nativescript) { // add `nativescript` property, necessary for resolving plugins diff --git a/lib/tools/node-modules/node-modules-dest-copy.ts b/lib/tools/node-modules/node-modules-dest-copy.ts index f3f534c373..37d6a03903 100644 --- a/lib/tools/node-modules/node-modules-dest-copy.ts +++ b/lib/tools/node-modules/node-modules-dest-copy.ts @@ -16,17 +16,17 @@ export class TnsModulesCopy { } public copyModules(dependencies: IDependencyData[], platform: string): void { - for (let entry in dependencies) { - let dependency = dependencies[entry]; + for (const entry in dependencies) { + const dependency = dependencies[entry]; this.copyDependencyDir(dependency); if (dependency.name === constants.TNS_CORE_MODULES_NAME) { - let tnsCoreModulesResourcePath = path.join(this.outputRoot, constants.TNS_CORE_MODULES_NAME); + const tnsCoreModulesResourcePath = path.join(this.outputRoot, constants.TNS_CORE_MODULES_NAME); // Remove .ts files - let allFiles = this.$fs.enumerateFilesInDirectorySync(tnsCoreModulesResourcePath); - let matchPattern = this.$options.release ? "**/*.ts" : "**/*.d.ts"; + const allFiles = this.$fs.enumerateFilesInDirectorySync(tnsCoreModulesResourcePath); + const matchPattern = this.$options.release ? "**/*.ts" : "**/*.d.ts"; allFiles.filter(file => minimatch(file, matchPattern, { nocase: true })).map(file => this.$fs.deleteFile(file)); shelljs.rm("-rf", path.join(tnsCoreModulesResourcePath, constants.NODE_MODULES_FOLDER_NAME)); @@ -98,7 +98,7 @@ export class NpmPluginPrepare { } private writePreparedDependencyInfo(dependencies: IDependencyData[], platform: string, projectData: IProjectData): void { - let prepareData: IDictionary = {}; + const prepareData: IDictionary = {}; _.each(dependencies, d => { prepareData[d.name] = true; }); @@ -145,11 +145,11 @@ export class NpmPluginPrepare { } await this.beforePrepare(dependencies, platform, projectData); - for (let dependencyKey in dependencies) { + for (const dependencyKey in dependencies) { const dependency = dependencies[dependencyKey]; - let isPlugin = !!dependency.nativescript; + const isPlugin = !!dependency.nativescript; if (isPlugin) { - let pluginData = this.$pluginsService.convertToPluginData(dependency, projectData.projectDir); + const pluginData = this.$pluginsService.convertToPluginData(dependency, projectData.projectDir); await this.$pluginsService.preparePluginNativeCode(pluginData, platform, projectData); } } @@ -162,14 +162,14 @@ export class NpmPluginPrepare { return; } - for (let dependencyKey in dependencies) { + for (const dependencyKey in dependencies) { const dependency = dependencies[dependencyKey]; - let isPlugin = !!dependency.nativescript; + const isPlugin = !!dependency.nativescript; if (isPlugin) { platform = platform.toLowerCase(); - let pluginData = this.$pluginsService.convertToPluginData(dependency, projectData.projectDir); - let platformData = this.$platformsData.getPlatformData(platform, projectData); - let appFolderExists = this.$fs.exists(path.join(platformData.appDestinationDirectoryPath, constants.APP_FOLDER_NAME)); + const pluginData = this.$pluginsService.convertToPluginData(dependency, projectData.projectDir); + const platformData = this.$platformsData.getPlatformData(platform, projectData); + const appFolderExists = this.$fs.exists(path.join(platformData.appDestinationDirectoryPath, constants.APP_FOLDER_NAME)); if (appFolderExists) { this.$pluginsService.preparePluginScripts(pluginData, platform, projectData, projectFilesConfig); // Show message diff --git a/lib/xml-validator.ts b/lib/xml-validator.ts index 25d31dcf89..6d33e1ca28 100644 --- a/lib/xml-validator.ts +++ b/lib/xml-validator.ts @@ -10,8 +10,8 @@ export class XmlValidator implements IXmlValidator { sourceFiles .filter(file => _.endsWith(file, constants.XML_FILE_EXTENSION)) .forEach(file => { - let errorOutput = this.getXmlFileErrors(file); - let hasErrors = !!errorOutput; + const errorOutput = this.getXmlFileErrors(file); + const hasErrors = !!errorOutput; xmlHasErrors = xmlHasErrors || hasErrors; if (hasErrors) { this.$logger.info(`${file} has syntax errors.`.red.bold); @@ -23,8 +23,8 @@ export class XmlValidator implements IXmlValidator { public getXmlFileErrors(sourceFile: string): string { let errorOutput = ""; - let fileContents = this.$fs.readText(sourceFile); - let domErrorHandler = (level: any, msg: string) => { + const fileContents = this.$fs.readText(sourceFile); + const domErrorHandler = (level: any, msg: string) => { errorOutput += level + EOL + msg + EOL; }; this.getDomParser(domErrorHandler).parseFromString(fileContents, "text/xml"); @@ -33,8 +33,8 @@ export class XmlValidator implements IXmlValidator { } private getDomParser(errorHandler: (level: any, msg: string) => void): any { - let DomParser = require("xmldom").DOMParser; - let parser = new DomParser({ + const DomParser = require("xmldom").DOMParser; + const parser = new DomParser({ locator: {}, errorHandler: errorHandler }); diff --git a/package.json b/package.json index 254c0143d9..7b8addf80b 100644 --- a/package.json +++ b/package.json @@ -16,7 +16,8 @@ "mocha": "node test-scripts/mocha.js", "tsc": "tsc", "tslint": "tslint -p tsconfig.json --type-check", - "test-watch": "node ./dev/tsc-to-mocha-watch.js" + "test-watch": "node ./dev/tsc-to-mocha-watch.js", + "tslint-fix": "tslint -p tsconfig.json --type-check --fix" }, "repository": { "type": "git", diff --git a/test/android-project-properties-manager.ts b/test/android-project-properties-manager.ts index 8b3a316e76..a92ab97f40 100644 --- a/test/android-project-properties-manager.ts +++ b/test/android-project-properties-manager.ts @@ -14,7 +14,7 @@ temp.track(); import { assert } from "chai"; function createTestInjector(): IInjector { - let testInjector = new yok.Yok(); + const testInjector = new yok.Yok(); testInjector.register("propertiesParser", ProjectPropertiesParserLib.PropertiesParser); testInjector.register("fs", FsLib.FileSystem); testInjector.register("hostInfo", HostInfoLib.HostInfo); @@ -29,113 +29,113 @@ function createTestInjector(): IInjector { describe("Android project properties parser tests", () => { it("adds project reference", async () => { - let testInjector = createTestInjector(); - let fs = testInjector.resolve("fs"); + const testInjector = createTestInjector(); + const fs = testInjector.resolve("fs"); - let projectPropertiesFileContent = 'target=android-21'; - let tempFolder = temp.mkdirSync("AndroidProjectPropertiesManager"); + const projectPropertiesFileContent = 'target=android-21'; + const tempFolder = temp.mkdirSync("AndroidProjectPropertiesManager"); fs.writeFile(path.join(tempFolder, "project.properties"), projectPropertiesFileContent); - let projectPropertiesManager: IAndroidProjectPropertiesManager = testInjector.resolve( + const projectPropertiesManager: IAndroidProjectPropertiesManager = testInjector.resolve( ProjectPropertiesManagerLib.AndroidProjectPropertiesManager, { directoryPath: tempFolder }); await projectPropertiesManager.addProjectReference("testValue"); - let expectedContent = 'target=android-21' + '\n' + + const expectedContent = 'target=android-21' + '\n' + 'android.library.reference.1=testValue'; - let actualContent = fs.readText(path.join(tempFolder, "project.properties")); + const actualContent = fs.readText(path.join(tempFolder, "project.properties")); assert.equal(expectedContent, actualContent); assert.equal(1, _.keys(await projectPropertiesManager.getProjectReferences()).length); }); it("adds project reference if another referencence already exists in project.properties file", async () => { - let testInjector = createTestInjector(); - let fs = testInjector.resolve("fs"); + const testInjector = createTestInjector(); + const fs = testInjector.resolve("fs"); - let projectPropertiesFileContent = 'target=android-21' + '\n' + + const projectPropertiesFileContent = 'target=android-21' + '\n' + 'android.library.reference.1=someValue'; - let tempFolder = temp.mkdirSync("AndroidProjectPropertiesManager"); + const tempFolder = temp.mkdirSync("AndroidProjectPropertiesManager"); fs.writeFile(path.join(tempFolder, "project.properties"), projectPropertiesFileContent); - let projectPropertiesManager = testInjector.resolve( + const projectPropertiesManager = testInjector.resolve( ProjectPropertiesManagerLib.AndroidProjectPropertiesManager, { directoryPath: tempFolder }); await projectPropertiesManager.addProjectReference("testValue"); - let expectedContent = ['target=android-21', + const expectedContent = ['target=android-21', 'android.library.reference.1=someValue', 'android.library.reference.2=testValue'].join('\n'); - let actualContent = fs.readText(path.join(tempFolder, "project.properties")); + const actualContent = fs.readText(path.join(tempFolder, "project.properties")); assert.equal(expectedContent, actualContent); assert.equal(2, _.keys(await projectPropertiesManager.getProjectReferences()).length); }); it("adds project reference if more than one references exist in project.properties file", async () => { - let testInjector = createTestInjector(); - let fs = testInjector.resolve("fs"); + const testInjector = createTestInjector(); + const fs = testInjector.resolve("fs"); - let projectPropertiesFileContent = ['target=android-21', + const projectPropertiesFileContent = ['target=android-21', 'android.library.reference.1=value1', 'android.library.reference.2=value2', 'android.library.reference.3=value3', 'android.library.reference.4=value4', 'android.library.reference.5=value5'].join('\n'); - let tempFolder = temp.mkdirSync("AndroidProjectPropertiesManager"); + const tempFolder = temp.mkdirSync("AndroidProjectPropertiesManager"); fs.writeFile(path.join(tempFolder, "project.properties"), projectPropertiesFileContent); - let projectPropertiesManager: IAndroidProjectPropertiesManager = testInjector.resolve( + const projectPropertiesManager: IAndroidProjectPropertiesManager = testInjector.resolve( ProjectPropertiesManagerLib.AndroidProjectPropertiesManager, { directoryPath: tempFolder }); await projectPropertiesManager.addProjectReference("testValue"); - let expectedContent = projectPropertiesFileContent + '\n' + + const expectedContent = projectPropertiesFileContent + '\n' + 'android.library.reference.6=testValue'; - let actualContent = fs.readText(path.join(tempFolder, "project.properties")); + const actualContent = fs.readText(path.join(tempFolder, "project.properties")); assert.equal(expectedContent, actualContent); assert.equal(6, _.keys(await projectPropertiesManager.getProjectReferences()).length); }); it("removes project reference if only one reference exists", async () => { - let testInjector = createTestInjector(); - let fs = testInjector.resolve("fs"); + const testInjector = createTestInjector(); + const fs = testInjector.resolve("fs"); - let projectPropertiesFileContent = 'android.library.reference.1=value1' + '\n' + + const projectPropertiesFileContent = 'android.library.reference.1=value1' + '\n' + 'target=android-21'; - let tempFolder = temp.mkdirSync("AndroidProjectPropertiesManager"); + const tempFolder = temp.mkdirSync("AndroidProjectPropertiesManager"); fs.writeFile(path.join(tempFolder, "project.properties"), projectPropertiesFileContent); - let projectPropertiesManager: IAndroidProjectPropertiesManager = testInjector.resolve( + const projectPropertiesManager: IAndroidProjectPropertiesManager = testInjector.resolve( ProjectPropertiesManagerLib.AndroidProjectPropertiesManager, { directoryPath: tempFolder }); await projectPropertiesManager.removeProjectReference("value1"); - let expectedContent = 'target=android-21'; - let actualContent = fs.readText(path.join(tempFolder, "project.properties")); + const expectedContent = 'target=android-21'; + const actualContent = fs.readText(path.join(tempFolder, "project.properties")); assert.equal(expectedContent, actualContent); assert.equal(0, _.keys(await projectPropertiesManager.getProjectReferences()).length); }); it("removes project reference when another references exist before and after the specified reference", async () => { - let testInjector = createTestInjector(); - let fs = testInjector.resolve("fs"); + const testInjector = createTestInjector(); + const fs = testInjector.resolve("fs"); - let projectPropertiesFileContent = ['target=android-17', + const projectPropertiesFileContent = ['target=android-17', 'android.library.reference.1=value1', 'android.library.reference.2=value2', 'android.library.reference.3=value3', 'android.library.reference.4=value4', 'android.library.reference.5=value5'].join('\n'); - let tempFolder = temp.mkdirSync("AndroidProjectPropertiesManager"); + const tempFolder = temp.mkdirSync("AndroidProjectPropertiesManager"); fs.writeFile(path.join(tempFolder, "project.properties"), projectPropertiesFileContent); - let projectPropertiesManager: IAndroidProjectPropertiesManager = testInjector.resolve( + const projectPropertiesManager: IAndroidProjectPropertiesManager = testInjector.resolve( ProjectPropertiesManagerLib.AndroidProjectPropertiesManager, { directoryPath: tempFolder }); await projectPropertiesManager.removeProjectReference("value3"); - let expectedContent = ['target=android-17', + const expectedContent = ['target=android-17', 'android.library.reference.1=value1', 'android.library.reference.2=value2', 'android.library.reference.3=value4', 'android.library.reference.4=value5'].join('\n') + '\n'; - let actualContent = fs.readText(path.join(tempFolder, "project.properties")); + const actualContent = fs.readText(path.join(tempFolder, "project.properties")); assert.equal(expectedContent, actualContent); assert.equal(4, _.keys(await projectPropertiesManager.getProjectReferences()).length); diff --git a/test/cocoapods-service.ts b/test/cocoapods-service.ts index f8e11c5958..f63770aeba 100644 --- a/test/cocoapods-service.ts +++ b/test/cocoapods-service.ts @@ -10,7 +10,7 @@ interface IMergePodfileHooksTestCase { } function createTestInjector(): IInjector { - let testInjector: IInjector = new yok.Yok(); + const testInjector: IInjector = new yok.Yok(); testInjector.register("fs", {}); testInjector.register("cocoapodsService", CocoaPodsService); @@ -31,8 +31,8 @@ describe("Cocoapods service", () => { let cocoapodsService: ICocoaPodsService; let newPodfileContent: string; - let mockFileSystem = (injector: IInjector, podfileContent: string): void => { - let fs: IFileSystem = injector.resolve("fs"); + const mockFileSystem = (injector: IInjector, podfileContent: string): void => { + const fs: IFileSystem = injector.resolve("fs"); fs.exists = () => true; fs.readText = () => podfileContent; @@ -41,7 +41,7 @@ describe("Cocoapods service", () => { }; }; - let testCaces: IMergePodfileHooksTestCase[] = [ + const testCaces: IMergePodfileHooksTestCase[] = [ { input: ` target 'MyApp' do diff --git a/test/debug.ts b/test/debug.ts index f004e806ff..efd107b116 100644 --- a/test/debug.ts +++ b/test/debug.ts @@ -15,7 +15,7 @@ const helpers = require("../lib/common/helpers"); const originalIsInteracive = helpers.isInteractive; function createTestInjector(): IInjector { - let testInjector: IInjector = new yok.Yok(); + const testInjector: IInjector = new yok.Yok(); testInjector.register("debug|android", DebugAndroidCommand); testInjector.register("config", Configuration); @@ -342,10 +342,10 @@ describe("debug command tests", () => { }); it("Ensures that beforePrepareAllPlugins will call gradle with clean option when *NOT* livesyncing", async () => { - let childProcess: stubs.ChildProcessStub = testInjector.resolve("childProcess"); - let androidProjectService: IPlatformProjectService = testInjector.resolve("androidProjectService"); - let projectData: IProjectData = testInjector.resolve("projectData"); - let spawnFromEventCount = childProcess.spawnFromEventCount; + const childProcess: stubs.ChildProcessStub = testInjector.resolve("childProcess"); + const androidProjectService: IPlatformProjectService = testInjector.resolve("androidProjectService"); + const projectData: IProjectData = testInjector.resolve("projectData"); + const spawnFromEventCount = childProcess.spawnFromEventCount; await androidProjectService.beforePrepareAllPlugins(projectData); assert.isTrue(childProcess.lastCommand.indexOf("gradle") !== -1); assert.isTrue(childProcess.lastCommandArgs[0] === "clean"); diff --git a/test/ios-entitlements-service.ts b/test/ios-entitlements-service.ts index 0987039ad6..2edfb58ba1 100644 --- a/test/ios-entitlements-service.ts +++ b/test/ios-entitlements-service.ts @@ -35,12 +35,12 @@ describe("IOSEntitlements Service Tests", () => { return testInjector; }; - let injector: IInjector, - platformsData: any, - projectData: IProjectData, - fs: IFileSystem, - iOSEntitlementsService: IOSEntitlementsService, - destinationFilePath: string; + let injector: IInjector; + let platformsData: any; + let projectData: IProjectData; + let fs: IFileSystem; + let iOSEntitlementsService: IOSEntitlementsService; + let destinationFilePath: string; beforeEach(() => { injector = createTestInjector(); @@ -61,7 +61,7 @@ describe("IOSEntitlements Service Tests", () => { describe("Ensure paths constructed are correct", () => { it("Ensure destination entitlements relative path is calculated correctly.", () => { const expected = path.join("testApp", "testApp.entitlements"); - let actual = iOSEntitlementsService.getPlatformsEntitlementsRelativePath(projectData); + const actual = iOSEntitlementsService.getPlatformsEntitlementsRelativePath(projectData); assert.equal(actual, expected); }); @@ -114,7 +114,7 @@ describe("IOSEntitlements Service Tests", () => { `; function assertContent(actual: string, expected: string) { - let strip = (x: string) => { + const strip = (x: string) => { return x.replace(EOL, '').trim(); }; assert.equal(strip(actual), strip(expected)); @@ -125,62 +125,62 @@ describe("IOSEntitlements Service Tests", () => { await iOSEntitlementsService.merge(projectData); // assert - let actual = fs.readText(destinationFilePath); + const actual = fs.readText(destinationFilePath); assertContent(actual, defaultPlistContent); }); it("Merge uses the entitlements from App_Resources folder", async () => { - let appResourcesEntitlement = (iOSEntitlementsService).getDefaultAppEntitlementsPath(projectData); + const appResourcesEntitlement = (iOSEntitlementsService).getDefaultAppEntitlementsPath(projectData); fs.writeFile(appResourcesEntitlement, defaultAppResourcesEntitlementsContent); // act await iOSEntitlementsService.merge(projectData); // assert - let actual = fs.readText(destinationFilePath); + const actual = fs.readText(destinationFilePath); assertContent(actual, defaultAppResourcesEntitlementsContent); }); it("Merge uses the entitlements file from a Plugin", async () => { - let pluginsService = injector.resolve("pluginsService"); - let testPluginFolderPath = temp.mkdirSync("testPlugin"); + const pluginsService = injector.resolve("pluginsService"); + const testPluginFolderPath = temp.mkdirSync("testPlugin"); pluginsService.getAllInstalledPlugins = async () => [{ pluginPlatformsFolderPath: (platform: string) => { return testPluginFolderPath; } }]; - let pluginAppEntitlementsPath = path.join(testPluginFolderPath, IOSEntitlementsService.DefaultEntitlementsName); + const pluginAppEntitlementsPath = path.join(testPluginFolderPath, IOSEntitlementsService.DefaultEntitlementsName); fs.writeFile(pluginAppEntitlementsPath, defaultPluginEntitlementsContent); // act await iOSEntitlementsService.merge(projectData); // assert - let actual = fs.readText(destinationFilePath); + const actual = fs.readText(destinationFilePath); assertContent(actual, defaultPluginEntitlementsContent); }); it("Merge uses App_Resources and Plugins and merges all keys", async () => { // setup app resoruces - let appResourcesEntitlement = (iOSEntitlementsService).getDefaultAppEntitlementsPath(projectData); + const appResourcesEntitlement = (iOSEntitlementsService).getDefaultAppEntitlementsPath(projectData); fs.writeFile(appResourcesEntitlement, namedAppResourcesEntitlementsContent); // setup plugin entitlements - let pluginsService = injector.resolve("pluginsService"); - let testPluginFolderPath = temp.mkdirSync("testPlugin"); + const pluginsService = injector.resolve("pluginsService"); + const testPluginFolderPath = temp.mkdirSync("testPlugin"); pluginsService.getAllInstalledPlugins = async () => [{ pluginPlatformsFolderPath: (platform: string) => { return testPluginFolderPath; } }]; - let pluginAppEntitlementsPath = path.join(testPluginFolderPath, IOSEntitlementsService.DefaultEntitlementsName); + const pluginAppEntitlementsPath = path.join(testPluginFolderPath, IOSEntitlementsService.DefaultEntitlementsName); fs.writeFile(pluginAppEntitlementsPath, defaultPluginEntitlementsContent); // act await iOSEntitlementsService.merge(projectData); // assert - let actual = fs.readText(destinationFilePath); + const actual = fs.readText(destinationFilePath); assertContent(actual, mergedEntitlementsContent); }); }); diff --git a/test/ios-project-service.ts b/test/ios-project-service.ts index aa9f32a494..30b7e58629 100644 --- a/test/ios-project-service.ts +++ b/test/ios-project-service.ts @@ -48,7 +48,7 @@ class IOSSimulatorDiscoveryMock extends DeviceDiscovery { } function createTestInjector(projectPath: string, projectName: string): IInjector { - let testInjector = new yok.Yok(); + const testInjector = new yok.Yok(); testInjector.register("childProcess", ChildProcessLib.ChildProcess); testInjector.register("config", ConfigLib.Configuration); testInjector.register("errors", ErrorsLib.Errors); @@ -118,7 +118,7 @@ function createTestInjector(projectPath: string, projectName: string): IInjector } function createPackageJson(testInjector: IInjector, projectPath: string, projectName: string) { - let packageJsonData = { + const packageJsonData = { "name": projectName, "version": "0.1.0", "nativescript": { @@ -134,14 +134,14 @@ function createPackageJson(testInjector: IInjector, projectPath: string, project } function expectOption(args: string[], option: string, value: string, message?: string): void { - let index = args.indexOf(option); + const index = args.indexOf(option); assert.ok(index >= 0, "Expected " + option + " to be set."); assert.ok(args.length > index + 1, "Expected " + option + " to have value"); assert.equal(args[index + 1], value, message); } function readOption(args: string[], option: string): string { - let index = args.indexOf(option); + const index = args.indexOf(option); assert.ok(index >= 0, "Expected " + option + " to be set."); assert.ok(args.length > index + 1, "Expected " + option + " to have value"); return args[index + 1]; @@ -150,16 +150,16 @@ function readOption(args: string[], option: string): string { describe("iOSProjectService", () => { describe("archive", () => { async function setupArchive(options?: { archivePath?: string }): Promise<{ run: () => Promise, assert: () => void }> { - let hasCustomArchivePath = options && options.archivePath; + const hasCustomArchivePath = options && options.archivePath; - let projectName = "projectDirectory"; - let projectPath = temp.mkdirSync(projectName); + const projectName = "projectDirectory"; + const projectPath = temp.mkdirSync(projectName); - let testInjector = createTestInjector(projectPath, projectName); - let iOSProjectService = testInjector.resolve("iOSProjectService"); - let projectData: IProjectData = testInjector.resolve("projectData"); + const testInjector = createTestInjector(projectPath, projectName); + const iOSProjectService = testInjector.resolve("iOSProjectService"); + const projectData: IProjectData = testInjector.resolve("projectData"); - let childProcess = testInjector.resolve("childProcess"); + const childProcess = testInjector.resolve("childProcess"); let xcodebuildExeced = false; let archivePath: string; @@ -204,12 +204,12 @@ describe("iOSProjectService", () => { console.log("Skipping iOS archive tests. They can work only on macOS"); } else { it("by default exports xcodearchive to platforms/ios/build/archive/.xcarchive", async () => { - let setup = await setupArchive(); + const setup = await setupArchive(); await setup.run(); setup.assert(); }); it("can pass archivePath to xcodebuild -archivePath", async () => { - let setup = await setupArchive({ archivePath: "myarchive.xcarchive" }); + const setup = await setupArchive({ archivePath: "myarchive.xcarchive" }); await setup.run(); setup.assert(); }); @@ -217,7 +217,7 @@ describe("iOSProjectService", () => { }); describe("exportArchive", () => { - let noTeamPlist = ` + const noTeamPlist = ` @@ -230,7 +230,7 @@ describe("iOSProjectService", () => { `; - let myTeamPlist = ` + const myTeamPlist = ` @@ -246,17 +246,17 @@ describe("iOSProjectService", () => { `; async function testExportArchive(options: { teamID?: string }, expectedPlistContent: string): Promise { - let projectName = "projectDirectory"; - let projectPath = temp.mkdirSync(projectName); + const projectName = "projectDirectory"; + const projectPath = temp.mkdirSync(projectName); - let testInjector = createTestInjector(projectPath, projectName); - let iOSProjectService = testInjector.resolve("iOSProjectService"); - let projectData: IProjectData = testInjector.resolve("projectData"); + const testInjector = createTestInjector(projectPath, projectName); + const iOSProjectService = testInjector.resolve("iOSProjectService"); + const projectData: IProjectData = testInjector.resolve("projectData"); - let archivePath = path.join(projectPath, "platforms", "ios", "build", "archive", projectName + ".xcarchive"); + const archivePath = path.join(projectPath, "platforms", "ios", "build", "archive", projectName + ".xcarchive"); - let childProcess = testInjector.resolve("childProcess"); - let fs = testInjector.resolve("fs"); + const childProcess = testInjector.resolve("childProcess"); + const fs = testInjector.resolve("fs"); let xcodebuildExeced = false; @@ -268,19 +268,19 @@ describe("iOSProjectService", () => { expectOption(args, "-archivePath", archivePath, "Expected the -archivePath to be passed to xcodebuild."); expectOption(args, "-exportPath", path.join(projectPath, "platforms", "ios", "build", "archive"), "Expected the -archivePath to be passed to xcodebuild."); - let plist = readOption(args, "-exportOptionsPlist"); + const plist = readOption(args, "-exportOptionsPlist"); assert.ok(plist); - let plistContent = fs.readText(plist); + const plistContent = fs.readText(plist); // There may be better way to equal property lists assert.equal(plistContent, expectedPlistContent, "Mismatch in exportOptionsPlist content"); return Promise.resolve(); }; - let resultIpa = await iOSProjectService.exportArchive(projectData, { archivePath, teamID: options.teamID }); - let expectedIpa = path.join(projectPath, "platforms", "ios", "build", "archive", projectName + ".ipa"); + const resultIpa = await iOSProjectService.exportArchive(projectData, { archivePath, teamID: options.teamID }); + const expectedIpa = path.join(projectPath, "platforms", "ios", "build", "archive", projectName + ".ipa"); assert.equal(resultIpa, expectedIpa, "Expected IPA at the specified location"); @@ -306,13 +306,13 @@ describe("Cocoapods support", () => { console.log("Skipping Cocoapods tests. They cannot work on windows"); } else { it("adds plugin with Podfile", async () => { - let projectName = "projectDirectory"; - let projectPath = temp.mkdirSync(projectName); + const projectName = "projectDirectory"; + const projectPath = temp.mkdirSync(projectName); - let testInjector = createTestInjector(projectPath, projectName); - let fs: IFileSystem = testInjector.resolve("fs"); + const testInjector = createTestInjector(projectPath, projectName); + const fs: IFileSystem = testInjector.resolve("fs"); - let packageJsonData = { + const packageJsonData = { "name": "myProject", "version": "0.1.0", "nativescript": { @@ -324,10 +324,10 @@ describe("Cocoapods support", () => { }; fs.writeJson(path.join(projectPath, "package.json"), packageJsonData); - let platformsFolderPath = path.join(projectPath, "platforms", "ios"); + const platformsFolderPath = path.join(projectPath, "platforms", "ios"); fs.createDirectory(platformsFolderPath); - let iOSProjectService = testInjector.resolve("iOSProjectService"); + const iOSProjectService = testInjector.resolve("iOSProjectService"); iOSProjectService.prepareFrameworks = (pluginPlatformsFolderPath: string, pluginData: IPluginData): Promise => { return Promise.resolve(); }; @@ -342,26 +342,26 @@ describe("Cocoapods support", () => { }; iOSProjectService.savePbxProj = (): Promise => Promise.resolve(); - let pluginPath = temp.mkdirSync("pluginDirectory"); - let pluginPlatformsFolderPath = path.join(pluginPath, "platforms", "ios"); - let pluginPodfilePath = path.join(pluginPlatformsFolderPath, "Podfile"); - let pluginPodfileContent = ["source 'https://github.com/CocoaPods/Specs.git'", "platform :ios, '8.1'", "pod 'GoogleMaps'"].join("\n"); + const pluginPath = temp.mkdirSync("pluginDirectory"); + const pluginPlatformsFolderPath = path.join(pluginPath, "platforms", "ios"); + const pluginPodfilePath = path.join(pluginPlatformsFolderPath, "Podfile"); + const pluginPodfileContent = ["source 'https://github.com/CocoaPods/Specs.git'", "platform :ios, '8.1'", "pod 'GoogleMaps'"].join("\n"); fs.writeFile(pluginPodfilePath, pluginPodfileContent); - let pluginData = { + const pluginData = { pluginPlatformsFolderPath(platform: string): string { return pluginPlatformsFolderPath; } }; - let projectData: IProjectData = testInjector.resolve("projectData"); + const projectData: IProjectData = testInjector.resolve("projectData"); await iOSProjectService.preparePluginNativeCode(pluginData, projectData); - let projectPodfilePath = path.join(platformsFolderPath, "Podfile"); + const projectPodfilePath = path.join(platformsFolderPath, "Podfile"); assert.isTrue(fs.exists(projectPodfilePath)); - let actualProjectPodfileContent = fs.readText(projectPodfilePath); - let expectedProjectPodfileContent = ["use_frameworks!\n", + const actualProjectPodfileContent = fs.readText(projectPodfilePath); + const expectedProjectPodfileContent = ["use_frameworks!\n", `target "${projectName}" do`, `# Begin Podfile - ${pluginPodfilePath} `, ` ${pluginPodfileContent} `, @@ -371,13 +371,13 @@ describe("Cocoapods support", () => { assert.equal(actualProjectPodfileContent, expectedProjectPodfileContent); }); it("adds and removes plugin with Podfile", async () => { - let projectName = "projectDirectory2"; - let projectPath = temp.mkdirSync(projectName); + const projectName = "projectDirectory2"; + const projectPath = temp.mkdirSync(projectName); - let testInjector = createTestInjector(projectPath, projectName); - let fs: IFileSystem = testInjector.resolve("fs"); + const testInjector = createTestInjector(projectPath, projectName); + const fs: IFileSystem = testInjector.resolve("fs"); - let packageJsonData = { + const packageJsonData = { "name": "myProject2", "version": "0.1.0", "nativescript": { @@ -389,10 +389,10 @@ describe("Cocoapods support", () => { }; fs.writeJson(path.join(projectPath, "package.json"), packageJsonData); - let platformsFolderPath = path.join(projectPath, "platforms", "ios"); + const platformsFolderPath = path.join(projectPath, "platforms", "ios"); fs.createDirectory(platformsFolderPath); - let iOSProjectService = testInjector.resolve("iOSProjectService"); + const iOSProjectService = testInjector.resolve("iOSProjectService"); iOSProjectService.prepareFrameworks = (pluginPlatformsFolderPath: string, pluginData: IPluginData): Promise => { return Promise.resolve(); }; @@ -413,26 +413,26 @@ describe("Cocoapods support", () => { }; iOSProjectService.savePbxProj = (): Promise => Promise.resolve(); - let pluginPath = temp.mkdirSync("pluginDirectory"); - let pluginPlatformsFolderPath = path.join(pluginPath, "platforms", "ios"); - let pluginPodfilePath = path.join(pluginPlatformsFolderPath, "Podfile"); - let pluginPodfileContent = ["source 'https://github.com/CocoaPods/Specs.git'", "platform :ios, '8.1'", "pod 'GoogleMaps'"].join("\n"); + const pluginPath = temp.mkdirSync("pluginDirectory"); + const pluginPlatformsFolderPath = path.join(pluginPath, "platforms", "ios"); + const pluginPodfilePath = path.join(pluginPlatformsFolderPath, "Podfile"); + const pluginPodfileContent = ["source 'https://github.com/CocoaPods/Specs.git'", "platform :ios, '8.1'", "pod 'GoogleMaps'"].join("\n"); fs.writeFile(pluginPodfilePath, pluginPodfileContent); - let pluginData = { + const pluginData = { pluginPlatformsFolderPath(platform: string): string { return pluginPlatformsFolderPath; } }; - let projectData: IProjectData = testInjector.resolve("projectData"); + const projectData: IProjectData = testInjector.resolve("projectData"); await iOSProjectService.preparePluginNativeCode(pluginData, projectData); - let projectPodfilePath = path.join(platformsFolderPath, "Podfile"); + const projectPodfilePath = path.join(platformsFolderPath, "Podfile"); assert.isTrue(fs.exists(projectPodfilePath)); - let actualProjectPodfileContent = fs.readText(projectPodfilePath); - let expectedProjectPodfileContent = ["use_frameworks!\n", + const actualProjectPodfileContent = fs.readText(projectPodfilePath); + const expectedProjectPodfileContent = ["use_frameworks!\n", `target "${projectName}" do`, `# Begin Podfile - ${pluginPodfilePath} `, ` ${pluginPodfileContent} `, @@ -454,17 +454,17 @@ describe("Static libraries support", () => { return; } - let projectName = "TNSApp"; - let projectPath = temp.mkdirSync(projectName); - let libraryName = "testLibrary1"; - let headers = ["TestHeader1.h", "TestHeader2.h"]; - let testInjector = createTestInjector(projectPath, projectName); - let fs: IFileSystem = testInjector.resolve("fs"); - let staticLibraryPath = path.join(path.join(temp.mkdirSync("pluginDirectory"), "platforms", "ios")); - let staticLibraryHeadersPath = path.join(staticLibraryPath, "include", libraryName); + const projectName = "TNSApp"; + const projectPath = temp.mkdirSync(projectName); + const libraryName = "testLibrary1"; + const headers = ["TestHeader1.h", "TestHeader2.h"]; + const testInjector = createTestInjector(projectPath, projectName); + const fs: IFileSystem = testInjector.resolve("fs"); + const staticLibraryPath = path.join(path.join(temp.mkdirSync("pluginDirectory"), "platforms", "ios")); + const staticLibraryHeadersPath = path.join(staticLibraryPath, "include", libraryName); it("checks validation of header files", async () => { - let iOSProjectService = testInjector.resolve("iOSProjectService"); + const iOSProjectService = testInjector.resolve("iOSProjectService"); fs.ensureDirectoryExists(staticLibraryHeadersPath); _.each(headers, header => { fs.writeFile(path.join(staticLibraryHeadersPath, header), ""); }); @@ -482,15 +482,15 @@ describe("Static libraries support", () => { }); it("checks generation of modulemaps", () => { - let iOSProjectService = testInjector.resolve("iOSProjectService"); + const iOSProjectService = testInjector.resolve("iOSProjectService"); fs.ensureDirectoryExists(staticLibraryHeadersPath); _.each(headers, header => { fs.writeFile(path.join(staticLibraryHeadersPath, header), ""); }); iOSProjectService.generateModulemap(staticLibraryHeadersPath, libraryName); // Read the generated modulemap and verify it. let modulemap = fs.readFile(path.join(staticLibraryHeadersPath, "module.modulemap")); - let headerCommands = _.map(headers, value => `header "${value}"`); - let modulemapExpectation = `module ${libraryName} { explicit module ${libraryName} { ${headerCommands.join(" ")} } }`; + const headerCommands = _.map(headers, value => `header "${value}"`); + const modulemapExpectation = `module ${libraryName} { explicit module ${libraryName} { ${headerCommands.join(" ")} } }`; assert.equal(modulemap, modulemapExpectation); @@ -511,16 +511,16 @@ describe("Static libraries support", () => { describe("Relative paths", () => { it("checks for correct calculation of relative paths", () => { - let projectName = "projectDirectory"; - let projectPath = temp.mkdirSync(projectName); - let subpath = path.join(projectPath, "sub", "path"); + const projectName = "projectDirectory"; + const projectPath = temp.mkdirSync(projectName); + const subpath = path.join(projectPath, "sub", "path"); - let testInjector = createTestInjector(projectPath, projectName); + const testInjector = createTestInjector(projectPath, projectName); createPackageJson(testInjector, projectPath, projectName); - let iOSProjectService = testInjector.resolve("iOSProjectService"); - let projectData: IProjectData = testInjector.resolve("projectData"); + const iOSProjectService = testInjector.resolve("iOSProjectService"); + const projectData: IProjectData = testInjector.resolve("projectData"); - let result = iOSProjectService.getLibSubpathRelativeToProjectPath(subpath, projectData); + const result = iOSProjectService.getLibSubpathRelativeToProjectPath(subpath, projectData); assert.equal(result, path.join("..", "..", "sub", "path")); }); }); @@ -621,7 +621,7 @@ describe("iOS Project Service Signing", () => { describe("Check for Changes", () => { it("sets signingChanged if no Xcode project exists", async () => { - let changes = {}; + const changes = {}; await iOSProjectService.checkForChanges(changes, { bundle: false, release: false, provision: "NativeScriptDev", teamId: undefined }, projectData); assert.isTrue(!!changes.signingChanged); }); @@ -635,7 +635,7 @@ describe("iOS Project Service Signing", () => { } }; }; - let changes = {}; + const changes = {}; await iOSProjectService.checkForChanges(changes, { bundle: false, release: false, provision: "NativeScriptDev", teamId: undefined }, projectData); assert.isTrue(!!changes.signingChanged); }); @@ -654,7 +654,7 @@ describe("iOS Project Service Signing", () => { } }; }; - let changes = {}; + const changes = {}; await iOSProjectService.checkForChanges(changes, { bundle: false, release: false, provision: "NativeScriptDev", teamId: undefined }, projectData); assert.isTrue(!!changes.signingChanged); }); @@ -673,7 +673,7 @@ describe("iOS Project Service Signing", () => { } }; }; - let changes = {}; + const changes = {}; await iOSProjectService.checkForChanges(changes, { bundle: false, release: false, provision: "NativeScriptDev", teamId: undefined }, projectData); assert.isFalse(!!changes.signingChanged); }); @@ -699,7 +699,7 @@ describe("iOS Project Service Signing", () => { } }); it("succeeds if the provision name is provided for development cert", async () => { - let stack: any = []; + const stack: any = []; pbxprojDomXcode.Xcode.open = function (path: string) { assert.equal(path, pbxproj); return { @@ -718,7 +718,7 @@ describe("iOS Project Service Signing", () => { assert.deepEqual(stack, [{ targetName: projectDirName, manualSigning: { team: "TKID101", uuid: "12345", name: "NativeScriptDev", identity: "iPhone Developer" } }, "save()"]); }); it("succeds if the provision name is provided for distribution cert", async () => { - let stack: any = []; + const stack: any = []; pbxprojDomXcode.Xcode.open = function (path: string) { assert.equal(path, pbxproj); return { @@ -737,7 +737,7 @@ describe("iOS Project Service Signing", () => { assert.deepEqual(stack, [{ targetName: projectDirName, manualSigning: { team: "TKID202", uuid: "6789", name: "NativeScriptDist", identity: "iPhone Distribution" } }, "save()"]); }); it("succeds if the provision name is provided for adhoc cert", async () => { - let stack: any = []; + const stack: any = []; pbxprojDomXcode.Xcode.open = function (path: string) { assert.equal(path, pbxproj); return { @@ -765,22 +765,22 @@ describe("Merge Project XCConfig files", () => { return; } const assertPropertyValues = (expected: any, xcconfigPath: string, injector: IInjector) => { - let service = injector.resolve('xCConfigService'); + const service = injector.resolve('xCConfigService'); _.forOwn(expected, (value, key) => { - let actual = service.readPropertyValue(xcconfigPath, key); + const actual = service.readPropertyValue(xcconfigPath, key); assert.equal(actual, value); }); }; - let projectName: string, - projectPath: string, - testInjector: IInjector, - iOSProjectService: IOSProjectService, - projectData: IProjectData, - fs: IFileSystem, - appResourcesXcconfigPath: string, - appResourceXCConfigContent: string, - iOSEntitlementsService: IOSEntitlementsService; + let projectName: string; + let projectPath: string; + let testInjector: IInjector; + let iOSProjectService: IOSProjectService; + let projectData: IProjectData; + let fs: IFileSystem; + let appResourcesXcconfigPath: string; + let appResourceXCConfigContent: string; + let iOSEntitlementsService: IOSEntitlementsService; beforeEach(() => { projectName = "projectDirectory"; @@ -801,7 +801,7 @@ describe("Merge Project XCConfig files", () => { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; ASSETCATALOG_COMPILER_LAUNCHIMAGE_NAME = LaunchImage; `; - let testPackageJson = { + const testPackageJson = { "name": "test-project", "version": "0.0.1" }; @@ -814,14 +814,14 @@ describe("Merge Project XCConfig files", () => { fs.writeFile(appResourcesXcconfigPath, appResourceXCConfigContent); // run merge for all release: debug|release - for (let release in [true, false]) { + for (const release in [true, false]) { await (iOSProjectService).mergeProjectXcconfigFiles(release, projectData); - let destinationFilePath = release ? (iOSProjectService).getPluginsReleaseXcconfigFilePath(projectData) + const destinationFilePath = release ? (iOSProjectService).getPluginsReleaseXcconfigFilePath(projectData) : (iOSProjectService).getPluginsDebugXcconfigFilePath(projectData); assert.isTrue(fs.exists(destinationFilePath), 'Target build xcconfig is missing for release: ' + release); - let expected = { + const expected = { 'ASSETCATALOG_COMPILER_APPICON_NAME': 'AppIcon', 'ASSETCATALOG_COMPILER_LAUNCHIMAGE_NAME': 'LaunchImage', 'CODE_SIGN_IDENTITY': 'iPhone Distribution' @@ -831,14 +831,14 @@ describe("Merge Project XCConfig files", () => { }); it("Adds the entitlements property if not set by the user", async () => { - for (let release in [true, false]) { + for (const release in [true, false]) { await (iOSProjectService).mergeProjectXcconfigFiles(release, projectData); - let destinationFilePath = release ? (iOSProjectService).getPluginsReleaseXcconfigFilePath(projectData) + const destinationFilePath = release ? (iOSProjectService).getPluginsReleaseXcconfigFilePath(projectData) : (iOSProjectService).getPluginsDebugXcconfigFilePath(projectData); assert.isTrue(fs.exists(destinationFilePath), 'Target build xcconfig is missing for release: ' + release); - let expected = { + const expected = { 'CODE_SIGN_ENTITLEMENTS': iOSEntitlementsService.getPlatformsEntitlementsRelativePath(projectData) }; assertPropertyValues(expected, destinationFilePath, testInjector); @@ -848,18 +848,18 @@ describe("Merge Project XCConfig files", () => { it("The user specified entitlements property takes precedence", async () => { // setup app_resource build.xcconfig const expectedEntitlementsFile = 'user.entitlements'; - let xcconfigEntitlements = appResourceXCConfigContent + `${EOL}CODE_SIGN_ENTITLEMENTS = ${expectedEntitlementsFile}`; + const xcconfigEntitlements = appResourceXCConfigContent + `${EOL}CODE_SIGN_ENTITLEMENTS = ${expectedEntitlementsFile}`; fs.writeFile(appResourcesXcconfigPath, xcconfigEntitlements); // run merge for all release: debug|release - for (let release in [true, false]) { + for (const release in [true, false]) { await (iOSProjectService).mergeProjectXcconfigFiles(release, projectData); - let destinationFilePath = release ? (iOSProjectService).getPluginsReleaseXcconfigFilePath(projectData) + const destinationFilePath = release ? (iOSProjectService).getPluginsReleaseXcconfigFilePath(projectData) : (iOSProjectService).getPluginsDebugXcconfigFilePath(projectData); assert.isTrue(fs.exists(destinationFilePath), 'Target build xcconfig is missing for release: ' + release); - let expected = { + const expected = { 'ASSETCATALOG_COMPILER_APPICON_NAME': 'AppIcon', 'ASSETCATALOG_COMPILER_LAUNCHIMAGE_NAME': 'LaunchImage', 'CODE_SIGN_IDENTITY': 'iPhone Distribution', diff --git a/test/npm-installation-manager.ts b/test/npm-installation-manager.ts index ef11d4098d..f36ff54e90 100644 --- a/test/npm-installation-manager.ts +++ b/test/npm-installation-manager.ts @@ -11,7 +11,7 @@ import * as yok from "../lib/common/yok"; import ChildProcessLib = require("../lib/common/child-process"); function createTestInjector(): IInjector { - let testInjector = new yok.Yok(); + const testInjector = new yok.Yok(); testInjector.register("config", ConfigLib.Configuration); testInjector.register("logger", LoggerLib.Logger); @@ -63,7 +63,7 @@ interface ITestData { } describe("Npm installation manager tests", () => { - let testData: IDictionary = { + const testData: IDictionary = { "when there's only one available version and it matches CLI's version": { versions: ["1.4.0"], packageLatestVersion: "1.4.0", @@ -157,19 +157,19 @@ describe("Npm installation manager tests", () => { _.each(testData, (currentTestData: ITestData, testName: string) => { it(`returns correct latest compatible version, ${testName}`, async () => { - let testInjector = createTestInjector(); + const testInjector = createTestInjector(); mockNpm(testInjector, currentTestData.versions, currentTestData.packageLatestVersion); // Mock staticConfig.version - let staticConfig = testInjector.resolve("staticConfig"); + const staticConfig = testInjector.resolve("staticConfig"); staticConfig.version = currentTestData.cliVersion; // Mock npmInstallationManager.getLatestVersion - let npmInstallationManager = testInjector.resolve("npmInstallationManager"); + const npmInstallationManager = testInjector.resolve("npmInstallationManager"); npmInstallationManager.getLatestVersion = (packageName: string) => Promise.resolve(currentTestData.packageLatestVersion); - let actualLatestCompatibleVersion = await npmInstallationManager.getLatestCompatibleVersion(""); + const actualLatestCompatibleVersion = await npmInstallationManager.getLatestCompatibleVersion(""); assert.equal(actualLatestCompatibleVersion, currentTestData.expectedResult); }); }); diff --git a/test/npm-support.ts b/test/npm-support.ts index 3e72a558bb..1b9bb23c3c 100644 --- a/test/npm-support.ts +++ b/test/npm-support.ts @@ -32,12 +32,12 @@ import path = require("path"); import temp = require("temp"); temp.track(); -let assert = require("chai").assert; -let nodeModulesFolderName = "node_modules"; -let packageJsonName = "package.json"; +const assert = require("chai").assert; +const nodeModulesFolderName = "node_modules"; +const packageJsonName = "package.json"; function createTestInjector(): IInjector { - let testInjector = new yok.Yok(); + const testInjector = new yok.Yok(); testInjector.register("fs", FsLib.FileSystem); testInjector.register("adb", {}); testInjector.register("options", OptionsLib.Options); @@ -91,15 +91,15 @@ function createTestInjector(): IInjector { } function createProject(testInjector: IInjector, dependencies?: any): string { - let tempFolder = temp.mkdirSync("npmSupportTests"); - let options = testInjector.resolve("options"); + const tempFolder = temp.mkdirSync("npmSupportTests"); + const options = testInjector.resolve("options"); options.path = tempFolder; dependencies = dependencies || { "lodash": "3.9.3" }; - let packageJsonData: any = { + const packageJsonData: any = { "name": "testModuleName", "version": "0.1.0", "nativescript": { @@ -121,27 +121,27 @@ function createProject(testInjector: IInjector, dependencies?: any): string { } async function setupProject(dependencies?: any): Promise { - let testInjector = createTestInjector(); - let projectFolder = createProject(testInjector, dependencies); + const testInjector = createTestInjector(); + const projectFolder = createProject(testInjector, dependencies); - let fs = testInjector.resolve("fs"); + const fs = testInjector.resolve("fs"); // Creates app folder - let appFolderPath = path.join(projectFolder, "app"); + const appFolderPath = path.join(projectFolder, "app"); fs.createDirectory(appFolderPath); - let appResourcesFolderPath = path.join(appFolderPath, "App_Resources"); + const appResourcesFolderPath = path.join(appFolderPath, "App_Resources"); fs.createDirectory(appResourcesFolderPath); fs.createDirectory(path.join(appResourcesFolderPath, "Android")); fs.createDirectory(path.join(appResourcesFolderPath, "Android", "mockdir")); fs.createDirectory(path.join(appFolderPath, "tns_modules")); // Creates platforms/android folder - let androidFolderPath = path.join(projectFolder, "platforms", "android"); + const androidFolderPath = path.join(projectFolder, "platforms", "android"); fs.ensureDirectoryExists(androidFolderPath); // Mock platform data - let appDestinationFolderPath = path.join(androidFolderPath, "assets"); - let platformsData = testInjector.resolve("platformsData"); + const appDestinationFolderPath = path.join(androidFolderPath, "assets"); + const platformsData = testInjector.resolve("platformsData"); platformsData.getPlatformData = (platform: string) => { return { @@ -176,15 +176,15 @@ async function setupProject(dependencies?: any): Promise { } async function addDependencies(testInjector: IInjector, projectFolder: string, dependencies: any, devDependencies?: any): Promise { - let fs = testInjector.resolve("fs"); - let packageJsonPath = path.join(projectFolder, "package.json"); - let packageJsonData = fs.readJson(packageJsonPath); + const fs = testInjector.resolve("fs"); + const packageJsonPath = path.join(projectFolder, "package.json"); + const packageJsonData = fs.readJson(packageJsonPath); - let currentDependencies = packageJsonData.dependencies; + const currentDependencies = packageJsonData.dependencies; _.extend(currentDependencies, dependencies); if (devDependencies) { - let currentDevDependencies = packageJsonData.devDependencies; + const currentDevDependencies = packageJsonData.devDependencies; _.extend(currentDevDependencies, devDependencies); } fs.writeJson(packageJsonPath, packageJsonData); @@ -202,13 +202,13 @@ async function preparePlatform(testInjector: IInjector): Promise { describe("Npm support tests", () => { let testInjector: IInjector, projectFolder: string, appDestinationFolderPath: string; beforeEach(async () => { - let projectSetup = await setupProject(); + const projectSetup = await setupProject(); testInjector = projectSetup.testInjector; projectFolder = projectSetup.projectFolder; appDestinationFolderPath = projectSetup.appDestinationFolderPath; }); it("Ensures that the installed dependencies are prepared correctly", async () => { - let fs: IFileSystem = testInjector.resolve("fs"); + const fs: IFileSystem = testInjector.resolve("fs"); // Setup await addDependencies(testInjector, projectFolder, { "bplist": "0.0.4" }); @@ -216,9 +216,9 @@ describe("Npm support tests", () => { await preparePlatform(testInjector); // Assert - let tnsModulesFolderPath = path.join(appDestinationFolderPath, "app", "tns_modules"); + const tnsModulesFolderPath = path.join(appDestinationFolderPath, "app", "tns_modules"); - let results = fs.enumerateFilesInDirectorySync(tnsModulesFolderPath, (file, stat) => { + const results = fs.enumerateFilesInDirectorySync(tnsModulesFolderPath, (file, stat) => { return true; }, { enumerateDirectories: true }); @@ -229,38 +229,38 @@ describe("Npm support tests", () => { }); it("Ensures that scoped dependencies are prepared correctly", async () => { // Setup - let fs = testInjector.resolve("fs"); - let scopedName = "@reactivex/rxjs"; - let dependencies: any = {}; + const fs = testInjector.resolve("fs"); + const scopedName = "@reactivex/rxjs"; + const dependencies: any = {}; dependencies[scopedName] = "0.0.0-prealpha.3"; // Do not pass dependencies object as the sinopia cannot work with scoped dependencies. Instead move them manually. await addDependencies(testInjector, projectFolder, dependencies); // Act await preparePlatform(testInjector); // Assert - let tnsModulesFolderPath = path.join(appDestinationFolderPath, "app", "tns_modules"); - let scopedDependencyPath = path.join(tnsModulesFolderPath, "@reactivex", "rxjs"); + const tnsModulesFolderPath = path.join(appDestinationFolderPath, "app", "tns_modules"); + const scopedDependencyPath = path.join(tnsModulesFolderPath, "@reactivex", "rxjs"); assert.isTrue(fs.exists(scopedDependencyPath)); }); it("Ensures that scoped dependencies are prepared correctly when are not in root level", async () => { // Setup - let customPluginName = "plugin-with-scoped-dependency"; - let customPluginDirectory = temp.mkdirSync("custom-plugin-directory"); + const customPluginName = "plugin-with-scoped-dependency"; + const customPluginDirectory = temp.mkdirSync("custom-plugin-directory"); - let fs: IFileSystem = testInjector.resolve("fs"); + const fs: IFileSystem = testInjector.resolve("fs"); await fs.unzip(path.join("resources", "test", `${customPluginName}.zip`), customPluginDirectory); await addDependencies(testInjector, projectFolder, { "plugin-with-scoped-dependency": `file:${path.join(customPluginDirectory, customPluginName)}` }); // Act await preparePlatform(testInjector); // Assert - let tnsModulesFolderPath = path.join(appDestinationFolderPath, "app", "tns_modules"); - let results = fs.enumerateFilesInDirectorySync(tnsModulesFolderPath, (file, stat) => { + const tnsModulesFolderPath = path.join(appDestinationFolderPath, "app", "tns_modules"); + const results = fs.enumerateFilesInDirectorySync(tnsModulesFolderPath, (file, stat) => { return true; }, { enumerateDirectories: true }); - let filteredResults = results.filter((val) => { + const filteredResults = results.filter((val) => { return _.endsWith(val, path.join("@scoped-plugin", "inner-plugin")); }); @@ -268,9 +268,9 @@ describe("Npm support tests", () => { }); it("Ensures that tns_modules absent when bundling", async () => { - let fs = testInjector.resolve("fs"); - let options = testInjector.resolve("options"); - let tnsModulesFolderPath = path.join(appDestinationFolderPath, "app", "tns_modules"); + const fs = testInjector.resolve("fs"); + const options = testInjector.resolve("options"); + const tnsModulesFolderPath = path.join(appDestinationFolderPath, "app", "tns_modules"); try { options.bundle = false; @@ -292,12 +292,12 @@ describe("Npm support tests", () => { describe("Flatten npm modules tests", () => { it("Doesn't handle the dependencies of devDependencies", async () => { - let projectSetup = await setupProject({}); - let testInjector = projectSetup.testInjector; - let projectFolder = projectSetup.projectFolder; - let appDestinationFolderPath = projectSetup.appDestinationFolderPath; + const projectSetup = await setupProject({}); + const testInjector = projectSetup.testInjector; + const projectFolder = projectSetup.projectFolder; + const appDestinationFolderPath = projectSetup.appDestinationFolderPath; - let devDependencies = { + const devDependencies = { "gulp": "3.9.0", "gulp-jscs": "1.6.0", "gulp-jshint": "1.11.0" @@ -308,32 +308,32 @@ describe("Flatten npm modules tests", () => { await preparePlatform(testInjector); // Assert - let fs = testInjector.resolve("fs"); - let tnsModulesFolderPath = path.join(appDestinationFolderPath, "app", "tns_modules"); + const fs = testInjector.resolve("fs"); + const tnsModulesFolderPath = path.join(appDestinationFolderPath, "app", "tns_modules"); - let gulpFolderPath = path.join(tnsModulesFolderPath, "gulp"); + const gulpFolderPath = path.join(tnsModulesFolderPath, "gulp"); assert.isFalse(fs.exists(gulpFolderPath)); - let gulpJscsFolderPath = path.join(tnsModulesFolderPath, "gulp-jscs"); + const gulpJscsFolderPath = path.join(tnsModulesFolderPath, "gulp-jscs"); assert.isFalse(fs.exists(gulpJscsFolderPath)); - let gulpJshint = path.join(tnsModulesFolderPath, "gulp-jshint"); + const gulpJshint = path.join(tnsModulesFolderPath, "gulp-jshint"); assert.isFalse(fs.exists(gulpJshint)); // Get all gulp dependencies - let gulpJsonContent = fs.readJson(path.join(projectFolder, nodeModulesFolderName, "gulp", packageJsonName)); + const gulpJsonContent = fs.readJson(path.join(projectFolder, nodeModulesFolderName, "gulp", packageJsonName)); _.each(_.keys(gulpJsonContent.dependencies), dependency => { assert.isFalse(fs.exists(path.join(tnsModulesFolderPath, dependency))); }); // Get all gulp-jscs dependencies - let gulpJscsJsonContent = fs.readJson(path.join(projectFolder, nodeModulesFolderName, "gulp-jscs", packageJsonName)); + const gulpJscsJsonContent = fs.readJson(path.join(projectFolder, nodeModulesFolderName, "gulp-jscs", packageJsonName)); _.each(_.keys(gulpJscsJsonContent.dependencies), dependency => { assert.isFalse(fs.exists(path.join(tnsModulesFolderPath, dependency))); }); // Get all gulp-jshint dependencies - let gulpJshintJsonContent = fs.readJson(path.join(projectFolder, nodeModulesFolderName, "gulp-jshint", packageJsonName)); + const gulpJshintJsonContent = fs.readJson(path.join(projectFolder, nodeModulesFolderName, "gulp-jshint", packageJsonName)); _.each(_.keys(gulpJshintJsonContent.dependencies), dependency => { assert.isFalse(fs.exists(path.join(tnsModulesFolderPath, dependency))); }); diff --git a/test/platform-commands.ts b/test/platform-commands.ts index 52a5695698..51dc5acb70 100644 --- a/test/platform-commands.ts +++ b/test/platform-commands.ts @@ -91,7 +91,7 @@ class PlatformsData implements IPlatformsData { } function createTestInjector() { - let testInjector = new yok.Yok(); + const testInjector = new yok.Yok(); testInjector.register("injector", testInjector); testInjector.register("hooksService", stubs.HooksServiceStub); @@ -438,8 +438,8 @@ describe('Platform Service Tests', () => { }); it("will call removePlatform and addPlatform on the platformService passing the provided platforms", async () => { - let platformActions: { action: string, platforms: string[] }[] = []; - let cleanCommand = testInjector.resolveCommand("platform|clean"); + const platformActions: { action: string, platforms: string[] }[] = []; + const cleanCommand = testInjector.resolveCommand("platform|clean"); platformService.removePlatforms = async (platforms: string[]) => { platformActions.push({ action: "removePlatforms", platforms }); @@ -453,7 +453,7 @@ describe('Platform Service Tests', () => { await cleanCommand.execute(["ios"]); - let expectedPlatformActions = [ + const expectedPlatformActions = [ { action: "removePlatforms", platforms: ["ios"] }, { action: "addPlatforms", platforms: ["ios"] }, ]; diff --git a/test/platform-service.ts b/test/platform-service.ts index 9333bb297e..8a4faa965a 100644 --- a/test/platform-service.ts +++ b/test/platform-service.ts @@ -21,11 +21,11 @@ import ProjectChangesLib = require("../lib/services/project-changes-service"); import { Messages } from "../lib/common/messages/messages"; require("should"); -let temp = require("temp"); +const temp = require("temp"); temp.track(); function createTestInjector() { - let testInjector = new yok.Yok(); + const testInjector = new yok.Yok(); testInjector.register('platformService', PlatformServiceLib.PlatformService); testInjector.register('errors', stubs.ErrorsStub); @@ -164,9 +164,9 @@ describe('Platform Service Tests', () => { describe("add platform unit tests", () => { describe("#add platform()", () => { it("should not fail if platform is not normalized", async () => { - let fs = testInjector.resolve("fs"); + const fs = testInjector.resolve("fs"); fs.exists = () => false; - let projectData: IProjectData = testInjector.resolve("projectData"); + const projectData: IProjectData = testInjector.resolve("projectData"); await platformService.addPlatforms(["Android"], "", projectData, config); await platformService.addPlatforms(["ANDROID"], "", projectData, config); await platformService.addPlatforms(["AnDrOiD"], "", projectData, config); @@ -178,19 +178,19 @@ describe('Platform Service Tests', () => { await platformService.addPlatforms(["iOs"], "", projectData, config); }); it("should fail if platform is already installed", async () => { - let projectData: IProjectData = testInjector.resolve("projectData"); + const projectData: IProjectData = testInjector.resolve("projectData"); // By default fs.exists returns true, so the platforms directory should exists await assert.isRejected(platformService.addPlatforms(["android"], "", projectData, config)); await assert.isRejected(platformService.addPlatforms(["ios"], "", projectData, config)); }); it("should fail if npm is unavalible", async () => { - let fs = testInjector.resolve("fs"); + const fs = testInjector.resolve("fs"); fs.exists = () => false; - let errorMessage = "Npm is unavalible"; - let npmInstallationManager = testInjector.resolve("npmInstallationManager"); + const errorMessage = "Npm is unavalible"; + const npmInstallationManager = testInjector.resolve("npmInstallationManager"); npmInstallationManager.install = () => { throw new Error(errorMessage); }; - let projectData: IProjectData = testInjector.resolve("projectData"); + const projectData: IProjectData = testInjector.resolve("projectData"); try { await platformService.addPlatforms(["android"], "", projectData, config); @@ -200,39 +200,39 @@ describe('Platform Service Tests', () => { }); it("should respect platform version in package.json's nativescript key", async () => { const versionString = "2.5.0"; - let fs = testInjector.resolve("fs"); + const fs = testInjector.resolve("fs"); fs.exists = () => false; - let nsValueObject: any = {}; + const nsValueObject: any = {}; nsValueObject[VERSION_STRING] = versionString; - let projectDataService = testInjector.resolve("projectDataService"); + const projectDataService = testInjector.resolve("projectDataService"); projectDataService.getNSValue = () => nsValueObject; - let npmInstallationManager = testInjector.resolve("npmInstallationManager"); + const npmInstallationManager = testInjector.resolve("npmInstallationManager"); npmInstallationManager.install = (packageName: string, packageDir: string, options: INpmInstallOptions) => { assert.deepEqual(options.version, versionString); return ""; }; - let projectData: IProjectData = testInjector.resolve("projectData"); + const projectData: IProjectData = testInjector.resolve("projectData"); await platformService.addPlatforms(["android"], "", projectData, config); await platformService.addPlatforms(["ios"], "", projectData, config); }); it("should install latest platform if no information found in package.json's nativescript key", async () => { - let fs = testInjector.resolve("fs"); + const fs = testInjector.resolve("fs"); fs.exists = () => false; - let projectDataService = testInjector.resolve("projectDataService"); + const projectDataService = testInjector.resolve("projectDataService"); projectDataService.getNSValue = (): any => null; - let npmInstallationManager = testInjector.resolve("npmInstallationManager"); + const npmInstallationManager = testInjector.resolve("npmInstallationManager"); npmInstallationManager.install = (packageName: string, packageDir: string, options: INpmInstallOptions) => { assert.deepEqual(options.version, undefined); return ""; }; - let projectData: IProjectData = testInjector.resolve("projectData"); + const projectData: IProjectData = testInjector.resolve("projectData"); await platformService.addPlatforms(["android"], "", projectData, config); await platformService.addPlatforms(["ios"], "", projectData, config); @@ -240,13 +240,13 @@ describe('Platform Service Tests', () => { }); describe("#add platform(ios)", () => { it("should call validate method", async () => { - let fs = testInjector.resolve("fs"); + const fs = testInjector.resolve("fs"); fs.exists = () => false; - let errorMessage = "Xcode is not installed or Xcode version is smaller that 5.0"; - let platformsData = testInjector.resolve("platformsData"); - let platformProjectService = platformsData.getPlatformData().platformProjectService; - let projectData: IProjectData = testInjector.resolve("projectData"); + const errorMessage = "Xcode is not installed or Xcode version is smaller that 5.0"; + const platformsData = testInjector.resolve("platformsData"); + const platformProjectService = platformsData.getPlatformData().platformProjectService; + const projectData: IProjectData = testInjector.resolve("projectData"); platformProjectService.validate = () => { throw new Error(errorMessage); }; @@ -260,16 +260,16 @@ describe('Platform Service Tests', () => { }); describe("#add platform(android)", () => { it("should fail if java, ant or android are not installed", async () => { - let fs = testInjector.resolve("fs"); + const fs = testInjector.resolve("fs"); fs.exists = () => false; - let errorMessage = "Java, ant or android are not installed"; - let platformsData = testInjector.resolve("platformsData"); - let platformProjectService = platformsData.getPlatformData().platformProjectService; + const errorMessage = "Java, ant or android are not installed"; + const platformsData = testInjector.resolve("platformsData"); + const platformProjectService = platformsData.getPlatformData().platformProjectService; platformProjectService.validate = () => { throw new Error(errorMessage); }; - let projectData: IProjectData = testInjector.resolve("projectData"); + const projectData: IProjectData = testInjector.resolve("projectData"); try { await platformService.addPlatforms(["android"], "", projectData, config); @@ -284,7 +284,7 @@ describe('Platform Service Tests', () => { it("should fail when platforms are not added", async () => { const ExpectedErrorsCaught = 2; let errorsCaught = 0; - let projectData: IProjectData = testInjector.resolve("projectData"); + const projectData: IProjectData = testInjector.resolve("projectData"); testInjector.resolve("fs").exists = () => false; try { @@ -302,7 +302,7 @@ describe('Platform Service Tests', () => { assert.isTrue(errorsCaught === ExpectedErrorsCaught); }); it("shouldn't fail when platforms are added", async () => { - let projectData: IProjectData = testInjector.resolve("projectData"); + const projectData: IProjectData = testInjector.resolve("projectData"); testInjector.resolve("fs").exists = () => false; await platformService.addPlatforms(["android"], "", projectData, config); @@ -314,21 +314,21 @@ describe('Platform Service Tests', () => { describe("clean platform unit tests", () => { it("should preserve the specified in the project nativescript version", async () => { const versionString = "2.4.1"; - let fs = testInjector.resolve("fs"); + const fs = testInjector.resolve("fs"); fs.exists = () => false; - let nsValueObject: any = {}; + const nsValueObject: any = {}; nsValueObject[VERSION_STRING] = versionString; - let projectDataService = testInjector.resolve("projectDataService"); + const projectDataService = testInjector.resolve("projectDataService"); projectDataService.getNSValue = () => nsValueObject; - let npmInstallationManager = testInjector.resolve("npmInstallationManager"); + const npmInstallationManager = testInjector.resolve("npmInstallationManager"); npmInstallationManager.install = (packageName: string, packageDir: string, options: INpmInstallOptions) => { assert.deepEqual(options.version, versionString); return ""; }; - let projectData: IProjectData = testInjector.resolve("projectData"); + const projectData: IProjectData = testInjector.resolve("projectData"); platformService.removePlatforms = (platforms: string[], prjctData: IProjectData): Promise => { nsValueObject[VERSION_STRING] = undefined; return Promise.resolve(); @@ -351,9 +351,9 @@ describe('Platform Service Tests', () => { describe("update Platform", () => { describe("#updatePlatform(platform)", () => { it("should fail when the versions are the same", async () => { - let npmInstallationManager: INpmInstallationManager = testInjector.resolve("npmInstallationManager"); + const npmInstallationManager: INpmInstallationManager = testInjector.resolve("npmInstallationManager"); npmInstallationManager.getLatestVersion = async () => "0.2.0"; - let projectData: IProjectData = testInjector.resolve("projectData"); + const projectData: IProjectData = testInjector.resolve("projectData"); await assert.isRejected(platformService.updatePlatforms(["android"], "", projectData, null)); }); @@ -370,22 +370,22 @@ describe('Platform Service Tests', () => { }); function prepareDirStructure() { - let tempFolder = temp.mkdirSync("prepare_platform"); + const tempFolder = temp.mkdirSync("prepare_platform"); - let appFolderPath = path.join(tempFolder, "app"); + const appFolderPath = path.join(tempFolder, "app"); fs.createDirectory(appFolderPath); - let nodeModulesPath = path.join(tempFolder, "node_modules"); + const nodeModulesPath = path.join(tempFolder, "node_modules"); fs.createDirectory(nodeModulesPath); - let testsFolderPath = path.join(appFolderPath, "tests"); + const testsFolderPath = path.join(appFolderPath, "tests"); fs.createDirectory(testsFolderPath); - let app1FolderPath = path.join(tempFolder, "app1"); + const app1FolderPath = path.join(tempFolder, "app1"); fs.createDirectory(app1FolderPath); - let appDestFolderPath = path.join(tempFolder, "appDest"); - let appResourcesFolderPath = path.join(appDestFolderPath, "App_Resources"); + const appDestFolderPath = path.join(tempFolder, "appDest"); + const appResourcesFolderPath = path.join(appDestFolderPath, "App_Resources"); fs.writeJson(path.join(tempFolder, "package.json"), { name: "testname", nativescript: { @@ -398,7 +398,7 @@ describe('Platform Service Tests', () => { async function execPreparePlatform(platformToTest: string, testDirData: any, release?: boolean) { - let platformsData = testInjector.resolve("platformsData"); + const platformsData = testInjector.resolve("platformsData"); platformsData.platformsNames = ["ios", "android"]; platformsData.getPlatformData = (platform: string) => { return { @@ -415,11 +415,11 @@ describe('Platform Service Tests', () => { afterCreateProject: (projectRoot: string): any => null, getAppResourcesDestinationDirectoryPath: (projectData: IProjectData, frameworkVersion?: string): string => { if (platform.toLowerCase() === "ios") { - let dirPath = path.join(testDirData.appDestFolderPath, "Resources"); + const dirPath = path.join(testDirData.appDestFolderPath, "Resources"); fs.ensureDirectoryExists(dirPath); return dirPath; } else { - let dirPath = path.join(testDirData.appDestFolderPath, "src", "main", "res"); + const dirPath = path.join(testDirData.appDestFolderPath, "src", "main", "res"); fs.ensureDirectoryExists(dirPath); return dirPath; } @@ -434,7 +434,7 @@ describe('Platform Service Tests', () => { }; }; - let projectData = testInjector.resolve("projectData"); + const projectData = testInjector.resolve("projectData"); projectData.projectDir = testDirData.tempFolder; projectData.appDirectoryPath = testDirData.appFolderPath; projectData.appResourcesDirectoryPath = path.join(testDirData.appFolderPath, "App_Resources"); @@ -446,21 +446,21 @@ describe('Platform Service Tests', () => { } async function testPreparePlatform(platformToTest: string, release?: boolean): Promise { - let testDirData = prepareDirStructure(); - let created: CreatedTestData = new CreatedTestData(); + const testDirData = prepareDirStructure(); + const created: CreatedTestData = new CreatedTestData(); created.testDirData = testDirData; // Add platform specific files to app and app1 folders - let platformSpecificFiles = [ + const platformSpecificFiles = [ "test1.ios.js", "test1-ios-js", "test2.android.js", "test2-android-js", "main.js" ]; - let destinationDirectories = [testDirData.appFolderPath, testDirData.app1FolderPath]; + const destinationDirectories = [testDirData.appFolderPath, testDirData.app1FolderPath]; _.each(destinationDirectories, directoryPath => { _.each(platformSpecificFiles, filePath => { - let fileFullPath = path.join(directoryPath, filePath); + const fileFullPath = path.join(directoryPath, filePath); fs.writeFile(fileFullPath, "testData"); created.files.push(fileFullPath); @@ -469,19 +469,19 @@ describe('Platform Service Tests', () => { // Add App_Resources file to app and app1 folders _.each(destinationDirectories, directoryPath => { - let iosIconFullPath = path.join(directoryPath, "App_Resources/iOS/icon.png"); + const iosIconFullPath = path.join(directoryPath, "App_Resources/iOS/icon.png"); fs.writeFile(iosIconFullPath, "test-image"); created.resources.ios.push(iosIconFullPath); - let androidFullPath = path.join(directoryPath, "App_Resources/Android/icon.png"); + const androidFullPath = path.join(directoryPath, "App_Resources/Android/icon.png"); fs.writeFile(androidFullPath, "test-image"); created.resources.android.push(androidFullPath); }); await execPreparePlatform(platformToTest, testDirData, release); - let test1FileName = platformToTest.toLowerCase() === "ios" ? "test1.js" : "test2.js"; - let test2FileName = platformToTest.toLowerCase() === "ios" ? "test2.js" : "test1.js"; + const test1FileName = platformToTest.toLowerCase() === "ios" ? "test1.js" : "test2.js"; + const test2FileName = platformToTest.toLowerCase() === "ios" ? "test2.js" : "test1.js"; // Asserts that the files in app folder are process as platform specific assert.isTrue(fs.exists(path.join(testDirData.appDestFolderPath, "app", test1FileName))); @@ -502,7 +502,7 @@ describe('Platform Service Tests', () => { } function updateFile(files: string[], fileName: string, content: string) { - let fileToUpdate = _.find(files, (f) => f.indexOf(fileName) !== -1); + const fileToUpdate = _.find(files, (f) => f.indexOf(fileName) !== -1); fs.writeFile(fileToUpdate, content); } @@ -523,7 +523,7 @@ describe('Platform Service Tests', () => { }); function getDefaultFolderVerificationData(platform: string, appDestFolderPath: string) { - let data: any = {}; + const data: any = {}; if (platform.toLowerCase() === "ios") { data[path.join(appDestFolderPath, "app")] = { missingFiles: ["test1.ios.js", "test2.android.js", "test2.js", "App_Resources"], @@ -559,13 +559,13 @@ describe('Platform Service Tests', () => { function mergeModifications(def: any, mod: any) { // custom merge to reflect changes - let merged: any = _.cloneDeep(def); + const merged: any = _.cloneDeep(def); _.forOwn(mod, (modFolder, folderRoot) => { // whole folder not present in Default if (!def.hasOwnProperty(folderRoot)) { merged[folderRoot] = _.cloneDeep(modFolder[folderRoot]); } else { - let defFolder = def[folderRoot]; + const defFolder = def[folderRoot]; merged[folderRoot].filesWithContent = _.merge(defFolder.filesWithContent || [], modFolder.filesWithContent || []); merged[folderRoot].missingFiles = (defFolder.missingFiles || []).concat(modFolder.missingFiles || []); merged[folderRoot].presentFiles = (defFolder.presentFiles || []).concat(modFolder.presentFiles || []); @@ -592,27 +592,27 @@ describe('Platform Service Tests', () => { // 4. Gets the Default Destination App Structure and merges it with the Modifications // 5. Asserts the Destination App matches our expectations async function testChangesApplied(platform: string, applyChangesFn: (createdTestData: CreatedTestData) => any) { - let createdTestData = await testPreparePlatform(platform); + const createdTestData = await testPreparePlatform(platform); - let modifications = applyChangesFn(createdTestData); + const modifications = applyChangesFn(createdTestData); await execPreparePlatform(platform, createdTestData.testDirData); - let defaultStructure = getDefaultFolderVerificationData(platform, createdTestData.testDirData.appDestFolderPath); + const defaultStructure = getDefaultFolderVerificationData(platform, createdTestData.testDirData.appDestFolderPath); - let merged = mergeModifications(defaultStructure, modifications); + const merged = mergeModifications(defaultStructure, modifications); DestinationFolderVerifier.verify(merged, fs); } it("should sync only changed files, without special folders (iOS)", async () => { - let applyChangesFn = (createdTestData: CreatedTestData) => { + const applyChangesFn = (createdTestData: CreatedTestData) => { // apply changes const expectedFileContent = "updated-content-ios"; updateFile(createdTestData.files, "test1.ios.js", expectedFileContent); // construct the folder modifications data - let modifications: any = {}; + const modifications: any = {}; modifications[path.join(createdTestData.testDirData.appDestFolderPath, "app")] = { filesWithContent: [ { @@ -627,13 +627,13 @@ describe('Platform Service Tests', () => { }); it("should sync only changed files, without special folders (Android) #2697", async () => { - let applyChangesFn = (createdTestData: CreatedTestData) => { + const applyChangesFn = (createdTestData: CreatedTestData) => { // apply changes const expectedFileContent = "updated-content-android"; updateFile(createdTestData.files, "test2.android.js", expectedFileContent); // construct the folder modifications data - let modifications: any = {}; + const modifications: any = {}; modifications[path.join(createdTestData.testDirData.appDestFolderPath, "app")] = { filesWithContent: [ { @@ -648,14 +648,14 @@ describe('Platform Service Tests', () => { }); it("Ensure App_Resources get reloaded after change in the app folder (iOS) #2560", async () => { - let applyChangesFn = (createdTestData: CreatedTestData) => { + const applyChangesFn = (createdTestData: CreatedTestData) => { // apply changes const expectedFileContent = "updated-icon-content"; - let iconPngPath = path.join(createdTestData.testDirData.appFolderPath, "App_Resources/iOS/icon.png"); + const iconPngPath = path.join(createdTestData.testDirData.appFolderPath, "App_Resources/iOS/icon.png"); fs.writeFile(iconPngPath, expectedFileContent); // construct the folder modifications data - let modifications: any = {}; + const modifications: any = {}; modifications[createdTestData.testDirData.appDestFolderPath] = { filesWithContent: [ { @@ -671,14 +671,14 @@ describe('Platform Service Tests', () => { }); it("Ensure App_Resources get reloaded after change in the app folder (Android) #2560", async () => { - let applyChangesFn = (createdTestData: CreatedTestData) => { + const applyChangesFn = (createdTestData: CreatedTestData) => { // apply changes const expectedFileContent = "updated-icon-content"; - let iconPngPath = path.join(createdTestData.testDirData.appFolderPath, "App_Resources/Android/icon.png"); + const iconPngPath = path.join(createdTestData.testDirData.appFolderPath, "App_Resources/Android/icon.png"); fs.writeFile(iconPngPath, expectedFileContent); // construct the folder modifications data - let modifications: any = {}; + const modifications: any = {}; modifications[createdTestData.testDirData.appDestFolderPath] = { filesWithContent: [ { @@ -694,14 +694,14 @@ describe('Platform Service Tests', () => { }); it("Ensure App_Resources get reloaded after a new file appears in the app folder (iOS) #2560", async () => { - let applyChangesFn = (createdTestData: CreatedTestData) => { + const applyChangesFn = (createdTestData: CreatedTestData) => { // apply changes const expectedFileContent = "new-file-content"; - let iconPngPath = path.join(createdTestData.testDirData.appFolderPath, "App_Resources/iOS/new-file.png"); + const iconPngPath = path.join(createdTestData.testDirData.appFolderPath, "App_Resources/iOS/new-file.png"); fs.writeFile(iconPngPath, expectedFileContent); // construct the folder modifications data - let modifications: any = {}; + const modifications: any = {}; modifications[createdTestData.testDirData.appDestFolderPath] = { filesWithContent: [ { @@ -717,14 +717,14 @@ describe('Platform Service Tests', () => { }); it("Ensure App_Resources get reloaded after a new file appears in the app folder (Android) #2560", async () => { - let applyChangesFn = (createdTestData: CreatedTestData) => { + const applyChangesFn = (createdTestData: CreatedTestData) => { // apply changes const expectedFileContent = "new-file-content"; - let iconPngPath = path.join(createdTestData.testDirData.appFolderPath, "App_Resources/Android/new-file.png"); + const iconPngPath = path.join(createdTestData.testDirData.appFolderPath, "App_Resources/Android/new-file.png"); fs.writeFile(iconPngPath, expectedFileContent); // construct the folder modifications data - let modifications: any = {}; + const modifications: any = {}; modifications[createdTestData.testDirData.appDestFolderPath] = { filesWithContent: [ { @@ -740,13 +740,13 @@ describe('Platform Service Tests', () => { }); it("should sync new platform specific files (iOS)", async () => { - let applyChangesFn = (createdTestData: CreatedTestData) => { + const applyChangesFn = (createdTestData: CreatedTestData) => { // apply changes const expectedFileContent = "new-content-ios"; fs.writeFile(path.join(createdTestData.testDirData.appFolderPath, "test3.ios.js"), expectedFileContent); // construct the folder modifications data - let modifications: any = {}; + const modifications: any = {}; modifications[path.join(createdTestData.testDirData.appDestFolderPath, "app")] = { filesWithContent: [ { @@ -762,13 +762,13 @@ describe('Platform Service Tests', () => { }); it("should sync new platform specific files (Android)", async () => { - let applyChangesFn = (createdTestData: CreatedTestData) => { + const applyChangesFn = (createdTestData: CreatedTestData) => { // apply changes const expectedFileContent = "new-content-android"; fs.writeFile(path.join(createdTestData.testDirData.appFolderPath, "test3.android.js"), expectedFileContent); // construct the folder modifications data - let modifications: any = {}; + const modifications: any = {}; modifications[path.join(createdTestData.testDirData.appDestFolderPath, "app")] = { filesWithContent: [ { @@ -784,13 +784,13 @@ describe('Platform Service Tests', () => { }); it("should sync new common files (iOS)", async () => { - let applyChangesFn = (createdTestData: CreatedTestData) => { + const applyChangesFn = (createdTestData: CreatedTestData) => { // apply changes const expectedFileContent = "new-content-ios"; fs.writeFile(path.join(createdTestData.testDirData.appFolderPath, "test3.js"), expectedFileContent); // construct the folder modifications data - let modifications: any = {}; + const modifications: any = {}; modifications[path.join(createdTestData.testDirData.appDestFolderPath, "app")] = { filesWithContent: [ { @@ -806,13 +806,13 @@ describe('Platform Service Tests', () => { }); it("should sync new common file (Android)", async () => { - let applyChangesFn = (createdTestData: CreatedTestData) => { + const applyChangesFn = (createdTestData: CreatedTestData) => { // apply changes const expectedFileContent = "new-content-android"; fs.writeFile(path.join(createdTestData.testDirData.appFolderPath, "test3.js"), expectedFileContent); // construct the folder modifications data - let modifications: any = {}; + const modifications: any = {}; modifications[path.join(createdTestData.testDirData.appDestFolderPath, "app")] = { filesWithContent: [ { @@ -829,13 +829,13 @@ describe('Platform Service Tests', () => { it("invalid xml is caught", async () => { require("colors"); - let testDirData = prepareDirStructure(); + const testDirData = prepareDirStructure(); // generate invalid xml - let fileFullPath = path.join(testDirData.appFolderPath, "file.xml"); + const fileFullPath = path.join(testDirData.appFolderPath, "file.xml"); fs.writeFile(fileFullPath, ""); - let platformsData = testInjector.resolve("platformsData"); + const platformsData = testInjector.resolve("platformsData"); platformsData.platformsNames = ["android"]; platformsData.getPlatformData = (platform: string) => { return { @@ -860,11 +860,11 @@ describe('Platform Service Tests', () => { }; }; - let projectData = testInjector.resolve("projectData"); + const projectData = testInjector.resolve("projectData"); projectData.projectDir = testDirData.tempFolder; platformService = testInjector.resolve("platformService"); - let oldLoggerWarner = testInjector.resolve("$logger").warn; + const oldLoggerWarner = testInjector.resolve("$logger").warn; let warnings: string = ""; try { testInjector.resolve("$logger").warn = (text: string) => warnings += text; diff --git a/test/plugin-variables-service.ts b/test/plugin-variables-service.ts index 3576c4d284..2beb1737e0 100644 --- a/test/plugin-variables-service.ts +++ b/test/plugin-variables-service.ts @@ -17,7 +17,7 @@ import * as temp from "temp"; temp.track(); function createTestInjector(): IInjector { - let testInjector = new Yok(); + const testInjector = new Yok(); testInjector.register("messagesService", MessagesService); testInjector.register("errors", Errors); @@ -32,7 +32,7 @@ function createTestInjector(): IInjector { testInjector.register("projectHelper", ProjectHelper); testInjector.register("prompter", { get: () => { - let errors: IErrors = testInjector.resolve("errors"); + const errors: IErrors = testInjector.resolve("errors"); errors.fail("$prompter.get function shouldn't be called!"); } }); @@ -42,12 +42,12 @@ function createTestInjector(): IInjector { } async function createProjectFile(testInjector: IInjector): Promise { - let tempFolder = temp.mkdirSync("pluginVariablesService"); + const tempFolder = temp.mkdirSync("pluginVariablesService"); - let options = testInjector.resolve("options"); + const options = testInjector.resolve("options"); options.path = tempFolder; - let projectData = { + const projectData = { "name": "myProject", "nativescript": {} }; @@ -57,7 +57,7 @@ async function createProjectFile(testInjector: IInjector): Promise { } function createPluginData(pluginVariables: any): IPluginData { - let pluginData = { + const pluginData = { name: "myTestPlugin", version: "", fullPath: "", @@ -82,19 +82,19 @@ describe("Plugin Variables service", () => { describe("plugin add when the console is non interactive", () => { beforeEach(() => { - let helpers = require("./../lib/common/helpers"); + const helpers = require("./../lib/common/helpers"); helpers.isInteractive = () => false; }); it("fails when no --var option and no default value are specified", async () => { await createProjectFile(testInjector); - let pluginVariables = { "MY_TEST_PLUGIN_VARIABLE": {} }; - let pluginData = createPluginData(pluginVariables); - let pluginVariablesService: IPluginVariablesService = testInjector.resolve("pluginVariablesService"); - let projectData: IProjectData = testInjector.resolve("projectData"); + const pluginVariables = { "MY_TEST_PLUGIN_VARIABLE": {} }; + const pluginData = createPluginData(pluginVariables); + const pluginVariablesService: IPluginVariablesService = testInjector.resolve("pluginVariablesService"); + const projectData: IProjectData = testInjector.resolve("projectData"); projectData.initializeProjectData(); - let expectedError = `Unable to find value for MY_TEST_PLUGIN_VARIABLE plugin variable from ${pluginData.name} plugin. Ensure the --var option is specified or the plugin variable has default value.`; + const expectedError = `Unable to find value for MY_TEST_PLUGIN_VARIABLE plugin variable from ${pluginData.name} plugin. Ensure the --var option is specified or the plugin variable has default value.`; let actualError: string = null; try { @@ -108,126 +108,126 @@ describe("Plugin Variables service", () => { it("does not fail when --var option is specified", async () => { await createProjectFile(testInjector); - let pluginVariableValue = "myAppId"; + const pluginVariableValue = "myAppId"; testInjector.resolve("options").var = { "MY_APP_ID": pluginVariableValue }; - let pluginVariables = { "MY_APP_ID": {} }; - let pluginData = createPluginData(pluginVariables); - let pluginVariablesService: IPluginVariablesService = testInjector.resolve("pluginVariablesService"); - let projectData: IProjectData = testInjector.resolve("projectData"); + const pluginVariables = { "MY_APP_ID": {} }; + const pluginData = createPluginData(pluginVariables); + const pluginVariablesService: IPluginVariablesService = testInjector.resolve("pluginVariablesService"); + const projectData: IProjectData = testInjector.resolve("projectData"); projectData.initializeProjectData(); await pluginVariablesService.savePluginVariablesInProjectFile(pluginData, projectData); - let fs = testInjector.resolve("fs"); - let staticConfig: IStaticConfig = testInjector.resolve("staticConfig"); + const fs = testInjector.resolve("fs"); + const staticConfig: IStaticConfig = testInjector.resolve("staticConfig"); - let projectFileContent = fs.readJson(path.join(projectData.projectDir, "package.json")); + const projectFileContent = fs.readJson(path.join(projectData.projectDir, "package.json")); assert.equal(pluginVariableValue, projectFileContent[staticConfig.CLIENT_NAME_KEY_IN_PROJECT_FILE][`${pluginData.name}-variables`]["MY_APP_ID"]); }); it("does not fail when default value is specified", async () => { await createProjectFile(testInjector); - let defaultPluginValue = "myDefaultValue"; - let pluginVariables = { "MY_TEST_PLUGIN_VARIABLE": { defaultValue: defaultPluginValue } }; - let pluginData = createPluginData(pluginVariables); - let pluginVariablesService: IPluginVariablesService = testInjector.resolve("pluginVariablesService"); - let projectData = testInjector.resolve("projectData"); + const defaultPluginValue = "myDefaultValue"; + const pluginVariables = { "MY_TEST_PLUGIN_VARIABLE": { defaultValue: defaultPluginValue } }; + const pluginData = createPluginData(pluginVariables); + const pluginVariablesService: IPluginVariablesService = testInjector.resolve("pluginVariablesService"); + const projectData = testInjector.resolve("projectData"); projectData.initializeProjectData(); await pluginVariablesService.savePluginVariablesInProjectFile(pluginData, projectData); - let fs = testInjector.resolve("fs"); - let staticConfig: IStaticConfig = testInjector.resolve("staticConfig"); + const fs = testInjector.resolve("fs"); + const staticConfig: IStaticConfig = testInjector.resolve("staticConfig"); - let projectFileContent = fs.readJson(path.join(projectData.projectDir, "package.json")); + const projectFileContent = fs.readJson(path.join(projectData.projectDir, "package.json")); assert.equal(defaultPluginValue, projectFileContent[staticConfig.CLIENT_NAME_KEY_IN_PROJECT_FILE][`${pluginData.name}-variables`]["MY_TEST_PLUGIN_VARIABLE"]); }); }); describe("plugin add when the console is interactive", () => { beforeEach(() => { - let helpers = require("./../lib/common/helpers"); + const helpers = require("./../lib/common/helpers"); helpers.isInteractive = () => true; }); it("prompt for plugin variable value when no --var option and no default value are specified", async () => { await createProjectFile(testInjector); - let pluginVariableValue = "testAppURL"; - let prompter = testInjector.resolve("prompter"); + const pluginVariableValue = "testAppURL"; + const prompter = testInjector.resolve("prompter"); prompter.get = async () => ({ "APP_URL": pluginVariableValue }); - let pluginVariables = { "APP_URL": {} }; - let pluginData = createPluginData(pluginVariables); - let pluginVariablesService: IPluginVariablesService = testInjector.resolve("pluginVariablesService"); - let projectData = testInjector.resolve("projectData"); + const pluginVariables = { "APP_URL": {} }; + const pluginData = createPluginData(pluginVariables); + const pluginVariablesService: IPluginVariablesService = testInjector.resolve("pluginVariablesService"); + const projectData = testInjector.resolve("projectData"); projectData.initializeProjectData(); await pluginVariablesService.savePluginVariablesInProjectFile(pluginData, projectData); - let fs = testInjector.resolve("fs"); - let staticConfig: IStaticConfig = testInjector.resolve("staticConfig"); + const fs = testInjector.resolve("fs"); + const staticConfig: IStaticConfig = testInjector.resolve("staticConfig"); - let projectFileContent = fs.readJson(path.join(projectData.projectDir, "package.json")); + const projectFileContent = fs.readJson(path.join(projectData.projectDir, "package.json")); assert.equal(pluginVariableValue, projectFileContent[staticConfig.CLIENT_NAME_KEY_IN_PROJECT_FILE][`${pluginData.name}-variables`]["APP_URL"]); }); it("does not prompt for plugin variable value when default value is specified", async () => { await createProjectFile(testInjector); - let defaultPluginValue = "myAppNAme"; - let pluginVariables = { "APP_NAME": { defaultValue: defaultPluginValue } }; - let pluginData = createPluginData(pluginVariables); - let pluginVariablesService: IPluginVariablesService = testInjector.resolve("pluginVariablesService"); - let projectData = testInjector.resolve("projectData"); + const defaultPluginValue = "myAppNAme"; + const pluginVariables = { "APP_NAME": { defaultValue: defaultPluginValue } }; + const pluginData = createPluginData(pluginVariables); + const pluginVariablesService: IPluginVariablesService = testInjector.resolve("pluginVariablesService"); + const projectData = testInjector.resolve("projectData"); projectData.initializeProjectData(); await pluginVariablesService.savePluginVariablesInProjectFile(pluginData, projectData); - let fs = testInjector.resolve("fs"); - let staticConfig: IStaticConfig = testInjector.resolve("staticConfig"); + const fs = testInjector.resolve("fs"); + const staticConfig: IStaticConfig = testInjector.resolve("staticConfig"); - let projectFileContent = fs.readJson(path.join(projectData.projectDir, "package.json")); + const projectFileContent = fs.readJson(path.join(projectData.projectDir, "package.json")); assert.equal(defaultPluginValue, projectFileContent[staticConfig.CLIENT_NAME_KEY_IN_PROJECT_FILE][`${pluginData.name}-variables`]["APP_NAME"]); }); it("does not prompt for plugin variable value when --var option is specified", async () => { await createProjectFile(testInjector); - let pluginVariableValue = "pencho.goshko"; + const pluginVariableValue = "pencho.goshko"; testInjector.resolve("options").var = { "USERNAME": pluginVariableValue }; - let pluginVariables = { "USERNAME": {} }; - let pluginData = createPluginData(pluginVariables); - let pluginVariablesService: IPluginVariablesService = testInjector.resolve("pluginVariablesService"); - let projectData = testInjector.resolve("projectData"); + const pluginVariables = { "USERNAME": {} }; + const pluginData = createPluginData(pluginVariables); + const pluginVariablesService: IPluginVariablesService = testInjector.resolve("pluginVariablesService"); + const projectData = testInjector.resolve("projectData"); projectData.initializeProjectData(); await pluginVariablesService.savePluginVariablesInProjectFile(pluginData, projectData); - let fs = testInjector.resolve("fs"); - let staticConfig: IStaticConfig = testInjector.resolve("staticConfig"); + const fs = testInjector.resolve("fs"); + const staticConfig: IStaticConfig = testInjector.resolve("staticConfig"); - let projectFileContent = fs.readJson(path.join(projectData.projectDir, "package.json")); + const projectFileContent = fs.readJson(path.join(projectData.projectDir, "package.json")); assert.equal(pluginVariableValue, projectFileContent[staticConfig.CLIENT_NAME_KEY_IN_PROJECT_FILE][`${pluginData.name}-variables`]["USERNAME"]); }); }); describe("plugin interpolation", () => { it("fails when the plugin value is undefined", async () => { - let tempFolder = await createProjectFile(testInjector); + const tempFolder = await createProjectFile(testInjector); - let pluginVariables = { "MY_VAR": {} }; - let pluginData = createPluginData(pluginVariables); + const pluginVariables = { "MY_VAR": {} }; + const pluginData = createPluginData(pluginVariables); - let fs: IFileSystem = testInjector.resolve("fs"); - let filePath = path.join(tempFolder, "myfile"); + const fs: IFileSystem = testInjector.resolve("fs"); + const filePath = path.join(tempFolder, "myfile"); fs.writeFile(filePath, ""); - let pluginVariablesService: IPluginVariablesService = testInjector.resolve("pluginVariablesService"); - let projectData = testInjector.resolve("projectData"); + const pluginVariablesService: IPluginVariablesService = testInjector.resolve("pluginVariablesService"); + const projectData = testInjector.resolve("projectData"); projectData.initializeProjectData(); - let expectedError = "Unable to find the value for MY_VAR plugin variable into project package.json file. Verify that your package.json file is correct and try again."; + const expectedError = "Unable to find the value for MY_VAR plugin variable into project package.json file. Verify that your package.json file is correct and try again."; let error: string = null; try { await pluginVariablesService.interpolatePluginVariables(pluginData, filePath, projectData); @@ -239,36 +239,36 @@ describe("Plugin Variables service", () => { }); it("interpolates correctly plugin variable value", async () => { - let tempFolder = await createProjectFile(testInjector); + const tempFolder = await createProjectFile(testInjector); - let projectData: IProjectData = testInjector.resolve("projectData"); + const projectData: IProjectData = testInjector.resolve("projectData"); projectData.initializeProjectData(); - let fs: IFileSystem = testInjector.resolve("fs"); + const fs: IFileSystem = testInjector.resolve("fs"); // Write plugin variables values to package.json file - let packageJsonFilePath = path.join(projectData.projectDir, "package.json"); - let data = fs.readJson(packageJsonFilePath); + const packageJsonFilePath = path.join(projectData.projectDir, "package.json"); + const data = fs.readJson(packageJsonFilePath); data["nativescript"]["myTestPlugin-variables"] = { "FB_APP_NAME": "myFacebookAppName" }; fs.writeJson(packageJsonFilePath, data); - let pluginVariables = { "FB_APP_NAME": {} }; - let pluginData = createPluginData(pluginVariables); - let pluginVariablesService: IPluginVariablesService = testInjector.resolve("pluginVariablesService"); - let pluginConfigurationFileContent = '' + + const pluginVariables = { "FB_APP_NAME": {} }; + const pluginData = createPluginData(pluginVariables); + const pluginVariablesService: IPluginVariablesService = testInjector.resolve("pluginVariablesService"); + const pluginConfigurationFileContent = '' + '' + '' + '' + '' + ''; - let filePath = path.join(tempFolder, "myfile"); + const filePath = path.join(tempFolder, "myfile"); fs.writeFile(filePath, pluginConfigurationFileContent); await pluginVariablesService.interpolatePluginVariables(pluginData, filePath, projectData); - let result = fs.readText(filePath); - let expectedResult = '' + + const result = fs.readText(filePath); + const expectedResult = '' + '' + '' + '' + @@ -279,36 +279,36 @@ describe("Plugin Variables service", () => { }); it("interpolates correctly case sensive plugin variable value", async () => { - let tempFolder = await createProjectFile(testInjector); + const tempFolder = await createProjectFile(testInjector); - let projectData: IProjectData = testInjector.resolve("projectData"); + const projectData: IProjectData = testInjector.resolve("projectData"); projectData.initializeProjectData(); - let fs: IFileSystem = testInjector.resolve("fs"); + const fs: IFileSystem = testInjector.resolve("fs"); // Write plugin variables values to package.json file - let packageJsonFilePath = path.join(projectData.projectDir, "package.json"); - let data = fs.readJson(packageJsonFilePath); + const packageJsonFilePath = path.join(projectData.projectDir, "package.json"); + const data = fs.readJson(packageJsonFilePath); data["nativescript"]["myTestPlugin-variables"] = { "FB_APP_NAME": "myFacebookAppName" }; fs.writeJson(packageJsonFilePath, data); - let pluginVariables = { "FB_APP_NAME": {} }; - let pluginData = createPluginData(pluginVariables); - let pluginVariablesService: IPluginVariablesService = testInjector.resolve("pluginVariablesService"); - let pluginConfigurationFileContent = '' + + const pluginVariables = { "FB_APP_NAME": {} }; + const pluginData = createPluginData(pluginVariables); + const pluginVariablesService: IPluginVariablesService = testInjector.resolve("pluginVariablesService"); + const pluginConfigurationFileContent = '' + '' + '' + '' + '' + ''; - let filePath = path.join(tempFolder, "myfile"); + const filePath = path.join(tempFolder, "myfile"); fs.writeFile(filePath, pluginConfigurationFileContent); await pluginVariablesService.interpolatePluginVariables(pluginData, filePath, projectData); - let result = fs.readText(filePath); - let expectedResult = '' + + const result = fs.readText(filePath); + const expectedResult = '' + '' + '' + '' + @@ -319,37 +319,37 @@ describe("Plugin Variables service", () => { }); it("interpolates correctly more than one plugin variables values", async () => { - let tempFolder = await createProjectFile(testInjector); + const tempFolder = await createProjectFile(testInjector); - let projectData: IProjectData = testInjector.resolve("projectData"); + const projectData: IProjectData = testInjector.resolve("projectData"); projectData.initializeProjectData(); - let fs: IFileSystem = testInjector.resolve("fs"); + const fs: IFileSystem = testInjector.resolve("fs"); - let packageJsonFilePath = path.join(projectData.projectDir, "package.json"); - let data = fs.readJson(packageJsonFilePath); + const packageJsonFilePath = path.join(projectData.projectDir, "package.json"); + const data = fs.readJson(packageJsonFilePath); data["nativescript"]["myTestPlugin-variables"] = { "FB_APP_NAME": "myFacebookAppName", "FB_APP_URL": "myFacebookAppURl" }; fs.writeJson(packageJsonFilePath, data); - let pluginVariables = { "FB_APP_NAME": {}, "FB_APP_URL": {} }; - let pluginData = createPluginData(pluginVariables); - let pluginVariablesService: IPluginVariablesService = testInjector.resolve("pluginVariablesService"); - let pluginConfigurationFileContent = '' + + const pluginVariables = { "FB_APP_NAME": {}, "FB_APP_URL": {} }; + const pluginData = createPluginData(pluginVariables); + const pluginVariablesService: IPluginVariablesService = testInjector.resolve("pluginVariablesService"); + const pluginConfigurationFileContent = '' + '' + '' + '' + '' + '' + ''; - let filePath = path.join(tempFolder, "myfile"); + const filePath = path.join(tempFolder, "myfile"); fs.writeFile(filePath, pluginConfigurationFileContent); await pluginVariablesService.interpolatePluginVariables(pluginData, filePath, projectData); - let result = fs.readText(filePath); - let expectedResult = '' + + const result = fs.readText(filePath); + const expectedResult = '' + '' + '' + '' + diff --git a/test/plugins-service.ts b/test/plugins-service.ts index 2744d5f055..57533401b3 100644 --- a/test/plugins-service.ts +++ b/test/plugins-service.ts @@ -38,7 +38,7 @@ temp.track(); let isErrorThrown = false; function createTestInjector() { - let testInjector = new Yok(); + const testInjector = new Yok(); testInjector.register("messagesService", MessagesService); testInjector.register("npm", NodePackageManager); testInjector.register("fs", FileSystem); @@ -101,11 +101,11 @@ function createTestInjector() { } function createProjectFile(testInjector: IInjector): string { - let tempFolder = temp.mkdirSync("pluginsService"); - let options = testInjector.resolve("options"); + const tempFolder = temp.mkdirSync("pluginsService"); + const options = testInjector.resolve("options"); options.path = tempFolder; - let packageJsonData = { + const packageJsonData = { "name": "testModuleName", "version": "0.1.0", "nativescript": { @@ -121,7 +121,7 @@ function createProjectFile(testInjector: IInjector): string { } function mockBeginCommand(testInjector: IInjector, expectedErrorMessage: string) { - let errors = testInjector.resolve("errors"); + const errors = testInjector.resolve("errors"); errors.beginCommand = async (action: () => Promise): Promise => { try { return await action(); @@ -135,7 +135,7 @@ function mockBeginCommand(testInjector: IInjector, expectedErrorMessage: string) async function addPluginWhenExpectingToFail(testInjector: IInjector, plugin: string, expectedErrorMessage: string, command?: string) { createProjectFile(testInjector); - let pluginsService: IPluginsService = testInjector.resolve("pluginsService"); + const pluginsService: IPluginsService = testInjector.resolve("pluginsService"); pluginsService.getAllInstalledPlugins = async (projectData: IProjectData) => { return [{ name: "" }]; }; @@ -146,14 +146,14 @@ async function addPluginWhenExpectingToFail(testInjector: IInjector, plugin: str mockBeginCommand(testInjector, "Exception: " + expectedErrorMessage); isErrorThrown = false; - let commandsService = testInjector.resolve(CommandsService); + const commandsService = testInjector.resolve(CommandsService); await commandsService.tryExecuteCommand(`plugin|${command}`, [plugin]); assert.isTrue(isErrorThrown); } function createAndroidManifestFile(projectFolder: string, fs: IFileSystem): void { - let manifest = ` + const manifest = ` @@ -179,7 +179,7 @@ function createAndroidManifestFile(projectFolder: string, fs: IFileSystem): void describe("Plugins service", () => { let testInjector: IInjector; - let commands = ["add", "install"]; + const commands = ["add", "install"]; beforeEach(() => { testInjector = createTestInjector(); testInjector.registerCommand("plugin|add", AddPluginCommand); @@ -195,18 +195,18 @@ describe("Plugins service", () => { await addPluginWhenExpectingToFail(testInjector, "lodash", "lodash is not a valid NativeScript plugin. Verify that the plugin package.json file contains a nativescript key and try again.", command); }); it("fails when the plugin is already installed", async () => { - let pluginName = "plugin1"; - let projectFolder = createProjectFile(testInjector); - let fs = testInjector.resolve("fs"); + const pluginName = "plugin1"; + const projectFolder = createProjectFile(testInjector); + const fs = testInjector.resolve("fs"); // Add plugin - let projectFilePath = path.join(projectFolder, "package.json"); - let projectData = require(projectFilePath); + const projectFilePath = path.join(projectFolder, "package.json"); + const projectData = require(projectFilePath); projectData.dependencies = {}; projectData.dependencies[pluginName] = "^1.0.0"; fs.writeJson(projectFilePath, projectData); - let pluginsService: IPluginsService = testInjector.resolve("pluginsService"); + const pluginsService: IPluginsService = testInjector.resolve("pluginsService"); pluginsService.getAllInstalledPlugins = async (projData: IProjectData) => { return [{ name: "plugin1" }]; }; @@ -214,20 +214,20 @@ describe("Plugins service", () => { mockBeginCommand(testInjector, "Exception: " + 'Plugin "plugin1" is already installed.'); isErrorThrown = false; - let commandsService = testInjector.resolve(CommandsService); + const commandsService = testInjector.resolve(CommandsService); await commandsService.tryExecuteCommand(`plugin|${command}`, [pluginName]); assert.isTrue(isErrorThrown); }); it("fails when the plugin does not support the installed framework", async () => { let isWarningMessageShown = false; - let expectedWarningMessage = "mySamplePlugin 1.5.0 for android is not compatible with the currently installed framework version 1.4.0."; + const expectedWarningMessage = "mySamplePlugin 1.5.0 for android is not compatible with the currently installed framework version 1.4.0."; // Creates plugin in temp folder - let pluginName = "mySamplePlugin"; - let projectFolder = createProjectFile(testInjector); - let pluginFolderPath = path.join(projectFolder, pluginName); - let pluginJsonData = { + const pluginName = "mySamplePlugin"; + const projectFolder = createProjectFile(testInjector); + const pluginFolderPath = path.join(projectFolder, pluginName); + const pluginJsonData = { "name": pluginName, "version": "0.0.1", "nativescript": { @@ -236,7 +236,7 @@ describe("Plugins service", () => { } }, }; - let fs = testInjector.resolve("fs"); + const fs = testInjector.resolve("fs"); fs.writeJson(path.join(pluginFolderPath, "package.json"), pluginJsonData); // Adds android platform @@ -245,22 +245,22 @@ describe("Plugins service", () => { fs.createDirectory(path.join(projectFolder, "platforms", "android", "app")); // Mock logger.warn - let logger = testInjector.resolve("logger"); + const logger = testInjector.resolve("logger"); logger.warn = (message: string) => { assert.equal(message, expectedWarningMessage); isWarningMessageShown = true; }; // Mock pluginsService - let pluginsService: IPluginsService = testInjector.resolve("pluginsService"); - let projectData: IProjectData = testInjector.resolve("projectData"); + const pluginsService: IPluginsService = testInjector.resolve("pluginsService"); + const projectData: IProjectData = testInjector.resolve("projectData"); projectData.initializeProjectData(); pluginsService.getAllInstalledPlugins = async (projData: IProjectData) => { return [{ name: "" }]; }; // Mock platformsData - let platformsData = testInjector.resolve("platformsData"); + const platformsData = testInjector.resolve("platformsData"); platformsData.getPlatformData = (platform: string) => { return { appDestinationDirectoryPath: path.join(projectFolder, "platforms", "android"), @@ -274,77 +274,77 @@ describe("Plugins service", () => { assert.isTrue(isWarningMessageShown); }); it("adds plugin by name", async () => { - let pluginName = "plugin1"; - let projectFolder = createProjectFile(testInjector); + const pluginName = "plugin1"; + const projectFolder = createProjectFile(testInjector); - let pluginsService: IPluginsService = testInjector.resolve("pluginsService"); + const pluginsService: IPluginsService = testInjector.resolve("pluginsService"); pluginsService.getAllInstalledPlugins = async (projectData: IProjectData) => { return [{ name: "" }]; }; - let commandsService = testInjector.resolve(CommandsService); + const commandsService = testInjector.resolve(CommandsService); await commandsService.tryExecuteCommand(`plugin|${command}`, [pluginName]); - let fs = testInjector.resolve("fs"); + const fs = testInjector.resolve("fs"); // Asserts that the all plugin's content is successfully added to node_modules folder - let nodeModulesFolderPath = path.join(projectFolder, "node_modules"); + const nodeModulesFolderPath = path.join(projectFolder, "node_modules"); assert.isTrue(fs.exists(nodeModulesFolderPath)); - let pluginFolderPath = path.join(nodeModulesFolderPath, pluginName); + const pluginFolderPath = path.join(nodeModulesFolderPath, pluginName); assert.isTrue(fs.exists(pluginFolderPath)); - let pluginFiles = ["injex.js", "main.js", "package.json"]; + const pluginFiles = ["injex.js", "main.js", "package.json"]; _.each(pluginFiles, pluginFile => { assert.isTrue(fs.exists(path.join(pluginFolderPath, pluginFile))); }); // Asserts that the plugin is added in package.json file - let packageJsonContent = fs.readJson(path.join(projectFolder, "package.json")); - let actualDependencies = packageJsonContent.dependencies; - let expectedDependencies = { "plugin1": "^1.0.3" }; - let expectedDependenciesExact = { "plugin1": "1.0.3" }; + const packageJsonContent = fs.readJson(path.join(projectFolder, "package.json")); + const actualDependencies = packageJsonContent.dependencies; + const expectedDependencies = { "plugin1": "^1.0.3" }; + const expectedDependenciesExact = { "plugin1": "1.0.3" }; assert.isTrue(_.isEqual(actualDependencies, expectedDependencies) || _.isEqual(actualDependencies, expectedDependenciesExact)); }); it("adds plugin by name and version", async () => { - let pluginName = "plugin1"; - let projectFolder = createProjectFile(testInjector); + const pluginName = "plugin1"; + const projectFolder = createProjectFile(testInjector); - let pluginsService: IPluginsService = testInjector.resolve("pluginsService"); + const pluginsService: IPluginsService = testInjector.resolve("pluginsService"); pluginsService.getAllInstalledPlugins = async (projectData: IProjectData) => { return [{ name: "" }]; }; - let commandsService = testInjector.resolve(CommandsService); + const commandsService = testInjector.resolve(CommandsService); await commandsService.tryExecuteCommand(`plugin|${command}`, [pluginName + "@1.0.0"]); - let fs = testInjector.resolve("fs"); + const fs = testInjector.resolve("fs"); // Assert that the all plugin's content is successfully added to node_modules folder - let nodeModulesFolderPath = path.join(projectFolder, "node_modules"); + const nodeModulesFolderPath = path.join(projectFolder, "node_modules"); assert.isTrue(fs.exists(nodeModulesFolderPath)); - let pluginFolderPath = path.join(nodeModulesFolderPath, pluginName); + const pluginFolderPath = path.join(nodeModulesFolderPath, pluginName); assert.isTrue(fs.exists(pluginFolderPath)); - let pluginFiles = ["injex.js", "main.js", "package.json"]; + const pluginFiles = ["injex.js", "main.js", "package.json"]; _.each(pluginFiles, pluginFile => { assert.isTrue(fs.exists(path.join(pluginFolderPath, pluginFile))); }); // Assert that the plugin is added in package.json file - let packageJsonContent = fs.readJson(path.join(projectFolder, "package.json")); - let actualDependencies = packageJsonContent.dependencies; - let expectedDependencies = { "plugin1": "^1.0.0" }; - let expectedDependenciesExact = { "plugin1": "1.0.0" }; + const packageJsonContent = fs.readJson(path.join(projectFolder, "package.json")); + const actualDependencies = packageJsonContent.dependencies; + const expectedDependencies = { "plugin1": "^1.0.0" }; + const expectedDependenciesExact = { "plugin1": "1.0.0" }; assert.isTrue(_.isEqual(actualDependencies, expectedDependencies) || _.isEqual(actualDependencies, expectedDependenciesExact)); }); it("adds plugin by local path", async () => { // Creates a plugin in tempFolder - let pluginName = "mySamplePlugin"; - let projectFolder = createProjectFile(testInjector); - let pluginFolderPath = path.join(projectFolder, pluginName); - let pluginJsonData = { + const pluginName = "mySamplePlugin"; + const projectFolder = createProjectFile(testInjector); + const pluginFolderPath = path.join(projectFolder, pluginName); + const pluginJsonData = { "name": pluginName, "version": "0.0.1", "nativescript": { @@ -353,23 +353,23 @@ describe("Plugins service", () => { } }, }; - let fs = testInjector.resolve("fs"); + const fs = testInjector.resolve("fs"); fs.writeJson(path.join(pluginFolderPath, "package.json"), pluginJsonData); - let pluginsService: IPluginsService = testInjector.resolve("pluginsService"); + const pluginsService: IPluginsService = testInjector.resolve("pluginsService"); pluginsService.getAllInstalledPlugins = async (projectData: IProjectData) => { return [{ name: "" }]; }; - let commandsService = testInjector.resolve(CommandsService); + const commandsService = testInjector.resolve(CommandsService); await commandsService.tryExecuteCommand(`plugin|${command}`, [pluginFolderPath]); // Assert that the all plugin's content is successfully added to node_modules folder - let nodeModulesFolderPath = path.join(projectFolder, "node_modules"); + const nodeModulesFolderPath = path.join(projectFolder, "node_modules"); assert.isTrue(fs.exists(nodeModulesFolderPath)); assert.isTrue(fs.exists(path.join(nodeModulesFolderPath, pluginName))); - let pluginFiles = ["package.json"]; + const pluginFiles = ["package.json"]; _.each(pluginFiles, pluginFile => { assert.isTrue(fs.exists(path.join(nodeModulesFolderPath, pluginName, pluginFile))); }); @@ -379,10 +379,10 @@ describe("Plugins service", () => { }); it("doesn't install dev dependencies when --production option is specified", async () => { // Creates a plugin in tempFolder - let pluginName = "mySamplePlugin"; - let projectFolder = createProjectFile(testInjector); - let pluginFolderPath = path.join(projectFolder, pluginName); - let pluginJsonData = { + const pluginName = "mySamplePlugin"; + const projectFolder = createProjectFile(testInjector); + const pluginFolderPath = path.join(projectFolder, pluginName); + const pluginJsonData = { "name": pluginName, "version": "0.0.1", "nativescript": { @@ -394,30 +394,30 @@ describe("Plugins service", () => { "grunt": "0.4.2" } }; - let fs = testInjector.resolve("fs"); + const fs = testInjector.resolve("fs"); fs.writeJson(path.join(pluginFolderPath, "package.json"), pluginJsonData); - let pluginsService: IPluginsService = testInjector.resolve("pluginsService"); + const pluginsService: IPluginsService = testInjector.resolve("pluginsService"); pluginsService.getAllInstalledPlugins = async (projectData: IProjectData) => { return [{ name: "" }]; }; // Mock options - let options = testInjector.resolve("options"); + const options = testInjector.resolve("options"); options.production = true; - let commandsService = testInjector.resolve(CommandsService); + const commandsService = testInjector.resolve(CommandsService); await commandsService.tryExecuteCommand(`plugin|${command}`, [pluginFolderPath]); - let nodeModulesFolderPath = path.join(projectFolder, "node_modules"); + const nodeModulesFolderPath = path.join(projectFolder, "node_modules"); assert.isFalse(fs.exists(path.join(nodeModulesFolderPath, pluginName, "node_modules", "grunt"))); }); it("install dev dependencies when --production option is not specified", async () => { // Creates a plugin in tempFolder - let pluginName = "mySamplePlugin"; - let projectFolder = createProjectFile(testInjector); - let pluginFolderPath = path.join(projectFolder, pluginName); - let pluginJsonData = { + const pluginName = "mySamplePlugin"; + const projectFolder = createProjectFile(testInjector); + const pluginFolderPath = path.join(projectFolder, pluginName); + const pluginJsonData = { "name": pluginName, "version": "0.0.1", "nativescript": { @@ -432,19 +432,19 @@ describe("Plugins service", () => { "grunt": "0.4.2" } }; - let fs = testInjector.resolve("fs"); + const fs = testInjector.resolve("fs"); fs.writeJson(path.join(pluginFolderPath, "package.json"), pluginJsonData); - let pluginsService: IPluginsService = testInjector.resolve("pluginsService"); + const pluginsService: IPluginsService = testInjector.resolve("pluginsService"); pluginsService.getAllInstalledPlugins = async (projectData: IProjectData) => { return [{ name: "" }]; }; // Mock options - let options = testInjector.resolve("options"); + const options = testInjector.resolve("options"); options.production = false; - let commandsService = testInjector.resolve(CommandsService); + const commandsService = testInjector.resolve(CommandsService); await commandsService.tryExecuteCommand(`plugin|${command}`, [pluginFolderPath]); }); }); @@ -456,10 +456,10 @@ describe("Plugins service", () => { testInjector.registerCommand("plugin|add", AddPluginCommand); }); it("fails if the plugin contains incorrect xml", async () => { - let pluginName = "mySamplePlugin"; - let projectFolder = createProjectFile(testInjector); - let pluginFolderPath = path.join(projectFolder, pluginName); - let pluginJsonData: IDependencyData = { + const pluginName = "mySamplePlugin"; + const projectFolder = createProjectFile(testInjector); + const pluginFolderPath = path.join(projectFolder, pluginName); + const pluginJsonData: IDependencyData = { name: pluginName, nativescript: { platforms: { @@ -469,22 +469,22 @@ describe("Plugins service", () => { depth: 0, directory: "some dir" }; - let fs = testInjector.resolve("fs"); + const fs = testInjector.resolve("fs"); fs.writeJson(path.join(pluginFolderPath, "package.json"), pluginJsonData); // Adds AndroidManifest.xml file in platforms/android folder createAndroidManifestFile(projectFolder, fs); // Mock plugins service - let pluginsService: IPluginsService = testInjector.resolve("pluginsService"); + const pluginsService: IPluginsService = testInjector.resolve("pluginsService"); pluginsService.getAllInstalledPlugins = async (projectData: IProjectData) => { return [{ name: "" }]; }; - let appDestinationDirectoryPath = path.join(projectFolder, "platforms", "android"); + const appDestinationDirectoryPath = path.join(projectFolder, "platforms", "android"); // Mock platformsData - let platformsData = testInjector.resolve("platformsData"); + const platformsData = testInjector.resolve("platformsData"); platformsData.getPlatformData = (platform: string) => { return { appDestinationDirectoryPath: appDestinationDirectoryPath, @@ -498,20 +498,20 @@ describe("Plugins service", () => { }; // Ensure the pluginDestinationPath folder exists - let pluginPlatformsDirPath = path.join(projectFolder, "node_modules", pluginName, "platforms", "android"); - let projectData: IProjectData = testInjector.resolve("projectData"); + const pluginPlatformsDirPath = path.join(projectFolder, "node_modules", pluginName, "platforms", "android"); + const projectData: IProjectData = testInjector.resolve("projectData"); projectData.initializeProjectData(); fs.ensureDirectoryExists(pluginPlatformsDirPath); // Creates invalid plugin's AndroidManifest.xml file - let xml = '' + + const xml = '' + '' + ''; - let pluginConfigurationFilePath = path.join(pluginPlatformsDirPath, "AndroidManifest.xml"); + const pluginConfigurationFilePath = path.join(pluginPlatformsDirPath, "AndroidManifest.xml"); fs.writeFile(pluginConfigurationFilePath, xml); // Expected error message. The assertion happens in mockBeginCommand - let expectedErrorMessage = `Exception: Invalid xml file ${pluginConfigurationFilePath}. Additional technical information: element parse error: Exception: Invalid xml file ` + + const expectedErrorMessage = `Exception: Invalid xml file ${pluginConfigurationFilePath}. Additional technical information: element parse error: Exception: Invalid xml file ` + `${pluginConfigurationFilePath}. Additional technical information: unclosed xml attribute` + `\n@#[line:1,col:39].` + `\n@#[line:1,col:39].`; diff --git a/test/post-install.ts b/test/post-install.ts index 2df08117b8..7f2f98bd7a 100644 --- a/test/post-install.ts +++ b/test/post-install.ts @@ -1,7 +1,7 @@ import { assert } from "chai"; // Use require instead of import in order to replace the `spawn` method of child_process -let childProcess = require("child_process"); +const childProcess = require("child_process"); import { SpawnOptions, ChildProcess } from "child_process"; import * as path from "path"; diff --git a/test/project-changes-service.ts b/test/project-changes-service.ts index f4b091bb73..47e8451bdd 100644 --- a/test/project-changes-service.ts +++ b/test/project-changes-service.ts @@ -91,8 +91,8 @@ describe("Project Changes Service Tests", () => { describe("Get Prepare Info File Path", () => { it("Gets the correct Prepare Info path for ios/android", () => { - for (let platform of ["ios", "android"]) { - let actualPrepareInfoPath = serviceTest.projectChangesService + for (const platform of ["ios", "android"]) { + const actualPrepareInfoPath = serviceTest.projectChangesService .getPrepareInfoFilePath(platform, this.projectData); const expectedPrepareInfoPath = path.join(serviceTest.projectDir, @@ -106,8 +106,8 @@ describe("Project Changes Service Tests", () => { describe("Get Prepare Info", () => { it("Returns empty if file path doesn't exists", () => { - for (let platform of ["ios", "android"]) { - let projectInfo = serviceTest.projectChangesService.getPrepareInfo(platform, this.projectData); + for (const platform of ["ios", "android"]) { + const projectInfo = serviceTest.projectChangesService.getPrepareInfo(platform, this.projectData); assert.isNull(projectInfo); } @@ -115,7 +115,7 @@ describe("Project Changes Service Tests", () => { it("Reads the Prepare Info correctly", () => { const fs: FileSystem = serviceTest.resolve("fs"); - for (let platform of ["ios", "android"]) { + for (const platform of ["ios", "android"]) { // arrange const prepareInfoPath = path.join(serviceTest.projectDir, Constants.PLATFORMS_DIR_NAME, platform, ".nsprepareinfo"); @@ -132,7 +132,7 @@ describe("Project Changes Service Tests", () => { fs.writeJson(prepareInfoPath, expectedPrepareInfo); // act - let actualPrepareInfo = serviceTest.projectChangesService.getPrepareInfo(platform, this.projectData); + const actualPrepareInfo = serviceTest.projectChangesService.getPrepareInfo(platform, this.projectData); // assert assert.deepEqual(actualPrepareInfo, expectedPrepareInfo); @@ -142,9 +142,9 @@ describe("Project Changes Service Tests", () => { describe("Accumulates Changes From Project Services", () => { it("accumulates changes from the project service", async () => { - let iOSChanges = await serviceTest.projectChangesService.checkForChanges("ios", serviceTest.projectData, { bundle: false, release: false, provision: undefined, teamId: undefined }); + const iOSChanges = await serviceTest.projectChangesService.checkForChanges("ios", serviceTest.projectData, { bundle: false, release: false, provision: undefined, teamId: undefined }); assert.isTrue(!!iOSChanges.signingChanged, "iOS signingChanged expected to be true"); - let androidChanges = await serviceTest.projectChangesService.checkForChanges("android", serviceTest.projectData, { bundle: false, release: false, provision: undefined, teamId: undefined }); + const androidChanges = await serviceTest.projectChangesService.checkForChanges("android", serviceTest.projectData, { bundle: false, release: false, provision: undefined, teamId: undefined }); assert.isFalse(!!androidChanges.signingChanged, "Android signingChanged expected to be false"); }); }); diff --git a/test/project-commands.ts b/test/project-commands.ts index 3b201324a1..d5ddccaa41 100644 --- a/test/project-commands.ts +++ b/test/project-commands.ts @@ -7,7 +7,7 @@ import { assert } from "chai"; let selectedTemplateName: string; let isProjectCreated: boolean; -let dummyArgs = ["dummyArgsString"]; +const dummyArgs = ["dummyArgsString"]; class ProjectServiceMock implements IProjectService { async createProject(projectOptions: IProjectSettings): Promise { @@ -27,7 +27,7 @@ class ProjectNameValidatorMock implements IProjectNameValidator { } function createTestInjector() { - let testInjector = new Yok(); + const testInjector = new Yok(); testInjector.register("injector", testInjector); testInjector.register("staticConfig", {}); diff --git a/test/project-files-provider.ts b/test/project-files-provider.ts index 2c910275e7..0edd3f5566 100644 --- a/test/project-files-provider.ts +++ b/test/project-files-provider.ts @@ -3,13 +3,13 @@ import { ProjectFilesProvider } from "../lib/providers/project-files-provider"; import { assert } from "chai"; import * as path from "path"; -let projectDir = "projectDir", +const projectDir = "projectDir", appDestinationDirectoryPath = "appDestinationDirectoryPath", appResourcesDestinationDirectoryPath = "appResourcesDestinationDirectoryPath", appSourceDir = path.join(projectDir, "app"); function createTestInjector(): IInjector { - let testInjector = new Yok(); + const testInjector = new Yok(); testInjector.register("mobileHelper", { platformNames: ["Android", "iOS"] }); @@ -36,8 +36,8 @@ function createTestInjector(): IInjector { } describe("project-files-provider", () => { - let testInjector: IInjector, - projectFilesProvider: IProjectFilesProvider; + let testInjector: IInjector; + let projectFilesProvider: IProjectFilesProvider; beforeEach(() => { testInjector = createTestInjector(); @@ -56,38 +56,38 @@ describe("project-files-provider", () => { describe("mapFilePath", () => { it("returns file path from prepared project when path from app dir is passed", () => { - let projectData: IProjectData = testInjector.resolve("projectData"); - let mappedFilePath = projectFilesProvider.mapFilePath(path.join(appSourceDir, "test.js"), "android", projectData, {}); + const projectData: IProjectData = testInjector.resolve("projectData"); + const mappedFilePath = projectFilesProvider.mapFilePath(path.join(appSourceDir, "test.js"), "android", projectData, {}); assert.deepEqual(mappedFilePath, path.join(appDestinationDirectoryPath, "app", "test.js")); }); it("returns file path from prepared project when path from app/App_Resources/platform dir is passed", () => { - let projectData: IProjectData = testInjector.resolve("projectData"); - let mappedFilePath = projectFilesProvider.mapFilePath(path.join(appSourceDir, "App_Resources", "android", "test.js"), "android", projectData, {}); + const projectData: IProjectData = testInjector.resolve("projectData"); + const mappedFilePath = projectFilesProvider.mapFilePath(path.join(appSourceDir, "App_Resources", "android", "test.js"), "android", projectData, {}); assert.deepEqual(mappedFilePath, path.join(appResourcesDestinationDirectoryPath, "test.js")); }); it("returns null when path from app/App_Resources/android dir is passed and iOS platform is specified", () => { - let projectData: IProjectData = testInjector.resolve("projectData"); - let mappedFilePath = projectFilesProvider.mapFilePath(path.join(appSourceDir, "App_Resources", "android", "test.js"), "iOS", projectData, {}); + const projectData: IProjectData = testInjector.resolve("projectData"); + const mappedFilePath = projectFilesProvider.mapFilePath(path.join(appSourceDir, "App_Resources", "android", "test.js"), "iOS", projectData, {}); assert.deepEqual(mappedFilePath, null); }); it("returns null when path from app/App_Resources/ dir (not platform specific) is passed", () => { - let projectData: IProjectData = testInjector.resolve("projectData"); - let mappedFilePath = projectFilesProvider.mapFilePath(path.join(appSourceDir, "App_Resources", "test.js"), "android", projectData, {}); + const projectData: IProjectData = testInjector.resolve("projectData"); + const mappedFilePath = projectFilesProvider.mapFilePath(path.join(appSourceDir, "App_Resources", "test.js"), "android", projectData, {}); assert.deepEqual(mappedFilePath, null); }); it("returns file path from prepared project when path from app dir is passed and it contains platform in its name", () => { - let projectData: IProjectData = testInjector.resolve("projectData"); - let mappedFilePath = projectFilesProvider.mapFilePath(path.join(appSourceDir, "test.android.js"), "android", projectData, {}); + const projectData: IProjectData = testInjector.resolve("projectData"); + const mappedFilePath = projectFilesProvider.mapFilePath(path.join(appSourceDir, "test.android.js"), "android", projectData, {}); assert.deepEqual(mappedFilePath, path.join(appDestinationDirectoryPath, "app", "test.js")); }); it("returns file path from prepared project when path from app dir is passed and it contains configuration in its name", () => { - let projectData: IProjectData = testInjector.resolve("projectData"); - let mappedFilePath = projectFilesProvider.mapFilePath(path.join(appSourceDir, "test.debug.js"), "android", projectData, {}); + const projectData: IProjectData = testInjector.resolve("projectData"); + const mappedFilePath = projectFilesProvider.mapFilePath(path.join(appSourceDir, "test.debug.js"), "android", projectData, {}); assert.deepEqual(mappedFilePath, path.join(appDestinationDirectoryPath, "app", "test.js")); }); }); diff --git a/test/project-name-service.ts b/test/project-name-service.ts index 2fa9bb3989..d354a295af 100644 --- a/test/project-name-service.ts +++ b/test/project-name-service.ts @@ -3,11 +3,11 @@ import { ProjectNameService } from "../lib/services/project-name-service"; import { assert } from "chai"; import { ErrorsStub, LoggerStub } from "./stubs"; -let mockProjectNameValidator = { +const mockProjectNameValidator = { validate: () => true }; -let dummyString: string = "dummyString"; +const dummyString: string = "dummyString"; function createTestInjector(): IInjector { let testInjector: IInjector; @@ -28,8 +28,8 @@ function createTestInjector(): IInjector { describe("Project Name Service Tests", () => { let testInjector: IInjector; let projectNameService: IProjectNameService; - let validProjectName = "valid"; - let invalidProjectNames = ["1invalid", "app"]; + const validProjectName = "valid"; + const invalidProjectNames = ["1invalid", "app"]; beforeEach(() => { testInjector = createTestInjector(); @@ -37,17 +37,17 @@ describe("Project Name Service Tests", () => { }); it("returns correct name when valid name is entered", async () => { - let actualProjectName = await projectNameService.ensureValidName(validProjectName); + const actualProjectName = await projectNameService.ensureValidName(validProjectName); assert.deepEqual(actualProjectName, validProjectName); }); _.each(invalidProjectNames, invalidProjectName => { it(`returns correct name when "${invalidProjectName}" is entered several times and then valid name is entered`, async () => { - let prompter = testInjector.resolve("prompter"); + const prompter = testInjector.resolve("prompter"); prompter.confirm = (message: string): Promise => Promise.resolve(false); - let incorrectInputsLimit = 5; + const incorrectInputsLimit = 5; let incorrectInputsCount = 0; prompter.getString = async (message: string): Promise => { @@ -60,13 +60,13 @@ describe("Project Name Service Tests", () => { } }; - let actualProjectName = await projectNameService.ensureValidName(invalidProjectName); + const actualProjectName = await projectNameService.ensureValidName(invalidProjectName); assert.deepEqual(actualProjectName, validProjectName); }); it(`returns the invalid name when "${invalidProjectName}" is entered and --force flag is present`, async () => { - let actualProjectName = await projectNameService.ensureValidName(validProjectName, { force: true }); + const actualProjectName = await projectNameService.ensureValidName(validProjectName, { force: true }); assert.deepEqual(actualProjectName, validProjectName); }); diff --git a/test/project-service.ts b/test/project-service.ts index 8fd3e9d574..4cb3367dce 100644 --- a/test/project-service.ts +++ b/test/project-service.ts @@ -19,13 +19,13 @@ import { Options } from "../lib/options"; import { HostInfo } from "../lib/common/host-info"; import { ProjectTemplatesService } from "../lib/services/project-templates-service"; -let mockProjectNameValidator = { +const mockProjectNameValidator = { validate: () => true }; -let dummyString: string = "dummyString"; +const dummyString: string = "dummyString"; let hasPromptedForString = false; -let originalIsInteractive = helpers.isInteractive; +const originalIsInteractive = helpers.isInteractive; temp.track(); @@ -33,8 +33,8 @@ async function prepareTestingPath(testInjector: IInjector, packageToInstall: str options = options || { dependencyType: "save" }; const fs = testInjector.resolve("fs"); - let npmInstallationManager = testInjector.resolve("npmInstallationManager"); - let defaultTemplateDir = temp.mkdirSync("project-service"); + const npmInstallationManager = testInjector.resolve("npmInstallationManager"); + const defaultTemplateDir = temp.mkdirSync("project-service"); fs.writeJson(path.join(defaultTemplateDir, constants.PACKAGE_JSON_FILE_NAME), { "name": "defaultTemplate", "version": "1.0.0", @@ -60,7 +60,7 @@ class ProjectIntegrationTest { } public async createProject(projectOptions: IProjectSettings): Promise { - let projectService: IProjectService = this.testInjector.resolve("projectService"); + const projectService: IProjectService = this.testInjector.resolve("projectService"); if (!projectOptions.template) { projectOptions.template = constants.RESERVED_TEMPLATE_NAMES["default"]; } @@ -68,13 +68,13 @@ class ProjectIntegrationTest { } public async assertProject(tempFolder: string, projectName: string, appId: string, projectSourceDirectory: string): Promise { - let fs: IFileSystem = this.testInjector.resolve("fs"); - let projectDir = path.join(tempFolder, projectName); - let appDirectoryPath = path.join(projectDir, "app"); - let platformsDirectoryPath = path.join(projectDir, "platforms"); - let tnsProjectFilePath = path.join(projectDir, "package.json"); - let tnsModulesPath = path.join(projectDir, constants.NODE_MODULES_FOLDER_NAME, constants.TNS_CORE_MODULES_NAME); - let packageJsonContent = fs.readJson(tnsProjectFilePath); + const fs: IFileSystem = this.testInjector.resolve("fs"); + const projectDir = path.join(tempFolder, projectName); + const appDirectoryPath = path.join(projectDir, "app"); + const platformsDirectoryPath = path.join(projectDir, "platforms"); + const tnsProjectFilePath = path.join(projectDir, "package.json"); + const tnsModulesPath = path.join(projectDir, constants.NODE_MODULES_FOLDER_NAME, constants.TNS_CORE_MODULES_NAME); + const packageJsonContent = fs.readJson(tnsProjectFilePath); assert.isTrue(fs.exists(appDirectoryPath)); assert.isTrue(fs.exists(platformsDirectoryPath)); @@ -84,37 +84,37 @@ class ProjectIntegrationTest { assert.isFalse(fs.isEmptyDir(appDirectoryPath)); assert.isTrue(fs.isEmptyDir(platformsDirectoryPath)); - let actualAppId = packageJsonContent["nativescript"].id; - let expectedAppId = appId; + const actualAppId = packageJsonContent["nativescript"].id; + const expectedAppId = appId; assert.equal(actualAppId, expectedAppId); - let tnsCoreModulesRecord = packageJsonContent["dependencies"][constants.TNS_CORE_MODULES_NAME]; + const tnsCoreModulesRecord = packageJsonContent["dependencies"][constants.TNS_CORE_MODULES_NAME]; assert.isTrue(tnsCoreModulesRecord !== null); - let sourceDir = projectSourceDirectory; + const sourceDir = projectSourceDirectory; // Hidden files (starting with dots ".") are not copied. - let expectedFiles = fs.enumerateFilesInDirectorySync(sourceDir, (file, stat) => stat.isDirectory() || !_.startsWith(path.basename(file), ".")); - let actualFiles = fs.enumerateFilesInDirectorySync(appDirectoryPath); + const expectedFiles = fs.enumerateFilesInDirectorySync(sourceDir, (file, stat) => stat.isDirectory() || !_.startsWith(path.basename(file), ".")); + const actualFiles = fs.enumerateFilesInDirectorySync(appDirectoryPath); assert.isTrue(actualFiles.length >= expectedFiles.length, "Files in created project must be at least as files in app dir."); _.each(expectedFiles, file => { - let relativeToProjectDir = helpers.getRelativeToRootPath(sourceDir, file); - let filePathInApp = path.join(appDirectoryPath, relativeToProjectDir); + const relativeToProjectDir = helpers.getRelativeToRootPath(sourceDir, file); + const filePathInApp = path.join(appDirectoryPath, relativeToProjectDir); assert.isTrue(fs.exists(filePathInApp), `File ${filePathInApp} does not exist.`); }); // assert dependencies and devDependencies are copied from template to real project - let sourcePackageJsonContent = fs.readJson(path.join(sourceDir, "package.json")); - let missingDeps = _.difference(_.keys(sourcePackageJsonContent.dependencies), _.keys(packageJsonContent.dependencies)); - let missingDevDeps = _.difference(_.keys(sourcePackageJsonContent.devDependencies), _.keys(packageJsonContent.devDependencies)); + const sourcePackageJsonContent = fs.readJson(path.join(sourceDir, "package.json")); + const missingDeps = _.difference(_.keys(sourcePackageJsonContent.dependencies), _.keys(packageJsonContent.dependencies)); + const missingDevDeps = _.difference(_.keys(sourcePackageJsonContent.devDependencies), _.keys(packageJsonContent.devDependencies)); assert.deepEqual(missingDeps, [], `All dependencies from template must be copied to project's package.json. Missing ones are: ${missingDeps.join(", ")}.`); assert.deepEqual(missingDevDeps, [], `All devDependencies from template must be copied to project's package.json. Missing ones are: ${missingDevDeps.join(", ")}.`); // assert App_Resources are prepared correctly - let appResourcesDir = path.join(appDirectoryPath, "App_Resources"); - let appResourcesContents = fs.readDirectory(appResourcesDir); + const appResourcesDir = path.join(appDirectoryPath, "App_Resources"); + const appResourcesContents = fs.readDirectory(appResourcesDir); assert.deepEqual(appResourcesContents, ["Android", "iOS"], "Project's app/App_Resources must contain Android and iOS directories."); } @@ -168,7 +168,7 @@ describe("Project Service Tests", () => { const noAppResourcesTemplateName = "tns-template-hello-world-ts"; before(async () => { - let projectIntegrationTest = new ProjectIntegrationTest(); + const projectIntegrationTest = new ProjectIntegrationTest(); defaultTemplatePath = await prepareTestingPath(projectIntegrationTest.testInjector, constants.RESERVED_TEMPLATE_NAMES["default"], constants.RESERVED_TEMPLATE_NAMES["default"]); defaultSpecificVersionTemplatePath = await prepareTestingPath(projectIntegrationTest.testInjector, constants.RESERVED_TEMPLATE_NAMES["default"], constants.RESERVED_TEMPLATE_NAMES["default"], { version: "1.4.0", dependencyType: "save" }); @@ -178,45 +178,45 @@ describe("Project Service Tests", () => { }); it("creates valid project from default template", async () => { - let projectIntegrationTest = new ProjectIntegrationTest(); - let tempFolder = temp.mkdirSync("project"); - let projectName = "myapp"; + const projectIntegrationTest = new ProjectIntegrationTest(); + const tempFolder = temp.mkdirSync("project"); + const projectName = "myapp"; await projectIntegrationTest.createProject({ projectName: projectName, pathToProject: tempFolder }); await projectIntegrationTest.assertProject(tempFolder, projectName, "org.nativescript.myapp", defaultTemplatePath); }); it("creates valid project from default template when --template default is specified", async () => { - let projectIntegrationTest = new ProjectIntegrationTest(); - let tempFolder = temp.mkdirSync("project"); - let projectName = "myapp"; + const projectIntegrationTest = new ProjectIntegrationTest(); + const tempFolder = temp.mkdirSync("project"); + const projectName = "myapp"; await projectIntegrationTest.createProject({ projectName: projectName, template: "default", pathToProject: tempFolder }); await projectIntegrationTest.assertProject(tempFolder, projectName, "org.nativescript.myapp", defaultTemplatePath); }); it("creates valid project from default template when --template default@version is specified", async () => { - let projectIntegrationTest = new ProjectIntegrationTest(); - let tempFolder = temp.mkdirSync("project"); - let projectName = "myapp"; + const projectIntegrationTest = new ProjectIntegrationTest(); + const tempFolder = temp.mkdirSync("project"); + const projectName = "myapp"; await projectIntegrationTest.createProject({ projectName: projectName, template: "default@1.4.0", pathToProject: tempFolder }); await projectIntegrationTest.assertProject(tempFolder, projectName, "org.nativescript.myapp", defaultSpecificVersionTemplatePath); }); it("creates valid project from a template without App_Resources", async () => { - let projectIntegrationTest = new ProjectIntegrationTest(); - let tempFolder = temp.mkdirSync("project"); - let projectName = "myapp"; + const projectIntegrationTest = new ProjectIntegrationTest(); + const tempFolder = temp.mkdirSync("project"); + const projectName = "myapp"; await projectIntegrationTest.createProject({ projectName: projectName, template: noAppResourcesTemplateName + "@2.0.0", pathToProject: tempFolder }); await projectIntegrationTest.assertProject(tempFolder, projectName, "org.nativescript.myapp", noAppResourcesTemplatePath); }); it("creates valid project from typescript template", async () => { - let projectIntegrationTest = new ProjectIntegrationTest(); - let tempFolder = temp.mkdirSync("projectTypescript"); - let projectName = "myapp"; + const projectIntegrationTest = new ProjectIntegrationTest(); + const tempFolder = temp.mkdirSync("projectTypescript"); + const projectName = "myapp"; await projectIntegrationTest.createProject({ projectName: projectName, template: "typescript", pathToProject: tempFolder }); @@ -224,18 +224,18 @@ describe("Project Service Tests", () => { }); it("creates valid project from tsc template", async () => { - let projectIntegrationTest = new ProjectIntegrationTest(); - let tempFolder = temp.mkdirSync("projectTsc"); - let projectName = "myapp"; + const projectIntegrationTest = new ProjectIntegrationTest(); + const tempFolder = temp.mkdirSync("projectTsc"); + const projectName = "myapp"; await projectIntegrationTest.createProject({ projectName: projectName, template: "tsc", pathToProject: tempFolder }); await projectIntegrationTest.assertProject(tempFolder, projectName, "org.nativescript.myapp", typescriptTemplatePath); }); it("creates valid project from angular template", async () => { - let projectIntegrationTest = new ProjectIntegrationTest(); - let tempFolder = temp.mkdirSync("projectAngular"); - let projectName = "myapp"; + const projectIntegrationTest = new ProjectIntegrationTest(); + const tempFolder = temp.mkdirSync("projectAngular"); + const projectName = "myapp"; await projectIntegrationTest.createProject({ projectName: projectName, template: "angular", pathToProject: tempFolder }); @@ -243,9 +243,9 @@ describe("Project Service Tests", () => { }); it("creates valid project from ng template", async () => { - let projectIntegrationTest = new ProjectIntegrationTest(); - let tempFolder = temp.mkdirSync("projectNg"); - let projectName = "myapp"; + const projectIntegrationTest = new ProjectIntegrationTest(); + const tempFolder = temp.mkdirSync("projectNg"); + const projectName = "myapp"; await projectIntegrationTest.createProject({ projectName: projectName, template: "ng", pathToProject: tempFolder }); @@ -253,14 +253,14 @@ describe("Project Service Tests", () => { }); it("creates valid project from local directory template", async () => { - let projectIntegrationTest = new ProjectIntegrationTest(); - let tempFolder = temp.mkdirSync("projectLocalDir"); - let projectName = "myapp"; - let options = projectIntegrationTest.testInjector.resolve("options"); + const projectIntegrationTest = new ProjectIntegrationTest(); + const tempFolder = temp.mkdirSync("projectLocalDir"); + const projectName = "myapp"; + const options = projectIntegrationTest.testInjector.resolve("options"); options.path = tempFolder; - let tempDir = temp.mkdirSync("template"); - let fs: IFileSystem = projectIntegrationTest.testInjector.resolve("fs"); + const tempDir = temp.mkdirSync("template"); + const fs: IFileSystem = projectIntegrationTest.testInjector.resolve("fs"); fs.writeJson(path.join(tempDir, "package.json"), { name: "myCustomTemplate", version: "1.0.0", @@ -287,9 +287,9 @@ describe("Project Service Tests", () => { }); it("creates valid project from tarball", async () => { - let projectIntegrationTest = new ProjectIntegrationTest(); - let tempFolder = temp.mkdirSync("projectLocalDir"); - let projectName = "myapp"; + const projectIntegrationTest = new ProjectIntegrationTest(); + const tempFolder = temp.mkdirSync("projectLocalDir"); + const projectName = "myapp"; const template = "https://github.com/NativeScript/template-hello-world/tarball/master"; await projectIntegrationTest.createProject({ @@ -303,9 +303,9 @@ describe("Project Service Tests", () => { }); it("creates valid project from git url", async () => { - let projectIntegrationTest = new ProjectIntegrationTest(); - let tempFolder = temp.mkdirSync("projectLocalDir"); - let projectName = "myapp"; + const projectIntegrationTest = new ProjectIntegrationTest(); + const tempFolder = temp.mkdirSync("projectLocalDir"); + const projectName = "myapp"; const template = "https://github.com/NativeScript/template-hello-world.git"; await projectIntegrationTest.createProject({ @@ -319,17 +319,17 @@ describe("Project Service Tests", () => { }); it("creates valid project with specified id from default template", async () => { - let projectIntegrationTest = new ProjectIntegrationTest(); - let tempFolder = temp.mkdirSync("project1"); - let projectName = "myapp"; + const projectIntegrationTest = new ProjectIntegrationTest(); + const tempFolder = temp.mkdirSync("project1"); + const projectName = "myapp"; await projectIntegrationTest.createProject({ projectName: projectName, pathToProject: tempFolder, appId: "my.special.id" }); await projectIntegrationTest.assertProject(tempFolder, projectName, "my.special.id", defaultTemplatePath); }); describe("project name validation tests", () => { - let validProjectName = "valid"; - let invalidProjectName = "1invalid"; + const validProjectName = "valid"; + const invalidProjectName = "1invalid"; let projectIntegrationTest: ProjectIntegrationTest; let tempFolder: string; let options: IOptions; @@ -349,13 +349,13 @@ describe("Project Service Tests", () => { }); it("creates project when is interactive and incorrect name is specified and the --force option is set", async () => { - let projectName = invalidProjectName; + const projectName = invalidProjectName; await projectIntegrationTest.createProject({ projectName: projectName, pathToProject: tempFolder, force: true }); await projectIntegrationTest.assertProject(tempFolder, projectName, `org.nativescript.${projectName}`, defaultTemplatePath); }); it("creates project when is interactive and incorrect name is specified and the user confirms to use the incorrect name", async () => { - let projectName = invalidProjectName; + const projectName = invalidProjectName; prompter.confirm = (message: string): Promise => Promise.resolve(true); await projectIntegrationTest.createProject({ projectName: projectName, pathToProject: tempFolder }); @@ -363,7 +363,7 @@ describe("Project Service Tests", () => { }); it("prompts for new name when is interactive and incorrect name is specified and the user does not confirm to use the incorrect name", async () => { - let projectName = invalidProjectName; + const projectName = invalidProjectName; prompter.confirm = (message: string): Promise => Promise.resolve(false); @@ -372,11 +372,11 @@ describe("Project Service Tests", () => { }); it("creates project when is interactive and incorrect name s specified and the user does not confirm to use the incorrect name and enters incorrect name again several times and then enters correct name", async () => { - let projectName = invalidProjectName; + const projectName = invalidProjectName; prompter.confirm = (message: string): Promise => Promise.resolve(false); - let incorrectInputsLimit = 5; + const incorrectInputsLimit = 5; let incorrectInputsCount = 0; prompter.getString = async (message: string): Promise => { @@ -396,14 +396,14 @@ describe("Project Service Tests", () => { }); it("does not create project when is not interactive and incorrect name is specified", async () => { - let projectName = invalidProjectName; + const projectName = invalidProjectName; helpers.isInteractive = () => false; await assert.isRejected(projectIntegrationTest.createProject({ projectName: projectName, pathToProject: tempFolder, force: false })); }); it("creates project when is not interactive and incorrect name is specified and the --force option is set", async () => { - let projectName = invalidProjectName; + const projectName = invalidProjectName; helpers.isInteractive = () => false; await projectIntegrationTest.createProject({ projectName: projectName, pathToProject: tempFolder, force: true }); diff --git a/test/project-templates-service.ts b/test/project-templates-service.ts index ac46ac405c..46e2d1c918 100644 --- a/test/project-templates-service.ts +++ b/test/project-templates-service.ts @@ -7,10 +7,10 @@ import temp = require("temp"); import * as constants from "../lib/constants"; let isDeleteDirectoryCalledForNodeModulesDir = false; -let nativeScriptValidatedTemplatePath = "nsValidatedTemplatePath"; +const nativeScriptValidatedTemplatePath = "nsValidatedTemplatePath"; function createTestInjector(configuration?: { shouldNpmInstallThrow: boolean, npmInstallationDirContents: string[], npmInstallationDirNodeModulesContents: string[] }): IInjector { - let injector = new Yok(); + const injector = new Yok(); injector.register("errors", stubs.ErrorsStub); injector.register("logger", stubs.LoggerStub); injector.register("fs", { @@ -67,7 +67,7 @@ describe("project-templates-service", () => { it("when npm install fails", async () => { testInjector = createTestInjector({ shouldNpmInstallThrow: true, npmInstallationDirContents: [], npmInstallationDirNodeModulesContents: null }); projectTemplatesService = testInjector.resolve("projectTemplatesService"); - let tempFolder = temp.mkdirSync("preparetemplate"); + const tempFolder = temp.mkdirSync("preparetemplate"); await assert.isRejected(projectTemplatesService.prepareTemplate("invalidName", tempFolder)); }); }); @@ -76,8 +76,8 @@ describe("project-templates-service", () => { it("when reserved template name is used", async () => { testInjector = createTestInjector({ shouldNpmInstallThrow: false, npmInstallationDirContents: [], npmInstallationDirNodeModulesContents: [] }); projectTemplatesService = testInjector.resolve("projectTemplatesService"); - let tempFolder = temp.mkdirSync("preparetemplate"); - let actualPathToTemplate = await projectTemplatesService.prepareTemplate("typescript", tempFolder); + const tempFolder = temp.mkdirSync("preparetemplate"); + const actualPathToTemplate = await projectTemplatesService.prepareTemplate("typescript", tempFolder); assert.strictEqual(path.basename(actualPathToTemplate), nativeScriptValidatedTemplatePath); assert.strictEqual(isDeleteDirectoryCalledForNodeModulesDir, true, "When correct path is returned, template's node_modules directory should be deleted."); }); @@ -85,8 +85,8 @@ describe("project-templates-service", () => { it("when reserved template name is used (case-insensitive test)", async () => { testInjector = createTestInjector({ shouldNpmInstallThrow: false, npmInstallationDirContents: [], npmInstallationDirNodeModulesContents: [] }); projectTemplatesService = testInjector.resolve("projectTemplatesService"); - let tempFolder = temp.mkdirSync("preparetemplate"); - let actualPathToTemplate = await projectTemplatesService.prepareTemplate("tYpEsCriPT", tempFolder); + const tempFolder = temp.mkdirSync("preparetemplate"); + const actualPathToTemplate = await projectTemplatesService.prepareTemplate("tYpEsCriPT", tempFolder); assert.strictEqual(path.basename(actualPathToTemplate), nativeScriptValidatedTemplatePath); assert.strictEqual(isDeleteDirectoryCalledForNodeModulesDir, true, "When correct path is returned, template's node_modules directory should be deleted."); }); @@ -94,8 +94,8 @@ describe("project-templates-service", () => { it("uses defaultTemplate when undefined is passed as parameter", async () => { testInjector = createTestInjector({ shouldNpmInstallThrow: false, npmInstallationDirContents: [], npmInstallationDirNodeModulesContents: [] }); projectTemplatesService = testInjector.resolve("projectTemplatesService"); - let tempFolder = temp.mkdirSync("preparetemplate"); - let actualPathToTemplate = await projectTemplatesService.prepareTemplate(constants.RESERVED_TEMPLATE_NAMES["default"], tempFolder); + const tempFolder = temp.mkdirSync("preparetemplate"); + const actualPathToTemplate = await projectTemplatesService.prepareTemplate(constants.RESERVED_TEMPLATE_NAMES["default"], tempFolder); assert.strictEqual(path.basename(actualPathToTemplate), nativeScriptValidatedTemplatePath); assert.strictEqual(isDeleteDirectoryCalledForNodeModulesDir, true, "When correct path is returned, template's node_modules directory should be deleted."); }); diff --git a/test/services/extensibility-service.ts b/test/services/extensibility-service.ts index a03138676f..3243331703 100644 --- a/test/services/extensibility-service.ts +++ b/test/services/extensibility-service.ts @@ -72,7 +72,7 @@ describe("extensibilityService", () => { fs.readDirectory = (dir: string): string[] => [userSpecifiedValue]; const npm: INodePackageManager = testInjector.resolve("npm"); - let argsPassedToNpmInstall: any = {}; + const argsPassedToNpmInstall: any = {}; npm.install = async (packageName: string, pathToSave: string, config?: any): Promise => { argsPassedToNpmInstall.packageName = packageName; argsPassedToNpmInstall.pathToSave = pathToSave; @@ -468,7 +468,7 @@ describe("extensibilityService", () => { fs.readDirectory = (dir: string): string[] => [userSpecifiedValue]; const npm: INodePackageManager = testInjector.resolve("npm"); - let argsPassedToNpmInstall: any = {}; + const argsPassedToNpmInstall: any = {}; npm.uninstall = async (packageName: string, config?: any, path?: string): Promise => { argsPassedToNpmInstall.packageName = packageName; argsPassedToNpmInstall.pathToSave = path; diff --git a/test/services/project-data-service.ts b/test/services/project-data-service.ts index 71f08eff31..71112f4abb 100644 --- a/test/services/project-data-service.ts +++ b/test/services/project-data-service.ts @@ -61,7 +61,7 @@ const createTestInjector = (readTextData?: string): IInjector => { describe("projectDataService", () => { const generateJsonDataFromTestData = (currentTestData: any, skipNativeScriptKey?: boolean) => { const props = currentTestData.propertyName.split("."); - let data: any = {}; + const data: any = {}; let currentData: any = skipNativeScriptKey ? data : (data[CLIENT_NAME_KEY_IN_PROJECT_FILE] = {}); _.each(props, (prop, index: number) => { @@ -157,7 +157,7 @@ describe("projectDataService", () => { const props = currentTestData.propertyName.split("."); props.splice(props.length - 1, 1); - let data: any = {}; + const data: any = {}; let currentData: any = data[CLIENT_NAME_KEY_IN_PROJECT_FILE] = {}; _.each(props, (prop) => { @@ -214,7 +214,7 @@ describe("projectDataService", () => { describe("removeDependency", () => { it("removes specified dependency from project file", () => { - let currentTestData = { + const currentTestData = { propertyName: "dependencies.myDeps", propertyValue: "1.0.0" }; diff --git a/test/services/subscription-service.ts b/test/services/subscription-service.ts index ac2106ad0c..c9fc7548e6 100644 --- a/test/services/subscription-service.ts +++ b/test/services/subscription-service.ts @@ -3,7 +3,7 @@ import { assert } from "chai"; import { SubscriptionService } from "../../lib/services/subscription-service"; import { LoggerStub } from "../stubs"; import { stringify } from "querystring"; -let helpers = require("../../lib/common/helpers"); +const helpers = require("../../lib/common/helpers"); interface IValidateTestData { name: string; diff --git a/test/stubs.ts b/test/stubs.ts index 8c98f21c2f..04f128f8dc 100644 --- a/test/stubs.ts +++ b/test/stubs.ts @@ -444,13 +444,13 @@ export class PrompterStub implements IPrompter { } async getPassword(prompt: string, options?: IAllowEmpty): Promise { chai.assert.ok(prompt in this.passwords, `PrompterStub didn't expect to give password for: ${prompt}`); - let result = this.passwords[prompt]; + const result = this.passwords[prompt]; delete this.passwords[prompt]; return result; } async getString(prompt: string, options?: IPrompterOptions): Promise { chai.assert.ok(prompt in this.strings, `PrompterStub didn't expect to be asked for: ${prompt}`); - let result = this.strings[prompt]; + const result = this.strings[prompt]; delete this.strings[prompt]; return result; } @@ -465,10 +465,10 @@ export class PrompterStub implements IPrompter { } assert() { - for (let key in this.strings) { + for (const key in this.strings) { throw unexpected(`PrompterStub was instructed to reply with "${this.strings[key]}" to a "${key}" question, but was never asked!`); } - for (let key in this.passwords) { + for (const key in this.passwords) { throw unexpected(`PrompterStub was instructed to reply with "${this.passwords[key]}" to a "${key}" password request, but was never asked!`); } } @@ -479,7 +479,7 @@ function unreachable(): Error { } function unexpected(msg: string): Error { - let err = new chai.AssertionError(msg); + const err = new chai.AssertionError(msg); err.showDiff = false; return err; } @@ -516,7 +516,7 @@ export class LiveSyncServiceStub implements ILiveSyncService { export class AndroidToolsInfoStub implements IAndroidToolsInfo { public getToolsInfo(): IAndroidToolsInfoData { - let infoData: IAndroidToolsInfoData = Object.create(null); + const infoData: IAndroidToolsInfoData = Object.create(null); infoData.androidHomeEnvVar = "ANDROID_HOME"; infoData.compileSdkVersion = 23; infoData.buildToolsVersion = "23"; diff --git a/test/tns-appstore-upload.ts b/test/tns-appstore-upload.ts index bc930731ce..50bb3afc3f 100644 --- a/test/tns-appstore-upload.ts +++ b/test/tns-appstore-upload.ts @@ -72,10 +72,10 @@ class AppStore { initInjector(services?: { commands?: { [service: string]: any }, services?: { [service: string]: any } }) { this.injector = new yok.Yok(); if (services) { - for (let cmd in services.commands) { + for (const cmd in services.commands) { this.injector.registerCommand(cmd, services.commands[cmd]); } - for (let serv in services.services) { + for (const serv in services.services) { this.injector.register(serv, services.services[serv]); } } diff --git a/test/tools/node-modules/node-modules-dependencies-builder.ts b/test/tools/node-modules/node-modules-dependencies-builder.ts index 8b25691fde..0b8d85dcb3 100644 --- a/test/tools/node-modules/node-modules-dependencies-builder.ts +++ b/test/tools/node-modules/node-modules-dependencies-builder.ts @@ -59,7 +59,7 @@ describe("nodeModulesDependenciesBuilder", () => { }; const getNodeModuleInfoForExpecteDependency = (name: string, depth: number, nativescript?: any, dependencies?: string[]): IDependencyData => { - let result: IDependencyData = { + const result: IDependencyData = { name: path.basename(name), directory: getPathToDependencyInNodeModules(name), depth, @@ -83,7 +83,7 @@ describe("nodeModulesDependenciesBuilder", () => { dependencies[innerDependency.name] = innerDependency.version; }); - let result: any = { + const result: any = { dependencies }; @@ -96,7 +96,7 @@ describe("nodeModulesDependenciesBuilder", () => { const getDependenciesObject = (filename: string, deps: IDependencyInfo[], parentDir: string): { dependencies: any } => { let result: { dependencies: any } = null; - for (let dependencyInfo of deps) { + for (const dependencyInfo of deps) { const pathToPackageJson = getPathToPackageJsonOfDependency(dependencyInfo.name, parentDir); if (filename === pathToPackageJson) { return getDependenciesObjectFromDependencyInfo(dependencyInfo.dependencies, dependencyInfo.nativescript); @@ -126,7 +126,7 @@ describe("nodeModulesDependenciesBuilder", () => { const isDirectory = (searchedPath: string, currentRootPath: string, deps: IDependencyInfo[], currentDepthLevel: number): boolean => { let result = false; - for (let dependencyInfo of deps) { + for (const dependencyInfo of deps) { const pathToDependency = path.join(currentRootPath, constants.NODE_MODULES_FOLDER_NAME, dependencyInfo.name); if (pathToDependency === searchedPath && currentDepthLevel === dependencyInfo.depth) { @@ -146,7 +146,7 @@ describe("nodeModulesDependenciesBuilder", () => { const isPackageJsonOfDependency = (searchedPath: string, currentRootPath: string, deps: IDependencyInfo[], currentDepthLevel: number): boolean => { let result = false; - for (let dependencyInfo of deps) { + for (const dependencyInfo of deps) { const pathToDependency = path.join(currentRootPath, constants.NODE_MODULES_FOLDER_NAME, dependencyInfo.name); const pathToPackageJson = path.join(pathToDependency, constants.PACKAGE_JSON_FILE_NAME); diff --git a/test/xcconfig-service.ts b/test/xcconfig-service.ts index ba9e13a330..9a96daecf8 100644 --- a/test/xcconfig-service.ts +++ b/test/xcconfig-service.ts @@ -21,9 +21,9 @@ describe("XCConfig Service Tests", () => { }; const assertPropertyValues = (expected: any, injector: IInjector) => { - let service = getXCConfigService(injector); + const service = getXCConfigService(injector); _.forOwn(expected, (value, key) => { - let actual = service.readPropertyValue("any", key); + const actual = service.readPropertyValue("any", key); assert.equal(actual, value); }); }; @@ -38,22 +38,22 @@ describe("XCConfig Service Tests", () => { describe("Read Property Value", () => { it("Return empty value, for unexistent file", () => { - let injector = createTestInjector(); + const injector = createTestInjector(); injector.register("fs", { exists: (path: string) => { return false; } }); - let service = getXCConfigService(injector); - let actual = service.readPropertyValue("any", "any"); + const service = getXCConfigService(injector); + const actual = service.readPropertyValue("any", "any"); assert.isNull(actual); }); it("Returns correct value for well-formatted document", () => { - let injector = createTestInjector(); - let fs = getFileSystemMock(injector); + const injector = createTestInjector(); + const fs = getFileSystemMock(injector); fs.readText = (filename: string, options?: IReadFileOptions | string): string => { return `// You can add custom settings here // for example you can uncomment the following line to force distribution code signing @@ -64,7 +64,7 @@ describe("XCConfig Service Tests", () => { ASSETCATALOG_COMPILER_LAUNCHIMAGE_NAME = LaunchImage;`; }; - let expected = { + const expected = { 'ASSETCATALOG_COMPILER_APPICON_NAME': 'AppIcon', 'ASSETCATALOG_COMPILER_LAUNCHIMAGE_NAME': 'LaunchImage', 'CODE_SIGN_IDENTITY': 'iPhone Distribution' @@ -74,8 +74,8 @@ describe("XCConfig Service Tests", () => { }); it("Returns correct value for values with missing ; at the end of the line.", () => { - let injector = createTestInjector(); - let fs = getFileSystemMock(injector); + const injector = createTestInjector(); + const fs = getFileSystemMock(injector); fs.readText = (filename: string, options?: IReadFileOptions | string): string => { return `// You can add custom settings here // for example you can uncomment the following line to force distribution code signing @@ -86,7 +86,7 @@ describe("XCConfig Service Tests", () => { ASSETCATALOG_COMPILER_LAUNCHIMAGE_NAME = LaunchImage`; }; - let expected = { + const expected = { 'ASSETCATALOG_COMPILER_APPICON_NAME': 'AppIcon', 'ASSETCATALOG_COMPILER_LAUNCHIMAGE_NAME': 'LaunchImage', 'CODE_SIGN_IDENTITY': 'iPhone Distribution' @@ -96,14 +96,14 @@ describe("XCConfig Service Tests", () => { }); it("Doesn't read value from a commented-out line.", () => { - let injector = createTestInjector(); - let fs = getFileSystemMock(injector); + const injector = createTestInjector(); + const fs = getFileSystemMock(injector); fs.readText = (filename: string, options?: IReadFileOptions | string): string => { return `// DEVELOPMENT_TEAM = YOUR_TEAM_ID; ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;`; }; - let expected = { + const expected = { 'ASSETCATALOG_COMPILER_APPICON_NAME': 'AppIcon', 'DEVELOPMENT_TEAM': null }; @@ -112,8 +112,8 @@ describe("XCConfig Service Tests", () => { }); it("Returns correct empty value.", () => { - let injector = createTestInjector(); - let fs = getFileSystemMock(injector); + const injector = createTestInjector(); + const fs = getFileSystemMock(injector); fs.readText = (filename: string, options?: IReadFileOptions | string): string => { return ` ASSETCATALOG_COMPILER_APPICON_NAME = ; @@ -121,7 +121,7 @@ describe("XCConfig Service Tests", () => { `; }; - let expected = { + const expected = { 'ASSETCATALOG_COMPILER_APPICON_NAME': '', 'ASSETCATALOG_COMPILER_LAUNCHIMAGE_NAME': 'LaunchImage' }; @@ -130,13 +130,13 @@ describe("XCConfig Service Tests", () => { }); it("First part only property doesn't break the service.", () => { - let injector = createTestInjector(); - let fs = getFileSystemMock(injector); + const injector = createTestInjector(); + const fs = getFileSystemMock(injector); fs.readText = (filename: string, options?: IReadFileOptions | string): string => { return `ASSETCATALOG_COMPILER_APPICON_NAME`; }; - let expected = { + const expected = { 'ASSETCATALOG_COMPILER_APPICON_NAME': null }; @@ -144,13 +144,13 @@ describe("XCConfig Service Tests", () => { }); it("Invalid config property value with = doesn't break the service.", () => { - let injector = createTestInjector(); - let fs = getFileSystemMock(injector); + const injector = createTestInjector(); + const fs = getFileSystemMock(injector); fs.readText = (filename: string, options?: IReadFileOptions | string): string => { return `ASSETCATALOG_COMPILER_APPICON_NAME=`; }; - let expected = { + const expected = { 'ASSETCATALOG_COMPILER_APPICON_NAME': null }; @@ -158,13 +158,13 @@ describe("XCConfig Service Tests", () => { }); it("Property with space is read correctly.", () => { - let injector = createTestInjector(); - let fs = getFileSystemMock(injector); + const injector = createTestInjector(); + const fs = getFileSystemMock(injector); fs.readText = (filename: string, options?: IReadFileOptions | string): string => { return `ASSETCATALOG_COMPILER_APPICON_NAME= `; }; - let expected = { + const expected = { 'ASSETCATALOG_COMPILER_APPICON_NAME': '' }; @@ -172,13 +172,13 @@ describe("XCConfig Service Tests", () => { }); it("Ensure property can be an empty value.", () => { - let injector = createTestInjector(); - let fs = getFileSystemMock(injector); + const injector = createTestInjector(); + const fs = getFileSystemMock(injector); fs.readText = (filename: string, options?: IReadFileOptions | string): string => { return `ASSETCATALOG_COMPILER_APPICON_NAME= ;`; }; - let expected = { + const expected = { 'ASSETCATALOG_COMPILER_APPICON_NAME': '' }; diff --git a/tslint.json b/tslint.json index e37be6cc07..908fdf9f32 100644 --- a/tslint.json +++ b/tslint.json @@ -13,6 +13,7 @@ false, 140 ], + "prefer-const": true, "no-consecutive-blank-lines": true, "no-construct": true, "no-debugger": true,