From 98a0dd800cf9b05830941c9c27232546176cb0e5 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Fri, 24 Jul 2026 19:46:08 -0300 Subject: [PATCH 1/2] refactor: move ambient const enums into real modules TypeScript inlines `const enum` values at compile time and erases the import, so declaring them in .d.ts files worked only because tsc has whole-program type information. Any file-local transpiler (esbuild, swc, tsx, vite, bun) cannot inline them and fails to resolve the import, which blocks running the sources without a full tsc pass. The 12 ambient const enums now live in real modules: - 5 from lib/common/declarations.d.ts -> lib/common/enums.ts - BuildNames -> lib/constants.ts, next to the other build-related enums - detached-process-enums, system-warnings and google-analytics-custom-dimensions -> .d.ts renamed to .ts; they held nothing but enums - SpecialKeys -> key-commands.d.ts renamed to .ts, which already exported everything, so importers are unchanged The four global files had no imports, making their enums globally visible; consumers now import them explicitly. GoogleAnalyticsCrossClientCustomDimensions is referenced nowhere and was dropped rather than converted into a dead runtime module. Renaming key-commands to .ts surfaced two interface methods whose missing return types an ambient context had allowed; both implementations return nothing, so they are annotated void. --- lib/commands/build.ts | 3 +- lib/commands/debug.ts | 1 + lib/commands/deploy.ts | 10 +- lib/commands/prepare.ts | 2 +- lib/commands/test.ts | 51 +++--- lib/common/declarations.d.ts | 154 +++++------------- .../{key-commands.d.ts => key-commands.ts} | 8 +- lib/common/enums.ts | 84 ++++++++++ lib/common/errors.ts | 25 +-- ... => google-analytics-custom-dimensions.ts} | 2 +- lib/common/services/cancellation.ts | 8 +- lib/common/services/commands-service.ts | 75 +++++---- lib/common/verify-node-version.ts | 1 + lib/constants.ts | 5 + lib/definitions/project.d.ts | 7 +- lib/definitions/system-warnings.d.ts | 4 - lib/definitions/system-warnings.ts | 4 + .../cleanup-js-subprocess.ts | 15 +- lib/detached-processes/cleanup-process.ts | 65 ++++---- ...s-enums.d.ts => detached-process-enums.ts} | 6 +- lib/detached-processes/file-log-service.ts | 8 +- lib/helpers/livesync-command-helper.ts | 48 +++--- lib/helpers/options-track-helper.ts | 6 +- lib/nativescript-cli.ts | 3 +- lib/options.ts | 2 +- .../analytics/analytics-broker-process.ts | 3 +- lib/services/analytics/analytics-broker.ts | 11 +- lib/services/analytics/analytics-service.ts | 10 +- ...lytics-cross-client-custom-dimensions.d.ts | 6 - .../analytics/google-analytics-provider.ts | 24 +-- lib/services/cleanup-service.ts | 12 +- lib/services/initialize-service.ts | 11 +- lib/services/ios-native-target-service.ts | 38 ++--- lib/services/test-execution-service.ts | 36 ++-- lib/sys-info.ts | 8 +- test/options.ts | 24 ++- test/services/analytics/analytics-service.ts | 122 +++++++------- test/sys-info.ts | 7 +- 38 files changed, 461 insertions(+), 448 deletions(-) rename lib/common/definitions/{key-commands.d.ts => key-commands.ts} (90%) create mode 100644 lib/common/enums.ts rename lib/common/services/analytics/{google-analytics-custom-dimensions.d.ts => google-analytics-custom-dimensions.ts} (86%) delete mode 100644 lib/definitions/system-warnings.d.ts create mode 100644 lib/definitions/system-warnings.ts rename lib/detached-processes/{detached-process-enums.d.ts => detached-process-enums.ts} (93%) delete mode 100644 lib/services/analytics/google-analytics-cross-client-custom-dimensions.d.ts diff --git a/lib/commands/build.ts b/lib/commands/build.ts index f3c3c1adb3..7216e8a3fc 100644 --- a/lib/commands/build.ts +++ b/lib/commands/build.ts @@ -13,7 +13,8 @@ import { import { IPlatformsDataService } from "../definitions/platform"; import { IBuildController, IBuildDataService } from "../definitions/build"; import { IMigrateController } from "../definitions/migrate"; -import { IErrors, OptionType } from "../common/declarations"; +import { IErrors } from "../common/declarations"; +import { OptionType } from "../common/enums"; import { ICommandParameter, ICommand } from "../common/definitions/commands"; import { injector } from "../common/yok"; diff --git a/lib/commands/debug.ts b/lib/commands/debug.ts index c7478ab09f..bd894e9019 100644 --- a/lib/commands/debug.ts +++ b/lib/commands/debug.ts @@ -17,6 +17,7 @@ import { ICleanupService } from "../definitions/cleanup-service"; import { IInjector } from "../common/definitions/yok"; import { injector } from "../common/yok"; import * as _ from "lodash"; +import { SystemWarningsSeverity } from "../definitions/system-warnings"; export class DebugPlatformCommand extends ValidatePlatformCommandBase diff --git a/lib/commands/deploy.ts b/lib/commands/deploy.ts index a06f6ea46f..2d2da7614f 100644 --- a/lib/commands/deploy.ts +++ b/lib/commands/deploy.ts @@ -10,12 +10,14 @@ import { IPlatformValidationService, IOptions } from "../declarations"; import { IPlatformsDataService } from "../definitions/platform"; import { IMigrateController } from "../definitions/migrate"; import { ICommand, ICommandParameter } from "../common/definitions/commands"; -import { OptionType, IErrors } from "../common/declarations"; +import { IErrors } from "../common/declarations"; +import { OptionType } from "../common/enums"; import { injector } from "../common/yok"; export class DeployOnDeviceCommand extends ValidatePlatformCommandBase - implements ICommand { + implements ICommand +{ public allowedParameters: ICommandParameter[] = []; public dashedOptions = { @@ -36,13 +38,13 @@ export class DeployOnDeviceCommand private $mobileHelper: Mobile.IMobileHelper, $platformsDataService: IPlatformsDataService, private $deployCommandHelper: DeployCommandHelper, - private $migrateController: IMigrateController + private $migrateController: IMigrateController, ) { super( $options, $platformsDataService, $platformValidationService, - $projectData + $projectData, ); this.$projectData.initializeProjectData(); } diff --git a/lib/commands/prepare.ts b/lib/commands/prepare.ts index 7a7944e568..c2fc7a8145 100644 --- a/lib/commands/prepare.ts +++ b/lib/commands/prepare.ts @@ -6,7 +6,7 @@ import { IOptions, IPlatformValidationService } from "../declarations"; import { IPlatformsDataService } from "../definitions/platform"; import { IMigrateController } from "../definitions/migrate"; import { ICommand, ICommandParameter } from "../common/definitions/commands"; -import { OptionType } from "../common/declarations"; +import { OptionType } from "../common/enums"; import { injector } from "../common/yok"; export class PrepareCommand diff --git a/lib/commands/test.ts b/lib/commands/test.ts index 2e12127477..0f51e2b8cb 100644 --- a/lib/commands/test.ts +++ b/lib/commands/test.ts @@ -9,12 +9,11 @@ import { IPlatformEnvironmentRequirements } from "../definitions/platform"; import { IMigrateController } from "../definitions/migrate"; import { ICommandParameter, ICommand } from "../common/definitions/commands"; import { - OptionType, IAnalyticsService, IErrors, IDictionary, - ErrorCodes, } from "../common/declarations"; +import { ErrorCodes, OptionType } from "../common/enums"; import { ICleanupService } from "../definitions/cleanup-service"; import { injector } from "../common/yok"; @@ -47,19 +46,18 @@ abstract class TestCommandBase { sdk: this.$options.sdk, }); - const selectedDeviceForDebug = await this.$devicesService.pickSingleDevice( - { + const selectedDeviceForDebug = + await this.$devicesService.pickSingleDevice({ onlyEmulators: this.$options.emulator, onlyDevices: this.$options.forDevice, deviceId: this.$options.device, - } - ); + }); devices = [selectedDeviceForDebug]; // const debugData = this.getDebugData(platform, projectData, deployOptions, { device: selectedDeviceForDebug.deviceInfo.identifier }); // await this.$debugService.debug(debugData, this.$options); } else { devices = await this.$liveSyncCommandHelper.getDeviceInstances( - this.platform + this.platform, ); } @@ -69,25 +67,26 @@ abstract class TestCommandBase { this.$options.env.unitTesting = true; const liveSyncInfo = this.$liveSyncCommandHelper.getLiveSyncData( - this.$projectData.projectDir + this.$projectData.projectDir, ); const deviceDebugMap: IDictionary = {}; devices.forEach( (device) => - (deviceDebugMap[device.deviceInfo.identifier] = this.$options.debugBrk) + (deviceDebugMap[device.deviceInfo.identifier] = this.$options.debugBrk), ); - const deviceDescriptors = await this.$liveSyncCommandHelper.createDeviceDescriptors( - devices, - this.platform, - { deviceDebugMap } - ); + const deviceDescriptors = + await this.$liveSyncCommandHelper.createDeviceDescriptors( + devices, + this.platform, + { deviceDebugMap }, + ); await this.$testExecutionService.startKarmaServer( this.platform, liveSyncInfo, - deviceDescriptors + deviceDescriptors, ); // if we got here, it means karma exited with exit code 0 (success) process.exit(0); @@ -100,7 +99,7 @@ abstract class TestCommandBase { // because the Runtime does not watch for the `/data/local/tmp-livesync-in-progress` file deletion. // The App is closing itself after each test execution and the bug will be reproducible on each LiveSync. this.$errors.fail( - "The `--hmr` option is not supported for this command." + "The `--hmr` option is not supported for this command.", ); } @@ -112,23 +111,21 @@ abstract class TestCommandBase { this.$projectData.initializeProjectData(); this.$analyticsService.setShouldDispose( - this.$options.justlaunch || !this.$options.watch + this.$options.justlaunch || !this.$options.watch, ); this.$cleanupService.setShouldDispose( - this.$options.justlaunch || !this.$options.watch + this.$options.justlaunch || !this.$options.watch, ); - const output = await this.$platformEnvironmentRequirements.checkEnvironmentRequirements( - { + const output = + await this.$platformEnvironmentRequirements.checkEnvironmentRequirements({ platform: this.platform, projectDir: this.$projectData.projectDir, options: this.$options, - } - ); + }); - const canStartKarmaServer = await this.$testExecutionService.canStartKarmaServer( - this.$projectData - ); + const canStartKarmaServer = + await this.$testExecutionService.canStartKarmaServer(this.$projectData); if (!canStartKarmaServer) { this.$errors.fail({ formatStr: @@ -154,7 +151,7 @@ class TestAndroidCommand extends TestCommandBase implements ICommand { protected $cleanupService: ICleanupService, protected $liveSyncCommandHelper: ILiveSyncCommandHelper, protected $devicesService: Mobile.IDevicesService, - protected $migrateController: IMigrateController + protected $migrateController: IMigrateController, ) { super(); } @@ -195,7 +192,7 @@ class TestIosCommand extends TestCommandBase implements ICommand { protected $cleanupService: ICleanupService, protected $liveSyncCommandHelper: ILiveSyncCommandHelper, protected $devicesService: Mobile.IDevicesService, - protected $migrateController: IMigrateController + protected $migrateController: IMigrateController, ) { super(); } diff --git a/lib/common/declarations.d.ts b/lib/common/declarations.d.ts index 9102cdea65..7051536343 100644 --- a/lib/common/declarations.d.ts +++ b/lib/common/declarations.d.ts @@ -35,10 +35,6 @@ interface IiTunesConnectApplicationType { * Their values are the names of the methods in universnal-analytics that have to be called to track this type of data. * Also known as Hit Type: https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters#t */ -declare const enum GoogleAnalyticsDataType { - Page = "pageview", - Event = "event", -} /** * Descibes iTunes Connect applications @@ -170,7 +166,7 @@ declare module Server { httpRequest(url: string): Promise; httpRequest( options: any, - proxySettings?: IProxySettings + proxySettings?: IProxySettings, ): Promise; } @@ -196,79 +192,14 @@ interface IShouldDispose { /** * Describes the type of data sent to analytics service. */ -declare const enum TrackingTypes { - /** - * Defines that the data contains information for initialization of a new Analytics monitor. - */ - Initialization = "initialization", - - /** - * Defines that the data contains exception that should be tracked. - */ - Exception = "exception", - - /** - * Defines that the data contains the answer of the question if user allows to be tracked. - */ - AcceptTrackFeatureUsage = "acceptTrackFeatureUsage", - - /** - * Defines data that will be tracked to Google Analytics. - */ - GoogleAnalyticsData = "googleAnalyticsData", - - /** - * Defines that the broker process should send all the pending information to Analytics. - * After that the process should send information it has finished tracking and die gracefully. - */ - FinishTracking = "FinishTracking", -} /** * Describes the status of the current Analytics status, i.e. has the user allowed to be tracked. */ -declare const enum AnalyticsStatus { - /** - * User has allowed to be tracked. - */ - enabled = "enabled", - - /** - * User has declined to be tracked. - */ - disabled = "disabled", - - /** - * User has not been asked to allow feature and error tracking. - */ - notConfirmed = "not confirmed", -} /** * Describes types of options that manage -- flags. */ -declare const enum OptionType { - /** - * String option - */ - String = "string", - /** - * Boolean option - */ - Boolean = "boolean", - /** - * Number option - */ - Number = "number", - /** - * Array option - */ - Array = "array", - /** - * Object option - */ - Object = "object", -} /** * Describes options that can be passed to fs.readFile method. @@ -289,13 +220,13 @@ interface IFileSystem { zipFiles( zipFile: string, files: string[], - zipPathCallback: (path: string) => string + zipPathCallback: (path: string) => string, ): Promise; unzip( zipFile: string, destinationDir: string, options?: { overwriteExisitingFiles?: boolean; caseSensitive?: boolean }, - fileFilters?: string[] + fileFilters?: string[], ): Promise; /** @@ -351,7 +282,7 @@ interface IFileSystem { futureFromEvent( eventEmitter: NodeJS.EventEmitter, - event: string + event: string, ): Promise; /** @@ -424,7 +355,7 @@ interface IFileSystem { filename: string, data: any, space?: string, - encoding?: string + encoding?: string, ): void; /** @@ -450,7 +381,7 @@ interface IFileSystem { isEmptyDir(directoryPath: string): boolean; isRelativePath( - path: string + path: string, ): boolean /* feels so lonely here, I don't have a Future */; /** @@ -523,7 +454,7 @@ interface IFileSystem { start?: number; end?: number; highWaterMark?: number; - } + }, ): NodeJS.ReadableStream; createWriteStream( path: string, @@ -531,7 +462,7 @@ interface IFileSystem { flags?: string; encoding?: string; string?: string; - } + }, ): any; /** @@ -546,7 +477,10 @@ interface IFileSystem { enumerateFilesInDirectorySync( directoryPath: string, filterCallback?: (file: string, stat: IFsStats) => boolean, - opts?: { enumerateDirectories?: boolean; includeEmptyDirectories?: boolean } + opts?: { + enumerateDirectories?: boolean; + includeEmptyDirectories?: boolean; + }, ): string[]; /** @@ -557,7 +491,7 @@ interface IFileSystem { */ getFileShasum( fileName: string, - options?: { algorithm?: string; encoding?: "hex" | "base64" } + options?: { algorithm?: string; encoding?: "hex" | "base64" }, ): Promise; // shell.js wrappers @@ -626,7 +560,7 @@ interface IErrors { failWithHelp(opts: IFailOptions, ...args: any[]): never; beginCommand( action: () => Promise, - printCommandHelp: () => Promise + printCommandHelp: () => Promise, ): Promise; verifyHeap(message: string): void; printCallStack: boolean; @@ -656,18 +590,6 @@ interface ICommandOptions { disableCommandHelpSuggestion?: boolean; } -declare const enum ErrorCodes { - UNCAUGHT = 120, - UNKNOWN = 127, - INVALID_ARGUMENT = 128, - RESOURCE_PROBLEM = 129, - KARMA_FAIL = 130, - UNHANDLED_REJECTION_FAILURE = 131, - DELETED_KILL_FILE = 132, - TESTS_INIT_REQUIRED = 133, - ALL_DEVICES_DISCONNECTED = 134, -} - interface IFutureDispatcher { run(): void; dispatch(action: () => Promise): void; @@ -691,33 +613,33 @@ interface IChildProcess extends NodeJS.EventEmitter { exec( command: string, options?: any, - execOptions?: IExecOptions + execOptions?: IExecOptions, ): Promise; execFile(command: string, args: string[]): Promise; spawn( command: string, args?: string[], - options?: any + options?: any, ): child_process.ChildProcess; // it returns child_process.ChildProcess you can safely cast to it spawnFromEvent( command: string, args: string[], event: string, options?: any, - spawnFromEventOptions?: ISpawnFromEventOptions + spawnFromEventOptions?: ISpawnFromEventOptions, ): Promise; trySpawnFromCloseEvent( command: string, args: string[], options?: any, - spawnFromEventOptions?: ISpawnFromEventOptions + spawnFromEventOptions?: ISpawnFromEventOptions, ): Promise; tryExecuteApplication( command: string, args: string[], event: string, errorMessage: string, - condition?: (childProcess: any) => boolean + condition?: (childProcess: any) => boolean, ): Promise; /** * This is a special case of the child_process.spawn() functionality for spawning Node.js processes. @@ -739,7 +661,7 @@ interface IChildProcess extends NodeJS.EventEmitter { silent?: boolean; uid?: number; gid?: number; - } + }, ): any; } @@ -781,7 +703,7 @@ interface IAnalyticsService { getStatusMessage( settingName: string, jsonFormat: boolean, - readableSettingName: string + readableSettingName: string, ): Promise; isEnabled(settingName: string): Promise; finishTracking(): Promise; @@ -828,7 +750,7 @@ interface IPrompterOptions extends IAllowEmpty { type IPrompterAnswers = { [id in T]: any }; interface IPrompterQuestion< - T extends IPrompterAnswers = IPrompterAnswers + T extends IPrompterAnswers = IPrompterAnswers, > { type?: string; name?: string; @@ -839,7 +761,7 @@ interface IPrompterQuestion< filter?(input: any, answers: T): any; validate?( input: any, - answers?: T + answers?: T, ): boolean | string | Promise; } @@ -906,11 +828,11 @@ interface IHooksService { hookArgsName: string; executeBeforeHooks( commandName: string, - hookArguments?: IDictionary + hookArguments?: IDictionary, ): Promise; executeAfterHooks( commandName: string, - hookArguments?: IDictionary + hookArguments?: IDictionary, ): Promise; } @@ -938,9 +860,7 @@ interface IRejectUnauthorized { * Proxy settings required for http request. */ interface IProxySettings - extends IRejectUnauthorized, - ICredentials, - IProxySettingsBase { + extends IRejectUnauthorized, ICredentials, IProxySettingsBase { /** * Hostname of the machine used for proxy. */ @@ -1077,7 +997,7 @@ interface ISystemWarning { interface ISysInfo { getSysInfo( - config?: NativeScriptDoctor.ISysInfoConfig + config?: NativeScriptDoctor.ISysInfoConfig, ): Promise; /** * Returns the currently installed version of Xcode. @@ -1438,14 +1358,14 @@ interface IProjectFilesManager { projectFilesPath: string, excludedProjectDirsAndFiles?: string[], filter?: (filePath: string, stat: IFsStats) => boolean, - opts?: any + opts?: any, ): string[]; /** * Checks if the file is excluded */ isFileExcluded( filePath: string, - excludedProjectDirsAndFiles?: string[] + excludedProjectDirsAndFiles?: string[], ): boolean; /** * Returns an object that maps every local file path to device file path @@ -1456,7 +1376,7 @@ interface IProjectFilesManager { projectFilesPath: string, files: string[], excludedProjectDirsAndFiles: string[], - projectFilesConfig?: IProjectFilesConfig + projectFilesConfig?: IProjectFilesConfig, ): Promise; /** @@ -1471,7 +1391,7 @@ interface IProjectFilesManager { directoryPath: string, platform: string, projectFilesConfig?: IProjectFilesConfig, - excludedDirs?: string[] + excludedDirs?: string[], ): void; } @@ -1487,7 +1407,7 @@ interface IProjectFilesProvider { filePath: string, platform: string, projectData: any, - projectFilesConfig?: IProjectFilesConfig + projectFilesConfig?: IProjectFilesConfig, ): string; /** @@ -1500,7 +1420,7 @@ interface IProjectFilesProvider { getProjectFileInfo( filePath: string, platform: string, - projectFilesConfig: IProjectFilesConfig + projectFilesConfig: IProjectFilesConfig, ): IProjectFileInfo; /** * Parses file by removing platform or configuration from its name. @@ -1510,7 +1430,7 @@ interface IProjectFilesProvider { */ getPreparedFilePath( filePath: string, - projectFilesConfig: IProjectFilesConfig + projectFilesConfig: IProjectFilesConfig, ): string; } @@ -1612,7 +1532,7 @@ interface INet { * @returns {boolean} true in case port is in LISTEN state, false otherwise. */ waitForPortToListen( - waitForPortListenData: IWaitForPortListenData + waitForPortListenData: IWaitForPortListenData, ): Promise; } @@ -1680,7 +1600,7 @@ interface IiOSNotificationService { awaitNotification( deviceIdentifier: string, socket: number, - timeout: number + timeout: number, ): Promise; /** @@ -1693,7 +1613,7 @@ interface IiOSNotificationService { postNotification( deviceIdentifier: string, notification: string, - commandType?: string + commandType?: string, ): Promise; } diff --git a/lib/common/definitions/key-commands.d.ts b/lib/common/definitions/key-commands.ts similarity index 90% rename from lib/common/definitions/key-commands.d.ts rename to lib/common/definitions/key-commands.ts index 2c4522b929..ff08673439 100644 --- a/lib/common/definitions/key-commands.d.ts +++ b/lib/common/definitions/key-commands.ts @@ -29,7 +29,7 @@ export type IKeysLowerCase = export type IKeysUpperCase = Uppercase; -export const enum SpecialKeys { +export enum SpecialKeys { CtrlC = "\u0003", QuestionMark = "?", } @@ -41,11 +41,11 @@ export type IValidKeyName = IKeysLowerCase | IKeysUpperCase | IKeysSpecial; export interface IKeyCommandHelper { attachKeyCommands: ( platform: IKeyCommandPlatform, - processType: SupportedProcessType + processType: SupportedProcessType, ) => void; - addOverride(key: IValidKeyName, execute: () => Promise); - removeOverride(key: IValidKeyName); + addOverride(key: IValidKeyName, execute: () => Promise): void; + removeOverride(key: IValidKeyName): void; printCommands(platform: IKeyCommandPlatform): void; } diff --git a/lib/common/enums.ts b/lib/common/enums.ts new file mode 100644 index 0000000000..f432f19269 --- /dev/null +++ b/lib/common/enums.ts @@ -0,0 +1,84 @@ +export enum GoogleAnalyticsDataType { + Page = "pageview", + Event = "event", +} + +export enum TrackingTypes { + /** + * Defines that the data contains information for initialization of a new Analytics monitor. + */ + Initialization = "initialization", + + /** + * Defines that the data contains exception that should be tracked. + */ + Exception = "exception", + + /** + * Defines that the data contains the answer of the question if user allows to be tracked. + */ + AcceptTrackFeatureUsage = "acceptTrackFeatureUsage", + + /** + * Defines data that will be tracked to Google Analytics. + */ + GoogleAnalyticsData = "googleAnalyticsData", + + /** + * Defines that the broker process should send all the pending information to Analytics. + * After that the process should send information it has finished tracking and die gracefully. + */ + FinishTracking = "FinishTracking", +} + +export enum AnalyticsStatus { + /** + * User has allowed to be tracked. + */ + enabled = "enabled", + + /** + * User has declined to be tracked. + */ + disabled = "disabled", + + /** + * User has not been asked to allow feature and error tracking. + */ + notConfirmed = "not confirmed", +} + +export enum OptionType { + /** + * String option + */ + String = "string", + /** + * Boolean option + */ + Boolean = "boolean", + /** + * Number option + */ + Number = "number", + /** + * Array option + */ + Array = "array", + /** + * Object option + */ + Object = "object", +} + +export enum ErrorCodes { + UNCAUGHT = 120, + UNKNOWN = 127, + INVALID_ARGUMENT = 128, + RESOURCE_PROBLEM = 129, + KARMA_FAIL = 130, + UNHANDLED_REJECTION_FAILURE = 131, + DELETED_KILL_FILE = 132, + TESTS_INIT_REQUIRED = 133, + ALL_DEVICES_DISCONNECTED = 134, +} diff --git a/lib/common/errors.ts b/lib/common/errors.ts index b75c8d759b..f0b9f489d8 100644 --- a/lib/common/errors.ts +++ b/lib/common/errors.ts @@ -4,7 +4,8 @@ import * as _ from "lodash"; import { SourceMapConsumer } from "source-map"; import { isInteractive } from "./helpers"; import { deprecated } from "./decorators"; -import { ErrorCodes, IErrors, IFailOptions } from "./declarations"; +import { IErrors, IFailOptions } from "./declarations"; +import { ErrorCodes } from "./enums"; import { IInjector } from "./definitions/yok"; import { injector } from "./yok"; @@ -64,7 +65,7 @@ async function resolveCallStack(error: Error): Promise { functionName, source, sourcePos.line, - sourcePos.column + sourcePos.column, ); } @@ -73,10 +74,10 @@ async function resolveCallStack(error: Error): Promise { functionName, fileName, line, - column + column, ); }); - }) + }), ); let outputMessage = remapped.join("\n"); @@ -90,7 +91,7 @@ async function resolveCallStack(error: Error): Promise { } export function installUncaughtExceptionListener( - actionOnException?: () => void + actionOnException?: () => void, ): void { const handler = async (err: Error) => { try { @@ -123,7 +124,7 @@ export function installUncaughtExceptionListener( async function tryTrackException( error: Error, - localInjector: IInjector + localInjector: IInjector, ): Promise { let disableAnalytics: boolean; try { @@ -190,13 +191,13 @@ export class Errors implements IErrors { exception.name = opts.name || "Exception"; exception.message = util.format.apply( null, - [opts.formatStr].concat(argsArray) + [opts.formatStr].concat(argsArray), ); try { const $messagesService = this.$injector.resolve("messagesService"); exception.message = $messagesService.getMessage.apply( $messagesService, - [opts.formatStr].concat(argsArray) + [opts.formatStr].concat(argsArray), ); } catch (err) { // Ignore @@ -214,7 +215,7 @@ export class Errors implements IErrors { public async beginCommand( action: () => Promise, - printCommandHelpSuggestion: () => Promise + printCommandHelpSuggestion: () => Promise, ): Promise { try { return await action(); @@ -228,8 +229,8 @@ export class Errors implements IErrors { const message = printCallStack ? await resolveCallStack(ex) : isInteractive() - ? `\x1B[31;1m${ex.message}\x1B[0m` - : ex.message; + ? `\x1B[31;1m${ex.message}\x1B[0m` + : ex.message; if (ex.printOnStdout) { logger.info(message); @@ -243,7 +244,7 @@ export class Errors implements IErrors { await tryTrackException(ex, this.$injector); process.exit( - _.isNumber(ex.errorCode) ? ex.errorCode : ErrorCodes.UNKNOWN + _.isNumber(ex.errorCode) ? ex.errorCode : ErrorCodes.UNKNOWN, ); } } diff --git a/lib/common/services/analytics/google-analytics-custom-dimensions.d.ts b/lib/common/services/analytics/google-analytics-custom-dimensions.ts similarity index 86% rename from lib/common/services/analytics/google-analytics-custom-dimensions.d.ts rename to lib/common/services/analytics/google-analytics-custom-dimensions.ts index 59897cd96e..d87ccf80cc 100644 --- a/lib/common/services/analytics/google-analytics-custom-dimensions.d.ts +++ b/lib/common/services/analytics/google-analytics-custom-dimensions.ts @@ -1,4 +1,4 @@ -declare const enum GoogleAnalyticsCustomDimensions { +export enum GoogleAnalyticsCustomDimensions { cliVersion = "cd1", projectType = "cd2", clientID = "cd3", diff --git a/lib/common/services/cancellation.ts b/lib/common/services/cancellation.ts index 98d25eaacf..f2f94c6522 100644 --- a/lib/common/services/cancellation.ts +++ b/lib/common/services/cancellation.ts @@ -7,8 +7,8 @@ import { IFileSystem, IDictionary, ICancellationService, - ErrorCodes, } from "../declarations"; +import { ErrorCodes } from "../enums"; import { injector } from "../yok"; class CancellationService implements ICancellationService { @@ -17,7 +17,7 @@ class CancellationService implements ICancellationService { constructor( private $fs: IFileSystem, private $logger: ILogger, - private $hostInfo: IHostInfo + private $hostInfo: IHostInfo, ) { if (this.$hostInfo.isWindows) { this.$fs.createDirectory(CancellationService.killSwitchDir); @@ -41,7 +41,7 @@ class CancellationService implements ICancellationService { .watch(triggerFile, { ignoreInitial: true }) .on("unlink", (filePath: string) => { this.$logger.info( - `Exiting process as the file ${filePath} has been deleted. Probably reinstalling CLI while there's a working instance.` + `Exiting process as the file ${filePath} has been deleted. Probably reinstalling CLI while there's a working instance.`, ); process.exit(ErrorCodes.DELETED_KILL_FILE); }); @@ -69,7 +69,7 @@ class CancellationService implements ICancellationService { return path.join( os.tmpdir(), process.env.SUDO_USER || process.env.USER || process.env.USERNAME || "", - "KillSwitches" + "KillSwitches", ); } diff --git a/lib/common/services/commands-service.ts b/lib/common/services/commands-service.ts index 898909c09e..5cfd87c9ad 100644 --- a/lib/common/services/commands-service.ts +++ b/lib/common/services/commands-service.ts @@ -4,12 +4,8 @@ import { CommandsDelimiters } from "../constants"; import { EOL } from "os"; import * as _ from "lodash"; import { IOptions, IOptionsTracker } from "../../declarations"; -import { - IErrors, - IHooksService, - IAnalyticsService, - GoogleAnalyticsDataType, -} from "../declarations"; +import { IErrors, IHooksService, IAnalyticsService } from "../declarations"; +import { GoogleAnalyticsDataType } from "../enums"; import { IInjector } from "../definitions/yok"; import { injector } from "../yok"; import { IExtensibilityService } from "../definitions/extensibility"; @@ -21,7 +17,10 @@ import { } from "../definitions/commands"; class CommandArgumentsValidationHelper { - constructor(public isValid: boolean, _remainingArguments: string[]) { + constructor( + public isValid: boolean, + _remainingArguments: string[], + ) { this.remainingArguments = _remainingArguments.slice(); } @@ -43,19 +42,19 @@ export class CommandsService implements ICommandsService { private $options: IOptions, private $staticConfig: Config.IStaticConfig, private $extensibilityService: IExtensibilityService, - private $optionsTracker: IOptionsTracker + private $optionsTracker: IOptionsTracker, ) {} public allCommands(opts: { includeDevCommands: boolean }): string[] { const commands = this.$injector.getRegisteredCommandsNames( - opts.includeDevCommands + opts.includeDevCommands, ); return _.reject(commands, (command) => _.includes(command, "|")); } public async executeCommandUnchecked( commandName: string, - commandArguments: string[] + commandArguments: string[], ): Promise { this.commands.push({ commandName, commandArguments }); const command = this.$injector.resolveCommand(commandName); @@ -70,7 +69,7 @@ export class CommandsService implements ICommandsService { await analyticsService.checkConsent(); const beautifiedCommandName = this.beautifyCommandName( - commandName + commandName, ).replace(/\|/g, " "); const googleAnalyticsPageData: IGoogleAnalyticsPageviewData = { @@ -90,18 +89,18 @@ export class CommandsService implements ICommandsService { // Handle correctly hierarchical commands const hierarchicalCommandName = this.$injector.buildHierarchicalCommand( commandName, - commandArguments + commandArguments, ); if (hierarchicalCommandName) { commandName = helpers.stringReplaceAll( hierarchicalCommandName.commandName, CommandsDelimiters.DefaultHierarchicalCommand, - CommandsDelimiters.HooksCommand + CommandsDelimiters.HooksCommand, ); commandName = helpers.stringReplaceAll( commandName, CommandsDelimiters.HierarchicalCommand, - CommandsDelimiters.HooksCommand + CommandsDelimiters.HooksCommand, ); } @@ -130,12 +129,12 @@ export class CommandsService implements ICommandsService { ? helpers.stringReplaceAll( this.beautifyCommandName(commandName), "|", - " " - ) + " " + " ", + ) + " " : ""; const commandHelp = `ns ${command}--help`; this.$logger.printMarkdown( - `__Run \`${commandHelp}\` for more information.__` + `__Run \`${commandHelp}\` for more information.__`, ); return; } @@ -145,18 +144,18 @@ export class CommandsService implements ICommandsService { commandArguments: string[], action: ( _commandName: string, - _commandArguments: string[] - ) => Promise + _commandArguments: string[], + ) => Promise, ): Promise { return this.$errors.beginCommand( () => action.apply(this, [commandName, commandArguments]), - () => this.printHelpSuggestion(commandName) + () => this.printHelpSuggestion(commandName), ); } private async tryExecuteCommandAction( commandName: string, - commandArguments: string[] + commandArguments: string[], ): Promise { const command = this.$injector.resolveCommand(commandName); if (!command || !command.isHierarchicalCommand) { @@ -169,12 +168,12 @@ export class CommandsService implements ICommandsService { public async tryExecuteCommand( commandName: string, - commandArguments: string[] + commandArguments: string[], ): Promise { const canExecuteResult: any = await this.executeCommandAction( commandName, commandArguments, - this.tryExecuteCommandAction + this.tryExecuteCommandAction, ); const canExecute = typeof canExecuteResult === "object" @@ -185,7 +184,7 @@ export class CommandsService implements ICommandsService { await this.executeCommandAction( commandName, commandArguments, - this.executeCommandUnchecked + this.executeCommandUnchecked, ); } else { // If canExecuteCommand returns false, the command cannot be executed or there's no such command at all. @@ -204,7 +203,7 @@ export class CommandsService implements ICommandsService { private async canExecuteCommand( commandName: string, commandArguments: string[], - isDynamicCommand?: boolean + isDynamicCommand?: boolean, ): Promise { const command = this.$injector.resolveCommand(commandName); const beautifiedName = helpers.stringReplaceAll(commandName, "|", " "); @@ -212,7 +211,7 @@ export class CommandsService implements ICommandsService { // Verify command is enabled if (command.isDisabled) { this.$errors.fail( - "This command is not applicable to your environment." + "This command is not applicable to your environment.", ); } @@ -225,7 +224,7 @@ export class CommandsService implements ICommandsService { if ( await this.$injector.isValidHierarchicalCommand( commandName, - commandArguments + commandArguments, ) ) { return true; @@ -247,7 +246,7 @@ export class CommandsService implements ICommandsService { const extensionData = await this.$extensibilityService.getExtensionNameWhereCommandIsRegistered( - commandInfo + commandInfo, ); if (extensionData) { @@ -263,11 +262,11 @@ export class CommandsService implements ICommandsService { private async validateMandatoryParams( commandArguments: string[], - mandatoryParams: ICommandParameter[] + mandatoryParams: ICommandParameter[], ): Promise { const commandArgsHelper = new CommandArgumentsValidationHelper( true, - commandArguments + commandArguments, ); if (mandatoryParams.length > 0) { @@ -275,12 +274,12 @@ export class CommandsService implements ICommandsService { if (mandatoryParams.length > commandArguments.length) { const customErrorMessages = _.map( mandatoryParams, - (mp) => mp.errorMessage + (mp) => mp.errorMessage, ); customErrorMessages.splice( 0, 0, - "You need to provide all the required parameters." + "You need to provide all the required parameters.", ); this.$errors.failWithHelp(customErrorMessages.join(EOL)); } @@ -308,7 +307,7 @@ export class CommandsService implements ICommandsService { if (argument) { helpers.remove( commandArgsHelper.remainingArguments, - (arg) => arg === argument + (arg) => arg === argument, ); } else { this.$errors.failWithHelp("Missing mandatory parameter."); @@ -321,15 +320,15 @@ export class CommandsService implements ICommandsService { private async validateCommandArguments( command: ICommand, - commandArguments: string[] + commandArguments: string[], ): Promise { const mandatoryParams: ICommandParameter[] = _.filter( command.allowedParameters, - (param) => param.mandatory + (param) => param.mandatory, ); const commandArgsHelper = await this.validateMandatoryParams( commandArguments, - mandatoryParams + mandatoryParams, ); if (!commandArgsHelper.isValid) { return false; @@ -343,7 +342,7 @@ export class CommandsService implements ICommandsService { } else { // Exclude mandatory params, we've already checked them const unverifiedAllowedParams = command.allowedParameters.filter( - (param) => !param.mandatory + (param) => !param.mandatory, ); for ( @@ -372,7 +371,7 @@ export class CommandsService implements ICommandsService { unverifiedAllowedParams.splice(index, 1); } else { this.$errors.failWithHelp( - `The parameter ${argument} is not valid for this command.` + `The parameter ${argument} is not valid for this command.`, ); } } diff --git a/lib/common/verify-node-version.ts b/lib/common/verify-node-version.ts index fa13e858ba..5a759c6478 100644 --- a/lib/common/verify-node-version.ts +++ b/lib/common/verify-node-version.ts @@ -2,6 +2,7 @@ import { color } from "../color"; import { ISystemWarning } from "./declarations"; +import { SystemWarningsSeverity } from "../definitions/system-warnings"; // Use only ES5 code here - pure JavaScript can be executed with any Node.js version (even 0.10, 0.12). /* tslint:disable:no-var-keyword no-var-requires prefer-const*/ diff --git a/lib/constants.ts b/lib/constants.ts index 59a3811b6a..e6584b274f 100644 --- a/lib/constants.ts +++ b/lib/constants.ts @@ -506,3 +506,8 @@ export enum PackageManagers { yarn2 = "yarn2", bun = "bun", } + +export enum BuildNames { + debug = "Debug", + release = "Release", +} diff --git a/lib/definitions/project.d.ts b/lib/definitions/project.d.ts index ce15f986c2..4dd9a85a6a 100644 --- a/lib/definitions/project.d.ts +++ b/lib/definitions/project.d.ts @@ -1,4 +1,4 @@ -import type { SupportedPlatform } from "../constants"; +import type { BuildNames, SupportedPlatform } from "../constants"; import { IAndroidBuildOptionsSettings, IProvision, @@ -810,11 +810,6 @@ interface ICocoaPodsPlatformManager { ): { replacedContent: string; podfilePlatformData: IPodfilePlatformData }; } -declare const enum BuildNames { - debug = "Debug", - release = "Release", -} - interface IXcodeTargetBuildConfigurationProperty { name: string; value: any; diff --git a/lib/definitions/system-warnings.d.ts b/lib/definitions/system-warnings.d.ts deleted file mode 100644 index 9985675340..0000000000 --- a/lib/definitions/system-warnings.d.ts +++ /dev/null @@ -1,4 +0,0 @@ -declare const enum SystemWarningsSeverity { - medium = "medium", - high = "high", -} diff --git a/lib/definitions/system-warnings.ts b/lib/definitions/system-warnings.ts new file mode 100644 index 0000000000..b6a53c1962 --- /dev/null +++ b/lib/definitions/system-warnings.ts @@ -0,0 +1,4 @@ +export enum SystemWarningsSeverity { + medium = "medium", + high = "high", +} diff --git a/lib/detached-processes/cleanup-js-subprocess.ts b/lib/detached-processes/cleanup-js-subprocess.ts index e5a5000077..9c262d2c4c 100644 --- a/lib/detached-processes/cleanup-js-subprocess.ts +++ b/lib/detached-processes/cleanup-js-subprocess.ts @@ -6,6 +6,7 @@ import * as fs from "fs"; import { v4 as uuidv4 } from "uuid"; import { FileLogService } from "./file-log-service"; import { injector } from "../common/yok"; +import { FileLogMessageType } from "./detached-process-enums"; const pathToBootstrap = process.argv[2]; if (!pathToBootstrap || !fs.existsSync(pathToBootstrap)) { @@ -51,28 +52,28 @@ const logMessage = (msg: string, type?: FileLogMessageType): void => { try { logMessage( `Passing data: ${JSON.stringify( - data - )} to the default function exported by currently required file ${jsFilePath}` + data, + )} to the default function exported by currently required file ${jsFilePath}`, ); await func(data); logMessage( `Finished execution with data: ${JSON.stringify( - data - )} to the default function exported by currently required file ${jsFilePath}` + data, + )} to the default function exported by currently required file ${jsFilePath}`, ); } catch (err) { logMessage( `Unable to execute action of file ${jsFilePath} when passed data is ${JSON.stringify( - data + data, )}. Error is: ${err}.`, - FileLogMessageType.Error + FileLogMessageType.Error, ); } } } catch (err) { logMessage( `Unable to require file: ${jsFilePath}. Error is: ${err}.`, - FileLogMessageType.Error + FileLogMessageType.Error, ); } })(); diff --git a/lib/detached-processes/cleanup-process.ts b/lib/detached-processes/cleanup-process.ts index 514766d7ba..2e0e9501b0 100644 --- a/lib/detached-processes/cleanup-process.ts +++ b/lib/detached-processes/cleanup-process.ts @@ -17,6 +17,11 @@ import { IFileCleanupMessage, } from "./cleanup-process-definitions"; import { Server, IChildProcess } from "../common/declarations"; +import { + CleanupProcessMessage, + DetachedProcessMessages, + FileLogMessageType, +} from "./detached-process-enums"; const pathToBootstrap = process.argv[2]; if (!pathToBootstrap || !fs.existsSync(pathToBootstrap)) { @@ -81,7 +86,7 @@ const executeJSCleanup = async (jsCommand: IJSCommand) => { JSON.stringify(jsCommand.data), ], {}, - { throwError: true, timeout: jsCommand.timeout || 3000 } + { throwError: true, timeout: jsCommand.timeout || 3000 }, ); fileLogService.logData({ message: `Finished executing action for file: ${ @@ -119,17 +124,17 @@ const executeCleanup = async () => { commandInfo.command, commandInfo.args, commandInfo.options || {}, - { throwError: true, timeout: commandInfo.timeout || 3000 } + { throwError: true, timeout: commandInfo.timeout || 3000 }, ); fileLogService.logData({ message: `Successfully executed command: ${JSON.stringify( - commandInfo + commandInfo, )}`, }); } catch (err) { fileLogService.logData({ message: `Unable to execute command: ${JSON.stringify( - commandInfo + commandInfo, )}. Error is: ${err}.`, type: FileLogMessageType.Error, }); @@ -145,7 +150,7 @@ const executeCleanup = async () => { } catch (err) { fileLogService.logData({ message: `Unable to delete files: ${JSON.stringify( - filesToDelete + filesToDelete, )}. Error is: ${err}.`, type: FileLogMessageType.Error, }); @@ -159,18 +164,18 @@ const executeCleanup = async () => { const addCleanupAction = (commandInfo: ISpawnCommandInfo): void => { if ( _.some(commandsInfos, (currentCommandInfo) => - _.isEqual(currentCommandInfo, commandInfo) + _.isEqual(currentCommandInfo, commandInfo), ) ) { fileLogService.logData({ message: `cleanup-process will not add command for execution as it has been added already: ${JSON.stringify( - commandInfo + commandInfo, )}`, }); } else { fileLogService.logData({ message: `cleanup-process added command for execution: ${JSON.stringify( - commandInfo + commandInfo, )}`, }); commandsInfos.push(commandInfo); @@ -180,21 +185,21 @@ const addCleanupAction = (commandInfo: ISpawnCommandInfo): void => { const removeCleanupAction = (commandInfo: ISpawnCommandInfo): void => { if ( _.some(commandsInfos, (currentCommandInfo) => - _.isEqual(currentCommandInfo, commandInfo) + _.isEqual(currentCommandInfo, commandInfo), ) ) { _.remove(commandsInfos, (currentCommandInfo) => - _.isEqual(currentCommandInfo, commandInfo) + _.isEqual(currentCommandInfo, commandInfo), ); fileLogService.logData({ message: `cleanup-process removed command for execution: ${JSON.stringify( - commandInfo + commandInfo, )}`, }); } else { fileLogService.logData({ message: `cleanup-process cannot remove command for execution as it has not been added before: ${JSON.stringify( - commandInfo + commandInfo, )}`, }); } @@ -203,18 +208,18 @@ const removeCleanupAction = (commandInfo: ISpawnCommandInfo): void => { const addRequest = (requestInfo: IRequestInfo): void => { if ( _.some(requests, (currentRequestInfo) => - _.isEqual(currentRequestInfo, requestInfo) + _.isEqual(currentRequestInfo, requestInfo), ) ) { fileLogService.logData({ message: `cleanup-process will not add request for execution as it has been added already: ${JSON.stringify( - requestInfo + requestInfo, )}`, }); } else { fileLogService.logData({ message: `cleanup-process added request for execution: ${JSON.stringify( - requestInfo + requestInfo, )}`, }); requests.push(requestInfo); @@ -224,21 +229,21 @@ const addRequest = (requestInfo: IRequestInfo): void => { const removeRequest = (requestInfo: IRequestInfo): void => { if ( _.some(requests, (currentRequestInfo) => - _.isEqual(currentRequestInfo, currentRequestInfo) + _.isEqual(currentRequestInfo, currentRequestInfo), ) ) { _.remove(requests, (currentRequestInfo) => - _.isEqual(currentRequestInfo, requestInfo) + _.isEqual(currentRequestInfo, requestInfo), ); fileLogService.logData({ message: `cleanup-process removed request for execution: ${JSON.stringify( - requestInfo + requestInfo, )}`, }); } else { fileLogService.logData({ message: `cleanup-process cannot remove request for execution as it has not been added before: ${JSON.stringify( - requestInfo + requestInfo, )}`, }); } @@ -281,18 +286,18 @@ const addJSFile = (jsCommand: IJSCommand): void => { if ( _.some(jsCommands, (currentJSCommand) => - _.isEqual(currentJSCommand, jsCommand) + _.isEqual(currentJSCommand, jsCommand), ) ) { fileLogService.logData({ message: `cleanup-process will not add JS file for execution as it has been added already: ${JSON.stringify( - jsCommand + jsCommand, )}`, }); } else { fileLogService.logData({ message: `cleanup-process added JS file for execution: ${JSON.stringify( - jsCommand + jsCommand, )}`, }); jsCommands.push(jsCommand); @@ -306,21 +311,21 @@ const removeJSFile = (jsCommand: IJSCommand): void => { if ( _.some(jsCommands, (currentJSCommand) => - _.isEqual(currentJSCommand, jsCommand) + _.isEqual(currentJSCommand, jsCommand), ) ) { _.remove(jsCommands, (currentJSCommand) => - _.isEqual(currentJSCommand, jsCommand) + _.isEqual(currentJSCommand, jsCommand), ); fileLogService.logData({ message: `cleanup-process removed JS action for execution: ${JSON.stringify( - jsCommand + jsCommand, )}`, }); } else { fileLogService.logData({ message: `cleanup-process cannot remove JS action for execution as it has not been added before: ${JSON.stringify( - jsCommand + jsCommand, )}`, }); } @@ -329,19 +334,19 @@ const removeJSFile = (jsCommand: IJSCommand): void => { process.on("message", async (cleanupProcessMessage: ICleanupMessageBase) => { fileLogService.logData({ message: `cleanup-process received message of type: ${JSON.stringify( - cleanupProcessMessage + cleanupProcessMessage, )}`, }); switch (cleanupProcessMessage.messageType) { case CleanupProcessMessage.AddCleanCommand: addCleanupAction( - (cleanupProcessMessage).commandInfo + (cleanupProcessMessage).commandInfo, ); break; case CleanupProcessMessage.RemoveCleanCommand: removeCleanupAction( - (cleanupProcessMessage).commandInfo + (cleanupProcessMessage).commandInfo, ); break; case CleanupProcessMessage.AddRequest: @@ -349,7 +354,7 @@ process.on("message", async (cleanupProcessMessage: ICleanupMessageBase) => { break; case CleanupProcessMessage.RemoveRequest: removeRequest( - (cleanupProcessMessage).requestInfo + (cleanupProcessMessage).requestInfo, ); break; case CleanupProcessMessage.AddDeleteFileAction: diff --git a/lib/detached-processes/detached-process-enums.d.ts b/lib/detached-processes/detached-process-enums.ts similarity index 93% rename from lib/detached-processes/detached-process-enums.d.ts rename to lib/detached-processes/detached-process-enums.ts index 13e11a78a3..4c6695ac60 100644 --- a/lib/detached-processes/detached-process-enums.d.ts +++ b/lib/detached-processes/detached-process-enums.ts @@ -1,7 +1,7 @@ /** * Defines messages used in communication between CLI's process and analytics subprocesses. */ -declare const enum DetachedProcessMessages { +export enum DetachedProcessMessages { /** * The detached process is initialized and is ready to receive information for tracking. */ @@ -16,7 +16,7 @@ declare const enum DetachedProcessMessages { /** * Defines the type of the messages that should be written in the local analyitcs log file (in case such is specified). */ -declare const enum FileLogMessageType { +export enum FileLogMessageType { /** * Information message. This is the default value in case type is not specified. */ @@ -28,7 +28,7 @@ declare const enum FileLogMessageType { Error = "Error", } -declare const enum CleanupProcessMessage { +export enum CleanupProcessMessage { /** * This type of message defines that cleanup procedure should execute specific command. */ diff --git a/lib/detached-processes/file-log-service.ts b/lib/detached-processes/file-log-service.ts index 6684784842..5ab23aee37 100644 --- a/lib/detached-processes/file-log-service.ts +++ b/lib/detached-processes/file-log-service.ts @@ -1,9 +1,13 @@ import { EOL } from "os"; import { getFixedLengthDateString } from "../common/helpers"; import { IFileSystem } from "../common/declarations"; +import { FileLogMessageType } from "./detached-process-enums"; export class FileLogService implements IFileLogService { - constructor(private $fs: IFileSystem, private logFile: string) {} + constructor( + private $fs: IFileSystem, + private logFile: string, + ) {} public logData(fileLoggingMessage: IFileLogMessage): void { if (this.logFile && fileLoggingMessage && fileLoggingMessage.message) { @@ -12,7 +16,7 @@ export class FileLogService implements IFileLogService { const formattedDate = getFixedLengthDateString(); this.$fs.appendFile( this.logFile, - `[${formattedDate}] [${fileLoggingMessage.type}] ${fileLoggingMessage.message}${EOL}` + `[${formattedDate}] [${fileLoggingMessage.type}] ${fileLoggingMessage.message}${EOL}`, ); } } diff --git a/lib/helpers/livesync-command-helper.ts b/lib/helpers/livesync-command-helper.ts index ea9cc44ea4..432b931e76 100644 --- a/lib/helpers/livesync-command-helper.ts +++ b/lib/helpers/livesync-command-helper.ts @@ -1,10 +1,10 @@ import * as _ from "lodash"; import { - ErrorCodes, IAnalyticsService, IDictionary, IErrors, } from "../common/declarations"; +import { ErrorCodes } from "../common/enums"; import { IInjector } from "../common/definitions/yok"; import { injector } from "../common/yok"; import { RunOnDeviceEvents } from "../constants"; @@ -31,7 +31,7 @@ export class LiveSyncCommandHelper implements ILiveSyncCommandHelper { private $errors: IErrors, private $iOSSimulatorLogProvider: Mobile.IiOSSimulatorLogProvider, private $cleanupService: ICleanupService, - private $runController: IRunController + private $runController: IRunController, ) {} private get $platformsDataService(): IPlatformsDataService { @@ -56,7 +56,7 @@ export class LiveSyncCommandHelper implements ILiveSyncCommandHelper { } public async getDeviceInstances( - platform?: string + platform?: string, ): Promise { await this.$devicesService.initialize({ platform, @@ -71,7 +71,7 @@ export class LiveSyncCommandHelper implements ILiveSyncCommandHelper { .filter( (d) => !platform || - d.deviceInfo.platform.toLowerCase() === platform.toLowerCase() + d.deviceInfo.platform.toLowerCase() === platform.toLowerCase(), ); return devices; @@ -80,7 +80,7 @@ export class LiveSyncCommandHelper implements ILiveSyncCommandHelper { public async createDeviceDescriptors( devices: Mobile.IDevice[], platform: string, - additionalOptions?: ILiveSyncCommandHelperAdditionalOptions + additionalOptions?: ILiveSyncCommandHelperAdditionalOptions, ): Promise { // Now let's take data for each device: const deviceDescriptors: ILiveSyncDeviceDescriptor[] = devices.map((d) => { @@ -105,7 +105,7 @@ export class LiveSyncCommandHelper implements ILiveSyncCommandHelper { forceRebuildNativeApp: additionalOptions.forceRebuildNativeApp, }, _device: d, - } + }, ); this.$androidBundleValidatorHelper.validateDeviceApiLevel(d, buildData); @@ -115,8 +115,8 @@ export class LiveSyncCommandHelper implements ILiveSyncCommandHelper { additionalOptions.buildPlatform, d.deviceInfo.platform, buildData, - this.$projectData - ) + this.$projectData, + ) : this.$buildController.build.bind(this.$buildController, buildData); const info: ILiveSyncDeviceDescriptor = { @@ -142,14 +142,14 @@ export class LiveSyncCommandHelper implements ILiveSyncCommandHelper { const availablePlatforms = platform ? [platform] : _.values( - this.$mobileHelper.platformNames.map((p) => p.toLowerCase()) - ); + this.$mobileHelper.platformNames.map((p) => p.toLowerCase()), + ); return availablePlatforms; } public async executeCommandLiveSync( platform?: string, - additionalOptions?: ILiveSyncCommandHelperAdditionalOptions + additionalOptions?: ILiveSyncCommandHelperAdditionalOptions, ) { const devices = await this.getDeviceInstances(platform); await this.executeLiveSyncOperation(devices, platform, additionalOptions); @@ -158,13 +158,13 @@ export class LiveSyncCommandHelper implements ILiveSyncCommandHelper { public async executeLiveSyncOperation( devices: Mobile.IDevice[], platform: string, - additionalOptions?: ILiveSyncCommandHelperAdditionalOptions + additionalOptions?: ILiveSyncCommandHelperAdditionalOptions, ): Promise { const { liveSyncInfo, deviceDescriptors } = await this.executeLiveSyncOperationCore( devices, platform, - additionalOptions + additionalOptions, ); if (this.$options.release) { @@ -204,19 +204,19 @@ export class LiveSyncCommandHelper implements ILiveSyncCommandHelper { }) => { const devices = await this.getDeviceInstances(platform); const remainingDevicesToSync = devices.map( - (d) => d.deviceInfo.identifier + (d) => d.deviceInfo.identifier, ); _.remove(remainingDevicesToSync, (d) => d === data.deviceIdentifier); if (remainingDevicesToSync.length === 0 && !data.keepProcessAlive) { process.exit(ErrorCodes.ALL_DEVICES_DISCONNECTED); } - } + }, ); } public async validatePlatform( - platform: string + platform: string, ): Promise> { const result: IDictionary = {}; @@ -224,12 +224,12 @@ export class LiveSyncCommandHelper implements ILiveSyncCommandHelper { for (const availablePlatform of availablePlatforms) { const platformData = this.$platformsDataService.getPlatformData( availablePlatform, - this.$projectData + this.$projectData, ); const platformProjectService = platformData.platformProjectService; const validateOutput = await platformProjectService.validate( this.$projectData, - this.$options + this.$options, ); result[availablePlatform.toLowerCase()] = validateOutput; } @@ -240,7 +240,7 @@ export class LiveSyncCommandHelper implements ILiveSyncCommandHelper { private async executeLiveSyncOperationCore( devices: Mobile.IDevice[], platform: string, - additionalOptions?: ILiveSyncCommandHelperAdditionalOptions + additionalOptions?: ILiveSyncCommandHelperAdditionalOptions, ): Promise<{ liveSyncInfo: ILiveSyncInfo; deviceDescriptors: ILiveSyncDeviceDescriptor[]; @@ -248,11 +248,11 @@ export class LiveSyncCommandHelper implements ILiveSyncCommandHelper { if (!devices || !devices.length) { if (platform) { this.$errors.fail( - "Unable to find applicable devices to execute operation. Ensure connected devices are trusted and try again." + "Unable to find applicable devices to execute operation. Ensure connected devices are trusted and try again.", ); } else { this.$errors.fail( - "Unable to find applicable devices to execute operation and unable to start emulator when platform is not specified." + "Unable to find applicable devices to execute operation and unable to start emulator when platform is not specified.", ); } } @@ -273,7 +273,7 @@ export class LiveSyncCommandHelper implements ILiveSyncCommandHelper { const deviceDescriptors = await this.createDeviceDescriptors( devices, platform, - additionalOptions + additionalOptions, ); const liveSyncInfo = this.getLiveSyncData(this.$projectData.projectDir); @@ -282,7 +282,7 @@ export class LiveSyncCommandHelper implements ILiveSyncCommandHelper { private async runInRelease( platform: string, - deviceDescriptors: ILiveSyncDeviceDescriptor[] + deviceDescriptors: ILiveSyncDeviceDescriptor[], ): Promise { await this.$devicesService.initialize({ platform, @@ -296,7 +296,7 @@ export class LiveSyncCommandHelper implements ILiveSyncCommandHelper { for (const deviceDescriptor of deviceDescriptors) { const device = this.$devicesService.getDeviceByIdentifier( - deviceDescriptor.identifier + deviceDescriptor.identifier, ); await device.applicationManager.startApplication({ appId: diff --git a/lib/helpers/options-track-helper.ts b/lib/helpers/options-track-helper.ts index cebcb12ae6..13d17b354b 100644 --- a/lib/helpers/options-track-helper.ts +++ b/lib/helpers/options-track-helper.ts @@ -5,8 +5,8 @@ import { IAnalyticsService, IDictionary, IDashedOption, - OptionType, } from "../common/declarations"; +import { OptionType } from "../common/enums"; import * as _ from "lodash"; import { injector } from "../common/yok"; @@ -35,7 +35,7 @@ export class OptionsTracker { private sanitizeTrackObject( data: IDictionary, - options?: IOptions + options?: IOptions, ): IDictionary { const shorthands = options ? options.shorthands : []; const optionsDefinitions = options ? options.options : {}; @@ -72,7 +72,7 @@ export class OptionsTracker { key: string, value: any, shorthands: string[] = [], - options: IDictionary = {} + options: IDictionary = {}, ): Boolean { if (shorthands.indexOf(key) >= 0) { return true; diff --git a/lib/nativescript-cli.ts b/lib/nativescript-cli.ts index 04b2f90fd3..cf122f948c 100644 --- a/lib/nativescript-cli.ts +++ b/lib/nativescript-cli.ts @@ -35,7 +35,8 @@ if (process.platform === "win32") { import { installUncaughtExceptionListener } from "./common/errors"; import { settlePromises } from "./common/helpers"; import { injector } from "./common/yok"; -import { ErrorCodes, IErrors, ICommandDispatcher } from "./common/declarations"; +import { IErrors, ICommandDispatcher } from "./common/declarations"; +import { ErrorCodes } from "./common/enums"; import { IExtensibilityService, IExtensionData, diff --git a/lib/options.ts b/lib/options.ts index 3f7dee1675..4c91738aee 100644 --- a/lib/options.ts +++ b/lib/options.ts @@ -5,10 +5,10 @@ import * as _ from "lodash"; import { IDictionary, IDashedOption, - OptionType, IErrors, ISettingsService, } from "./common/declarations"; +import { OptionType } from "./common/enums"; import { injector } from "./common/yok"; import { APP_FOLDER_NAME } from "./constants"; export class Options { diff --git a/lib/services/analytics/analytics-broker-process.ts b/lib/services/analytics/analytics-broker-process.ts index 24e202ac46..970e0579e8 100644 --- a/lib/services/analytics/analytics-broker-process.ts +++ b/lib/services/analytics/analytics-broker-process.ts @@ -6,7 +6,8 @@ import { AnalyticsBroker } from "./analytics-broker"; import { FileLogService } from "../../detached-processes/file-log-service"; import { IAnalyticsBroker, ITrackingInformation } from "./analytics"; import { injector } from "../../common/yok"; -import { TrackingTypes } from "../../common/declarations"; +import { TrackingTypes } from "../../common/enums"; +import { DetachedProcessMessages } from "../../detached-processes/detached-process-enums"; const pathToBootstrap = process.argv[2]; if (!pathToBootstrap || !fs.existsSync(pathToBootstrap)) { diff --git a/lib/services/analytics/analytics-broker.ts b/lib/services/analytics/analytics-broker.ts index 8a12dbe4ae..338eb9d52a 100644 --- a/lib/services/analytics/analytics-broker.ts +++ b/lib/services/analytics/analytics-broker.ts @@ -7,12 +7,11 @@ import { } from "./analytics"; import { IAnalyticsSettingsService } from "../../common/declarations"; import { IInjector } from "../../common/definitions/yok"; +import { FileLogMessageType } from "../../detached-processes/detached-process-enums"; export class AnalyticsBroker implements IAnalyticsBroker { @cache() - private async getGoogleAnalyticsProvider(): Promise< - IGoogleAnalyticsProvider - > { + private async getGoogleAnalyticsProvider(): Promise { const clientId = await this.$analyticsSettingsService.getClientId(); return this.$injector.resolve("googleAnalyticsProvider", { clientId, @@ -23,16 +22,16 @@ export class AnalyticsBroker implements IAnalyticsBroker { constructor( private $analyticsSettingsService: IAnalyticsSettingsService, private $injector: IInjector, - private analyticsLoggingService: IFileLogService + private analyticsLoggingService: IFileLogService, ) {} public async sendDataForTracking( - trackInfo: ITrackingInformation + trackInfo: ITrackingInformation, ): Promise { try { const googleProvider = await this.getGoogleAnalyticsProvider(); await googleProvider.trackHit( - trackInfo + trackInfo, ); } catch (err) { this.analyticsLoggingService.logData({ diff --git a/lib/services/analytics/analytics-service.ts b/lib/services/analytics/analytics-service.ts index f9b10ee644..6eec0f7aa9 100644 --- a/lib/services/analytics/analytics-service.ts +++ b/lib/services/analytics/analytics-service.ts @@ -11,15 +11,17 @@ import { IAnalyticsService, IDisposable, IDictionary, - AnalyticsStatus, IUserSettingsService, IAnalyticsSettingsService, IChildProcess, IProjectHelper, - GoogleAnalyticsDataType, IStringDictionary, - TrackingTypes, } from "../../common/declarations"; +import { + AnalyticsStatus, + GoogleAnalyticsDataType, + TrackingTypes, +} from "../../common/enums"; import { IGoogleAnalyticsTrackingInformation, ITrackingInformation, @@ -31,6 +33,8 @@ import { IEventActionData, } from "../../common/definitions/google-analytics"; import { injector } from "../../common/yok"; +import { DetachedProcessMessages } from "../../detached-processes/detached-process-enums"; +import { GoogleAnalyticsCustomDimensions } from "../../common/services/analytics/google-analytics-custom-dimensions"; export class AnalyticsService implements IAnalyticsService, IDisposable { private static ANALYTICS_BROKER_START_TIMEOUT = 10 * 1000; diff --git a/lib/services/analytics/google-analytics-cross-client-custom-dimensions.d.ts b/lib/services/analytics/google-analytics-cross-client-custom-dimensions.d.ts deleted file mode 100644 index c58e2b54c0..0000000000 --- a/lib/services/analytics/google-analytics-cross-client-custom-dimensions.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -// Sync indexes with the custom dimensions of the cross client analytics project -declare const enum GoogleAnalyticsCrossClientCustomDimensions { - sessionId = "cd9", - clientId = "cd10", - crossClientId = "cd12", -} diff --git a/lib/services/analytics/google-analytics-provider.ts b/lib/services/analytics/google-analytics-provider.ts index 3feb0454bf..d7a0a8253d 100644 --- a/lib/services/analytics/google-analytics-provider.ts +++ b/lib/services/analytics/google-analytics-provider.ts @@ -6,9 +6,9 @@ import { IStaticConfig, IConfiguration } from "../../declarations"; import { IAnalyticsSettingsService, IProxyService, - GoogleAnalyticsDataType, IStringDictionary, } from "../../common/declarations"; +import { GoogleAnalyticsDataType } from "../../common/enums"; import { IGoogleAnalyticsProvider } from "./analytics"; import { IGoogleAnalyticsData, @@ -17,6 +17,8 @@ import { } from "../../common/definitions/google-analytics"; import * as _ from "lodash"; import { injector } from "../../common/yok"; +import { FileLogMessageType } from "../../detached-processes/detached-process-enums"; +import { GoogleAnalyticsCustomDimensions } from "../../common/services/analytics/google-analytics-custom-dimensions"; export class GoogleAnalyticsProvider implements IGoogleAnalyticsProvider { private currentPage: string; @@ -28,7 +30,7 @@ export class GoogleAnalyticsProvider implements IGoogleAnalyticsProvider { private $logger: ILogger, private $proxyService: IProxyService, private $config: IConfiguration, - private analyticsLoggingService: IFileLogService + private analyticsLoggingService: IFileLogService, ) {} public async trackHit(trackInfo: IGoogleAnalyticsData): Promise { @@ -40,7 +42,7 @@ export class GoogleAnalyticsProvider implements IGoogleAnalyticsProvider { this.analyticsLoggingService.logData({ type: FileLogMessageType.Error, message: `Unable to track information ${JSON.stringify( - trackInfo + trackInfo, )}. Error is: ${e}`, }); this.$logger.trace("Analytics exception: ", e); @@ -57,7 +59,7 @@ export class GoogleAnalyticsProvider implements IGoogleAnalyticsProvider { cid: this.clientId, headers: { ["User-Agent"]: this.$analyticsSettingsService.getUserAgentString( - `tnsCli/${this.$staticConfig.version}` + `tnsCli/${this.$staticConfig.version}`, ), }, requestOptions: { @@ -75,7 +77,7 @@ export class GoogleAnalyticsProvider implements IGoogleAnalyticsProvider { private async track( gaTrackingId: string, trackInfo: IGoogleAnalyticsData, - sessionId: string + sessionId: string, ): Promise { const proxySettings = await this.$proxyService.getCache(); const proxy = proxySettings && proxySettings.proxy; @@ -85,14 +87,14 @@ export class GoogleAnalyticsProvider implements IGoogleAnalyticsProvider { await this.setCustomDimensions( visitor, trackInfo.customDimensions, - sessionId + sessionId, ); switch (trackInfo.googleAnalyticsDataType) { case GoogleAnalyticsDataType.Page: await this.trackPageView( visitor, - trackInfo + trackInfo, ); break; case GoogleAnalyticsDataType.Event: @@ -104,7 +106,7 @@ export class GoogleAnalyticsProvider implements IGoogleAnalyticsProvider { private async setCustomDimensions( visitor: ua.Visitor, customDimensions: IStringDictionary, - sessionId: string + sessionId: string, ): Promise { const defaultValues: IStringDictionary = { [GoogleAnalyticsCustomDimensions.cliVersion]: this.$staticConfig.version, @@ -128,7 +130,7 @@ export class GoogleAnalyticsProvider implements IGoogleAnalyticsProvider { private trackEvent( visitor: ua.Visitor, - trackInfo: IGoogleAnalyticsEventData + trackInfo: IGoogleAnalyticsEventData, ): Promise { return new Promise((resolve, reject) => { visitor.event( @@ -154,14 +156,14 @@ export class GoogleAnalyticsProvider implements IGoogleAnalyticsProvider { message: `Tracked event with category: '${trackInfo.category}', action: '${trackInfo.action}', label: '${trackInfo.label}', value: '${trackInfo.value}' attached page: ${this.currentPage}.`, }); resolve(); - } + }, ); }); } private trackPageView( visitor: ua.Visitor, - trackInfo: IGoogleAnalyticsPageviewData + trackInfo: IGoogleAnalyticsPageviewData, ): Promise { return new Promise((resolve, reject) => { this.currentPage = trackInfo.path; diff --git a/lib/services/cleanup-service.ts b/lib/services/cleanup-service.ts index 4255e94a60..7defe5826a 100644 --- a/lib/services/cleanup-service.ts +++ b/lib/services/cleanup-service.ts @@ -14,6 +14,10 @@ import { IJSCleanupMessage, } from "../detached-processes/cleanup-process-definitions"; import { injector } from "../common/yok"; +import { + CleanupProcessMessage, + DetachedProcessMessages, +} from "../detached-processes/detached-process-enums"; export class CleanupService implements ICleanupService { private static CLEANUP_PROCESS_START_TIMEOUT = 10 * 1000; @@ -23,7 +27,7 @@ export class CleanupService implements ICleanupService { constructor( $options: IOptions, private $staticConfig: Config.IStaticConfig, - private $childProcess: IChildProcess + private $childProcess: IChildProcess, ) { this.pathToCleanupLogFile = $options.cleanupLogFile; } @@ -31,7 +35,7 @@ export class CleanupService implements ICleanupService { public shouldDispose = true; public async addCleanupCommand( - commandInfo: ISpawnCommandInfo + commandInfo: ISpawnCommandInfo, ): Promise { const cleanupProcess = await this.getCleanupProcess(); cleanupProcess.send({ @@ -41,7 +45,7 @@ export class CleanupService implements ICleanupService { } public async removeCleanupCommand( - commandInfo: ISpawnCommandInfo + commandInfo: ISpawnCommandInfo, ): Promise { const cleanupProcess = await this.getCleanupProcess(); cleanupProcess.send({ @@ -136,7 +140,7 @@ export class CleanupService implements ICleanupService { { stdio: ["ignore", "ignore", "ignore", "ipc"], detached: true, - } + }, ); cleanupProcess.unref(); diff --git a/lib/services/initialize-service.ts b/lib/services/initialize-service.ts index 8214b43a3d..a1990cd979 100644 --- a/lib/services/initialize-service.ts +++ b/lib/services/initialize-service.ts @@ -10,6 +10,7 @@ import { import { IInjector } from "../common/definitions/yok"; import { injector } from "../common/yok"; import { IExtensibilityService } from "../common/definitions/extensibility"; +import { SystemWarningsSeverity } from "../definitions/system-warnings"; export class InitializeService implements IInitializeService { // NOTE: Do not inject anything here, use $injector.resolve in the code @@ -30,17 +31,15 @@ export class InitializeService implements IInitializeService { } if (initOpts.settingsServiceOptions) { - const $settingsService = this.$injector.resolve( - "settingsService" - ); + const $settingsService = + this.$injector.resolve("settingsService"); $settingsService.setSettings(initOpts.settingsServiceOptions); } if (initOpts.extensibilityOptions) { if (initOpts.extensibilityOptions.pathToExtensions) { - const $extensibilityService = this.$injector.resolve< - IExtensibilityService - >("extensibilityService"); + const $extensibilityService = + this.$injector.resolve("extensibilityService"); $extensibilityService.pathToExtensions = initOpts.extensibilityOptions.pathToExtensions; } diff --git a/lib/services/ios-native-target-service.ts b/lib/services/ios-native-target-service.ts index f003329522..7f961f554a 100644 --- a/lib/services/ios-native-target-service.ts +++ b/lib/services/ios-native-target-service.ts @@ -4,8 +4,8 @@ import { IIOSNativeTargetService, IProjectData, IXcodeTargetBuildConfigurationProperty, - BuildNames, } from "../definitions/project"; +import { BuildNames } from "../constants"; import { IPlatformData } from "../definitions/platform"; import { IFileSystem } from "../common/declarations"; import { injector } from "../common/yok"; @@ -14,7 +14,7 @@ export class IOSNativeTargetService implements IIOSNativeTargetService { constructor( protected $fs: IFileSystem, protected $pbxprojDomXcode: IPbxprojDomXcode, - protected $logger: ILogger + protected $logger: ILogger, ) {} public addTargetToProject( @@ -23,12 +23,12 @@ export class IOSNativeTargetService implements IIOSNativeTargetService { targetType: string, project: IXcode.project, platformData: IPlatformData, - parentTarget?: string + parentTarget?: string, ): IXcode.target { const targetPath = path.join(targetRootPath, targetFolder); const targetRelativePath = path.relative( platformData.projectRoot, - targetPath + targetPath, ); const files = this.$fs .readDirectory(targetPath) @@ -38,20 +38,20 @@ export class IOSNativeTargetService implements IIOSNativeTargetService { targetFolder, targetType, targetRelativePath, - parentTarget + parentTarget, ); project.addBuildPhase([], "PBXSourcesBuildPhase", "Sources", target.uuid); project.addBuildPhase( [], "PBXResourcesBuildPhase", "Resources", - target.uuid + target.uuid, ); project.addBuildPhase( [], "PBXFrameworksBuildPhase", "Frameworks", - target.uuid + target.uuid, ); project.addPbxGroup(files, targetFolder, targetPath, null, { @@ -61,7 +61,7 @@ export class IOSNativeTargetService implements IIOSNativeTargetService { }); project.addToHeaderSearchPaths( targetPath, - target.pbxNativeTarget.productName + target.pbxNativeTarget.productName, ); return target; } @@ -69,7 +69,7 @@ export class IOSNativeTargetService implements IIOSNativeTargetService { public prepareSigning( targetUuids: string[], projectData: IProjectData, - projectPath: string + projectPath: string, ): void { const xcode = this.$pbxprojDomXcode.Xcode.open(projectPath); const signing = xcode.getSigning(projectData.projectName); @@ -82,7 +82,7 @@ export class IOSNativeTargetService implements IIOSNativeTargetService { const signingConfiguration = signing.configurations[config]; xcode.setManualSigningStyleByTargetKey( targetUuid, - signingConfiguration + signingConfiguration, ); break; } @@ -104,7 +104,7 @@ export class IOSNativeTargetService implements IIOSNativeTargetService { public setXcodeTargetBuildConfigurationProperties( properties: IXcodeTargetBuildConfigurationProperty[], targetName: string, - project: IXcode.project + project: IXcode.project, ): void { properties.forEach((property) => { const buildNames = property.buildNames || [ @@ -116,7 +116,7 @@ export class IOSNativeTargetService implements IIOSNativeTargetService { property.name, property.value, buildName, - targetName + targetName, ); }); }); @@ -126,7 +126,7 @@ export class IOSNativeTargetService implements IIOSNativeTargetService { jsonPath: string, targetUuid: string, targetName: string, - project: IXcode.project + project: IXcode.project, ): void { if (this.$fs.exists(jsonPath)) { const configurationJson = this.$fs.readJson(jsonPath) || {}; @@ -139,7 +139,7 @@ export class IOSNativeTargetService implements IIOSNativeTargetService { project.addToBuildSettings( "ASSETCATALOG_COMPILER_APPICON_NAME", configurationJson.assetcatalogCompilerAppiconName, - targetUuid + targetUuid, ); } const properties: IXcodeTargetBuildConfigurationProperty[] = []; @@ -148,7 +148,7 @@ export class IOSNativeTargetService implements IIOSNativeTargetService { if (configurationJson.targetBuildConfigurationProperties) { _.forEach( configurationJson.targetBuildConfigurationProperties, - (value, name: string) => properties.push({ value, name }) + (value, name: string) => properties.push({ value, name }), ); } @@ -169,23 +169,23 @@ export class IOSNativeTargetService implements IIOSNativeTargetService { default: { this.$logger.warn( "Ignoring targetNamedBuildConfigurationProperties: %s. Only 'release', 'debug' are allowed.", - name + name, ); } } if (buildName) { _.forEach(value, (value, name: string) => - properties.push({ value, name, buildNames: [buildName] }) + properties.push({ value, name, buildNames: [buildName] }), ); } - } + }, ); } this.setXcodeTargetBuildConfigurationProperties( properties, targetName, - project + project, ); } } diff --git a/lib/services/test-execution-service.ts b/lib/services/test-execution-service.ts index 7cd37fe2c1..8ba4eda276 100644 --- a/lib/services/test-execution-service.ts +++ b/lib/services/test-execution-service.ts @@ -9,12 +9,8 @@ import { } from "../definitions/project"; import { IConfiguration, IOptions } from "../declarations"; import { IPluginsService } from "../definitions/plugins"; -import { - Server, - IFileSystem, - IChildProcess, - ErrorCodes, -} from "../common/declarations"; +import { Server, IFileSystem, IChildProcess } from "../common/declarations"; +import { ErrorCodes } from "../common/enums"; import * as _ from "lodash"; import { injector } from "../common/yok"; import { ICommandParameter } from "../common/definitions/commands"; @@ -39,7 +35,7 @@ export class TestExecutionService implements ITestExecutionService { private $options: IOptions, private $pluginsService: IPluginsService, private $projectDataService: IProjectDataService, - private $childProcess: IChildProcess + private $childProcess: IChildProcess, ) {} public platform: string; @@ -47,13 +43,13 @@ export class TestExecutionService implements ITestExecutionService { public async startKarmaServer( platform: string, liveSyncInfo: ILiveSyncInfo, - deviceDescriptors: ILiveSyncDeviceDescriptor[] + deviceDescriptors: ILiveSyncDeviceDescriptor[], ): Promise { platform = platform.toLowerCase(); this.platform = platform; const projectData = this.$projectDataService.getProjectData( - liveSyncInfo.projectDir + liveSyncInfo.projectDir, ); // We need the dependencies installed here, so we can start the Karma server. @@ -64,12 +60,12 @@ export class TestExecutionService implements ITestExecutionService { const karmaRunner = this.$childProcess.spawn( process.execPath, [path.join(__dirname, "karma-execution.js")], - { stdio: ["inherit", "inherit", "inherit", "ipc"] } + { stdio: ["inherit", "inherit", "inherit", "ipc"] }, ); const launchKarmaTests = async (karmaData: any) => { this.$logger.trace( "## Unit-testing: Parent process received message", - karmaData + karmaData, ); let port: string; if (karmaData.url) { @@ -80,23 +76,23 @@ export class TestExecutionService implements ITestExecutionService { this.$fs.writeFile( path.join( liveSyncInfo.projectDir, - TestExecutionService.SOCKETIO_JS_FILE_NAME + TestExecutionService.SOCKETIO_JS_FILE_NAME, ), - JSON.parse(socketIoJs) + JSON.parse(socketIoJs), ); } if (karmaData.launcherConfig) { const configOptions: IKarmaConfigOptions = JSON.parse( - karmaData.launcherConfig + karmaData.launcherConfig, ); const configJs = this.generateConfig(port, configOptions); this.$fs.writeFile( path.join( liveSyncInfo.projectDir, - TestExecutionService.CONFIG_FILE_NAME + TestExecutionService.CONFIG_FILE_NAME, ), - configJs + configJs, ); } @@ -137,7 +133,7 @@ export class TestExecutionService implements ITestExecutionService { } public async canStartKarmaServer( - projectData: IProjectData + projectData: IProjectData, ): Promise { let canStartKarmaServer = true; const requiredDependencies = ["@nativescript/unit-test-runner"]; // we need @nativescript/unit-test-runner at the local level because of hooks! @@ -165,8 +161,8 @@ export class TestExecutionService implements ITestExecutionService { .map( (nicName) => nics[nicName].filter( - (binding: any) => binding.family === "IPv4" || binding.family === 4 - )[0] + (binding: any) => binding.family === "IPv4" || binding.family === 4, + )[0], ) .filter((binding) => !!binding) .map((binding) => binding.address); @@ -182,7 +178,7 @@ export class TestExecutionService implements ITestExecutionService { private getKarmaConfiguration( platform: string, - projectData: IProjectData + projectData: IProjectData, ): any { const karmaConfig: any = { browsers: [platform], diff --git a/lib/sys-info.ts b/lib/sys-info.ts index 98a9a22692..8675df917b 100644 --- a/lib/sys-info.ts +++ b/lib/sys-info.ts @@ -16,14 +16,18 @@ import { ISystemWarning, } from "./common/declarations"; import { injector } from "./common/yok"; +import { SystemWarningsSeverity } from "./definitions/system-warnings"; export class SysInfo implements ISysInfo { private sysInfo: ISysInfoData = null; - constructor(private $fs: IFileSystem, private $hostInfo: IHostInfo) {} + constructor( + private $fs: IFileSystem, + private $hostInfo: IHostInfo, + ) {} public async getSysInfo( - config?: NativeScriptDoctor.ISysInfoConfig + config?: NativeScriptDoctor.ISysInfoConfig, ): Promise { if (!this.sysInfo) { const pathToNativeScriptCliPackageJson = diff --git a/test/options.ts b/test/options.ts index e5c5f5e8a5..2d7e9a3b38 100644 --- a/test/options.ts +++ b/test/options.ts @@ -6,9 +6,9 @@ import { IOptions } from "../lib/declarations"; import { IInjector } from "../lib/common/definitions/yok"; import { IConfigurationSettings, - OptionType, ISettingsService, } from "../lib/common/declarations"; +import { OptionType } from "../lib/common/enums"; import * as _ from "lodash"; let isExecutionStopped = false; @@ -241,12 +241,11 @@ describe("options", () => { const expectedProfileDir = "TestDir"; process.argv.push("--profile-dir"); process.argv.push(expectedProfileDir); - const settingsService = testInjector.resolve( - "settingsService" - ); + const settingsService = + testInjector.resolve("settingsService"); let valuePassedToSetSettings: string; settingsService.setSettings = ( - settings: IConfigurationSettings + settings: IConfigurationSettings, ): any => { valuePassedToSetSettings = settings.profileDir; }; @@ -274,7 +273,7 @@ describe("options", () => { assert.isFalse( isExecutionStopped, "Dashed options should be validated in specific way. Make sure validation allows yargs specific behavior:" + - "Dashed options (profile-dir) are added to yargs.argv in two ways: profile-dir and profileDir" + "Dashed options (profile-dir) are added to yargs.argv in two ways: profile-dir and profileDir", ); }); @@ -288,7 +287,7 @@ describe("options", () => { assert.isFalse( isExecutionStopped, "Dashed options should be validated in specific way. Make sure validation allows yargs specific behavior:" + - "Dashed options (some-dashed-value) are added to yargs.argv in two ways: some-dashed-value and someDashedValue" + "Dashed options (some-dashed-value) are added to yargs.argv in two ways: some-dashed-value and someDashedValue", ); }); @@ -305,7 +304,7 @@ describe("options", () => { assert.isFalse( isExecutionStopped, "Dashed options should be validated in specific way. Make sure validation allows yargs specific behavior:" + - "Dashed options (special-dashed-v) are added to yargs.argv in two ways: special-dashed-v and specialDashedV" + "Dashed options (special-dashed-v) are added to yargs.argv in two ways: special-dashed-v and specialDashedV", ); }); }); @@ -350,8 +349,7 @@ describe("options", () => { expectedHmrValue: false, }, { - name: - "should set hmr to false when provided through dashed options from command", + name: "should set hmr to false when provided through dashed options from command", commandSpecificDashedOptions: { hmr: { type: OptionType.Boolean, @@ -362,14 +360,12 @@ describe("options", () => { expectedHmrValue: false, }, { - name: - "should set hmr to false by default when --release option is provided", + name: "should set hmr to false by default when --release option is provided", args: ["--release"], expectedHmrValue: false, }, { - name: - "should set hmr to false by default when --debug-brk option is provided", + name: "should set hmr to false by default when --debug-brk option is provided", args: ["--debugBrk"], expectedHmrValue: false, }, diff --git a/test/services/analytics/analytics-service.ts b/test/services/analytics/analytics-service.ts index 88f08320d6..3246e81e21 100644 --- a/test/services/analytics/analytics-service.ts +++ b/test/services/analytics/analytics-service.ts @@ -11,8 +11,10 @@ import { IInjector } from "../../../lib/common/definitions/yok"; import { IChildProcess, IAnalyticsService, - GoogleAnalyticsDataType, } from "../../../lib/common/declarations"; +import { GoogleAnalyticsDataType } from "../../../lib/common/enums"; +import { DetachedProcessMessages } from "../../../lib/detached-processes/detached-process-enums"; +import { GoogleAnalyticsCustomDimensions } from "../../../lib/common/services/analytics/google-analytics-custom-dimensions"; const helpers = require("../../../lib/common/helpers"); const originalIsInteractive = helpers.isInteractive; @@ -59,8 +61,8 @@ const createTestInjector = (opts?: { "projectHelper", new stubs.ProjectHelperStub( opts && opts.projectHelperErrorMsg, - opts && opts.projectDir - ) + opts && opts.projectDir, + ), ); return testInjector; @@ -82,20 +84,20 @@ describe("analyticsService", () => { }; }) => { const testInjector = createTestInjector(); - const staticConfig = testInjector.resolve( - "staticConfig" - ); + const staticConfig = + testInjector.resolve("staticConfig"); staticConfig.disableAnalytics = configuration.disableAnalytics; - configuration.userSettingsServiceOpts = configuration.userSettingsServiceOpts || { - trackFeatureUsageValue: "false", - defaultValue: "true", - }; + configuration.userSettingsServiceOpts = + configuration.userSettingsServiceOpts || { + trackFeatureUsageValue: "false", + defaultValue: "true", + }; const userSettingsService = testInjector.resolve( - "userSettingsService" + "userSettingsService", ); userSettingsService.getSettingValue = async ( - settingName: string + settingName: string, ): Promise => { if (settingName === trackFeatureUsage) { return configuration.userSettingsServiceOpts.trackFeatureUsageValue; @@ -105,20 +107,18 @@ describe("analyticsService", () => { }; let isChildProcessSpawned = false; - const childProcess = testInjector.resolve( - "childProcess" - ); + const childProcess = + testInjector.resolve("childProcess"); childProcess.spawn = ( command: string, args?: string[], - options?: any + options?: any, ): any => { isChildProcessSpawned = true; }; - const analyticsService = testInjector.resolve( - AnalyticsService - ); + const analyticsService = + testInjector.resolve(AnalyticsService); await analyticsService.trackInGoogleAnalytics({ googleAnalyticsDataType: GoogleAnalyticsDataType.Page, customDimensions: { @@ -169,11 +169,10 @@ describe("analyticsService", () => { describe("does not fail", () => { const assertExpectedError = async ( testInjector: IInjector, - opts: { isChildProcessSpawned: boolean; expectedErrorMessage: string } + opts: { isChildProcessSpawned: boolean; expectedErrorMessage: string }, ) => { - const analyticsService = testInjector.resolve( - AnalyticsService - ); + const analyticsService = + testInjector.resolve(AnalyticsService); await analyticsService.trackInGoogleAnalytics({ googleAnalyticsDataType: GoogleAnalyticsDataType.Page, customDimensions: { @@ -185,13 +184,13 @@ describe("analyticsService", () => { const logger = testInjector.resolve("logger"); assert.isTrue( logger.traceOutput.indexOf(opts.expectedErrorMessage) !== -1, - `Tried to find error '${opts.expectedErrorMessage}', but couldn't. logger's trace output is: ${logger.traceOutput}` + `Tried to find error '${opts.expectedErrorMessage}', but couldn't. logger's trace output is: ${logger.traceOutput}`, ); }; const setupTest = ( expectedErrorMessage: string, - projectHelperErrorMsg?: string + projectHelperErrorMsg?: string, ): any => { const testInjector = createTestInjector({ projectHelperErrorMsg }); const opts = { @@ -199,9 +198,8 @@ describe("analyticsService", () => { expectedErrorMessage, }; - const childProcess = testInjector.resolve( - "childProcess" - ); + const childProcess = + testInjector.resolve("childProcess"); return { testInjector, opts, @@ -211,12 +209,12 @@ describe("analyticsService", () => { it("when unable to start broker process", async () => { const { testInjector, childProcess, opts } = setupTest( - "Unable to get broker instance due to error: Error: custom error" + "Unable to get broker instance due to error: Error: custom error", ); childProcess.spawn = ( command: string, args?: string[], - options?: any + options?: any, ): any => { opts.isChildProcessSpawned = true; throw new Error("custom error"); @@ -227,13 +225,13 @@ describe("analyticsService", () => { it("when broker cannot start for required timeout", async () => { const { testInjector, childProcess, opts } = setupTest( - "Unable to get broker instance due to error: Error: Unable to start Analytics Broker process." + "Unable to get broker instance due to error: Error: Unable to start Analytics Broker process.", ); const originalSetTimeout = setTimeout; childProcess.spawn = ( command: string, args?: string[], - options?: any + options?: any, ): any => { opts.isChildProcessSpawned = true; (global).setTimeout = ( @@ -251,13 +249,13 @@ describe("analyticsService", () => { it("when broker is not connected", async () => { const { testInjector, childProcess, opts } = setupTest( - "Broker not found or not connected." + "Broker not found or not connected.", ); childProcess.spawn = ( command: string, args?: string[], - options?: any + options?: any, ): any => { opts.isChildProcessSpawned = true; const spawnedProcess: any = getSpawnedProcess(); @@ -268,9 +266,9 @@ describe("analyticsService", () => { () => spawnedProcess.emit( "message", - DetachedProcessMessages.ProcessReadyToReceive + DetachedProcessMessages.ProcessReadyToReceive, ), - 1 + 1, ); return spawnedProcess; }; @@ -280,13 +278,13 @@ describe("analyticsService", () => { it("when sending message fails", async () => { const { testInjector, childProcess, opts } = setupTest( - "Error while trying to send message to broker: Error: Failed to sent data." + "Error while trying to send message to broker: Error: Failed to sent data.", ); childProcess.spawn = ( command: string, args?: string[], - options?: any + options?: any, ): any => { opts.isChildProcessSpawned = true; const spawnedProcess: any = getSpawnedProcess(); @@ -300,9 +298,9 @@ describe("analyticsService", () => { () => spawnedProcess.emit( "message", - DetachedProcessMessages.ProcessReadyToReceive + DetachedProcessMessages.ProcessReadyToReceive, ), - 1 + 1, ); return spawnedProcess; }; @@ -314,12 +312,12 @@ describe("analyticsService", () => { const projectHelperErrorMsg = "Failed to find project directory."; const { testInjector, childProcess, opts } = setupTest( `Unable to get the projectDir from projectHelper Error: ${projectHelperErrorMsg}`, - projectHelperErrorMsg + projectHelperErrorMsg, ); childProcess.spawn = ( command: string, args?: string[], - options?: any + options?: any, ): any => { opts.isChildProcessSpawned = true; const spawnedProcess: any = getSpawnedProcess(); @@ -334,9 +332,9 @@ describe("analyticsService", () => { () => spawnedProcess.emit( "message", - DetachedProcessMessages.ProcessReadyToReceive + DetachedProcessMessages.ProcessReadyToReceive, ), - 1 + 1, ); return spawnedProcess; }; @@ -350,7 +348,7 @@ describe("analyticsService", () => { expectedResult: any, dataToSend: any, terminalOpts?: { isInteractive: boolean }, - projectHelperOpts?: { projectDir: string } + projectHelperOpts?: { projectDir: string }, ): { testInjector: IInjector; opts: any } => { helpers.isInteractive = () => terminalOpts ? terminalOpts.isInteractive : true; @@ -363,13 +361,12 @@ describe("analyticsService", () => { messageSent: null, }; - const childProcess = testInjector.resolve( - "childProcess" - ); + const childProcess = + testInjector.resolve("childProcess"); childProcess.spawn = ( command: string, args?: string[], - options?: any + options?: any, ): any => { opts.isChildProcessSpawned = true; const spawnedProcess: any = getSpawnedProcess(); @@ -384,9 +381,9 @@ describe("analyticsService", () => { () => spawnedProcess.emit( "message", - DetachedProcessMessages.ProcessReadyToReceive + DetachedProcessMessages.ProcessReadyToReceive, ), - 1 + 1, ); return spawnedProcess; @@ -405,11 +402,10 @@ describe("analyticsService", () => { expectedResult: any; messageSent: any; dataToSend: any; - } + }, ) => { - const analyticsService = testInjector.resolve( - AnalyticsService - ); + const analyticsService = + testInjector.resolve(AnalyticsService); await analyticsService.trackInGoogleAnalytics(opts.dataToSend); assert.isTrue(opts.isChildProcessSpawned); @@ -426,7 +422,7 @@ describe("analyticsService", () => { const getExpectedResult = ( gaDataType: string, analyticsClient?: string, - projectType?: string + projectType?: string, ): any => { const expectedResult: any = { type: "googleAnalyticsData", @@ -456,7 +452,7 @@ describe("analyticsService", () => { it(`when data is ${googleAnalyticsDataType}`, async () => { const { testInjector, opts } = setupTest( getExpectedResult(googleAnalyticsDataType), - getDataToSend(googleAnalyticsDataType) + getDataToSend(googleAnalyticsDataType), ); await assertExpectedResult(testInjector, opts); }); @@ -466,11 +462,11 @@ describe("analyticsService", () => { getExpectedResult( googleAnalyticsDataType, null, - sampleProjectType + sampleProjectType, ), getDataToSend(googleAnalyticsDataType), null, - { projectDir: "/some-dir" } + { projectDir: "/some-dir" }, ); await assertExpectedResult(testInjector, opts); }); @@ -479,10 +475,10 @@ describe("analyticsService", () => { const { testInjector, opts } = setupTest( getExpectedResult( googleAnalyticsDataType, - AnalyticsClients.Unknown + AnalyticsClients.Unknown, ), getDataToSend(googleAnalyticsDataType), - { isInteractive: false } + { isInteractive: false }, ); await assertExpectedResult(testInjector, opts); }); @@ -496,7 +492,7 @@ describe("analyticsService", () => { const { testInjector, opts } = setupTest( getExpectedResult(googleAnalyticsDataType, analyticsClient), getDataToSend(googleAnalyticsDataType), - { isInteractive } + { isInteractive }, ); const options = testInjector.resolve("options"); options.analyticsClient = analyticsClient; @@ -504,7 +500,7 @@ describe("analyticsService", () => { await assertExpectedResult(testInjector, opts); }); }); - } + }, ); }); }); diff --git a/test/sys-info.ts b/test/sys-info.ts index 0433b4df04..f2f9d31ef1 100644 --- a/test/sys-info.ts +++ b/test/sys-info.ts @@ -12,6 +12,7 @@ import { ISysInfo, IFileSystem, } from "../lib/common/declarations"; +import { SystemWarningsSeverity } from "../lib/definitions/system-warnings"; const verifyNodeVersion = require("../lib/common/verify-node-version"); describe("sysInfo", () => { @@ -49,8 +50,8 @@ describe("sysInfo", () => { ? { message: opts.nodeJsWarning, severity: SystemWarningsSeverity.medium, - } - : null + } + : null, ); const testInjector = createTestInjector(); @@ -111,7 +112,7 @@ describe("sysInfo", () => { describe("getMacOSWarningMessage", () => { const getMacOSWarning = async ( - macOSDeprecatedVersion?: string + macOSDeprecatedVersion?: string, ): Promise => { sandbox.stub(verifyNodeVersion, "getNodeWarning").returns(null); From e6510540e157124674d82a11c47e0797f6425ab9 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sat, 25 Jul 2026 13:48:40 -0300 Subject: [PATCH 2/2] chore: enable isolatedModules Moving the ambient const enums into real modules removed the last thing standing in the way: tsc --noEmit --isolatedModules reports 244 errors on main (all TS2748, 'Cannot access ambient const enums') and none once they are real modules. This is not emit-neutral. With isolatedModules on, tsc stops inlining const enums and emits them as runtime objects, so 33 files change: consumers go from a baked-in literal to a property lookup, and lib/constants.js now emits ShouldMigrate, NativePlatformStatus, DebugTools, TrackActionNames, BuildStates and PlatformTypes. The values are unchanged - verified at runtime - and the suite is unchanged at 1513 passing, with the CLI still rendering help and reporting its version. That change is arguably the point. oxc and esbuild cannot inline a const enum across files, so today tsc's output and every other transpiler's output disagree for exactly those six. Now they agree. It also means the const modifier on the remaining ten declarations no longer buys inlining, so it is decorative; converting them to plain enum is a sensible follow-up. --- tsconfig.json | 1 + 1 file changed, 1 insertion(+) diff --git a/tsconfig.json b/tsconfig.json index c79b1ad953..72a247f2c9 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -7,6 +7,7 @@ "removeComments": false, "noImplicitAny": true, "experimentalDecorators": true, + "isolatedModules": true, "skipLibCheck": true, "alwaysStrict": true, "noUnusedLocals": true,